Remove unneeded interfaces (#1779)

* Remove unneeded interfaces

* Remove unused code
This commit is contained in:
Tomas Touceda
2021-08-24 18:49:56 -03:00
committed by GitHub
parent 9158b6168a
commit 5fb5995b83
55 changed files with 2167 additions and 2993 deletions
+1 -1
View File
@@ -46,7 +46,7 @@ func (ds *Datastore) RecordPolicyQueryExecutions(host *fleet.Host, results map[u
// Sort the results to have generated SQL queries ordered to minimize
// deadlocks. See https://github.com/fleetdm/fleet/issues/1146.
orderedIDs := make([]uint, 0, len(results))
for policyID, _ := range results {
for policyID := range results {
orderedIDs = append(orderedIDs, policyID)
}
sort.Slice(orderedIDs, func(i, j int) bool { return orderedIDs[i] < orderedIDs[j] })
-10
View File
@@ -1,7 +1,6 @@
package fleet
import (
"context"
"encoding/json"
)
@@ -32,15 +31,6 @@ const (
ActivityTypeLiveQuery = "live_query"
)
type ActivitiesStore interface {
NewActivity(user *User, activityType string, details *map[string]interface{}) error
ListActivities(opt ListOptions) ([]*Activity, error)
}
type ActivitiesService interface {
ListActivities(ctx context.Context, opt ListOptions) ([]*Activity, error)
}
type Activity struct {
CreateTimestamp
ID uint `json:"id" db:"id"`
-9
View File
@@ -1,18 +1,9 @@
package fleet
import (
"context"
"encoding/json"
)
type AgentOptionsService interface {
// AgentOptionsForHost gets the agent options for the provided host.
//
// The host information should be used for filtering based on team,
// platform, etc.
AgentOptionsForHost(ctx context.Context, host *Host) (json.RawMessage, error)
}
type AgentOptions struct {
// Config is the base config options.
Config json.RawMessage `json:"config"`
-54
View File
@@ -1,66 +1,12 @@
package fleet
import (
"context"
"encoding/json"
"time"
"github.com/fleetdm/fleet/v4/server/config"
"github.com/kolide/kit/version"
)
// AppConfigStore contains method for saving and retrieving
// application configuration
type AppConfigStore interface {
NewAppConfig(info *AppConfig) (*AppConfig, error)
AppConfig() (*AppConfig, error)
SaveAppConfig(info *AppConfig) error
// VerifyEnrollSecret checks that the provided secret matches an active
// enroll secret. If it is successfully matched, that secret is returned.
// Otherwise an error is returned.
VerifyEnrollSecret(secret string) (*EnrollSecret, error)
// GetEnrollSecrets gets the enroll secrets for a team (or global if teamID is nil).
GetEnrollSecrets(teamID *uint) ([]*EnrollSecret, error)
// ApplyEnrollSecrets replaces the current enroll secrets for a team with the provided secrets.
ApplyEnrollSecrets(teamID *uint, secrets []*EnrollSecret) error
}
// AppConfigService provides methods for configuring
// the Fleet application
type AppConfigService interface {
NewAppConfig(ctx context.Context, p AppConfig) (info *AppConfig, err error)
AppConfig(ctx context.Context) (info *AppConfig, err error)
ModifyAppConfig(ctx context.Context, p []byte) (info *AppConfig, err error)
// ApplyEnrollSecretSpec adds and updates the enroll secrets specified in
// the spec.
ApplyEnrollSecretSpec(ctx context.Context, spec *EnrollSecretSpec) error
// GetEnrollSecretSpec gets the spec for the current enroll secrets.
GetEnrollSecretSpec(ctx context.Context) (*EnrollSecretSpec, error)
// CertificateChain returns the PEM encoded certificate chain for osqueryd TLS termination.
// For cases where the connection is self-signed, the server will attempt to
// connect using the InsecureSkipVerify option in tls.Config.
CertificateChain(ctx context.Context) (cert []byte, err error)
// SetupRequired returns whether the app config setup needs to be performed
// (only when first initializing a Fleet server).
SetupRequired(ctx context.Context) (bool, error)
// Version returns version and build information.
Version(ctx context.Context) (*version.Info, error)
// License returns the licensing information.
License(ctx context.Context) (*LicenseInfo, error)
// LoggingConfig parses config.FleetConfig instance and returns a Logging.
LoggingConfig(ctx context.Context) (*Logging, error)
// UpdateIntervalConfig returns the duration for different update intervals configured in osquery
UpdateIntervalConfig(ctx context.Context) (*UpdateIntervalConfig, error)
}
// SMTP settings names returned from API, these map to SMTPAuthType and
// SMTPAuthMethod
const (
-53
View File
@@ -1,58 +1,5 @@
package fleet
import (
"context"
"time"
"github.com/fleetdm/fleet/v4/server/websocket"
)
// CampaignStore defines the distributed query campaign related datastore
// methods
type CampaignStore interface {
// NewDistributedQueryCampaign creates a new distributed query campaign
NewDistributedQueryCampaign(camp *DistributedQueryCampaign) (*DistributedQueryCampaign, error)
// DistributedQueryCampaign loads a distributed query campaign by ID
DistributedQueryCampaign(id uint) (*DistributedQueryCampaign, error)
// SaveDistributedQueryCampaign updates an existing distributed query
// campaign
SaveDistributedQueryCampaign(camp *DistributedQueryCampaign) error
// DistributedQueryCampaignTargetIDs gets the IDs of the targets for
// the query campaign of the provided ID
DistributedQueryCampaignTargetIDs(id uint) (targets *HostTargets, err error)
// NewDistributedQueryCampaignTarget adds a new target to an existing
// distributed query campaign
NewDistributedQueryCampaignTarget(target *DistributedQueryCampaignTarget) (*DistributedQueryCampaignTarget, error)
// CleanupDistributedQueryCampaigns will clean and trim metadata for old
// distributed query campaigns. Any campaign in the QueryWaiting state will
// be moved to QueryComplete after one minute. Any campaign in the
// QueryRunning state will be moved to QueryComplete after one day. Times
// are from creation time. The now parameter makes this method easier to
// test. The return values indicate how many campaigns were expired and any error.
CleanupDistributedQueryCampaigns(now time.Time) (expired uint, err error)
}
// CampaignService defines the distributed query campaign related service
// methods
type CampaignService interface {
// NewDistributedQueryCampaign creates a new distributed query campaign with
// the provided query (or the query referenced by ID) and host/label targets
// (specified by name).
NewDistributedQueryCampaignByNames(ctx context.Context, queryString string, queryID *uint, hosts []string, labels []string) (*DistributedQueryCampaign, error)
// NewDistributedQueryCampaign creates a new distributed query campaign
// with the provided query (or the query referenced by ID) and host/label targets
NewDistributedQueryCampaign(ctx context.Context, queryString string, queryID *uint, targets HostTargets) (*DistributedQueryCampaign, error)
// StreamCampaignResults streams updates with query results and
// expected host totals over the provided websocket. Note that the type
// signature is somewhat inconsistent due to this being a streaming API
// and not the typical go-kit RPC style.
StreamCampaignResults(ctx context.Context, conn *websocket.Conn, campaignID uint)
}
// DistributedQueryStatus is the lifecycle status of a distributed query
// campaign.
type DistributedQueryStatus int
-24
View File
@@ -1,33 +1,9 @@
package fleet
import (
"context"
"time"
)
type CarveStore interface {
NewCarve(metadata *CarveMetadata) (*CarveMetadata, error)
UpdateCarve(metadata *CarveMetadata) error
Carve(carveId int64) (*CarveMetadata, error)
CarveBySessionId(sessionId string) (*CarveMetadata, error)
CarveByName(name string) (*CarveMetadata, error)
ListCarves(opt CarveListOptions) ([]*CarveMetadata, error)
NewBlock(metadata *CarveMetadata, blockId int64, data []byte) error
GetBlock(metadata *CarveMetadata, blockId int64) ([]byte, error)
// CleanupCarves will mark carves older than 24 hours expired, and delete the
// associated data blocks. This behaves differently for carves stored in S3
// (check the implementation godoc comment for more details)
CleanupCarves(now time.Time) (expired int, err error)
}
type CarveService interface {
CarveBegin(ctx context.Context, payload CarveBeginPayload) (*CarveMetadata, error)
CarveBlock(ctx context.Context, payload CarveBlockPayload) error
GetCarve(ctx context.Context, id int64) (*CarveMetadata, error)
ListCarves(ctx context.Context, opt CarveListOptions) ([]*CarveMetadata, error)
GetBlock(ctx context.Context, carveId, blockId int64) ([]byte, error)
}
type CarveMetadata struct {
// ID is the DB auto-increment ID for the carve.
ID int64 `json:"id" db:"id"`
+342 -23
View File
@@ -1,25 +1,347 @@
package fleet
import "time"
type CarveStore interface {
NewCarve(metadata *CarveMetadata) (*CarveMetadata, error)
UpdateCarve(metadata *CarveMetadata) error
Carve(carveId int64) (*CarveMetadata, error)
CarveBySessionId(sessionId string) (*CarveMetadata, error)
CarveByName(name string) (*CarveMetadata, error)
ListCarves(opt CarveListOptions) ([]*CarveMetadata, error)
NewBlock(metadata *CarveMetadata, blockId int64, data []byte) error
GetBlock(metadata *CarveMetadata, blockId int64) ([]byte, error)
// CleanupCarves will mark carves older than 24 hours expired, and delete the associated data blocks. This behaves
// differently for carves stored in S3 (check the implementation godoc comment for more details)
CleanupCarves(now time.Time) (expired int, err error)
}
// Datastore combines all the interfaces in the Fleet DAL
type Datastore interface {
UserStore
QueryStore
CampaignStore
PackStore
LabelStore
HostStore
TargetStore
PasswordResetStore
SessionStore
AppConfigStore
InviteStore
ScheduledQueryStore
CarveStore
TeamStore
SoftwareStore
ActivitiesStore
StatisticsStore
GlobalPoliciesStore
///////////////////////////////////////////////////////////////////////////////
// UserStore contains methods for managing users in a datastore
NewUser(user *User) (*User, error)
ListUsers(opt UserListOptions) ([]*User, error)
UserByEmail(email string) (*User, error)
UserByID(id uint) (*User, error)
SaveUser(user *User) error
SaveUsers(users []*User) error
// DeleteUser permanently deletes the user identified by the provided ID.
DeleteUser(id uint) error
// PendingEmailChange creates a record with a pending email change for a user identified by uid. The change record
// is keyed by a unique token. The token is emailed to the user with a link that they can use to confirm the change.
PendingEmailChange(userID uint, newEmail, token string) error
// ConfirmPendingEmailChange will confirm new email address identified by token is valid. The new email will be
// written to user record. userID is the ID of the user whose e-mail is being changed.
ConfirmPendingEmailChange(userID uint, token string) (string, error)
///////////////////////////////////////////////////////////////////////////////
// QueryStore
// ApplyQueries applies a list of queries (likely from a yaml file) to the datastore. Existing queries are updated,
// and new queries are created.
ApplyQueries(authorID uint, queries []*Query) error
// NewQuery creates a new query object in thie datastore. The returned query should have the ID updated.
NewQuery(query *Query, opts ...OptionalArg) (*Query, error)
// SaveQuery saves changes to an existing query object.
SaveQuery(query *Query) error
// DeleteQuery deletes an existing query object.
DeleteQuery(name string) error
// DeleteQueries deletes the existing query objects with the provided IDs. The number of deleted queries is returned
// along with any error.
DeleteQueries(ids []uint) (uint, error)
// Query returns the query associated with the provided ID. Associated packs should also be loaded.
Query(id uint) (*Query, error)
// ListQueries returns a list of queries with the provided sorting and paging options. Associated packs should also
// be loaded.
ListQueries(opt ListOptions) ([]*Query, error)
// QueryByName looks up a query by name.
QueryByName(name string, opts ...OptionalArg) (*Query, error)
///////////////////////////////////////////////////////////////////////////////
// CampaignStore defines the distributed query campaign related datastore methods
// NewDistributedQueryCampaign creates a new distributed query campaign
NewDistributedQueryCampaign(camp *DistributedQueryCampaign) (*DistributedQueryCampaign, error)
// DistributedQueryCampaign loads a distributed query campaign by ID
DistributedQueryCampaign(id uint) (*DistributedQueryCampaign, error)
// SaveDistributedQueryCampaign updates an existing distributed query campaign
SaveDistributedQueryCampaign(camp *DistributedQueryCampaign) error
// DistributedQueryCampaignTargetIDs gets the IDs of the targets for the query campaign of the provided ID
DistributedQueryCampaignTargetIDs(id uint) (targets *HostTargets, err error)
// NewDistributedQueryCampaignTarget adds a new target to an existing distributed query campaign
NewDistributedQueryCampaignTarget(target *DistributedQueryCampaignTarget) (*DistributedQueryCampaignTarget, error)
// CleanupDistributedQueryCampaigns will clean and trim metadata for old distributed query campaigns. Any campaign
// in the QueryWaiting state will be moved to QueryComplete after one minute. Any campaign in the QueryRunning state
// will be moved to QueryComplete after one day. Times are from creation time. The now parameter makes this method
// easier to test. The return values indicate how many campaigns were expired and any error.
CleanupDistributedQueryCampaigns(now time.Time) (expired uint, err error)
///////////////////////////////////////////////////////////////////////////////
// PackStore is the datastore interface for managing query packs.
// ApplyPackSpecs applies a list of PackSpecs to the datastore, creating and updating packs as necessary.
ApplyPackSpecs(specs []*PackSpec) error
// GetPackSpecs returns all of the stored PackSpecs.
GetPackSpecs() ([]*PackSpec, error)
// GetPackSpec returns the spec for the named pack.
GetPackSpec(name string) (*PackSpec, error)
// NewPack creates a new pack in the datastore.
NewPack(pack *Pack, opts ...OptionalArg) (*Pack, error)
// SavePack updates an existing pack in the datastore.
SavePack(pack *Pack) error
// DeletePack deletes a pack record from the datastore.
DeletePack(name string) error
// Pack retrieves a pack from the datastore by ID.
Pack(pid uint) (*Pack, error)
// ListPacks lists all packs in the datastore.
ListPacks(opt PackListOptions) ([]*Pack, error)
// PackByName fetches pack if it exists, if the pack exists the bool return value is true
PackByName(name string, opts ...OptionalArg) (*Pack, bool, error)
// ListPacksForHost lists the packs that a host should execute.
ListPacksForHost(hid uint) (packs []*Pack, err error)
// EnsureGlobalPack gets or inserts a pack with type global
EnsureGlobalPack() (*Pack, error)
// EnsureTeamPack gets or inserts a pack with type global
EnsureTeamPack(teamID uint) (*Pack, error)
///////////////////////////////////////////////////////////////////////////////
// LabelStore
// ApplyLabelSpecs applies a list of LabelSpecs to the datastore, creating and updating labels as necessary.
ApplyLabelSpecs(specs []*LabelSpec) error
// GetLabelSpecs returns all of the stored LabelSpecs.
GetLabelSpecs() ([]*LabelSpec, error)
// GetLabelSpec returns the spec for the named label.
GetLabelSpec(name string) (*LabelSpec, error)
NewLabel(Label *Label, opts ...OptionalArg) (*Label, error)
SaveLabel(label *Label) (*Label, error)
DeleteLabel(name string) error
Label(lid uint) (*Label, error)
ListLabels(filter TeamFilter, opt ListOptions) ([]*Label, error)
// LabelQueriesForHost returns the label queries that should be executed for the given host. The cutoff is the
// minimum timestamp a query execution should have to be considered "fresh". Executions that are not fresh will be
// repeated. Results are returned in a map of label id -> query
LabelQueriesForHost(host *Host, cutoff time.Time) (map[string]string, error)
// RecordLabelQueryExecutions saves the results of label queries. The results map is a map of label id -> whether or
// not the label matches. The time parameter is the timestamp to save with the query execution.
RecordLabelQueryExecutions(host *Host, results map[uint]*bool, t time.Time) error
// ListLabelsForHost returns the labels that the given host is in.
ListLabelsForHost(hid uint) ([]*Label, error)
// ListHostsInLabel returns a slice of hosts in the label with the given ID.
ListHostsInLabel(filter TeamFilter, lid uint, opt HostListOptions) ([]*Host, error)
// ListUniqueHostsInLabels returns a slice of all of the hosts in the given label IDs. A host will only appear once
// in the results even if it is in multiple of the provided labels.
ListUniqueHostsInLabels(filter TeamFilter, labels []uint) ([]*Host, error)
SearchLabels(filter TeamFilter, query string, omit ...uint) ([]*Label, error)
// LabelIDsByName Retrieve the IDs associated with the given labels
LabelIDsByName(labels []string) ([]uint, error)
///////////////////////////////////////////////////////////////////////////////
// HostStore
// NewHost is deprecated and will be removed. Hosts should always be enrolled via EnrollHost.
NewHost(host *Host) (*Host, error)
SaveHost(host *Host) error
DeleteHost(hid uint) error
Host(id uint) (*Host, error)
// EnrollHost will enroll a new host with the given identifier, setting the node key, and team. Implementations of
// this method should respect the provided host enrollment cooldown, by returning an error if the host has enrolled
// within the cooldown period.
EnrollHost(osqueryHostId, nodeKey string, teamID *uint, cooldown time.Duration) (*Host, error)
ListHosts(filter TeamFilter, opt HostListOptions) ([]*Host, error)
// AuthenticateHost authenticates and returns host metadata by node key. This method should not return the host
// "additional" information as this is not typically necessary for the operations performed by the osquery
// endpoints.
AuthenticateHost(nodeKey string) (*Host, error)
MarkHostSeen(host *Host, t time.Time) error
MarkHostsSeen(hostIDs []uint, t time.Time) error
SearchHosts(filter TeamFilter, query string, omit ...uint) ([]*Host, error)
// CleanupIncomingHosts deletes hosts that have enrolled but never updated their status details. This clears dead
// "incoming hosts" that never complete their registration.
// A host is considered incoming if both the hostname and osquery_version fields are empty. This means that multiple
// different osquery queries failed to populate details.
CleanupIncomingHosts(now time.Time) error
// GenerateHostStatusStatistics retrieves the count of online, offline, MIA and new hosts.
GenerateHostStatusStatistics(filter TeamFilter, now time.Time) (online, offline, mia, new uint, err error)
// HostIDsByName Retrieve the IDs associated with the given hostnames
HostIDsByName(filter TeamFilter, hostnames []string) ([]uint, error)
// HostByIdentifier returns one host matching the provided identifier. Possible matches can be on
// osquery_host_identifier, node_key, UUID, or hostname.
HostByIdentifier(identifier string) (*Host, error)
// AddHostsToTeam adds hosts to an existing team, clearing their team settings if teamID is nil.
AddHostsToTeam(teamID *uint, hostIDs []uint) error
// SaveHostAdditional saves the information generated by the additional_queries.
SaveHostAdditional(host *Host) error
///////////////////////////////////////////////////////////////////////////////
// TargetStore
// CountHostsInTargets returns the metrics of the hosts in the provided labels, teams, and explicit host IDs.
CountHostsInTargets(filter TeamFilter, targets HostTargets, now time.Time) (TargetMetrics, error)
// HostIDsInTargets returns the host IDs of the hosts in the provided labels, teams, and explicit host IDs. The
// returned host IDs should be sorted in ascending order.
HostIDsInTargets(filter TeamFilter, targets HostTargets) ([]uint, error)
///////////////////////////////////////////////////////////////////////////////
// PasswordResetStore manages password resets in the Datastore
NewPasswordResetRequest(req *PasswordResetRequest) (*PasswordResetRequest, error)
SavePasswordResetRequest(req *PasswordResetRequest) error
DeletePasswordResetRequest(req *PasswordResetRequest) error
DeletePasswordResetRequestsForUser(userID uint) error
FindPassswordResetByID(id uint) (*PasswordResetRequest, error)
FindPassswordResetsByUserID(id uint) ([]*PasswordResetRequest, error)
FindPassswordResetByToken(token string) (*PasswordResetRequest, error)
FindPassswordResetByTokenAndUserID(token string, id uint) (*PasswordResetRequest, error)
///////////////////////////////////////////////////////////////////////////////
// SessionStore is the abstract interface that all session backends must conform to.
// SessionByKey returns, given a session key, a session object or an error if one could not be found for the given
// key
SessionByKey(key string) (*Session, error)
// SessionByID returns, given a session id, find and return a session object or an error if one could not be found
// for the given id
SessionByID(id uint) (*Session, error)
// ListSessionsForUser finds all the active sessions for a given user
ListSessionsForUser(id uint) ([]*Session, error)
// NewSession stores a new session struct
NewSession(session *Session) (*Session, error)
// DestroySession destroys the currently tracked session
DestroySession(session *Session) error
// DestroyAllSessionsForUser destroys all of the sessions for a given user
DestroyAllSessionsForUser(id uint) error
// MarkSessionAccessed marks the currently tracked session as access to extend expiration
MarkSessionAccessed(session *Session) error
///////////////////////////////////////////////////////////////////////////////
// AppConfigStore contains method for saving and retrieving application configuration
NewAppConfig(info *AppConfig) (*AppConfig, error)
AppConfig() (*AppConfig, error)
SaveAppConfig(info *AppConfig) error
// VerifyEnrollSecret checks that the provided secret matches an active enroll secret. If it is successfully
// matched, that secret is returned. Otherwise, an error is returned.
VerifyEnrollSecret(secret string) (*EnrollSecret, error)
// GetEnrollSecrets gets the enroll secrets for a team (or global if teamID is nil).
GetEnrollSecrets(teamID *uint) ([]*EnrollSecret, error)
// ApplyEnrollSecrets replaces the current enroll secrets for a team with the provided secrets.
ApplyEnrollSecrets(teamID *uint, secrets []*EnrollSecret) error
///////////////////////////////////////////////////////////////////////////////
// InviteStore contains the methods for managing user invites in a datastore.
// NewInvite creates and stores a new invitation in a DB.
NewInvite(i *Invite) (*Invite, error)
// ListInvites lists all invites in the datastore.
ListInvites(opt ListOptions) ([]*Invite, error)
// Invite retrieves an invite by its ID.
Invite(id uint) (*Invite, error)
// InviteByEmail retrieves an invite for a specific email address.
InviteByEmail(email string) (*Invite, error)
// InviteByToken retrieves and invite using the token string.
InviteByToken(token string) (*Invite, error)
// DeleteInvite deletes an invitation.
DeleteInvite(id uint) error
///////////////////////////////////////////////////////////////////////////////
// ScheduledQueryStore
ListScheduledQueriesInPack(id uint, opts ListOptions) ([]*ScheduledQuery, error)
NewScheduledQuery(sq *ScheduledQuery, opts ...OptionalArg) (*ScheduledQuery, error)
SaveScheduledQuery(sq *ScheduledQuery) (*ScheduledQuery, error)
DeleteScheduledQuery(id uint) error
ScheduledQuery(id uint) (*ScheduledQuery, error)
CleanupOrphanScheduledQueryStats() error
///////////////////////////////////////////////////////////////////////////////
// TeamStore
// NewTeam creates a new Team object in the store.
NewTeam(team *Team) (*Team, error)
// SaveTeam saves any changes to the team.
SaveTeam(team *Team) (*Team, error)
// Team retrieves the Team by ID.
Team(tid uint) (*Team, error)
// Team deletes the Team by ID.
DeleteTeam(tid uint) error
// TeamByName retrieves the Team by Name.
TeamByName(name string) (*Team, error)
// ListTeams lists teams with the ordering and filters in the provided options.
ListTeams(filter TeamFilter, opt ListOptions) ([]*Team, error)
// SearchTeams searches teams using the provided query and ommitting the provided existing selection.
SearchTeams(filter TeamFilter, matchQuery string, omit ...uint) ([]*Team, error)
// TeamEnrollSecrets lists the enroll secrets for the team.
TeamEnrollSecrets(teamID uint) ([]*EnrollSecret, error)
///////////////////////////////////////////////////////////////////////////////
// SoftwareStore
SaveHostSoftware(host *Host) error
LoadHostSoftware(host *Host) error
AllSoftwareWithoutCPEIterator() (SoftwareIterator, error)
AddCPEForSoftware(software Software, cpe string) error
AllCPEs() ([]string, error)
InsertCVEForCPE(cve string, cpes []string) error
///////////////////////////////////////////////////////////////////////////////
// ActivitiesStore
NewActivity(user *User, activityType string, details *map[string]interface{}) error
ListActivities(opt ListOptions) ([]*Activity, error)
///////////////////////////////////////////////////////////////////////////////
// StatisticsStore
ShouldSendStatistics(frequency time.Duration) (StatisticsPayload, bool, error)
RecordStatisticsSent() error
///////////////////////////////////////////////////////////////////////////////
// GlobalPoliciesStore interface {
NewGlobalPolicy(queryID uint) (*Policy, error)
Policy(id uint) (*Policy, error)
RecordPolicyQueryExecutions(host *Host, results map[uint]*bool, updated time.Time) error
ListGlobalPolicies() ([]*Policy, error)
DeleteGlobalPolicies(ids []uint) ([]uint, error)
PolicyQueriesForHost(host *Host) (map[string]string, error)
Name() string
Drop() error
@@ -27,8 +349,7 @@ type Datastore interface {
MigrateTables() error
// MigrateData populates built-in data
MigrateData() error
// MigrationStatus returns nil if migrations are complete, and an error
// if migrations need to be run.
// MigrationStatus returns nil if migrations are complete, and an error if migrations need to be run.
MigrationStatus() (MigrationStatus, error)
Begin() (Transaction, error)
}
@@ -55,15 +376,13 @@ func IsNotFound(err error) bool {
return e.IsNotFound()
}
// AlreadyExists is returned when creating a datastore resource that already
// exists.
// AlreadyExistsError is returned when creating a datastore resource that already exists.
type AlreadyExistsError interface {
error
IsExists() bool
}
// ForeignKeyError is returned when the operation fails due to foreign key
// constraints.
// ForeignKeyError is returned when the operation fails due to foreign key constraints.
type ForeignKeyError interface {
error
IsForeignKey() bool
-12
View File
@@ -4,18 +4,6 @@ import (
"time"
)
// PasswordResetStore manages password resets in the Datastore
type PasswordResetStore interface {
NewPasswordResetRequest(req *PasswordResetRequest) (*PasswordResetRequest, error)
SavePasswordResetRequest(req *PasswordResetRequest) error
DeletePasswordResetRequest(req *PasswordResetRequest) error
DeletePasswordResetRequestsForUser(userID uint) error
FindPassswordResetByID(id uint) (*PasswordResetRequest, error)
FindPassswordResetsByUserID(id uint) ([]*PasswordResetRequest, error)
FindPassswordResetByToken(token string) (*PasswordResetRequest, error)
FindPassswordResetByTokenAndUserID(token string, id uint) (*PasswordResetRequest, error)
}
// Mailer is an email campaign
// Types which implement the Campaign interface
// can be marshalled into an email body
-23
View File
@@ -1,28 +1,5 @@
package fleet
import (
"context"
"time"
)
type GlobalPoliciesService interface {
NewGlobalPolicy(ctx context.Context, queryID uint) (*Policy, error)
ListGlobalPolicies(ctx context.Context) ([]*Policy, error)
DeleteGlobalPolicies(ctx context.Context, ids []uint) ([]uint, error)
GetPolicyByIDQueries(ctx context.Context, policyID uint) (*Policy, error)
}
type GlobalPoliciesStore interface {
NewGlobalPolicy(queryID uint) (*Policy, error)
Policy(id uint) (*Policy, error)
RecordPolicyQueryExecutions(host *Host, results map[uint]*bool, updated time.Time) error
ListGlobalPolicies() ([]*Policy, error)
DeleteGlobalPolicies(ids []uint) ([]uint, error)
PolicyQueriesForHost(host *Host) (map[string]string, error)
}
type Policy struct {
ID uint `json:"id"`
QueryID uint `json:"query_id" db:"query_id"`
-11
View File
@@ -1,16 +1,5 @@
package fleet
import (
"context"
)
type GlobalScheduleService interface {
GlobalScheduleQuery(ctx context.Context, sq *ScheduledQuery) (*ScheduledQuery, error)
GetGlobalScheduledQueries(ctx context.Context, opts ListOptions) ([]*ScheduledQuery, error)
ModifyGlobalScheduledQueries(ctx context.Context, id uint, q ScheduledQueryPayload) (*ScheduledQuery, error)
DeleteGlobalScheduledQueries(ctx context.Context, id uint) error
}
type GlobalSchedulePayload struct {
GlobalSchedule []*ScheduledQuery `json:"global_schedule"`
}
-69
View File
@@ -1,7 +1,6 @@
package fleet
import (
"context"
"encoding/json"
"time"
)
@@ -33,74 +32,6 @@ const (
OnlineIntervalBuffer = 30
)
type HostStore interface {
// NewHost is deprecated and will be removed. Hosts should always be
// enrolled via EnrollHost.
NewHost(host *Host) (*Host, error)
SaveHost(host *Host) error
DeleteHost(hid uint) error
Host(id uint) (*Host, error)
// EnrollHost will enroll a new host with the given identifier, setting the
// node key, and team. Implementations of this method should respect the
// provided host enrollment cooldown, by returning an error if the host has
// enrolled within the cooldown period.
EnrollHost(osqueryHostId, nodeKey string, teamID *uint, cooldown time.Duration) (*Host, error)
ListHosts(filter TeamFilter, opt HostListOptions) ([]*Host, error)
// AuthenticateHost authenticates and returns host metadata by node key.
// This method should not return the host "additional" information as this
// is not typically necessary for the operations performed by the osquery
// endpoints.
AuthenticateHost(nodeKey string) (*Host, error)
MarkHostSeen(host *Host, t time.Time) error
MarkHostsSeen(hostIDs []uint, t time.Time) error
SearchHosts(filter TeamFilter, query string, omit ...uint) ([]*Host, error)
// CleanupIncomingHosts deletes hosts that have enrolled but never
// updated their status details. This clears dead "incoming hosts" that
// never complete their registration.
//
// A host is considered incoming if both the hostname and
// osquery_version fields are empty. This means that multiple different
// osquery queries failed to populate details.
CleanupIncomingHosts(now time.Time) error
// GenerateHostStatusStatistics retrieves the count of online, offline,
// MIA and new hosts.
GenerateHostStatusStatistics(filter TeamFilter, now time.Time) (online, offline, mia, new uint, err error)
// HostIDsByName Retrieve the IDs associated with the given hostnames
HostIDsByName(filter TeamFilter, hostnames []string) ([]uint, error)
// HostByIdentifier returns one host matching the provided identifier.
// Possible matches can be on osquery_host_identifier, node_key, UUID, or
// hostname.
HostByIdentifier(identifier string) (*Host, error)
// AddHostsToTeam adds hosts to an existing team, clearing their team
// settings if teamID is nil.
AddHostsToTeam(teamID *uint, hostIDs []uint) error
// SaveHostAdditional saves the information generated by the
// additional_queries.
SaveHostAdditional(host *Host) error
}
type HostService interface {
ListHosts(ctx context.Context, opt HostListOptions) (hosts []*Host, err error)
GetHost(ctx context.Context, id uint) (host *HostDetail, err error)
GetHostSummary(ctx context.Context) (summary *HostSummary, err error)
DeleteHost(ctx context.Context, id uint) (err error)
// HostByIdentifier returns one host matching the provided identifier.
// Possible matches can be on osquery_host_identifier, node_key, UUID, or
// hostname.
HostByIdentifier(ctx context.Context, identifier string) (*HostDetail, error)
// RefetchHost requests a refetch of host details for the provided host.
RefetchHost(ctx context.Context, id uint) (err error)
FlushSeenHosts(ctx context.Context) error
// AddHostsToTeam adds hosts to an existing team, clearing their team
// settings if teamID is nil.
AddHostsToTeam(ctx context.Context, teamID *uint, hostIDs []uint) error
// AddHostsToTeamByFilter adds hosts to an existing team, clearing their
// team settings if teamID is nil. Hosts are selected by the label and
// HostListOptions provided.
AddHostsToTeamByFilter(ctx context.Context, teamID *uint, opt HostListOptions, lid *uint) error
}
type HostListOptions struct {
ListOptions
-238
View File
@@ -1,238 +0,0 @@
package fleet
import (
"bytes"
"context"
"errors"
"fmt"
"strconv"
"strings"
)
type ImportConfigService interface {
// ImportConfig create packs, queries, options etc based on imported
// osquery configuration.
ImportConfig(ctx context.Context, cfg *ImportConfig) (*ImportConfigResponse, error)
}
// ImportSection is used to categorize information associated with the import
// of a particular section of an imported osquery configuration file.
type ImportSection string
const (
OptionsSection ImportSection = "options"
PacksSection = "packs"
QueriesSection = "queries"
DecoratorsSection = "decorators"
FilePathsSection = "file_paths"
YARASigSection = "yara_signature_group"
YARAFileSection = "yara_file_group"
)
// WarningType is used to group associated warnings for options, packs etc
// when importing on osquery configuration file.
type WarningType string
const (
PackDuplicate WarningType = "duplicate_pack"
DifferentQuerySameName = "different_query_same_name"
OptionAlreadySet = "option_already_set"
OptionReadonly = "option_readonly"
OptionUnknown = "option_unknown"
QueryDuplicate = "duplicate_query"
FIMDuplicate = "duplicate_fim"
YARADuplicate = "duplicate_yara"
Unsupported = "unsupported"
)
// ImportStatus contains information pertaining to the import of a section
// of an osquery configuration file.
type ImportStatus struct {
// Title human readable name of the section of the import file that this
// status pertains to.
Title string `json:"title"`
// ImportCount count of items successfully imported.
ImportCount int `json:"import_count"`
// SkipCount count of items that are skipped. The reasons for the omissions
// can be found in Warnings.
SkipCount int `json:"skip_count"`
// Warnings groups categories of warnings with one or more detail messages.
Warnings map[WarningType][]string `json:"warnings"`
// Messages contains an entry for each import attempt.
Messages []string `json:"messages"`
}
// Warning is used to add a warning message to ImportStatus.
func (is *ImportStatus) Warning(warnType WarningType, fmtMsg string, fmtArgs ...interface{}) {
is.Warnings[warnType] = append(is.Warnings[warnType], fmt.Sprintf(fmtMsg, fmtArgs...))
}
// Message is used to add a general message to ImportStatus, usually indicating
// what was changed in a successful import.
func (is *ImportStatus) Message(fmtMsg string, args ...interface{}) {
is.Messages = append(is.Messages, fmt.Sprintf(fmtMsg, args...))
}
// ImportConfigResponse contains information about the import of an osquery
// configuration file.
type ImportConfigResponse struct {
ImportStatusBySection map[ImportSection]*ImportStatus `json:"import_status"`
}
// Status returns a structure that contains information about the import
// of a particular section of an osquery configuration file.
func (ic *ImportConfigResponse) Status(section ImportSection) (status *ImportStatus) {
var ok bool
if status, ok = ic.ImportStatusBySection[section]; !ok {
status = new(ImportStatus)
status.Title = strings.Title(string(section))
status.Warnings = make(map[WarningType][]string)
ic.ImportStatusBySection[section] = status
}
return status
}
const (
GlobPacks = "*"
// ImportPackName is a custom pack name used for a pack we create to
// hold imported scheduled queries.
ImportPackName = "imported"
)
// QueryDetails represents the query objects used in the packs and the
// schedule section of an osquery configuration.
type QueryDetails struct {
Query string `json:"query"`
Interval OsQueryConfigInt `json:"interval"`
// Optional fields
Removed *bool `json:"removed"`
Platform *string `json:"platform"`
Version *string `json:"version"`
Shard *OsQueryConfigInt `json:"shard"`
Snapshot *bool `json:"snapshot"`
}
// PackDetails represents the "packs" section of an osquery configuration
// file.
type PackDetails struct {
Queries QueryNameToQueryDetailsMap `json:"queries"`
Shard *OsQueryConfigInt `json:"shard"`
Version *string `json:"version"`
Platform string `json:"platform"`
Discovery []string `json:"discovery"`
}
// YARAConfig yara configuration maps keys to lists of files.
// See https://osquery.readthedocs.io/en/stable/deployment/yara/
type YARAConfig struct {
Signatures map[string][]string `json:"signatures"`
FilePaths map[string][]string `json:"file_paths"`
}
// Decorator section of osquery config each section contains rows of decorator
// queries.
type DecoratorConfig struct {
Load []string `json:"load"`
Always []string `json:"always"`
/*
Interval maps a string representation of a numeric interval to a set
of decorator queries.
{
"interval": {
"3600": [
"SELECT total_seconds FROM uptime;"
]
}
}
*/
Interval map[string][]string `json:"interval"`
}
type OptionNameToValueMap map[string]interface{}
type QueryNameToQueryDetailsMap map[string]QueryDetails
type PackNameMap map[string]interface{}
type FIMCategoryToPaths map[string][]string
type PackNameToPackDetails map[string]PackDetails
// ImportConfig is a representation of an Osquery configuration. Osquery
// documentation has further details.
// See https://osquery.readthedocs.io/en/stable/deployment/configuration/
type ImportConfig struct {
// DryRun if true an import will be attempted, and if successful will be completely rolled back
DryRun bool
// Options is a map of option name to a value which can be an int,
// bool, or string.
Options OptionNameToValueMap `json:"options"`
// Schedule is a map of query names to details
Schedule QueryNameToQueryDetailsMap `json:"schedule"`
// Packs is a map of pack names to either PackDetails, or a string
// containing a file path with a pack config. If a string, we expect
// PackDetails to be stored in ExternalPacks.
Packs PackNameMap `json:"packs"`
// FileIntegrityMonitoring file integrity monitoring information.
// See https://osquery.readthedocs.io/en/stable/deployment/file-integrity-monitoring/
FileIntegrityMonitoring FIMCategoryToPaths `json:"file_paths"`
// YARA configuration
YARA *YARAConfig `json:"yara"`
Decorators *DecoratorConfig `json:"decorators"`
// ExternalPacks are packs referenced when an item in the Packs map references
// an external file. The PackName here must match the PackName in the Packs map.
ExternalPacks PackNameToPackDetails `json:"-"`
// GlobPackNames lists pack names that are globbed.
GlobPackNames []string `json:"glob"`
}
func (ic *ImportConfig) fetchGlobPacks(packs *PackNameToPackDetails) error {
for _, packName := range ic.GlobPackNames {
pack, ok := ic.ExternalPacks[packName]
if !ok {
return fmt.Errorf("glob pack '%s' details not found", packName)
}
(*packs)[packName] = pack
}
return nil
}
// CollectPacks consolidates packs, globbed packs and external packs.
func (ic *ImportConfig) CollectPacks() (PackNameToPackDetails, error) {
result := make(PackNameToPackDetails)
for packName, packContent := range ic.Packs {
// special case handling for Globbed packs
if packName == GlobPacks {
if err := ic.fetchGlobPacks(&result); err != nil {
return nil, err
}
continue
}
// content can either be a file path, in which case we expect to find
// pack in ExternalPacks, or pack details
switch content := packContent.(type) {
case string:
pack, ok := ic.ExternalPacks[packName]
if !ok {
return nil, fmt.Errorf("external pack '%s' details not found", packName)
}
result[packName] = pack
case PackDetails:
result[packName] = content
default:
return nil, errors.New("unexpected pack content")
}
}
return result, nil
}
// OsQueryConfigInt is provided becase integers in the osquery config file may
// be represented as strings in the json. If we know a particular field is
// supposed to be an Integer, we convert from string to int if we can.
type OsQueryConfigInt uint
func (c *OsQueryConfigInt) UnmarshalJSON(b []byte) error {
stripped := bytes.Trim(b, `"`)
v, err := strconv.ParseUint(string(stripped), 10, 64)
if err != nil {
return err
}
*c = OsQueryConfigInt(v)
return nil
}
-180
View File
@@ -1,180 +0,0 @@
package fleet
import (
"bytes"
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConfigUnmarshalling(t *testing.T) {
contents := `
{
"options":null,
"schedule":null,
"packs":{
"internal_stuff":{
"discovery":["select pid from processes where name = 'ldap';"],
"platform":"linux",
"queries":{
"active_directory":{
"description":"Check each user's active directory cached settings.",
"interval":"1200",
"query":"select * from ad_config;"
}
},
"version":"1.5.2"
},
"testing":{
"queries":{
"suid_bins":{
"interval":"3600",
"query":"select * from suid_bins;"
}
},
"shard":"10"
}
},
"file_paths":null,
"yara":null,
"prometheus_targets":null,
"decorators":null
}
`
conf := ImportConfig{
Packs: make(PackNameMap),
ExternalPacks: make(PackNameToPackDetails),
}
err := json.Unmarshal([]byte(contents), &conf)
assert.Nil(t, err)
require.NotNil(t, conf.Packs["testing"])
// platform is not defined in the testing pack, so, per osquery docs
// we default to 'all' platforms
details, ok := conf.Packs["testing"].(PackDetails)
require.True(t, ok)
assert.Equal(t, "", details.Platform)
}
func TestIntervalUnmarshal(t *testing.T) {
scenarios := []struct {
name string
testVal interface{}
errExpected bool
expectedResult OsQueryConfigInt
}{
{"string to uint", "100", false, 100},
{"float to uint", float64(123), false, 123},
{"nil to zero value int", nil, false, 0},
{"invalid string", "hi there", true, 0},
}
for _, scenario := range scenarios {
t.Run(fmt.Sprintf(": %s", scenario.name), func(tt *testing.T) {
v, e := unmarshalInteger(scenario.testVal)
if scenario.errExpected {
assert.NotNil(t, e)
} else {
require.Nil(t, e)
assert.Equal(t, scenario.expectedResult, v)
}
})
}
}
type importIntTest struct {
Val OsQueryConfigInt `json:"val"`
}
func TestConfigImportInt(t *testing.T) {
buff := bytes.NewBufferString(`{"val":"23"}`)
var ts importIntTest
err := json.NewDecoder(buff).Decode(&ts)
assert.Nil(t, err)
assert.Equal(t, 23, int(ts.Val))
buff = bytes.NewBufferString(`{"val":456}`)
err = json.NewDecoder(buff).Decode(&ts)
assert.Nil(t, err)
assert.Equal(t, 456, int(ts.Val))
buff = bytes.NewBufferString(`{"val":"hi 456"}`)
err = json.NewDecoder(buff).Decode(&ts)
assert.NotNil(t, err)
}
func TestPackNameMapUnmarshal(t *testing.T) {
s2p := func(s string) *string { return &s }
u2p := func(ui uint) *OsQueryConfigInt { ci := OsQueryConfigInt(ui); return &ci }
pnm := PackNameMap{
"path": "/this/is/a/path",
"details": PackDetails{
Queries: QueryNameToQueryDetailsMap{
"q1": QueryDetails{
Query: "select from foo",
Interval: 100,
Removed: new(bool),
Platform: s2p("linux"),
Shard: new(OsQueryConfigInt),
Snapshot: new(bool),
},
},
Discovery: []string{
"select from something",
},
},
}
b, _ := json.Marshal(pnm)
actual := make(PackNameMap)
err := json.Unmarshal(b, &actual)
require.Nil(t, err)
assert.Len(t, actual, 2)
pnm = PackNameMap{
"path": "/this/is/a/path",
"details": PackDetails{
Queries: QueryNameToQueryDetailsMap{
"q1": QueryDetails{
Query: "select from foo",
Interval: 100,
Removed: new(bool),
Platform: s2p("linux"),
Shard: new(OsQueryConfigInt),
Snapshot: new(bool),
},
},
Shard: u2p(10),
Version: s2p("1.0"),
Platform: "linux",
Discovery: []string{
"select from something",
},
},
"details2": PackDetails{
Queries: QueryNameToQueryDetailsMap{
"q1": QueryDetails{
Query: "select from bar",
Interval: 100,
Removed: new(bool),
Platform: s2p("linux"),
Shard: new(OsQueryConfigInt),
Snapshot: new(bool),
},
},
Shard: u2p(10),
Version: s2p("1.0"),
Platform: "linux",
},
}
b, _ = json.Marshal(pnm)
actual = make(PackNameMap)
err = json.Unmarshal(b, &actual)
require.Nil(t, err)
assert.Len(t, actual, 3)
}
-200
View File
@@ -1,200 +0,0 @@
package fleet
import (
"encoding/json"
"strconv"
"github.com/pkg/errors"
"github.com/spf13/cast"
)
var wrongTypeError = errors.New("argument missing or unexpected type")
// UnmarshalJSON custom unmarshaling for PackNameMap will determine whether
// the pack section of an osquery config file refers to a file path, or
// pack details. Pack details are unmarshalled into into PackDetails structure
// as opposed to nested map[string]interface{}
func (pnm PackNameMap) UnmarshalJSON(b []byte) error {
var temp map[string]interface{}
err := json.Unmarshal(b, &temp)
if err != nil {
return err
}
for key, val := range temp {
switch t := val.(type) {
case string:
pnm[key] = t
case map[string]interface{}:
val, err := unmarshalPackDetails(t)
if err != nil {
return err
}
pnm[key] = val
default:
return errors.Errorf("can't unmarshal %s %v", key, val)
}
}
return nil
}
func strptr(v interface{}) (*string, error) {
if v == nil {
return nil, nil
}
s, ok := v.(string)
if !ok {
return nil, wrongTypeError
}
return &s, nil
}
func boolptr(v interface{}) (*bool, error) {
if v == nil {
return nil, nil
}
b, ok := v.(bool)
if !ok {
return nil, wrongTypeError
}
return &b, nil
}
// We expect a float64 here because of the way JSON represents numbers
func uintptr(v interface{}) (*OsQueryConfigInt, error) {
if v == nil {
return nil, nil
}
i, err := unmarshalInteger(v)
if err != nil {
return nil, err
}
return &i, nil
}
func unmarshalPackDetails(v map[string]interface{}) (PackDetails, error) {
var result PackDetails
queries, err := unmarshalQueryDetails(v["queries"])
if err != nil {
return result, err
}
discovery, err := unmarshalDiscovery(v["discovery"])
if err != nil {
return result, err
}
platform := cast.ToString(v["platform"])
shard, err := uintptr(v["shard"])
if err != nil {
return result, err
}
version, err := strptr(v["version"])
if err != nil {
return result, err
}
result = PackDetails{
Queries: queries,
Shard: shard,
Version: version,
Platform: platform,
Discovery: discovery,
}
return result, nil
}
func unmarshalDiscovery(val interface{}) ([]string, error) {
var result []string
if val == nil {
return result, nil
}
v, ok := val.([]interface{})
if !ok {
return result, wrongTypeError
}
for _, val := range v {
query, err := cast.ToStringE(val)
if err != nil {
return result, err
}
result = append(result, query)
}
return result, nil
}
func unmarshalQueryDetails(v interface{}) (QueryNameToQueryDetailsMap, error) {
var err error
result := make(QueryNameToQueryDetailsMap)
if v == nil {
return result, nil
}
for qn, details := range v.(map[string]interface{}) {
result[qn], err = unmarshalQueryDetail(details)
if err != nil {
return nil, err
}
}
return result, nil
}
func unmarshalQueryDetail(val interface{}) (QueryDetails, error) {
var result QueryDetails
v, ok := val.(map[string]interface{})
if !ok {
return result, errors.New("argument was missing or the wrong type")
}
interval, err := unmarshalInteger(v["interval"])
if err != nil {
return result, err
}
query, err := cast.ToStringE(v["query"])
if err != nil {
return result, err
}
removed, err := boolptr(v["removed"])
if err != nil {
return result, err
}
platform, err := strptr(v["platform"])
if err != nil {
return result, err
}
version, err := strptr(v["version"])
if err != nil {
return result, err
}
shard, err := uintptr(v["shard"])
if err != nil {
return result, err
}
snapshot, err := boolptr(v["snapshot"])
if err != nil {
return result, nil
}
result = QueryDetails{
Query: query,
Interval: interval,
Removed: removed,
Platform: platform,
Version: version,
Shard: shard,
Snapshot: snapshot,
}
return result, nil
}
// It is valid for the interval can be a string that is convertable to an int,
// or an float64. The float64 is how all numbers in JSON are represented, so
// we need to convert to uint
func unmarshalInteger(val interface{}) (OsQueryConfigInt, error) {
// if interval is nil return zero value
if val == nil {
return OsQueryConfigInt(0), nil
}
switch v := val.(type) {
case string:
i, err := strconv.ParseUint(v, 10, 64)
return OsQueryConfigInt(i), err
case float64:
return OsQueryConfigInt(v), nil
default:
return OsQueryConfigInt(0), wrongTypeError
}
}
-41
View File
@@ -1,50 +1,9 @@
package fleet
import (
"context"
"gopkg.in/guregu/null.v3"
)
// InviteStore contains the methods for
// managing user invites in a datastore.
type InviteStore interface {
// NewInvite creates and stores a new invitation in a DB.
NewInvite(i *Invite) (*Invite, error)
// Invites lists all invites in the datastore.
ListInvites(opt ListOptions) ([]*Invite, error)
// Invite retrieves an invite by it's ID.
Invite(id uint) (*Invite, error)
// InviteByEmail retrieves an invite for a specific email address.
InviteByEmail(email string) (*Invite, error)
// InviteByToken retrieves and invite using the token string.
InviteByToken(token string) (*Invite, error)
// DeleteInvite deletes an invitation.
DeleteInvite(id uint) error
}
// InviteService contains methods for a service which deals with
// user invites.
type InviteService interface {
// InviteNewUser creates an invite for a new user to join Fleet.
InviteNewUser(ctx context.Context, payload InvitePayload) (invite *Invite, err error)
// DeleteInvite removes an invite.
DeleteInvite(ctx context.Context, id uint) (err error)
// Invites returns a list of all invites.
ListInvites(ctx context.Context, opt ListOptions) (invites []*Invite, err error)
// VerifyInvite verifies that an invite exists and that it matches the
// invite token.
VerifyInvite(ctx context.Context, token string) (invite *Invite, err error)
}
// InvitePayload contains fields required to create a new user invite.
type InvitePayload struct {
Email *string
-74
View File
@@ -1,85 +1,11 @@
package fleet
import (
"context"
"time"
"github.com/pkg/errors"
)
type LabelStore interface {
// ApplyLabelSpecs applies a list of LabelSpecs to the datastore,
// creating and updating labels as necessary.
ApplyLabelSpecs(specs []*LabelSpec) error
// GetLabelSpecs returns all of the stored LabelSpecs.
GetLabelSpecs() ([]*LabelSpec, error)
// GetLabelSpec returns the spec for the named label.
GetLabelSpec(name string) (*LabelSpec, error)
// Label methods
NewLabel(Label *Label, opts ...OptionalArg) (*Label, error)
SaveLabel(label *Label) (*Label, error)
DeleteLabel(name string) error
Label(lid uint) (*Label, error)
ListLabels(filter TeamFilter, opt ListOptions) ([]*Label, error)
// LabelQueriesForHost returns the label queries that should be executed
// for the given host. The cutoff is the minimum timestamp a query
// execution should have to be considered "fresh". Executions that are
// not fresh will be repeated. Results are returned in a map of label
// id -> query
LabelQueriesForHost(host *Host, cutoff time.Time) (map[string]string, error)
// RecordLabelQueryExecutions saves the results of label queries. The
// results map is a map of label id -> whether or not the label
// matches. The time parameter is the timestamp to save with the query
// execution.
RecordLabelQueryExecutions(host *Host, results map[uint]*bool, t time.Time) error
// LabelsForHost returns the labels that the given host is in.
ListLabelsForHost(hid uint) ([]*Label, error)
// ListHostsInLabel returns a slice of hosts in the label with the
// given ID.
ListHostsInLabel(filter TeamFilter, lid uint, opt HostListOptions) ([]*Host, error)
// ListUniqueHostsInLabels returns a slice of all of the hosts in the
// given label IDs. A host will only appear once in the results even if
// it is in multiple of the provided labels.
ListUniqueHostsInLabels(filter TeamFilter, labels []uint) ([]*Host, error)
SearchLabels(filter TeamFilter, query string, omit ...uint) ([]*Label, error)
// LabelIDsByName Retrieve the IDs associated with the given labels
LabelIDsByName(labels []string) ([]uint, error)
}
type LabelService interface {
// ApplyLabelSpecs applies a list of LabelSpecs to the datastore,
// creating and updating labels as necessary.
ApplyLabelSpecs(ctx context.Context, specs []*LabelSpec) error
// GetLabelSpecs returns all of the stored LabelSpecs.
GetLabelSpecs(ctx context.Context) ([]*LabelSpec, error)
// GetLabelSpec gets the spec for the label with the given name.
GetLabelSpec(ctx context.Context, name string) (*LabelSpec, error)
NewLabel(ctx context.Context, p LabelPayload) (label *Label, err error)
ModifyLabel(ctx context.Context, id uint, payload ModifyLabelPayload) (*Label, error)
ListLabels(ctx context.Context, opt ListOptions) (labels []*Label, err error)
GetLabel(ctx context.Context, id uint) (label *Label, err error)
DeleteLabel(ctx context.Context, name string) (err error)
// DeleteLabelByID is for backwards compatibility with the UI
DeleteLabelByID(ctx context.Context, id uint) (err error)
// ListHostsInLabel returns a slice of hosts in the label with the
// given ID.
ListHostsInLabel(ctx context.Context, lid uint, opt HostListOptions) ([]*Host, error)
// LabelsForHost returns the labels that the given host is in.
ListLabelsForHost(ctx context.Context, hid uint) ([]*Label, error)
}
// ModifyLabelPayload is used to change editable fields for a Label
type ModifyLabelPayload struct {
Name *string `json:"name"`
-23
View File
@@ -1,28 +1,5 @@
package fleet
import (
"context"
"encoding/json"
)
type OsqueryService interface {
EnrollAgent(ctx context.Context, enrollSecret, hostIdentifier string, hostDetails map[string](map[string]string)) (nodeKey string, err error)
AuthenticateHost(ctx context.Context, nodeKey string) (host *Host, err error)
GetClientConfig(ctx context.Context) (config map[string]interface{}, err error)
// GetDistributedQueries retrieves the distributed queries to run for
// the host in the provided context. These may be detail queries, label
// queries, or user-initiated distributed queries. A map from query
// name to query is returned. To enable the osquery "accelerated
// checkins" feature, a positive integer (number of seconds to activate
// for) should be returned. Returning 0 for this will not activate the
// feature.
GetDistributedQueries(ctx context.Context) (queries map[string]string, accelerate uint, err error)
SubmitDistributedQueryResults(ctx context.Context, results OsqueryDistributedQueryResults, statuses map[string]OsqueryStatus, messages map[string]string) (err error)
SubmitStatusLogs(ctx context.Context, logs []json.RawMessage) (err error)
SubmitResultLogs(ctx context.Context, logs []json.RawMessage) (err error)
//CarveBegin(ctx context.Context)
}
// OsqueryDistributedQueryResults represents the format of the results of an
// osquery distributed query.
type OsqueryDistributedQueryResults map[string][]map[string]string
-75
View File
@@ -1,80 +1,5 @@
package fleet
import (
"context"
)
// PackStore is the datastore interface for managing query packs.
type PackStore interface {
// ApplyPackSpecs applies a list of PackSpecs to the datastore,
// creating and updating packs as necessary.
ApplyPackSpecs(specs []*PackSpec) error
// GetPackSpecs returns all of the stored PackSpecs.
GetPackSpecs() ([]*PackSpec, error)
// GetPackSpec returns the spec for the named pack.
GetPackSpec(name string) (*PackSpec, error)
// NewPack creates a new pack in the datastore.
NewPack(pack *Pack, opts ...OptionalArg) (*Pack, error)
// SavePack updates an existing pack in the datastore.
SavePack(pack *Pack) error
// DeletePack deletes a pack record from the datastore.
DeletePack(name string) error
// Pack retrieves a pack from the datastore by ID.
Pack(pid uint) (*Pack, error)
// ListPacks lists all packs in the datastore.
ListPacks(opt PackListOptions) ([]*Pack, error)
// PackByName fetches pack if it exists, if the pack
// exists the bool return value is true
PackByName(name string, opts ...OptionalArg) (*Pack, bool, error)
// ListPacksForHost lists the packs that a host should execute.
ListPacksForHost(hid uint) (packs []*Pack, err error)
// EnsureGlobalPack gets or inserts a pack with type global
EnsureGlobalPack() (*Pack, error)
// EnsureTeamPack gets or inserts a pack with type global
EnsureTeamPack(teamID uint) (*Pack, error)
}
// PackService is the service interface for managing query packs.
type PackService interface {
// ApplyPackSpecs applies a list of PackSpecs to the datastore,
// creating and updating packs as necessary.
ApplyPackSpecs(ctx context.Context, specs []*PackSpec) ([]*PackSpec, error)
// GetPackSpecs returns all of the stored PackSpecs.
GetPackSpecs(ctx context.Context) ([]*PackSpec, error)
// GetPackSpec gets the spec for the pack with the given name.
GetPackSpec(ctx context.Context, name string) (*PackSpec, error)
// NewPack creates a new pack in the datastore.
NewPack(ctx context.Context, p PackPayload) (pack *Pack, err error)
// ModifyPack modifies an existing pack in the datastore.
ModifyPack(ctx context.Context, id uint, p PackPayload) (pack *Pack, err error)
// ListPacks lists all packs in the application.
ListPacks(ctx context.Context, opt PackListOptions) (packs []*Pack, err error)
// GetPack retrieves a pack by ID.
GetPack(ctx context.Context, id uint) (pack *Pack, err error)
// DeletePack deletes a pack record from the datastore.
DeletePack(ctx context.Context, name string) (err error)
// DeletePackByID is for backwards compatibility with the UI
DeletePackByID(ctx context.Context, id uint) (err error)
// ListPacksForHost lists the packs that a host should execute.
ListPacksForHost(ctx context.Context, hid uint) (packs []*Pack, err error)
}
type PackListOptions struct {
ListOptions
-51
View File
@@ -1,7 +1,6 @@
package fleet
import (
"context"
"fmt"
"regexp"
"strings"
@@ -10,56 +9,6 @@ import (
"github.com/pkg/errors"
)
type QueryStore interface {
// ApplyQueries applies a list of queries (likely from a yaml file) to
// the datastore. Existing queries are updated, and new queries are
// created.
ApplyQueries(authorID uint, queries []*Query) error
// NewQuery creates a new query object in thie datastore. The returned
// query should have the ID updated.
NewQuery(query *Query, opts ...OptionalArg) (*Query, error)
// SaveQuery saves changes to an existing query object.
SaveQuery(query *Query) error
// DeleteQuery deletes an existing query object.
DeleteQuery(name string) error
// DeleteQueries deletes the existing query objects with the provided IDs.
// The number of deleted queries is returned along with any error.
DeleteQueries(ids []uint) (uint, error)
// Query returns the query associated with the provided ID. Associated
// packs should also be loaded.
Query(id uint) (*Query, error)
// ListQueries returns a list of queries with the provided sorting and
// paging options. Associated packs should also be loaded.
ListQueries(opt ListOptions) ([]*Query, error)
// QueryByName looks up a query by name.
QueryByName(name string, opts ...OptionalArg) (*Query, error)
}
type QueryService interface {
// ApplyQuerySpecs applies a list of queries (creating or updating
// them as necessary)
ApplyQuerySpecs(ctx context.Context, specs []*QuerySpec) error
// GetQuerySpecs gets the YAML file representing all the stored queries.
GetQuerySpecs(ctx context.Context) ([]*QuerySpec, error)
// GetQuerySpec gets the spec for the query with the given name.
GetQuerySpec(ctx context.Context, name string) (*QuerySpec, error)
// ListQueries returns a list of saved queries. Note only saved queries
// should be returned (those that are created for distributed queries
// but not saved should not be returned).
ListQueries(ctx context.Context, opt ListOptions) ([]*Query, error)
GetQuery(ctx context.Context, id uint) (*Query, error)
NewQuery(ctx context.Context, p QueryPayload) (*Query, error)
ModifyQuery(ctx context.Context, id uint, p QueryPayload) (*Query, error)
DeleteQuery(ctx context.Context, name string) error
// For backwards compatibility with UI
DeleteQueryByID(ctx context.Context, id uint) error
// DeleteQueries deletes the existing query objects with the provided IDs.
// The number of deleted queries is returned along with any error.
DeleteQueries(ctx context.Context, ids []uint) (uint, error)
}
type QueryPayload struct {
Name *string
Description *string
-18
View File
@@ -1,29 +1,11 @@
package fleet
import (
"context"
"time"
"gopkg.in/guregu/null.v3"
)
type ScheduledQueryStore interface {
ListScheduledQueriesInPack(id uint, opts ListOptions) ([]*ScheduledQuery, error)
NewScheduledQuery(sq *ScheduledQuery, opts ...OptionalArg) (*ScheduledQuery, error)
SaveScheduledQuery(sq *ScheduledQuery) (*ScheduledQuery, error)
DeleteScheduledQuery(id uint) error
ScheduledQuery(id uint) (*ScheduledQuery, error)
CleanupOrphanScheduledQueryStats() error
}
type ScheduledQueryService interface {
GetScheduledQueriesInPack(ctx context.Context, id uint, opts ListOptions) (queries []*ScheduledQuery, err error)
GetScheduledQuery(ctx context.Context, id uint) (query *ScheduledQuery, err error)
ScheduleQuery(ctx context.Context, sq *ScheduledQuery) (query *ScheduledQuery, err error)
DeleteScheduledQuery(ctx context.Context, id uint) (err error)
ModifyScheduledQuery(ctx context.Context, id uint, p ScheduledQueryPayload) (query *ScheduledQuery, err error)
}
type ScheduledQuery struct {
UpdateCreateTimestamps
ID uint `json:"id"`
+391 -22
View File
@@ -1,27 +1,396 @@
package fleet
// service a interface stub
import (
"context"
"encoding/json"
"github.com/fleetdm/fleet/v4/server/websocket"
"github.com/kolide/kit/version"
)
type OsqueryService interface {
EnrollAgent(
ctx context.Context, enrollSecret, hostIdentifier string, hostDetails map[string](map[string]string),
) (nodeKey string, err error)
AuthenticateHost(ctx context.Context, nodeKey string) (host *Host, err error)
GetClientConfig(ctx context.Context) (config map[string]interface{}, err error)
// GetDistributedQueries retrieves the distributed queries to run for the host in the provided context. These may be
// detail queries, label queries, or user-initiated distributed queries. A map from query name to query is returned.
// To enable the osquery "accelerated checkins" feature, a positive integer (number of seconds to activate for)
// should be returned. Returning 0 for this will not activate the feature.
GetDistributedQueries(ctx context.Context) (queries map[string]string, accelerate uint, err error)
SubmitDistributedQueryResults(
ctx context.Context,
results OsqueryDistributedQueryResults,
statuses map[string]OsqueryStatus,
messages map[string]string,
) (err error)
SubmitStatusLogs(ctx context.Context, logs []json.RawMessage) (err error)
SubmitResultLogs(ctx context.Context, logs []json.RawMessage) (err error)
}
type Service interface {
UserService
SessionService
PackService
LabelService
QueryService
CampaignService
OsqueryService
AgentOptionsService
HostService
AppConfigService
InviteService
TargetService
ScheduledQueryService
StatusService
CarveService
TeamService
ActivitiesService
UserRolesService
GlobalScheduleService
TranslatorService
TeamScheduleService
GlobalPoliciesService
///////////////////////////////////////////////////////////////////////////////
// UserService contains methods for managing a Fleet User.
// CreateUserFromInvite creates a new User from a request payload when there is already an existing invitation.
CreateUserFromInvite(ctx context.Context, p UserPayload) (user *User, err error)
// CreateUser allows an admin to create a new user without first creating and validating invite tokens.
CreateUser(ctx context.Context, p UserPayload) (user *User, err error)
// CreateInitialUser creates the first user, skipping authorization checks. If a user already exists this method
// should fail.
CreateInitialUser(ctx context.Context, p UserPayload) (user *User, err error)
// User returns a valid User given a User ID.
User(ctx context.Context, id uint) (user *User, err error)
// UserUnauthorized returns a valid User given a User ID, *skipping authorization checks*
// This method should only be used in middleware where there is not yet a viewer context and we need to load up a
// user to create that context.
UserUnauthorized(ctx context.Context, id uint) (user *User, err error)
// AuthenticatedUser returns the current user from the viewer context.
AuthenticatedUser(ctx context.Context) (user *User, err error)
// ListUsers returns all users.
ListUsers(ctx context.Context, opt UserListOptions) (users []*User, err error)
// ChangePassword validates the existing password, and sets the new password. User is retrieved from the viewer
// context.
ChangePassword(ctx context.Context, oldPass, newPass string) error
// RequestPasswordReset generates a password reset request for the user specified by email. The request results
// in a token emailed to the user.
RequestPasswordReset(ctx context.Context, email string) (err error)
// RequirePasswordReset requires a password reset for the user specified by ID (if require is true). It deletes
// all the user's sessions, and requires that their password be reset upon the next login. Setting require to
// false will take a user out of this state. The updated user is returned.
RequirePasswordReset(ctx context.Context, uid uint, require bool) (*User, error)
// PerformRequiredPasswordReset resets a password for a user that is in the required reset state. It must be called
// with the logged in viewer context of that user.
PerformRequiredPasswordReset(ctx context.Context, password string) (*User, error)
// ResetPassword validates the provided password reset token and updates the user's password.
ResetPassword(ctx context.Context, token, password string) (err error)
// ModifyUser updates a user's parameters given a UserPayload.
ModifyUser(ctx context.Context, userID uint, p UserPayload) (user *User, err error)
// DeleteUser permanently deletes the user identified by the provided ID.
DeleteUser(ctx context.Context, id uint) error
// ChangeUserEmail is used to confirm new email address and if confirmed,
// write the new email address to user.
ChangeUserEmail(ctx context.Context, token string) (string, error)
///////////////////////////////////////////////////////////////////////////////
// Session
// InitiateSSO is used to initiate an SSO session and returns a URL that can be used in a redirect to the IDP.
// Arguments: redirectURL is the URL of the protected resource that the user was trying to access when they were
// prompted to log in.
InitiateSSO(ctx context.Context, redirectURL string) (string, error)
// CallbackSSO handles the IDP response. The original URL the viewer attempted to access is returned from this
// function, so we can redirect back to the front end and load the page the viewer originally attempted to access
// when prompted for login.
CallbackSSO(ctx context.Context, auth Auth) (*SSOSession, error)
// SSOSettings returns non-sensitive single sign on information used before authentication
SSOSettings(ctx context.Context) (*SessionSSOSettings, error)
Login(ctx context.Context, email, password string) (user *User, sessionKey string, err error)
Logout(ctx context.Context) (err error)
DestroySession(ctx context.Context) (err error)
GetInfoAboutSessionsForUser(ctx context.Context, id uint) (sessions []*Session, err error)
DeleteSessionsForUser(ctx context.Context, id uint) (err error)
GetInfoAboutSession(ctx context.Context, id uint) (session *Session, err error)
GetSessionByKey(ctx context.Context, key string) (session *Session, err error)
DeleteSession(ctx context.Context, id uint) (err error)
///////////////////////////////////////////////////////////////////////////////
// PackService is the service interface for managing query packs.
// ApplyPackSpecs applies a list of PackSpecs to the datastore, creating and updating packs as necessary.
ApplyPackSpecs(ctx context.Context, specs []*PackSpec) ([]*PackSpec, error)
// GetPackSpecs returns all of the stored PackSpecs.
GetPackSpecs(ctx context.Context) ([]*PackSpec, error)
// GetPackSpec gets the spec for the pack with the given name.
GetPackSpec(ctx context.Context, name string) (*PackSpec, error)
// NewPack creates a new pack in the datastore.
NewPack(ctx context.Context, p PackPayload) (pack *Pack, err error)
// ModifyPack modifies an existing pack in the datastore.
ModifyPack(ctx context.Context, id uint, p PackPayload) (pack *Pack, err error)
// ListPacks lists all packs in the application.
ListPacks(ctx context.Context, opt PackListOptions) (packs []*Pack, err error)
// GetPack retrieves a pack by ID.
GetPack(ctx context.Context, id uint) (pack *Pack, err error)
// DeletePack deletes a pack record from the datastore.
DeletePack(ctx context.Context, name string) (err error)
// DeletePackByID is for backwards compatibility with the UI
DeletePackByID(ctx context.Context, id uint) (err error)
// ListPacksForHost lists the packs that a host should execute.
ListPacksForHost(ctx context.Context, hid uint) (packs []*Pack, err error)
///////////////////////////////////////////////////////////////////////////////
// LabelService
// ApplyLabelSpecs applies a list of LabelSpecs to the datastore, creating and updating labels as necessary.
ApplyLabelSpecs(ctx context.Context, specs []*LabelSpec) error
// GetLabelSpecs returns all of the stored LabelSpecs.
GetLabelSpecs(ctx context.Context) ([]*LabelSpec, error)
// GetLabelSpec gets the spec for the label with the given name.
GetLabelSpec(ctx context.Context, name string) (*LabelSpec, error)
NewLabel(ctx context.Context, p LabelPayload) (label *Label, err error)
ModifyLabel(ctx context.Context, id uint, payload ModifyLabelPayload) (*Label, error)
ListLabels(ctx context.Context, opt ListOptions) (labels []*Label, err error)
GetLabel(ctx context.Context, id uint) (label *Label, err error)
DeleteLabel(ctx context.Context, name string) (err error)
// DeleteLabelByID is for backwards compatibility with the UI
DeleteLabelByID(ctx context.Context, id uint) (err error)
// ListHostsInLabel returns a slice of hosts in the label with the given ID.
ListHostsInLabel(ctx context.Context, lid uint, opt HostListOptions) ([]*Host, error)
// ListLabelsForHost returns the labels that the given host is in.
ListLabelsForHost(ctx context.Context, hid uint) ([]*Label, error)
///////////////////////////////////////////////////////////////////////////////
// QueryService
// ApplyQuerySpecs applies a list of queries (creating or updating them as necessary)
ApplyQuerySpecs(ctx context.Context, specs []*QuerySpec) error
// GetQuerySpecs gets the YAML file representing all the stored queries.
GetQuerySpecs(ctx context.Context) ([]*QuerySpec, error)
// GetQuerySpec gets the spec for the query with the given name.
GetQuerySpec(ctx context.Context, name string) (*QuerySpec, error)
// ListQueries returns a list of saved queries. Note only saved queries should be returned (those that are created
// for distributed queries but not saved should not be returned).
ListQueries(ctx context.Context, opt ListOptions) ([]*Query, error)
GetQuery(ctx context.Context, id uint) (*Query, error)
NewQuery(ctx context.Context, p QueryPayload) (*Query, error)
ModifyQuery(ctx context.Context, id uint, p QueryPayload) (*Query, error)
DeleteQuery(ctx context.Context, name string) error
// DeleteQueryByID deletes a query by ID. For backwards compatibility with UI
DeleteQueryByID(ctx context.Context, id uint) error
// DeleteQueries deletes the existing query objects with the provided IDs. The number of deleted queries is returned
// along with any error.
DeleteQueries(ctx context.Context, ids []uint) (uint, error)
///////////////////////////////////////////////////////////////////////////////
// CampaignService defines the distributed query campaign related service methods
// NewDistributedQueryCampaignByNames creates a new distributed query campaign with the provided query (or the query
// referenced by ID) and host/label targets (specified by name).
NewDistributedQueryCampaignByNames(
ctx context.Context, queryString string, queryID *uint, hosts []string, labels []string,
) (*DistributedQueryCampaign, error)
// NewDistributedQueryCampaign creates a new distributed query campaign with the provided query (or the query
// referenced by ID) and host/label targets
NewDistributedQueryCampaign(
ctx context.Context, queryString string, queryID *uint, targets HostTargets,
) (*DistributedQueryCampaign, error)
// StreamCampaignResults streams updates with query results and expected host totals over the provided websocket.
// Note that the type signature is somewhat inconsistent due to this being a streaming API and not the typical
// go-kit RPC style.
StreamCampaignResults(ctx context.Context, conn *websocket.Conn, campaignID uint)
///////////////////////////////////////////////////////////////////////////////
// AgentOptionsService
// AgentOptionsForHost gets the agent options for the provided host. The host information should be used for
// filtering based on team, platform, etc.
AgentOptionsForHost(ctx context.Context, host *Host) (json.RawMessage, error)
///////////////////////////////////////////////////////////////////////////////
// HostService
ListHosts(ctx context.Context, opt HostListOptions) (hosts []*Host, err error)
GetHost(ctx context.Context, id uint) (host *HostDetail, err error)
GetHostSummary(ctx context.Context) (summary *HostSummary, err error)
DeleteHost(ctx context.Context, id uint) (err error)
// HostByIdentifier returns one host matching the provided identifier. Possible matches can be on
// osquery_host_identifier, node_key, UUID, or hostname.
HostByIdentifier(ctx context.Context, identifier string) (*HostDetail, error)
// RefetchHost requests a refetch of host details for the provided host.
RefetchHost(ctx context.Context, id uint) (err error)
FlushSeenHosts(ctx context.Context) error
// AddHostsToTeam adds hosts to an existing team, clearing their team settings if teamID is nil.
AddHostsToTeam(ctx context.Context, teamID *uint, hostIDs []uint) error
// AddHostsToTeamByFilter adds hosts to an existing team, clearing their team settings if teamID is nil. Hosts are
// selected by the label and HostListOptions provided.
AddHostsToTeamByFilter(ctx context.Context, teamID *uint, opt HostListOptions, lid *uint) error
///////////////////////////////////////////////////////////////////////////////
// AppConfigService provides methods for configuring the Fleet application
NewAppConfig(ctx context.Context, p AppConfig) (info *AppConfig, err error)
AppConfig(ctx context.Context) (info *AppConfig, err error)
ModifyAppConfig(ctx context.Context, p []byte) (info *AppConfig, err error)
// ApplyEnrollSecretSpec adds and updates the enroll secrets specified in the spec.
ApplyEnrollSecretSpec(ctx context.Context, spec *EnrollSecretSpec) error
// GetEnrollSecretSpec gets the spec for the current enroll secrets.
GetEnrollSecretSpec(ctx context.Context) (*EnrollSecretSpec, error)
// CertificateChain returns the PEM encoded certificate chain for osqueryd TLS termination. For cases where the
// connection is self-signed, the server will attempt to connect using the InsecureSkipVerify option in tls.Config.
CertificateChain(ctx context.Context) (cert []byte, err error)
// SetupRequired returns whether the app config setup needs to be performed (only when first initializing a Fleet
// server).
SetupRequired(ctx context.Context) (bool, error)
// Version returns version and build information.
Version(ctx context.Context) (*version.Info, error)
// License returns the licensing information.
License(ctx context.Context) (*LicenseInfo, error)
// LoggingConfig parses config.FleetConfig instance and returns a Logging.
LoggingConfig(ctx context.Context) (*Logging, error)
// UpdateIntervalConfig returns the duration for different update intervals configured in osquery
UpdateIntervalConfig(ctx context.Context) (*UpdateIntervalConfig, error)
///////////////////////////////////////////////////////////////////////////////
// InviteService contains methods for a service which deals with user invites.
// InviteNewUser creates an invite for a new user to join Fleet.
InviteNewUser(ctx context.Context, payload InvitePayload) (invite *Invite, err error)
// DeleteInvite removes an invite.
DeleteInvite(ctx context.Context, id uint) (err error)
// ListInvites returns a list of all invites.
ListInvites(ctx context.Context, opt ListOptions) (invites []*Invite, err error)
// VerifyInvite verifies that an invite exists and that it matches the invite token.
VerifyInvite(ctx context.Context, token string) (invite *Invite, err error)
///////////////////////////////////////////////////////////////////////////////
// TargetService
// SearchTargets will accept a search query, a slice of IDs of hosts to omit, and a slice of IDs of labels to omit,
// and it will return a set of targets (hosts and label) which match the supplied search query. If the query ID is
// provided and the referenced query allows observers to run, targets will include hosts that the user has observer
// role for.
SearchTargets(
ctx context.Context, searchQuery string, queryID *uint, targets HostTargets,
) (*TargetSearchResults, error)
// CountHostsInTargets returns the metrics of the hosts in the provided label and explicit host IDs. If the query ID
// is provided and the referenced query allows observers to run, targets will include hosts that the user has
// observer role for.
CountHostsInTargets(ctx context.Context, queryID *uint, targets HostTargets) (*TargetMetrics, error)
///////////////////////////////////////////////////////////////////////////////
// ScheduledQueryService
GetScheduledQueriesInPack(ctx context.Context, id uint, opts ListOptions) (queries []*ScheduledQuery, err error)
GetScheduledQuery(ctx context.Context, id uint) (query *ScheduledQuery, err error)
ScheduleQuery(ctx context.Context, sq *ScheduledQuery) (query *ScheduledQuery, err error)
DeleteScheduledQuery(ctx context.Context, id uint) (err error)
ModifyScheduledQuery(ctx context.Context, id uint, p ScheduledQueryPayload) (query *ScheduledQuery, err error)
///////////////////////////////////////////////////////////////////////////////
// StatusService
// StatusResultStore returns nil if the result store is functioning correctly, or an error indicating the problem.
StatusResultStore(ctx context.Context) error
// StatusLiveQuery returns nil if live queries are enabled, or an
// error indicating the problem.
StatusLiveQuery(ctx context.Context) error
///////////////////////////////////////////////////////////////////////////////
// CarveService
CarveBegin(ctx context.Context, payload CarveBeginPayload) (*CarveMetadata, error)
CarveBlock(ctx context.Context, payload CarveBlockPayload) error
GetCarve(ctx context.Context, id int64) (*CarveMetadata, error)
ListCarves(ctx context.Context, opt CarveListOptions) ([]*CarveMetadata, error)
GetBlock(ctx context.Context, carveId, blockId int64) ([]byte, error)
///////////////////////////////////////////////////////////////////////////////
// TeamService
// NewTeam creates a new team.
NewTeam(ctx context.Context, p TeamPayload) (*Team, error)
// ModifyTeam modifies an existing team (besides agent options).
ModifyTeam(ctx context.Context, id uint, payload TeamPayload) (*Team, error)
// ModifyTeamAgentOptions modifies agent options for a team.
ModifyTeamAgentOptions(ctx context.Context, id uint, options json.RawMessage) (*Team, error)
// AddTeamUsers adds users to an existing team.
AddTeamUsers(ctx context.Context, teamID uint, users []TeamUser) (*Team, error)
// DeleteTeamUsers deletes users from an existing team.
DeleteTeamUsers(ctx context.Context, teamID uint, users []TeamUser) (*Team, error)
// DeleteTeam deletes an existing team.
DeleteTeam(ctx context.Context, id uint) error
// ListTeams lists teams with the ordering and filters in the provided options.
ListTeams(ctx context.Context, opt ListOptions) ([]*Team, error)
// ListTeamUsers lists users on the team with the provided list options.
ListTeamUsers(ctx context.Context, teamID uint, opt ListOptions) ([]*User, error)
// TeamEnrollSecrets lists the enroll secrets for the team.
TeamEnrollSecrets(ctx context.Context, teamID uint) ([]*EnrollSecret, error)
// ApplyTeamSpecs applies the changes for each team as defined in the specs.
ApplyTeamSpecs(ctx context.Context, specs []*TeamSpec) error
///////////////////////////////////////////////////////////////////////////////
// ActivitiesService
ListActivities(ctx context.Context, opt ListOptions) ([]*Activity, error)
///////////////////////////////////////////////////////////////////////////////
// UserRolesService
// ApplyUserRolesSpecs applies a list of user global and team role changes
ApplyUserRolesSpecs(ctx context.Context, specs UsersRoleSpec) error
///////////////////////////////////////////////////////////////////////////////
// GlobalScheduleService
GlobalScheduleQuery(ctx context.Context, sq *ScheduledQuery) (*ScheduledQuery, error)
GetGlobalScheduledQueries(ctx context.Context, opts ListOptions) ([]*ScheduledQuery, error)
ModifyGlobalScheduledQueries(ctx context.Context, id uint, q ScheduledQueryPayload) (*ScheduledQuery, error)
DeleteGlobalScheduledQueries(ctx context.Context, id uint) error
///////////////////////////////////////////////////////////////////////////////
// TranslatorService
Translate(ctx context.Context, payloads []TranslatePayload) ([]TranslatePayload, error)
///////////////////////////////////////////////////////////////////////////////
// TeamScheduleService
TeamScheduleQuery(ctx context.Context, teamID uint, sq *ScheduledQuery) (*ScheduledQuery, error)
GetTeamScheduledQueries(ctx context.Context, teamID uint, opts ListOptions) ([]*ScheduledQuery, error)
ModifyTeamScheduledQueries(
ctx context.Context, teamID uint, scheduledQueryID uint, q ScheduledQueryPayload,
) (*ScheduledQuery, error)
DeleteTeamScheduledQueries(ctx context.Context, teamID uint, id uint) error
///////////////////////////////////////////////////////////////////////////////
// GlobalPolicyService
NewGlobalPolicy(ctx context.Context, queryID uint) (*Policy, error)
ListGlobalPolicies(ctx context.Context) ([]*Policy, error)
DeleteGlobalPolicies(ctx context.Context, ids []uint) ([]uint, error)
GetPolicyByIDQueries(ctx context.Context, policyID uint) (*Policy, error)
}
-51
View File
@@ -1,65 +1,14 @@
package fleet
import (
"context"
"time"
)
// SessionStore is the abstract interface that all session backends must
// conform to.
type SessionStore interface {
// Given a session key, find and return a session object or an error if one
// could not be found for the given key
SessionByKey(key string) (*Session, error)
// Given a session id, find and return a session object or an error if one
// could not be found for the given id
SessionByID(id uint) (*Session, error)
// Find all of the active sessions for a given user
ListSessionsForUser(id uint) ([]*Session, error)
// Store a new session struct
NewSession(session *Session) (*Session, error)
// Destroy the currently tracked session
DestroySession(session *Session) error
// Destroy all of the sessions for a given user
DestroyAllSessionsForUser(id uint) error
// Mark the currently tracked session as access to extend expiration
MarkSessionAccessed(session *Session) error
}
type Auth interface {
UserID() string
RequestID() string
}
type SessionService interface {
// InitiateSSO is used to initiate an SSO session and returns a URL that
// can be used in a redirect to the IDP.
// Arguments: redirectURL is the URL of the protected resource that the user
// was trying to access when they were promted to log in.
InitiateSSO(ctx context.Context, redirectURL string) (string, error)
// CallbackSSO handles the IDP response. The original URL the viewer attempted
// to access is returned from this function so we can redirect back to the front end and
// load the page the viewer originally attempted to access when prompted for login.
CallbackSSO(ctx context.Context, auth Auth) (*SSOSession, error)
// SessionSSOSettings returns non sensitive single sign on information used before
// authentication
SSOSettings(ctx context.Context) (*SessionSSOSettings, error)
Login(ctx context.Context, email, password string) (user *User, sessionKey string, err error)
Logout(ctx context.Context) (err error)
DestroySession(ctx context.Context) (err error)
GetInfoAboutSessionsForUser(ctx context.Context, id uint) (sessions []*Session, err error)
DeleteSessionsForUser(ctx context.Context, id uint) (err error)
GetInfoAboutSession(ctx context.Context, id uint) (session *Session, err error)
GetSessionByKey(ctx context.Context, key string) (session *Session, err error)
DeleteSession(ctx context.Context, id uint) (err error)
}
type SSOSession struct {
Token string
RedirectURL string
-9
View File
@@ -8,15 +8,6 @@ import (
"github.com/pkg/errors"
)
type SoftwareStore interface {
SaveHostSoftware(host *Host) error
LoadHostSoftware(host *Host) error
AllSoftwareWithoutCPEIterator() (SoftwareIterator, error)
AddCPEForSoftware(software Software, cpe string) error
AllCPEs() ([]string, error)
InsertCVEForCPE(cve string, cpes []string) error
}
type SoftwareCVE struct {
CVE string `json:"cve" db:"cve"`
DetailsLink string `json:"details_link" db:"details_link"`
-5
View File
@@ -8,11 +8,6 @@ type StatisticsPayload struct {
NumHostsEnrolled int `json:"numHostsEnrolled"`
}
type StatisticsStore interface {
ShouldSendStatistics(frequency time.Duration) (StatisticsPayload, bool, error)
RecordStatisticsSent() error
}
const (
StatisticsFrequency = time.Hour * 24 * 7
)
-13
View File
@@ -1,13 +0,0 @@
package fleet
import "context"
type StatusService interface {
// StatusResultStore returns nil if the result store is functioning
// correctly, or an error indicating the problem.
StatusResultStore(ctx context.Context) error
// StatusLiveQuery returns nil if live queries are enabled, or an
// error indicating the problem.
StatusLiveQuery(ctx context.Context) error
}
-30
View File
@@ -1,10 +1,5 @@
package fleet
import (
"context"
"time"
)
type TargetSearchResults struct {
Hosts []*Host
Labels []*Label
@@ -32,31 +27,6 @@ type TargetMetrics struct {
NewHosts uint `db:"new"`
}
type TargetService interface {
// SearchTargets will accept a search query, a slice of IDs of hosts to
// omit, and a slice of IDs of labels to omit, and it will return a set of
// targets (hosts and label) which match the supplied search query. If the
// query ID is provided and the referenced query allows observers to run,
// targets will include hosts that the user has observer role for.
SearchTargets(ctx context.Context, searchQuery string, queryID *uint, targets HostTargets) (*TargetSearchResults, error)
// CountHostsInTargets returns the metrics of the hosts in the provided
// label and explicit host IDs. If the query ID is provided and the
// referenced query allows observers to run, targets will include hosts that
// the user has observer role for.
CountHostsInTargets(ctx context.Context, queryID *uint, targets HostTargets) (*TargetMetrics, error)
}
type TargetStore interface {
// CountHostsInTargets returns the metrics of the hosts in the provided
// labels, teams, and explicit host IDs.
CountHostsInTargets(filter TeamFilter, targets HostTargets, now time.Time) (TargetMetrics, error)
// HostIDsInTargets returns the host IDs of the hosts in the provided
// labels, teams, and explicit host IDs. The returned host IDs should be
// sorted in ascending order.
HostIDsInTargets(filter TeamFilter, targets HostTargets) ([]uint, error)
}
// HostTargets is the set of targets for a campaign (live query). These
// targets are additive (include all hosts and all hosts in labels and all hosts
// in teams).
-10
View File
@@ -1,10 +0,0 @@
package fleet
import "context"
type TeamScheduleService interface {
TeamScheduleQuery(ctx context.Context, teamID uint, sq *ScheduledQuery) (*ScheduledQuery, error)
GetTeamScheduledQueries(ctx context.Context, teamID uint, opts ListOptions) ([]*ScheduledQuery, error)
ModifyTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint, q ScheduledQueryPayload) (*ScheduledQuery, error)
DeleteTeamScheduledQueries(ctx context.Context, teamID uint, id uint) error
}
-46
View File
@@ -1,7 +1,6 @@
package fleet
import (
"context"
"encoding/json"
"time"
)
@@ -12,51 +11,6 @@ const (
RoleObserver = "observer"
)
type TeamStore interface {
// NewTeam creates a new Team object in the store.
NewTeam(team *Team) (*Team, error)
// SaveTeam saves any changes to the team.
SaveTeam(team *Team) (*Team, error)
// Team retrieves the Team by ID.
Team(tid uint) (*Team, error)
// Team deletes the Team by ID.
DeleteTeam(tid uint) error
// TeamByName retrieves the Team by Name.
TeamByName(name string) (*Team, error)
// ListTeams lists teams with the ordering and filters in the provided
// options.
ListTeams(filter TeamFilter, opt ListOptions) ([]*Team, error)
// SearchTeams searches teams using the provided query and ommitting the
// provided existing selection.
SearchTeams(filter TeamFilter, matchQuery string, omit ...uint) ([]*Team, error)
// TeamEnrollSecrets lists the enroll secrets for the team.
TeamEnrollSecrets(teamID uint) ([]*EnrollSecret, error)
}
type TeamService interface {
// NewTeam creates a new team.
NewTeam(ctx context.Context, p TeamPayload) (*Team, error)
// ModifyTeam modifies an existing team (besides agent options).
ModifyTeam(ctx context.Context, id uint, payload TeamPayload) (*Team, error)
// ModifyTeam modifies agent options for a team.
ModifyTeamAgentOptions(ctx context.Context, id uint, options json.RawMessage) (*Team, error)
// AddTeamUsers adds users to an existing team.
AddTeamUsers(ctx context.Context, teamID uint, users []TeamUser) (*Team, error)
// DeleteTeamUsers deletes users from an existing team.
DeleteTeamUsers(ctx context.Context, teamID uint, users []TeamUser) (*Team, error)
// DeleteTeam deletes an existing team.
DeleteTeam(ctx context.Context, id uint) error
// ListTeams lists teams with the ordering and filters in the provided
// options.
ListTeams(ctx context.Context, opt ListOptions) ([]*Team, error)
// ListTeams lists users on the team with the provided list options.
ListTeamUsers(ctx context.Context, teamID uint, opt ListOptions) ([]*User, error)
// TeamEnrollSecrets lists the enroll secrets for the team.
TeamEnrollSecrets(ctx context.Context, teamID uint) ([]*EnrollSecret, error)
// ApplyTeamSpecs applies the changes for each team as defined in the specs.
ApplyTeamSpecs(ctx context.Context, specs []*TeamSpec) error
}
type TeamPayload struct {
Name *string `json:"name"`
Description *string `json:"description"`
-8
View File
@@ -1,9 +1,5 @@
package fleet
import (
"context"
)
const (
TranslatorTypeUserEmail = "user"
TranslatorTypeLabel = "label"
@@ -20,7 +16,3 @@ type StringIdentifierToIDPayload struct {
Identifier string `json:"identifier"`
ID uint `json:"id"`
}
type TranslatorService interface {
Translate(ctx context.Context, payloads []TranslatePayload) ([]TranslatePayload, error)
}
-7
View File
@@ -1,7 +1,5 @@
package fleet
import "context"
const (
UserRolesKind = "user_roles"
)
@@ -19,8 +17,3 @@ type TeamRoleSpec struct {
Name string `json:"team"`
Role string `json:"role"`
}
type UserRolesService interface {
// ApplyUserRolesSpecs applies a list of user global and team role changes
ApplyUserRolesSpecs(ctx context.Context, specs UsersRoleSpec) error
}
-85
View File
@@ -1,97 +1,12 @@
package fleet
import (
"context"
"fmt"
"github.com/fleetdm/fleet/v4/server"
"golang.org/x/crypto/bcrypt"
)
// UserStore contains methods for managing users in a datastore
type UserStore interface {
NewUser(user *User) (*User, error)
ListUsers(opt UserListOptions) ([]*User, error)
UserByEmail(email string) (*User, error)
UserByID(id uint) (*User, error)
SaveUser(user *User) error
SaveUsers(users []*User) error
// DeleteUser permanently deletes the user identified by the provided ID.
DeleteUser(id uint) error
// PendingEmailChange creates a record with a pending email change for a user identified
// by uid. The change record is keyed by a unique token. The token is emailed to the user
// with a link that they can use to confirm the change.
PendingEmailChange(userID uint, newEmail, token string) error
// ConfirmPendingEmailChange will confirm new email address identified by token is valid.
// The new email will be written to user record. userID is the ID of the
// user whose e-mail is being changed.
ConfirmPendingEmailChange(userID uint, token string) (string, error)
}
// UserService contains methods for managing a Fleet User.
type UserService interface {
// CreateUserWithInvite creates a new User from a request payload when there is
// already an existing invitation.
CreateUserFromInvite(ctx context.Context, p UserPayload) (user *User, err error)
// CreateUser allows an admin to create a new user without first creating
// and validating invite tokens.
CreateUser(ctx context.Context, p UserPayload) (user *User, err error)
// CreateInitialUser creates the first user, skipping authorization checks.
// If a user already exists this method should fail.
CreateInitialUser(ctx context.Context, p UserPayload) (user *User, err error)
// User returns a valid User given a User ID.
User(ctx context.Context, id uint) (user *User, err error)
// UserUnauthorized returns a valid User given a User ID, *skipping authorization checks*
//
// This method should only be used in middleware where there is not yet a viewer context and we need to load up a user to create that context.
UserUnauthorized(ctx context.Context, id uint) (user *User, err error)
// AuthenticatedUser returns the current user from the viewer context.
AuthenticatedUser(ctx context.Context) (user *User, err error)
// ListUsers returns all users.
ListUsers(ctx context.Context, opt UserListOptions) (users []*User, err error)
// ChangePassword validates the existing password, and sets the new
// password. User is retrieved from the viewer context.
ChangePassword(ctx context.Context, oldPass, newPass string) error
// RequestPasswordReset generates a password reset request for the user
// specified by email. The request results in a token emailed to the
// user.
RequestPasswordReset(ctx context.Context, email string) (err error)
// RequirePasswordReset requires a password reset for the user
// specified by ID (if require is true). It deletes all of the user's
// sessions, and requires that their password be reset upon the next
// login. Setting require to false will take a user out of this state.
// The updated user is returned.
RequirePasswordReset(ctx context.Context, uid uint, require bool) (*User, error)
// PerformRequiredPasswordReset resets a password for a user that is in
// the required reset state. It must be called with the logged in
// viewer context of that user.
PerformRequiredPasswordReset(ctx context.Context, password string) (*User, error)
// ResetPassword validates the provided password reset token and
// updates the user's password.
ResetPassword(ctx context.Context, token, password string) (err error)
// ModifyUser updates a user's parameters given a UserPayload.
ModifyUser(ctx context.Context, userID uint, p UserPayload) (user *User, err error)
// DeleteUser permanently deletes the user identified by the provided ID.
DeleteUser(ctx context.Context, id uint) error
// ChangeUserEmail is used to confirm new email address and if confirmed,
// write the new email address to user.
ChangeUserEmail(ctx context.Context, token string) (string, error)
}
// User is the model struct that represents a Fleet user.
type User struct {
UpdateCreateTimestamps
+8 -54
View File
@@ -2,70 +2,24 @@ package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
//go:generate mockimpl -o datastore_activities.go "s *ActivitiesStore" "fleet.ActivitiesStore"
//go:generate mockimpl -o datastore_appconfig.go "s *AppConfigStore" "fleet.AppConfigStore"
//go:generate mockimpl -o datastore_campaigns.go "s *CampaignStore" "fleet.CampaignStore"
//go:generate mockimpl -o datastore_carves.go "s *CarveStore" "fleet.CarveStore"
//go:generate mockimpl -o datastore_hosts.go "s *HostStore" "fleet.HostStore"
//go:generate mockimpl -o datastore_invites.go "s *InviteStore" "fleet.InviteStore"
//go:generate mockimpl -o datastore_labels.go "s *LabelStore" "fleet.LabelStore"
//go:generate mockimpl -o datastore_packs.go "s *PackStore" "fleet.PackStore"
//go:generate mockimpl -o datastore_queries.go "s *QueryStore" "fleet.QueryStore"
//go:generate mockimpl -o datastore_mock.go "s *DataStore" "fleet.Datastore"
//go:generate mockimpl -o datastore_query_results.go "s *QueryResultStore" "fleet.QueryResultStore"
//go:generate mockimpl -o datastore_scheduled_queries.go "s *ScheduledQueryStore" "fleet.ScheduledQueryStore"
//go:generate mockimpl -o datastore_sessions.go "s *SessionStore" "fleet.SessionStore"
//go:generate mockimpl -o datastore_software.go "s *SoftwareStore" "fleet.SoftwareStore"
//go:generate mockimpl -o datastore_statistics.go "s *StatisticsStore" "fleet.StatisticsStore"
//go:generate mockimpl -o datastore_targets.go "s *TargetStore" "fleet.TargetStore"
//go:generate mockimpl -o datastore_teams.go "s *TeamStore" "fleet.TeamStore"
//go:generate mockimpl -o datastore_users.go "s *UserStore" "fleet.UserStore"
//go:generate mockimpl -o datastore_policies.go "s *GlobalPoliciesStore" "fleet.GlobalPoliciesStore"
var _ fleet.Datastore = (*Store)(nil)
type Store struct {
fleet.PasswordResetStore
TeamStore
TargetStore
SessionStore
CampaignStore
ScheduledQueryStore
AppConfigStore
HostStore
InviteStore
LabelStore
PackStore
UserStore
QueryStore
QueryResultStore
CarveStore
SoftwareStore
ActivitiesStore
StatisticsStore
GlobalPoliciesStore
DataStore
}
func (m *Store) Drop() error {
return nil
}
func (m *Store) MigrateTables() error {
return nil
}
func (m *Store) MigrateData() error {
return nil
}
func (m *Store) MigrationStatus() (fleet.MigrationStatus, error) {
return 0, nil
}
func (m *Store) Name() string {
return "mock"
}
func (m *Store) Drop() error { return nil }
func (m *Store) MigrateTables() error { return nil }
func (m *Store) MigrateData() error { return nil }
func (m *Store) MigrationStatus() (fleet.MigrationStatus, error) { return 0, nil }
func (m *Store) Name() string { return "mock" }
type mockTransaction struct{}
func (m *mockTransaction) Commit() error { return nil }
func (m *mockTransaction) Rollback() error { return nil }
func (m *Store) Begin() (fleet.Transaction, error) {
return &mockTransaction{}, nil
}
func (m *Store) Begin() (fleet.Transaction, error) { return &mockTransaction{}, nil }
-29
View File
@@ -1,29 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.ActivitiesStore = (*ActivitiesStore)(nil)
type NewActivityFunc func(user *fleet.User, activityType string, details *map[string]interface{}) error
type ListActivitiesFunc func(opt fleet.ListOptions) ([]*fleet.Activity, error)
type ActivitiesStore struct {
NewActivityFunc NewActivityFunc
NewActivityFuncInvoked bool
ListActivitiesFunc ListActivitiesFunc
ListActivitiesFuncInvoked bool
}
func (s *ActivitiesStore) NewActivity(user *fleet.User, activityType string, details *map[string]interface{}) error {
s.NewActivityFuncInvoked = true
return s.NewActivityFunc(user, activityType, details)
}
func (s *ActivitiesStore) ListActivities(opt fleet.ListOptions) ([]*fleet.Activity, error) {
s.ListActivitiesFuncInvoked = true
return s.ListActivitiesFunc(opt)
}
-69
View File
@@ -1,69 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.AppConfigStore = (*AppConfigStore)(nil)
type NewAppConfigFunc func(info *fleet.AppConfig) (*fleet.AppConfig, error)
type AppConfigFunc func() (*fleet.AppConfig, error)
type SaveAppConfigFunc func(info *fleet.AppConfig) error
type VerifyEnrollSecretFunc func(secret string) (*fleet.EnrollSecret, error)
type GetEnrollSecretsFunc func(teamID *uint) ([]*fleet.EnrollSecret, error)
type ApplyEnrollSecretsFunc func(teamID *uint, secrets []*fleet.EnrollSecret) error
type AppConfigStore struct {
NewAppConfigFunc NewAppConfigFunc
NewAppConfigFuncInvoked bool
AppConfigFunc AppConfigFunc
AppConfigFuncInvoked bool
SaveAppConfigFunc SaveAppConfigFunc
SaveAppConfigFuncInvoked bool
VerifyEnrollSecretFunc VerifyEnrollSecretFunc
VerifyEnrollSecretFuncInvoked bool
GetEnrollSecretsFunc GetEnrollSecretsFunc
GetEnrollSecretsFuncInvoked bool
ApplyEnrollSecretsFunc ApplyEnrollSecretsFunc
ApplyEnrollSecretsFuncInvoked bool
}
func (s *AppConfigStore) NewAppConfig(info *fleet.AppConfig) (*fleet.AppConfig, error) {
s.NewAppConfigFuncInvoked = true
return s.NewAppConfigFunc(info)
}
func (s *AppConfigStore) AppConfig() (*fleet.AppConfig, error) {
s.AppConfigFuncInvoked = true
return s.AppConfigFunc()
}
func (s *AppConfigStore) SaveAppConfig(info *fleet.AppConfig) error {
s.SaveAppConfigFuncInvoked = true
return s.SaveAppConfigFunc(info)
}
func (s *AppConfigStore) VerifyEnrollSecret(secret string) (*fleet.EnrollSecret, error) {
s.VerifyEnrollSecretFuncInvoked = true
return s.VerifyEnrollSecretFunc(secret)
}
func (s *AppConfigStore) GetEnrollSecrets(teamID *uint) ([]*fleet.EnrollSecret, error) {
s.GetEnrollSecretsFuncInvoked = true
return s.GetEnrollSecretsFunc(teamID)
}
func (s *AppConfigStore) ApplyEnrollSecrets(teamID *uint, secrets []*fleet.EnrollSecret) error {
s.ApplyEnrollSecretsFuncInvoked = true
return s.ApplyEnrollSecretsFunc(teamID, secrets)
}
@@ -1,9 +0,0 @@
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
func ReturnFakeAppConfig(fake *fleet.AppConfig) AppConfigFunc {
return func() (*fleet.AppConfig, error) {
return fake, nil
}
}
-73
View File
@@ -1,73 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import (
"time"
"github.com/fleetdm/fleet/v4/server/fleet"
)
var _ fleet.CampaignStore = (*CampaignStore)(nil)
type NewDistributedQueryCampaignFunc func(camp *fleet.DistributedQueryCampaign) (*fleet.DistributedQueryCampaign, error)
type DistributedQueryCampaignFunc func(id uint) (*fleet.DistributedQueryCampaign, error)
type SaveDistributedQueryCampaignFunc func(camp *fleet.DistributedQueryCampaign) error
type DistributedQueryCampaignTargetIDsFunc func(id uint) (targets *fleet.HostTargets, err error)
type NewDistributedQueryCampaignTargetFunc func(target *fleet.DistributedQueryCampaignTarget) (*fleet.DistributedQueryCampaignTarget, error)
type CleanupDistributedQueryCampaignsFunc func(now time.Time) (expired uint, err error)
type CampaignStore struct {
NewDistributedQueryCampaignFunc NewDistributedQueryCampaignFunc
NewDistributedQueryCampaignFuncInvoked bool
DistributedQueryCampaignFunc DistributedQueryCampaignFunc
DistributedQueryCampaignFuncInvoked bool
SaveDistributedQueryCampaignFunc SaveDistributedQueryCampaignFunc
SaveDistributedQueryCampaignFuncInvoked bool
DistributedQueryCampaignTargetIDsFunc DistributedQueryCampaignTargetIDsFunc
DistributedQueryCampaignTargetIDsFuncInvoked bool
NewDistributedQueryCampaignTargetFunc NewDistributedQueryCampaignTargetFunc
NewDistributedQueryCampaignTargetFuncInvoked bool
CleanupDistributedQueryCampaignsFunc CleanupDistributedQueryCampaignsFunc
CleanupDistributedQueryCampaignsFuncInvoked bool
}
func (s *CampaignStore) NewDistributedQueryCampaign(camp *fleet.DistributedQueryCampaign) (*fleet.DistributedQueryCampaign, error) {
s.NewDistributedQueryCampaignFuncInvoked = true
return s.NewDistributedQueryCampaignFunc(camp)
}
func (s *CampaignStore) DistributedQueryCampaign(id uint) (*fleet.DistributedQueryCampaign, error) {
s.DistributedQueryCampaignFuncInvoked = true
return s.DistributedQueryCampaignFunc(id)
}
func (s *CampaignStore) SaveDistributedQueryCampaign(camp *fleet.DistributedQueryCampaign) error {
s.SaveDistributedQueryCampaignFuncInvoked = true
return s.SaveDistributedQueryCampaignFunc(camp)
}
func (s *CampaignStore) DistributedQueryCampaignTargetIDs(id uint) (targets *fleet.HostTargets, err error) {
s.DistributedQueryCampaignTargetIDsFuncInvoked = true
return s.DistributedQueryCampaignTargetIDsFunc(id)
}
func (s *CampaignStore) NewDistributedQueryCampaignTarget(target *fleet.DistributedQueryCampaignTarget) (*fleet.DistributedQueryCampaignTarget, error) {
s.NewDistributedQueryCampaignTargetFuncInvoked = true
return s.NewDistributedQueryCampaignTargetFunc(target)
}
func (s *CampaignStore) CleanupDistributedQueryCampaigns(now time.Time) (expired uint, err error) {
s.CleanupDistributedQueryCampaignsFuncInvoked = true
return s.CleanupDistributedQueryCampaignsFunc(now)
}
-103
View File
@@ -1,103 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import (
"time"
"github.com/fleetdm/fleet/v4/server/fleet"
)
var _ fleet.CarveStore = (*CarveStore)(nil)
type NewCarveFunc func(metadata *fleet.CarveMetadata) (*fleet.CarveMetadata, error)
type UpdateCarveFunc func(metadata *fleet.CarveMetadata) error
type CarveFunc func(carveId int64) (*fleet.CarveMetadata, error)
type CarveBySessionIdFunc func(sessionId string) (*fleet.CarveMetadata, error)
type CarveByNameFunc func(name string) (*fleet.CarveMetadata, error)
type ListCarvesFunc func(opt fleet.CarveListOptions) ([]*fleet.CarveMetadata, error)
type NewBlockFunc func(metadata *fleet.CarveMetadata, blockId int64, data []byte) error
type GetBlockFunc func(metadata *fleet.CarveMetadata, blockId int64) ([]byte, error)
type CleanupCarvesFunc func(now time.Time) (expired int, err error)
type CarveStore struct {
NewCarveFunc NewCarveFunc
NewCarveFuncInvoked bool
UpdateCarveFunc UpdateCarveFunc
UpdateCarveFuncInvoked bool
CarveFunc CarveFunc
CarveFuncInvoked bool
CarveBySessionIdFunc CarveBySessionIdFunc
CarveBySessionIdFuncInvoked bool
CarveByNameFunc CarveByNameFunc
CarveByNameFuncInvoked bool
ListCarvesFunc ListCarvesFunc
ListCarvesFuncInvoked bool
NewBlockFunc NewBlockFunc
NewBlockFuncInvoked bool
GetBlockFunc GetBlockFunc
GetBlockFuncInvoked bool
CleanupCarvesFunc CleanupCarvesFunc
CleanupCarvesFuncInvoked bool
}
func (s *CarveStore) NewCarve(metadata *fleet.CarveMetadata) (*fleet.CarveMetadata, error) {
s.NewCarveFuncInvoked = true
return s.NewCarveFunc(metadata)
}
func (s *CarveStore) UpdateCarve(metadata *fleet.CarveMetadata) error {
s.UpdateCarveFuncInvoked = true
return s.UpdateCarveFunc(metadata)
}
func (s *CarveStore) Carve(carveId int64) (*fleet.CarveMetadata, error) {
s.CarveFuncInvoked = true
return s.CarveFunc(carveId)
}
func (s *CarveStore) CarveBySessionId(sessionId string) (*fleet.CarveMetadata, error) {
s.CarveBySessionIdFuncInvoked = true
return s.CarveBySessionIdFunc(sessionId)
}
func (s *CarveStore) CarveByName(name string) (*fleet.CarveMetadata, error) {
s.CarveByNameFuncInvoked = true
return s.CarveByNameFunc(name)
}
func (s *CarveStore) ListCarves(opt fleet.CarveListOptions) ([]*fleet.CarveMetadata, error) {
s.ListCarvesFuncInvoked = true
return s.ListCarvesFunc(opt)
}
func (s *CarveStore) NewBlock(metadata *fleet.CarveMetadata, blockId int64, data []byte) error {
s.NewBlockFuncInvoked = true
return s.NewBlockFunc(metadata, blockId, data)
}
func (s *CarveStore) GetBlock(metadata *fleet.CarveMetadata, blockId int64) ([]byte, error) {
s.GetBlockFuncInvoked = true
return s.GetBlockFunc(metadata, blockId)
}
func (s *CarveStore) CleanupCarves(now time.Time) (expired int, err error) {
s.CleanupCarvesFuncInvoked = true
return s.CleanupCarvesFunc(now)
}
-173
View File
@@ -1,173 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import (
"time"
"github.com/fleetdm/fleet/v4/server/fleet"
)
var _ fleet.HostStore = (*HostStore)(nil)
type NewHostFunc func(host *fleet.Host) (*fleet.Host, error)
type SaveHostFunc func(host *fleet.Host) error
type DeleteHostFunc func(hid uint) error
type HostFunc func(id uint) (*fleet.Host, error)
type EnrollHostFunc func(osqueryHostId string, nodeKey string, teamID *uint, cooldown time.Duration) (*fleet.Host, error)
type ListHostsFunc func(filter fleet.TeamFilter, opt fleet.HostListOptions) ([]*fleet.Host, error)
type AuthenticateHostFunc func(nodeKey string) (*fleet.Host, error)
type MarkHostSeenFunc func(host *fleet.Host, t time.Time) error
type MarkHostsSeenFunc func(hostIDs []uint, t time.Time) error
type SearchHostsFunc func(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Host, error)
type CleanupIncomingHostsFunc func(now time.Time) error
type GenerateHostStatusStatisticsFunc func(filter fleet.TeamFilter, now time.Time) (online uint, offline uint, mia uint, new uint, err error)
type HostIDsByNameFunc func(filter fleet.TeamFilter, hostnames []string) ([]uint, error)
type HostByIdentifierFunc func(identifier string) (*fleet.Host, error)
type AddHostsToTeamFunc func(teamID *uint, hostIDs []uint) error
type SaveHostAdditionalFunc func(host *fleet.Host) error
type HostStore struct {
NewHostFunc NewHostFunc
NewHostFuncInvoked bool
SaveHostFunc SaveHostFunc
SaveHostFuncInvoked bool
DeleteHostFunc DeleteHostFunc
DeleteHostFuncInvoked bool
HostFunc HostFunc
HostFuncInvoked bool
EnrollHostFunc EnrollHostFunc
EnrollHostFuncInvoked bool
ListHostsFunc ListHostsFunc
ListHostsFuncInvoked bool
AuthenticateHostFunc AuthenticateHostFunc
AuthenticateHostFuncInvoked bool
MarkHostSeenFunc MarkHostSeenFunc
MarkHostSeenFuncInvoked bool
MarkHostsSeenFunc MarkHostsSeenFunc
MarkHostsSeenFuncInvoked bool
SearchHostsFunc SearchHostsFunc
SearchHostsFuncInvoked bool
CleanupIncomingHostsFunc CleanupIncomingHostsFunc
CleanupIncomingHostsFuncInvoked bool
GenerateHostStatusStatisticsFunc GenerateHostStatusStatisticsFunc
GenerateHostStatusStatisticsFuncInvoked bool
HostIDsByNameFunc HostIDsByNameFunc
HostIDsByNameFuncInvoked bool
HostByIdentifierFunc HostByIdentifierFunc
HostByIdentifierFuncInvoked bool
AddHostsToTeamFunc AddHostsToTeamFunc
AddHostsToTeamFuncInvoked bool
SaveHostAdditionalFunc SaveHostAdditionalFunc
SaveHostAdditionalFuncInvoked bool
}
func (s *HostStore) NewHost(host *fleet.Host) (*fleet.Host, error) {
s.NewHostFuncInvoked = true
return s.NewHostFunc(host)
}
func (s *HostStore) SaveHost(host *fleet.Host) error {
s.SaveHostFuncInvoked = true
return s.SaveHostFunc(host)
}
func (s *HostStore) DeleteHost(hid uint) error {
s.DeleteHostFuncInvoked = true
return s.DeleteHostFunc(hid)
}
func (s *HostStore) Host(id uint) (*fleet.Host, error) {
s.HostFuncInvoked = true
return s.HostFunc(id)
}
func (s *HostStore) EnrollHost(osqueryHostId string, nodeKey string, teamID *uint, cooldown time.Duration) (*fleet.Host, error) {
s.EnrollHostFuncInvoked = true
return s.EnrollHostFunc(osqueryHostId, nodeKey, teamID, cooldown)
}
func (s *HostStore) ListHosts(filter fleet.TeamFilter, opt fleet.HostListOptions) ([]*fleet.Host, error) {
s.ListHostsFuncInvoked = true
return s.ListHostsFunc(filter, opt)
}
func (s *HostStore) AuthenticateHost(nodeKey string) (*fleet.Host, error) {
s.AuthenticateHostFuncInvoked = true
return s.AuthenticateHostFunc(nodeKey)
}
func (s *HostStore) MarkHostSeen(host *fleet.Host, t time.Time) error {
s.MarkHostSeenFuncInvoked = true
return s.MarkHostSeenFunc(host, t)
}
func (s *HostStore) MarkHostsSeen(hostIDs []uint, t time.Time) error {
s.MarkHostsSeenFuncInvoked = true
return s.MarkHostsSeenFunc(hostIDs, t)
}
func (s *HostStore) SearchHosts(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Host, error) {
s.SearchHostsFuncInvoked = true
return s.SearchHostsFunc(filter, query, omit...)
}
func (s *HostStore) CleanupIncomingHosts(now time.Time) error {
s.CleanupIncomingHostsFuncInvoked = true
return s.CleanupIncomingHostsFunc(now)
}
func (s *HostStore) GenerateHostStatusStatistics(filter fleet.TeamFilter, now time.Time) (online uint, offline uint, mia uint, new uint, err error) {
s.GenerateHostStatusStatisticsFuncInvoked = true
return s.GenerateHostStatusStatisticsFunc(filter, now)
}
func (s *HostStore) HostIDsByName(filter fleet.TeamFilter, hostnames []string) ([]uint, error) {
s.HostIDsByNameFuncInvoked = true
return s.HostIDsByNameFunc(filter, hostnames)
}
func (s *HostStore) HostByIdentifier(identifier string) (*fleet.Host, error) {
s.HostByIdentifierFuncInvoked = true
return s.HostByIdentifierFunc(identifier)
}
func (s *HostStore) AddHostsToTeam(teamID *uint, hostIDs []uint) error {
s.AddHostsToTeamFuncInvoked = true
return s.AddHostsToTeamFunc(teamID, hostIDs)
}
func (s *HostStore) SaveHostAdditional(host *fleet.Host) error {
s.SaveHostAdditionalFuncInvoked = true
return s.SaveHostAdditionalFunc(host)
}
-69
View File
@@ -1,69 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.InviteStore = (*InviteStore)(nil)
type NewInviteFunc func(i *fleet.Invite) (*fleet.Invite, error)
type ListInvitesFunc func(opt fleet.ListOptions) ([]*fleet.Invite, error)
type InviteFunc func(id uint) (*fleet.Invite, error)
type InviteByEmailFunc func(email string) (*fleet.Invite, error)
type InviteByTokenFunc func(token string) (*fleet.Invite, error)
type DeleteInviteFunc func(id uint) error
type InviteStore struct {
NewInviteFunc NewInviteFunc
NewInviteFuncInvoked bool
ListInvitesFunc ListInvitesFunc
ListInvitesFuncInvoked bool
InviteFunc InviteFunc
InviteFuncInvoked bool
InviteByEmailFunc InviteByEmailFunc
InviteByEmailFuncInvoked bool
InviteByTokenFunc InviteByTokenFunc
InviteByTokenFuncInvoked bool
DeleteInviteFunc DeleteInviteFunc
DeleteInviteFuncInvoked bool
}
func (s *InviteStore) NewInvite(i *fleet.Invite) (*fleet.Invite, error) {
s.NewInviteFuncInvoked = true
return s.NewInviteFunc(i)
}
func (s *InviteStore) ListInvites(opt fleet.ListOptions) ([]*fleet.Invite, error) {
s.ListInvitesFuncInvoked = true
return s.ListInvitesFunc(opt)
}
func (s *InviteStore) Invite(id uint) (*fleet.Invite, error) {
s.InviteFuncInvoked = true
return s.InviteFunc(id)
}
func (s *InviteStore) InviteByEmail(email string) (*fleet.Invite, error) {
s.InviteByEmailFuncInvoked = true
return s.InviteByEmailFunc(email)
}
func (s *InviteStore) InviteByToken(token string) (*fleet.Invite, error) {
s.InviteByTokenFuncInvoked = true
return s.InviteByTokenFunc(token)
}
func (s *InviteStore) DeleteInvite(id uint) error {
s.DeleteInviteFuncInvoked = true
return s.DeleteInviteFunc(id)
}
-163
View File
@@ -1,163 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import (
"time"
"github.com/fleetdm/fleet/v4/server/fleet"
)
var _ fleet.LabelStore = (*LabelStore)(nil)
type ApplyLabelSpecsFunc func(specs []*fleet.LabelSpec) error
type GetLabelSpecsFunc func() ([]*fleet.LabelSpec, error)
type GetLabelSpecFunc func(name string) (*fleet.LabelSpec, error)
type NewLabelFunc func(Label *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error)
type SaveLabelFunc func(label *fleet.Label) (*fleet.Label, error)
type DeleteLabelFunc func(name string) error
type LabelFunc func(lid uint) (*fleet.Label, error)
type ListLabelsFunc func(filter fleet.TeamFilter, opt fleet.ListOptions) ([]*fleet.Label, error)
type LabelQueriesForHostFunc func(host *fleet.Host, cutoff time.Time) (map[string]string, error)
type RecordLabelQueryExecutionsFunc func(host *fleet.Host, results map[uint]*bool, t time.Time) error
type ListLabelsForHostFunc func(hid uint) ([]*fleet.Label, error)
type ListHostsInLabelFunc func(filter fleet.TeamFilter, lid uint, opt fleet.HostListOptions) ([]*fleet.Host, error)
type ListUniqueHostsInLabelsFunc func(filter fleet.TeamFilter, labels []uint) ([]*fleet.Host, error)
type SearchLabelsFunc func(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Label, error)
type LabelIDsByNameFunc func(labels []string) ([]uint, error)
type LabelStore struct {
ApplyLabelSpecsFunc ApplyLabelSpecsFunc
ApplyLabelSpecsFuncInvoked bool
GetLabelSpecsFunc GetLabelSpecsFunc
GetLabelSpecsFuncInvoked bool
GetLabelSpecFunc GetLabelSpecFunc
GetLabelSpecFuncInvoked bool
NewLabelFunc NewLabelFunc
NewLabelFuncInvoked bool
SaveLabelFunc SaveLabelFunc
SaveLabelFuncInvoked bool
DeleteLabelFunc DeleteLabelFunc
DeleteLabelFuncInvoked bool
LabelFunc LabelFunc
LabelFuncInvoked bool
ListLabelsFunc ListLabelsFunc
ListLabelsFuncInvoked bool
LabelQueriesForHostFunc LabelQueriesForHostFunc
LabelQueriesForHostFuncInvoked bool
RecordLabelQueryExecutionsFunc RecordLabelQueryExecutionsFunc
RecordLabelQueryExecutionsFuncInvoked bool
ListLabelsForHostFunc ListLabelsForHostFunc
ListLabelsForHostFuncInvoked bool
ListHostsInLabelFunc ListHostsInLabelFunc
ListHostsInLabelFuncInvoked bool
ListUniqueHostsInLabelsFunc ListUniqueHostsInLabelsFunc
ListUniqueHostsInLabelsFuncInvoked bool
SearchLabelsFunc SearchLabelsFunc
SearchLabelsFuncInvoked bool
LabelIDsByNameFunc LabelIDsByNameFunc
LabelIDsByNameFuncInvoked bool
}
func (s *LabelStore) ApplyLabelSpecs(specs []*fleet.LabelSpec) error {
s.ApplyLabelSpecsFuncInvoked = true
return s.ApplyLabelSpecsFunc(specs)
}
func (s *LabelStore) GetLabelSpecs() ([]*fleet.LabelSpec, error) {
s.GetLabelSpecsFuncInvoked = true
return s.GetLabelSpecsFunc()
}
func (s *LabelStore) GetLabelSpec(name string) (*fleet.LabelSpec, error) {
s.GetLabelSpecFuncInvoked = true
return s.GetLabelSpecFunc(name)
}
func (s *LabelStore) NewLabel(Label *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
s.NewLabelFuncInvoked = true
return s.NewLabelFunc(Label, opts...)
}
func (s *LabelStore) SaveLabel(label *fleet.Label) (*fleet.Label, error) {
s.SaveLabelFuncInvoked = true
return s.SaveLabelFunc(label)
}
func (s *LabelStore) DeleteLabel(name string) error {
s.DeleteLabelFuncInvoked = true
return s.DeleteLabelFunc(name)
}
func (s *LabelStore) Label(lid uint) (*fleet.Label, error) {
s.LabelFuncInvoked = true
return s.LabelFunc(lid)
}
func (s *LabelStore) ListLabels(filter fleet.TeamFilter, opt fleet.ListOptions) ([]*fleet.Label, error) {
s.ListLabelsFuncInvoked = true
return s.ListLabelsFunc(filter, opt)
}
func (s *LabelStore) LabelQueriesForHost(host *fleet.Host, cutoff time.Time) (map[string]string, error) {
s.LabelQueriesForHostFuncInvoked = true
return s.LabelQueriesForHostFunc(host, cutoff)
}
func (s *LabelStore) RecordLabelQueryExecutions(host *fleet.Host, results map[uint]*bool, t time.Time) error {
s.RecordLabelQueryExecutionsFuncInvoked = true
return s.RecordLabelQueryExecutionsFunc(host, results, t)
}
func (s *LabelStore) ListLabelsForHost(hid uint) ([]*fleet.Label, error) {
s.ListLabelsForHostFuncInvoked = true
return s.ListLabelsForHostFunc(hid)
}
func (s *LabelStore) ListHostsInLabel(filter fleet.TeamFilter, lid uint, opt fleet.HostListOptions) ([]*fleet.Host, error) {
s.ListHostsInLabelFuncInvoked = true
return s.ListHostsInLabelFunc(filter, lid, opt)
}
func (s *LabelStore) ListUniqueHostsInLabels(filter fleet.TeamFilter, labels []uint) ([]*fleet.Host, error) {
s.ListUniqueHostsInLabelsFuncInvoked = true
return s.ListUniqueHostsInLabelsFunc(filter, labels)
}
func (s *LabelStore) SearchLabels(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Label, error) {
s.SearchLabelsFuncInvoked = true
return s.SearchLabelsFunc(filter, query, omit...)
}
func (s *LabelStore) LabelIDsByName(labels []string) ([]uint, error) {
s.LabelIDsByNameFuncInvoked = true
return s.LabelIDsByNameFunc(labels)
}
File diff suppressed because it is too large Load Diff
-129
View File
@@ -1,129 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.PackStore = (*PackStore)(nil)
type ApplyPackSpecsFunc func(specs []*fleet.PackSpec) error
type GetPackSpecsFunc func() ([]*fleet.PackSpec, error)
type GetPackSpecFunc func(name string) (*fleet.PackSpec, error)
type NewPackFunc func(pack *fleet.Pack, opts ...fleet.OptionalArg) (*fleet.Pack, error)
type SavePackFunc func(pack *fleet.Pack) error
type DeletePackFunc func(name string) error
type PackFunc func(pid uint) (*fleet.Pack, error)
type ListPacksFunc func(opt fleet.PackListOptions) ([]*fleet.Pack, error)
type PackByNameFunc func(name string, opts ...fleet.OptionalArg) (*fleet.Pack, bool, error)
type ListPacksForHostFunc func(hid uint) (packs []*fleet.Pack, err error)
type EnsureGlobalPackFunc func() (*fleet.Pack, error)
type EnsureTeamPackFunc func(teamID uint) (*fleet.Pack, error)
type PackStore struct {
ApplyPackSpecsFunc ApplyPackSpecsFunc
ApplyPackSpecsFuncInvoked bool
GetPackSpecsFunc GetPackSpecsFunc
GetPackSpecsFuncInvoked bool
GetPackSpecFunc GetPackSpecFunc
GetPackSpecFuncInvoked bool
NewPackFunc NewPackFunc
NewPackFuncInvoked bool
SavePackFunc SavePackFunc
SavePackFuncInvoked bool
DeletePackFunc DeletePackFunc
DeletePackFuncInvoked bool
PackFunc PackFunc
PackFuncInvoked bool
ListPacksFunc ListPacksFunc
ListPacksFuncInvoked bool
PackByNameFunc PackByNameFunc
PackByNameFuncInvoked bool
ListPacksForHostFunc ListPacksForHostFunc
ListPacksForHostFuncInvoked bool
EnsureGlobalPackFunc EnsureGlobalPackFunc
EnsureGlobalPackFuncInvoked bool
EnsureTeamPackFunc EnsureTeamPackFunc
EnsureTeamPackFuncInvoked bool
}
func (s *PackStore) ApplyPackSpecs(specs []*fleet.PackSpec) error {
s.ApplyPackSpecsFuncInvoked = true
return s.ApplyPackSpecsFunc(specs)
}
func (s *PackStore) GetPackSpecs() ([]*fleet.PackSpec, error) {
s.GetPackSpecsFuncInvoked = true
return s.GetPackSpecsFunc()
}
func (s *PackStore) GetPackSpec(name string) (*fleet.PackSpec, error) {
s.GetPackSpecFuncInvoked = true
return s.GetPackSpecFunc(name)
}
func (s *PackStore) NewPack(pack *fleet.Pack, opts ...fleet.OptionalArg) (*fleet.Pack, error) {
s.NewPackFuncInvoked = true
return s.NewPackFunc(pack, opts...)
}
func (s *PackStore) SavePack(pack *fleet.Pack) error {
s.SavePackFuncInvoked = true
return s.SavePackFunc(pack)
}
func (s *PackStore) DeletePack(name string) error {
s.DeletePackFuncInvoked = true
return s.DeletePackFunc(name)
}
func (s *PackStore) Pack(pid uint) (*fleet.Pack, error) {
s.PackFuncInvoked = true
return s.PackFunc(pid)
}
func (s *PackStore) ListPacks(opt fleet.PackListOptions) ([]*fleet.Pack, error) {
s.ListPacksFuncInvoked = true
return s.ListPacksFunc(opt)
}
func (s *PackStore) PackByName(name string, opts ...fleet.OptionalArg) (*fleet.Pack, bool, error) {
s.PackByNameFuncInvoked = true
return s.PackByNameFunc(name, opts...)
}
func (s *PackStore) ListPacksForHost(hid uint) (packs []*fleet.Pack, err error) {
s.ListPacksForHostFuncInvoked = true
return s.ListPacksForHostFunc(hid)
}
func (s *PackStore) EnsureGlobalPack() (*fleet.Pack, error) {
s.EnsureGlobalPackFuncInvoked = true
return s.EnsureGlobalPackFunc()
}
func (s *PackStore) EnsureTeamPack(teamID uint) (*fleet.Pack, error) {
s.EnsureTeamPackFuncInvoked = true
return s.EnsureTeamPackFunc(teamID)
}
-73
View File
@@ -1,73 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import (
"time"
"github.com/fleetdm/fleet/v4/server/fleet"
)
var _ fleet.GlobalPoliciesStore = (*GlobalPoliciesStore)(nil)
type NewGlobalPolicyFunc func(queryID uint) (*fleet.Policy, error)
type PolicyFunc func(id uint) (*fleet.Policy, error)
type RecordPolicyQueryExecutionsFunc func(host *fleet.Host, results map[uint]*bool, updated time.Time) error
type ListGlobalPoliciesFunc func() ([]*fleet.Policy, error)
type DeleteGlobalPoliciesFunc func(ids []uint) ([]uint, error)
type PolicyQueriesForHostFunc func(host *fleet.Host) (map[string]string, error)
type GlobalPoliciesStore struct {
NewGlobalPolicyFunc NewGlobalPolicyFunc
NewGlobalPolicyFuncInvoked bool
PolicyFunc PolicyFunc
PolicyFuncInvoked bool
RecordPolicyQueryExecutionsFunc RecordPolicyQueryExecutionsFunc
RecordPolicyQueryExecutionsFuncInvoked bool
ListGlobalPoliciesFunc ListGlobalPoliciesFunc
ListGlobalPoliciesFuncInvoked bool
DeleteGlobalPoliciesFunc DeleteGlobalPoliciesFunc
DeleteGlobalPoliciesFuncInvoked bool
PolicyQueriesForHostFunc PolicyQueriesForHostFunc
PolicyQueriesForHostFuncInvoked bool
}
func (s *GlobalPoliciesStore) NewGlobalPolicy(queryID uint) (*fleet.Policy, error) {
s.NewGlobalPolicyFuncInvoked = true
return s.NewGlobalPolicyFunc(queryID)
}
func (s *GlobalPoliciesStore) Policy(id uint) (*fleet.Policy, error) {
s.PolicyFuncInvoked = true
return s.PolicyFunc(id)
}
func (s *GlobalPoliciesStore) RecordPolicyQueryExecutions(host *fleet.Host, results map[uint]*bool, updated time.Time) error {
s.RecordPolicyQueryExecutionsFuncInvoked = true
return s.RecordPolicyQueryExecutionsFunc(host, results, updated)
}
func (s *GlobalPoliciesStore) ListGlobalPolicies() ([]*fleet.Policy, error) {
s.ListGlobalPoliciesFuncInvoked = true
return s.ListGlobalPoliciesFunc()
}
func (s *GlobalPoliciesStore) DeleteGlobalPolicies(ids []uint) ([]uint, error) {
s.DeleteGlobalPoliciesFuncInvoked = true
return s.DeleteGlobalPoliciesFunc(ids)
}
func (s *GlobalPoliciesStore) PolicyQueriesForHost(host *fleet.Host) (map[string]string, error) {
s.PolicyQueriesForHostFuncInvoked = true
return s.PolicyQueriesForHostFunc(host)
}
-89
View File
@@ -1,89 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.QueryStore = (*QueryStore)(nil)
type ApplyQueriesFunc func(authorID uint, queries []*fleet.Query) error
type NewQueryFunc func(query *fleet.Query, opts ...fleet.OptionalArg) (*fleet.Query, error)
type SaveQueryFunc func(query *fleet.Query) error
type DeleteQueryFunc func(name string) error
type DeleteQueriesFunc func(ids []uint) (uint, error)
type QueryFunc func(id uint) (*fleet.Query, error)
type ListQueriesFunc func(opt fleet.ListOptions) ([]*fleet.Query, error)
type QueryByNameFunc func(name string, opts ...fleet.OptionalArg) (*fleet.Query, error)
type QueryStore struct {
ApplyQueriesFunc ApplyQueriesFunc
ApplyQueriesFuncInvoked bool
NewQueryFunc NewQueryFunc
NewQueryFuncInvoked bool
SaveQueryFunc SaveQueryFunc
SaveQueryFuncInvoked bool
DeleteQueryFunc DeleteQueryFunc
DeleteQueryFuncInvoked bool
DeleteQueriesFunc DeleteQueriesFunc
DeleteQueriesFuncInvoked bool
QueryFunc QueryFunc
QueryFuncInvoked bool
ListQueriesFunc ListQueriesFunc
ListQueriesFuncInvoked bool
QueryByNameFunc QueryByNameFunc
QueryByNameFuncInvoked bool
}
func (s *QueryStore) ApplyQueries(authorID uint, queries []*fleet.Query) error {
s.ApplyQueriesFuncInvoked = true
return s.ApplyQueriesFunc(authorID, queries)
}
func (s *QueryStore) NewQuery(query *fleet.Query, opts ...fleet.OptionalArg) (*fleet.Query, error) {
s.NewQueryFuncInvoked = true
return s.NewQueryFunc(query, opts...)
}
func (s *QueryStore) SaveQuery(query *fleet.Query) error {
s.SaveQueryFuncInvoked = true
return s.SaveQueryFunc(query)
}
func (s *QueryStore) DeleteQuery(name string) error {
s.DeleteQueryFuncInvoked = true
return s.DeleteQueryFunc(name)
}
func (s *QueryStore) DeleteQueries(ids []uint) (uint, error) {
s.DeleteQueriesFuncInvoked = true
return s.DeleteQueriesFunc(ids)
}
func (s *QueryStore) Query(id uint) (*fleet.Query, error) {
s.QueryFuncInvoked = true
return s.QueryFunc(id)
}
func (s *QueryStore) ListQueries(opt fleet.ListOptions) ([]*fleet.Query, error) {
s.ListQueriesFuncInvoked = true
return s.ListQueriesFunc(opt)
}
func (s *QueryStore) QueryByName(name string, opts ...fleet.OptionalArg) (*fleet.Query, error) {
s.QueryByNameFuncInvoked = true
return s.QueryByNameFunc(name, opts...)
}
@@ -1,69 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.ScheduledQueryStore = (*ScheduledQueryStore)(nil)
type ListScheduledQueriesInPackFunc func(id uint, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error)
type NewScheduledQueryFunc func(sq *fleet.ScheduledQuery, opts ...fleet.OptionalArg) (*fleet.ScheduledQuery, error)
type SaveScheduledQueryFunc func(sq *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error)
type DeleteScheduledQueryFunc func(id uint) error
type ScheduledQueryFunc func(id uint) (*fleet.ScheduledQuery, error)
type CleanupOrphanScheduledQueryStatsFunc func() error
type ScheduledQueryStore struct {
ListScheduledQueriesInPackFunc ListScheduledQueriesInPackFunc
ListScheduledQueriesInPackFuncInvoked bool
NewScheduledQueryFunc NewScheduledQueryFunc
NewScheduledQueryFuncInvoked bool
SaveScheduledQueryFunc SaveScheduledQueryFunc
SaveScheduledQueryFuncInvoked bool
DeleteScheduledQueryFunc DeleteScheduledQueryFunc
DeleteScheduledQueryFuncInvoked bool
ScheduledQueryFunc ScheduledQueryFunc
ScheduledQueryFuncInvoked bool
CleanupOrphanScheduledQueryStatsFunc CleanupOrphanScheduledQueryStatsFunc
CleanupOrphanScheduledQueryStatsFuncInvoked bool
}
func (s *ScheduledQueryStore) ListScheduledQueriesInPack(id uint, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {
s.ListScheduledQueriesInPackFuncInvoked = true
return s.ListScheduledQueriesInPackFunc(id, opts)
}
func (s *ScheduledQueryStore) NewScheduledQuery(sq *fleet.ScheduledQuery, opts ...fleet.OptionalArg) (*fleet.ScheduledQuery, error) {
s.NewScheduledQueryFuncInvoked = true
return s.NewScheduledQueryFunc(sq, opts...)
}
func (s *ScheduledQueryStore) SaveScheduledQuery(sq *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {
s.SaveScheduledQueryFuncInvoked = true
return s.SaveScheduledQueryFunc(sq)
}
func (s *ScheduledQueryStore) DeleteScheduledQuery(id uint) error {
s.DeleteScheduledQueryFuncInvoked = true
return s.DeleteScheduledQueryFunc(id)
}
func (s *ScheduledQueryStore) ScheduledQuery(id uint) (*fleet.ScheduledQuery, error) {
s.ScheduledQueryFuncInvoked = true
return s.ScheduledQueryFunc(id)
}
func (s *ScheduledQueryStore) CleanupOrphanScheduledQueryStats() error {
s.CleanupOrphanScheduledQueryStatsFuncInvoked = true
return s.CleanupOrphanScheduledQueryStatsFunc()
}
-79
View File
@@ -1,79 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.SessionStore = (*SessionStore)(nil)
type SessionByKeyFunc func(key string) (*fleet.Session, error)
type SessionByIDFunc func(id uint) (*fleet.Session, error)
type ListSessionsForUserFunc func(id uint) ([]*fleet.Session, error)
type NewSessionFunc func(session *fleet.Session) (*fleet.Session, error)
type DestroySessionFunc func(session *fleet.Session) error
type DestroyAllSessionsForUserFunc func(id uint) error
type MarkSessionAccessedFunc func(session *fleet.Session) error
type SessionStore struct {
SessionByKeyFunc SessionByKeyFunc
SessionByKeyFuncInvoked bool
SessionByIDFunc SessionByIDFunc
SessionByIDFuncInvoked bool
ListSessionsForUserFunc ListSessionsForUserFunc
ListSessionsForUserFuncInvoked bool
NewSessionFunc NewSessionFunc
NewSessionFuncInvoked bool
DestroySessionFunc DestroySessionFunc
DestroySessionFuncInvoked bool
DestroyAllSessionsForUserFunc DestroyAllSessionsForUserFunc
DestroyAllSessionsForUserFuncInvoked bool
MarkSessionAccessedFunc MarkSessionAccessedFunc
MarkSessionAccessedFuncInvoked bool
}
func (s *SessionStore) SessionByKey(key string) (*fleet.Session, error) {
s.SessionByKeyFuncInvoked = true
return s.SessionByKeyFunc(key)
}
func (s *SessionStore) SessionByID(id uint) (*fleet.Session, error) {
s.SessionByIDFuncInvoked = true
return s.SessionByIDFunc(id)
}
func (s *SessionStore) ListSessionsForUser(id uint) ([]*fleet.Session, error) {
s.ListSessionsForUserFuncInvoked = true
return s.ListSessionsForUserFunc(id)
}
func (s *SessionStore) NewSession(session *fleet.Session) (*fleet.Session, error) {
s.NewSessionFuncInvoked = true
return s.NewSessionFunc(session)
}
func (s *SessionStore) DestroySession(session *fleet.Session) error {
s.DestroySessionFuncInvoked = true
return s.DestroySessionFunc(session)
}
func (s *SessionStore) DestroyAllSessionsForUser(id uint) error {
s.DestroyAllSessionsForUserFuncInvoked = true
return s.DestroyAllSessionsForUserFunc(id)
}
func (s *SessionStore) MarkSessionAccessed(session *fleet.Session) error {
s.MarkSessionAccessedFuncInvoked = true
return s.MarkSessionAccessedFunc(session)
}
-69
View File
@@ -1,69 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.SoftwareStore = (*SoftwareStore)(nil)
type SaveHostSoftwareFunc func(host *fleet.Host) error
type LoadHostSoftwareFunc func(host *fleet.Host) error
type AllSoftwareWithoutCPEIteratorFunc func() (fleet.SoftwareIterator, error)
type AddCPEForSoftwareFunc func(software fleet.Software, cpe string) error
type AllCPEsFunc func() ([]string, error)
type InsertCVEForCPEFunc func(cve string, cpes []string) error
type SoftwareStore struct {
SaveHostSoftwareFunc SaveHostSoftwareFunc
SaveHostSoftwareFuncInvoked bool
LoadHostSoftwareFunc LoadHostSoftwareFunc
LoadHostSoftwareFuncInvoked bool
AllSoftwareWithoutCPEIteratorFunc AllSoftwareWithoutCPEIteratorFunc
AllSoftwareWithoutCPEIteratorFuncInvoked bool
AddCPEForSoftwareFunc AddCPEForSoftwareFunc
AddCPEForSoftwareFuncInvoked bool
AllCPEsFunc AllCPEsFunc
AllCPEsFuncInvoked bool
InsertCVEForCPEFunc InsertCVEForCPEFunc
InsertCVEForCPEFuncInvoked bool
}
func (s *SoftwareStore) SaveHostSoftware(host *fleet.Host) error {
s.SaveHostSoftwareFuncInvoked = true
return s.SaveHostSoftwareFunc(host)
}
func (s *SoftwareStore) LoadHostSoftware(host *fleet.Host) error {
s.LoadHostSoftwareFuncInvoked = true
return s.LoadHostSoftwareFunc(host)
}
func (s *SoftwareStore) AllSoftwareWithoutCPEIterator() (fleet.SoftwareIterator, error) {
s.AllSoftwareWithoutCPEIteratorFuncInvoked = true
return s.AllSoftwareWithoutCPEIteratorFunc()
}
func (s *SoftwareStore) AddCPEForSoftware(software fleet.Software, cpe string) error {
s.AddCPEForSoftwareFuncInvoked = true
return s.AddCPEForSoftwareFunc(software, cpe)
}
func (s *SoftwareStore) AllCPEs() ([]string, error) {
s.AllCPEsFuncInvoked = true
return s.AllCPEsFunc()
}
func (s *SoftwareStore) InsertCVEForCPE(cve string, cpes []string) error {
s.InsertCVEForCPEFuncInvoked = true
return s.InsertCVEForCPEFunc(cve, cpes)
}
-33
View File
@@ -1,33 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import (
"time"
"github.com/fleetdm/fleet/v4/server/fleet"
)
var _ fleet.StatisticsStore = (*StatisticsStore)(nil)
type ShouldSendStatisticsFunc func(frequency time.Duration) (fleet.StatisticsPayload, bool, error)
type RecordStatisticsSentFunc func() error
type StatisticsStore struct {
ShouldSendStatisticsFunc ShouldSendStatisticsFunc
ShouldSendStatisticsFuncInvoked bool
RecordStatisticsSentFunc RecordStatisticsSentFunc
RecordStatisticsSentFuncInvoked bool
}
func (s *StatisticsStore) ShouldSendStatistics(frequency time.Duration) (fleet.StatisticsPayload, bool, error) {
s.ShouldSendStatisticsFuncInvoked = true
return s.ShouldSendStatisticsFunc(frequency)
}
func (s *StatisticsStore) RecordStatisticsSent() error {
s.RecordStatisticsSentFuncInvoked = true
return s.RecordStatisticsSentFunc()
}
-33
View File
@@ -1,33 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import (
"time"
"github.com/fleetdm/fleet/v4/server/fleet"
)
var _ fleet.TargetStore = (*TargetStore)(nil)
type CountHostsInTargetsFunc func(filter fleet.TeamFilter, targets fleet.HostTargets, now time.Time) (fleet.TargetMetrics, error)
type HostIDsInTargetsFunc func(filter fleet.TeamFilter, targets fleet.HostTargets) ([]uint, error)
type TargetStore struct {
CountHostsInTargetsFunc CountHostsInTargetsFunc
CountHostsInTargetsFuncInvoked bool
HostIDsInTargetsFunc HostIDsInTargetsFunc
HostIDsInTargetsFuncInvoked bool
}
func (s *TargetStore) CountHostsInTargets(filter fleet.TeamFilter, targets fleet.HostTargets, now time.Time) (fleet.TargetMetrics, error) {
s.CountHostsInTargetsFuncInvoked = true
return s.CountHostsInTargetsFunc(filter, targets, now)
}
func (s *TargetStore) HostIDsInTargets(filter fleet.TeamFilter, targets fleet.HostTargets) ([]uint, error) {
s.HostIDsInTargetsFuncInvoked = true
return s.HostIDsInTargetsFunc(filter, targets)
}
-89
View File
@@ -1,89 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.TeamStore = (*TeamStore)(nil)
type NewTeamFunc func(team *fleet.Team) (*fleet.Team, error)
type SaveTeamFunc func(team *fleet.Team) (*fleet.Team, error)
type TeamFunc func(tid uint) (*fleet.Team, error)
type DeleteTeamFunc func(tid uint) error
type TeamByNameFunc func(name string) (*fleet.Team, error)
type ListTeamsFunc func(filter fleet.TeamFilter, opt fleet.ListOptions) ([]*fleet.Team, error)
type SearchTeamsFunc func(filter fleet.TeamFilter, matchQuery string, omit ...uint) ([]*fleet.Team, error)
type TeamEnrollSecretsFunc func(teamID uint) ([]*fleet.EnrollSecret, error)
type TeamStore struct {
NewTeamFunc NewTeamFunc
NewTeamFuncInvoked bool
SaveTeamFunc SaveTeamFunc
SaveTeamFuncInvoked bool
TeamFunc TeamFunc
TeamFuncInvoked bool
DeleteTeamFunc DeleteTeamFunc
DeleteTeamFuncInvoked bool
TeamByNameFunc TeamByNameFunc
TeamByNameFuncInvoked bool
ListTeamsFunc ListTeamsFunc
ListTeamsFuncInvoked bool
SearchTeamsFunc SearchTeamsFunc
SearchTeamsFuncInvoked bool
TeamEnrollSecretsFunc TeamEnrollSecretsFunc
TeamEnrollSecretsFuncInvoked bool
}
func (s *TeamStore) NewTeam(team *fleet.Team) (*fleet.Team, error) {
s.NewTeamFuncInvoked = true
return s.NewTeamFunc(team)
}
func (s *TeamStore) SaveTeam(team *fleet.Team) (*fleet.Team, error) {
s.SaveTeamFuncInvoked = true
return s.SaveTeamFunc(team)
}
func (s *TeamStore) Team(tid uint) (*fleet.Team, error) {
s.TeamFuncInvoked = true
return s.TeamFunc(tid)
}
func (s *TeamStore) DeleteTeam(tid uint) error {
s.DeleteTeamFuncInvoked = true
return s.DeleteTeamFunc(tid)
}
func (s *TeamStore) TeamByName(name string) (*fleet.Team, error) {
s.TeamByNameFuncInvoked = true
return s.TeamByNameFunc(name)
}
func (s *TeamStore) ListTeams(filter fleet.TeamFilter, opt fleet.ListOptions) ([]*fleet.Team, error) {
s.ListTeamsFuncInvoked = true
return s.ListTeamsFunc(filter, opt)
}
func (s *TeamStore) SearchTeams(filter fleet.TeamFilter, matchQuery string, omit ...uint) ([]*fleet.Team, error) {
s.SearchTeamsFuncInvoked = true
return s.SearchTeamsFunc(filter, matchQuery, omit...)
}
func (s *TeamStore) TeamEnrollSecrets(teamID uint) ([]*fleet.EnrollSecret, error) {
s.TeamEnrollSecretsFuncInvoked = true
return s.TeamEnrollSecretsFunc(teamID)
}
-99
View File
@@ -1,99 +0,0 @@
// Automatically generated by mockimpl. DO NOT EDIT!
package mock
import "github.com/fleetdm/fleet/v4/server/fleet"
var _ fleet.UserStore = (*UserStore)(nil)
type NewUserFunc func(user *fleet.User) (*fleet.User, error)
type ListUsersFunc func(opt fleet.UserListOptions) ([]*fleet.User, error)
type UserByEmailFunc func(email string) (*fleet.User, error)
type UserByIDFunc func(id uint) (*fleet.User, error)
type SaveUserFunc func(user *fleet.User) error
type SaveUsersFunc func(users []*fleet.User) error
type DeleteUserFunc func(id uint) error
type PendingEmailChangeFunc func(userID uint, newEmail string, token string) error
type ConfirmPendingEmailChangeFunc func(userID uint, token string) (string, error)
type UserStore struct {
NewUserFunc NewUserFunc
NewUserFuncInvoked bool
ListUsersFunc ListUsersFunc
ListUsersFuncInvoked bool
UserByEmailFunc UserByEmailFunc
UserByEmailFuncInvoked bool
UserByIDFunc UserByIDFunc
UserByIDFuncInvoked bool
SaveUserFunc SaveUserFunc
SaveUserFuncInvoked bool
SaveUsersFunc SaveUsersFunc
SaveUsersFuncInvoked bool
DeleteUserFunc DeleteUserFunc
DeleteUserFuncInvoked bool
PendingEmailChangeFunc PendingEmailChangeFunc
PendingEmailChangeFuncInvoked bool
ConfirmPendingEmailChangeFunc ConfirmPendingEmailChangeFunc
ConfirmPendingEmailChangeFuncInvoked bool
}
func (s *UserStore) NewUser(user *fleet.User) (*fleet.User, error) {
s.NewUserFuncInvoked = true
return s.NewUserFunc(user)
}
func (s *UserStore) ListUsers(opt fleet.UserListOptions) ([]*fleet.User, error) {
s.ListUsersFuncInvoked = true
return s.ListUsersFunc(opt)
}
func (s *UserStore) UserByEmail(email string) (*fleet.User, error) {
s.UserByEmailFuncInvoked = true
return s.UserByEmailFunc(email)
}
func (s *UserStore) UserByID(id uint) (*fleet.User, error) {
s.UserByIDFuncInvoked = true
return s.UserByIDFunc(id)
}
func (s *UserStore) SaveUser(user *fleet.User) error {
s.SaveUserFuncInvoked = true
return s.SaveUserFunc(user)
}
func (s *UserStore) SaveUsers(users []*fleet.User) error {
s.SaveUsersFuncInvoked = true
return s.SaveUsersFunc(users)
}
func (s *UserStore) DeleteUser(id uint) error {
s.DeleteUserFuncInvoked = true
return s.DeleteUserFunc(id)
}
func (s *UserStore) PendingEmailChange(userID uint, newEmail string, token string) error {
s.PendingEmailChangeFuncInvoked = true
return s.PendingEmailChangeFunc(userID, newEmail, token)
}
func (s *UserStore) ConfirmPendingEmailChange(userID uint, token string) (string, error) {
s.ConfirmPendingEmailChangeFuncInvoked = true
return s.ConfirmPendingEmailChangeFunc(userID, token)
}
+2 -2
View File
@@ -8,12 +8,12 @@ func (e *Error) Error() string {
return e.Message
}
// implement fleet.NotFoundError
// IsNotFound implements fleet.NotFoundError
func (e *Error) IsNotFound() bool {
return true
}
// implement fleet.AlreadyExistsError
// IsExists implements fleet.AlreadyExistsError
func (e *Error) IsExists() bool {
return true
}
+3 -3
View File
@@ -79,9 +79,9 @@ func makeGetAppConfigEndpoint(svc fleet.Service) endpoint.Endpoint {
HostExpirySettings: hostExpirySettings,
AgentOptions: agentOptions,
},
UpdateInterval: updateIntervalConfig,
License: license,
Logging: loggingConfig,
UpdateInterval: updateIntervalConfig,
License: license,
Logging: loggingConfig,
}
return response, nil
}
+4 -3
View File
@@ -18,9 +18,10 @@ import (
func TestInviteNewUserMock(t *testing.T) {
ms := new(mock.Store)
ms.UserByEmailFunc = mock.UserWithEmailNotFound()
ms.AppConfigFunc = mock.ReturnFakeAppConfig(&fleet.AppConfig{
ServerSettings: fleet.ServerSettings{ServerURL: "https://acme.co"},
})
ms.AppConfigFunc = func() (*fleet.AppConfig, error) {
return &fleet.AppConfig{ServerSettings: fleet.ServerSettings{ServerURL: "https://acme.co"}}, nil
}
ms.NewInviteFunc = func(i *fleet.Invite) (*fleet.Invite, error) {
return i, nil
}
+3 -6
View File
@@ -912,12 +912,9 @@ func TestDetailQueries(t *testing.T) {
}
func TestNewDistributedQueryCampaign(t *testing.T) {
ds := &mock.Store{
AppConfigStore: mock.AppConfigStore{
AppConfigFunc: func() (*fleet.AppConfig, error) {
return &fleet.AppConfig{}, nil
},
},
ds := new(mock.Store)
ds.AppConfigFunc = func() (*fleet.AppConfig, error) {
return &fleet.AppConfig{}, nil
}
rs := &mock.QueryResultStore{
HealthCheckFunc: func() error {