types

package
v0.28.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Guardrail targets.
	GuardrailTargetLLM = "llm"
	GuardrailTargetMCP = "mcp"

	// Guardrail stages a policy applies to.
	GuardrailApplyInput  = "input"
	GuardrailApplyOutput = "output"
	GuardrailApplyBoth   = "both"

	// Guardrail actions.
	GuardrailActionBlock  = "block"
	GuardrailActionRedact = "redact"
	GuardrailActionLog    = "log"

	// Guardrail input scopes.
	GuardrailScopeAll    = "all"
	GuardrailScopeLatest = "latest"
)
View Source
const (
	LLMAuditOutcomeSuccess  = "success"
	LLMAuditOutcomeCanceled = "canceled"
	LLMAuditOutcomeError    = "error"
)
View Source
const (
	// Subject types of MCP guardrail filters.
	LLMGatewayBudgetSubjectUser     = "user"
	LLMGatewayBudgetSubjectGroup    = "group"
	LLMGatewayBudgetSubjectEveryone = "everyone"

	// LLM gateway budget limit metrics.
	LLMGatewayBudgetMetricSpend        = "spend"
	LLMGatewayBudgetMetricTokens       = "tokens"
	LLMGatewayBudgetMetricInputTokens  = "input_tokens"
	LLMGatewayBudgetMetricOutputTokens = "output_tokens"
	LLMGatewayBudgetMetricRequests     = "requests"
)
View Source
const (
	// SCIMConnectionStateConnected means SCIM provisions users and groups, and has replaced login-time directory
	// synchronization, but users that SCIM has not provisioned can still sign in.
	SCIMConnectionStateConnected SCIMConnectionState = "connected"
	// SCIMConnectionStateEnforced means sign-in requires a SCIM binding.
	SCIMConnectionStateEnforced SCIMConnectionState = "enforced"

	// SCIMConnectionOriginSCIMFirst means the connection was created when its auth provider was configured without
	// directory credentials, so the provider never synchronized its directory at sign-in.
	SCIMConnectionOriginSCIMFirst SCIMConnectionOrigin = "scim_first"
	// SCIMConnectionOriginMigrated means the connection replaced the login-time directory synchronization of an auth
	// provider that was already configured.
	SCIMConnectionOriginMigrated SCIMConnectionOrigin = "migrated"

	// SCIMGroupBindingOriginExisting means the binding took over a group that existed before the identity provider
	// pushed it, keeping its ID.
	SCIMGroupBindingOriginExisting SCIMGroupBindingOrigin = "existing"
	// SCIMGroupBindingOriginCreated means SCIM created the group when the identity provider pushed it.
	SCIMGroupBindingOriginCreated SCIMGroupBindingOrigin = "created"

	SCIMResourceTypeUser  SCIMResourceType = "User"
	SCIMResourceTypeGroup SCIMResourceType = "Group"

	// SCIMTokenLifetime is how long a bearer token is accepted after it is issued. The identity provider keeps the
	// token for as long as provisioning runs, so this bounds how long a leaked token that nobody revoked keeps
	// working. A token must be rotated before it expires.
	SCIMTokenLifetime = 365 * 24 * time.Hour
)
View Source
const (
	TokenRequestPurposeDeviceLogin = "device-login"
	TokenRequestPurposeSetup       = "setup"

	// TokenRequestPurposeAuthProviderVerify backs the one-time login used to prove a staged
	// replacement auth provider works before it is activated.
	TokenRequestPurposeAuthProviderVerify = "auth-provider-verify"
)
View Source
const (
	DevicePrincipalPrefix = "device"
)

DevicePrincipalPrefix namespaces the principal identity (Name/UID) of an enrolled device so it never collides with user UIDs or configuration principals.

View Source
const (
	MDMConfigurationPrincipalPrefix = "mdm-configuration"
)

MDMConfigurationPrincipalPrefix namespaces the principal identity (Name/UID) of a MDM configuration so it never collides with user UIDs or device principals. An enrollment credential authenticates as its configuration.

Variables

View Source
var (
	// UserLifecycleColumns are the user columns that only lifecycle operations write. Every other user write
	// omits them, so that a stale copy of a user can neither disable nor re-enable the account.
	UserLifecycleColumns = []string{"disabled_at", "disabled_reason"}
)

Functions

func ConvertAPIActivity added in v0.7.1

func ConvertAPIActivity(a APIActivity) types2.APIActivity

func ConvertDevice added in v0.24.0

func ConvertDevice(d Device) types2.Device

ConvertDevice maps a gateway device record to its API representation, dropping the registered public key.

func ConvertDeviceScan added in v0.22.0

func ConvertDeviceScan(s DeviceScan) types2.DeviceScan

ConvertDeviceScan converts internal DeviceScan to API type. Children must already be loaded (via Preload) for them to appear in the result.

func ConvertDeviceScanClient added in v0.22.0

func ConvertDeviceScanClient(c DeviceScanClient) types2.DeviceScanClient

func ConvertDeviceScanFile added in v0.22.0

func ConvertDeviceScanFile(f DeviceScanFile) types2.DeviceScanFile

ConvertDeviceScanFile converts a stored file row to its wire form. Content is included only when the file wasn't flagged as oversized.

func ConvertDeviceScanMCPServer added in v0.22.0

func ConvertDeviceScanMCPServer(m DeviceScanMCPServer) types2.DeviceScanMCPServer

func ConvertDeviceScanPlugin added in v0.22.0

func ConvertDeviceScanPlugin(p DeviceScanPlugin) types2.DeviceScanPlugin

func ConvertDeviceScanSkill added in v0.22.0

func ConvertDeviceScanSkill(s DeviceScanSkill) types2.DeviceScanSkill

func ConvertLLMAuditLog added in v0.24.0

func ConvertLLMAuditLog(a LLMAuditLog) types2.LLMAuditLog

func ConvertMCPUsageStats added in v0.8.0

func ConvertMCPUsageStats(s MCPUsageStatItem) types2.MCPUsageStatItem

ConvertMCPUsageStats converts internal MCPUsageStatItem to API type

func ConvertTokenActivity added in v0.8.0

func ConvertTokenActivity(a RunTokenActivity) types2.TokenUsage

func ConvertUser

func ConvertUser(u *User, authProviderName string) *types2.User

func ConvertUserWithEffectiveRole added in v0.15.0

func ConvertUserWithEffectiveRole(u *User, authProviderName string, effectiveRole types2.Role) *types2.User

func DevicePrincipalName added in v0.24.0

func DevicePrincipalName(deviceID string) string

DevicePrincipalName returns the stable principal identity for an enrolled device, e.g. "device:abc-123". This is what a device authenticates as when submitting a scan; the scan itself is identified by DeviceScan.DeviceID (device submissions leave SubmittedBy empty).

func MDMConfigurationPrincipalName added in v0.24.0

func MDMConfigurationPrincipalName(id uint) string

MDMConfigurationPrincipalName returns the stable principal identity for a configuration, e.g. "mdm-configuration:12".

func NormalizeSCIMGroupName added in v0.27.0

func NormalizeSCIMGroupName(name string) string

NormalizeSCIMGroupName trims and case-folds a SCIM group display name for comparison.

func SCIMUserNameKey added in v0.27.0

func SCIMUserNameKey(userName string) (string, error)

SCIMUserNameKey returns the key that SCIM userNames are compared and checked for uniqueness by, as RFC 7644 section 5 requires: the PRECIS UsernameCaseMapped profile of RFC 8265, applied to each whitespace-separated part of the userName, which maps full-width characters and case, and normalizes to NFC. It returns an error for a userName that the profile does not allow, such as one that is empty or has control characters.

Types

type APIActivity added in v0.7.1

type APIActivity struct {
	ID     uint
	UserID string    `gorm:"index:idx_api_activity_date_user,priority:2"`
	Date   time.Time `gorm:"index:idx_api_activity_date_user,priority:1"`
}

type APIKey added in v0.16.0

type APIKey struct {
	APIKeyScopes `json:",inline"`

	ID     uint `json:"id" gorm:"primaryKey;autoIncrement"`
	UserID uint `json:"userId" gorm:"index"`

	// ClaudeEnvironment is set only by the server when issuing runner credentials.
	ClaudeEnvironment bool `json:"-"`

	Name         string     `json:"name"`                  // User-provided name for the key
	Description  string     `json:"description,omitempty"` // Optional description
	HashedSecret string     `json:"-"`                     // bcrypt hash of the secret portion only
	CreatedAt    time.Time  `json:"createdAt"`
	LastUsedAt   *time.Time `json:"lastUsedAt,omitempty"`
	ExpiresAt    *time.Time `json:"expiresAt,omitempty"` // nil means no expiration
	RevokedAt    *time.Time `json:"revokedAt,omitempty" gorm:"index"`

	// OwnerStatus is the lifecycle status of the key's user, read during validation.
	OwnerStatus types.UserStatus `json:"-" gorm:"-"`
}

APIKey represents an API key for a user to access the Obot API. The key format is: ok1-<user_id>-<key_id>-<secret> Lookups are done by key ID (extracted from the token), then bcrypt.CompareHashAndPassword is used to verify the secret portion.

type APIKeyCreateResponse added in v0.16.0

type APIKeyCreateResponse struct {
	APIKey
	Key string `json:"key"` // The full key, only shown once
}

APIKeyCreateResponse is returned when creating an API key. This is the only time the full key is visible.

type APIKeyOwnerLifecycle added in v0.27.0

type APIKeyOwnerLifecycle struct {
	OwnerID         *uint
	OwnerDeletedAt  *time.Time
	OwnerDisabledAt *time.Time
}

APIKeyOwnerLifecycle is the lifecycle state of an API key's user, read with the key.

func (APIKeyOwnerLifecycle) Status added in v0.27.0

Status returns the owner's lifecycle status. An owner with no user row is treated as deleted.

type APIKeyScopes added in v0.23.0

type APIKeyScopes struct {
	CanAccessAPI         bool `json:"canAccessAPI" gorm:"default:false;not null"`
	CanAccessSkills      bool `json:"canAccessSkills" gorm:"default:false;not null"`
	CanAccessLLMProxy    bool `json:"canAccessLLMProxy" gorm:"default:false;not null"`
	CanAccessDeviceScans bool `json:"canAccessDeviceScans" gorm:"default:false;not null"`

	// MCPServerIDs contains resource names of MCPServers or VMCPs this key can access.
	// Supports all server types: single-user, multi-user, remote, and composite.
	// Use "*" as a wildcard to grant access to all servers the user can access.
	// This may be empty for skills-only API keys.
	MCPServerIDs []string `json:"mcpServerIds,omitempty" gorm:"serializer:json"`
}

func (APIKeyScopes) Groups added in v0.23.0

func (as APIKeyScopes) Groups(u *User) []string

func (APIKeyScopes) HasSomeScope added in v0.23.0

func (as APIKeyScopes) HasSomeScope() bool

type AuthToken

type AuthToken struct {
	ID                    string    `json:"id" gorm:"index:idx_id_hashed_token"`
	UserID                uint      `json:"-" gorm:"index"`
	AuthProviderNamespace string    `json:"-" gorm:"index"`
	AuthProviderName      string    `json:"-" gorm:"index"`
	AuthProviderUserID    string    `json:"-"`
	HashedToken           string    `json:"-" gorm:"index:idx_id_hashed_token"`
	CreatedAt             time.Time `json:"createdAt"`
	ExpiresAt             time.Time `json:"expiresAt,omitzero"`
	NoExpiration          bool      `json:"noExpiration"`
}

type ClaudeEgressSecret added in v0.27.0

type ClaudeEgressSecret struct {
	ID       string `json:"id"`
	Hostname string `json:"hostname"`
	Header   string `json:"header"`
	Value    string `json:"value,omitempty"`
}

ClaudeEgressSecret values are write-only in the API and stored separately on the environment.

type ClaudeEnvironment added in v0.27.0

type ClaudeEnvironment struct {
	EgressSecrets          []ClaudeEgressSecret       `gorm:"serializer:json" json:"egressSecrets,omitempty"`
	EgressSecretValues     map[string]string          `gorm:"serializer:json" json:"-"`
	EgressSecretsEncrypted bool                       `json:"-"`
	ID                     string                     `gorm:"primaryKey" json:"id"`
	DisplayName            string                     `json:"displayName"`
	OrganizationID         string                     `json:"organizationID"`
	EnvironmentID          string                     `gorm:"uniqueIndex" json:"environmentID"`
	Profiles               []ClaudeEnvironmentProfile `gorm:"serializer:json" json:"profiles"`
	Runtime                ClaudeRuntime              `gorm:"serializer:json" json:"runtime"`
	Revision               string                     `json:"-"`
	ClaudeTagUserID        string                     `json:"claudeTagUserID,omitempty"`
	ClaudeTagEnabled       bool                       `json:"claudeTagEnabled"`
}

type ClaudeEnvironmentProfile added in v0.27.0

type ClaudeEnvironmentProfile struct {
	AllowClaudeMCP bool                 `json:"allowClaudeMCP,omitempty"`
	EgressSecrets  []ClaudeEgressSecret `json:"egressSecrets,omitempty"`
	Name           string               `json:"name"`
	Subjects       []api.Subject        `json:"subjects"`
	MCPServerIDs   []string             `json:"mcpServerIDs"`
	EgressHosts    []string             `json:"egressHosts,omitempty"`
	AllowAllEgress bool                 `json:"allowAllEgress,omitempty"`
	Resources      ClaudeResources      `json:"resources"`
}

type ClaudeOrganizationAccount added in v0.27.0

type ClaudeOrganizationAccount struct {
	OrganizationID string `gorm:"primaryKey" json:"organizationID"`
	Account        string `gorm:"primaryKey" json:"account"`
	UUID           string `json:"uuid"`
	DisplayName    string `json:"displayName"`
	Email          string `json:"email"`
	UserID         string `json:"userID"`
}

ClaudeOrganizationAccount is an admin-managed or just-in-time identity mapping shared by every environment in an organization. Empty UserID explicitly leaves it unmapped.

type ClaudeResources added in v0.27.0

type ClaudeResources struct {
	ActorCPU             string `json:"actorCPU,omitempty"`
	ActorMemory          string `json:"actorMemory,omitempty"`
	IdleTimeoutMinutes   int    `json:"idleTimeoutMinutes,omitempty"`
	SessionRetentionDays int    `json:"sessionRetentionDays,omitempty"`
}

ClaudeResources can be overridden by profiles. Zero/empty values inherit the environment value; matching profiles are combined using the maximum per field.

type ClaudeRuntime added in v0.27.0

type ClaudeRuntime struct {
	ManagedSettings json.RawMessage `json:"managedSettings,omitempty"`
	Image           string          `json:"image"`
	WorkerImage     string          `json:"workerImage"`
	Worker          ClaudeWorker    `json:"worker"`
	AllowAllEgress  bool            `json:"allowAllEgress,omitempty"`
	// LLMProxy sends the environment's model requests through Obot's LLM proxy.
	LLMProxy    bool            `json:"llmProxy,omitempty"`
	EgressHosts []string        `json:"egressHosts"`
	Resources   ClaudeResources `json:"resources"`
}

type ClaudeWorkOrder added in v0.27.0

type ClaudeWorkOrder struct {
	Name      string `gorm:"primaryKey"`
	CreatedAt time.Time
}

ClaudeWorkOrder prevents redelivery from launching a deleted execution again.

type ClaudeWorker added in v0.27.0

type ClaudeWorker struct {
	WorkerReplicas int    `json:"workerReplicas,omitempty"`
	CPULimit       string `json:"cpuLimit,omitempty"`
	MemoryLimit    string `json:"memoryLimit,omitempty"`
}

type ClientStat added in v0.22.0

type ClientStat struct {
	Name             string `gorm:"column:name"`
	DeviceCount      int64  `gorm:"column:device_count"`
	UserCount        int64  `gorm:"column:user_count"`
	ObservationCount int64  `gorm:"column:observation_count"`
}

ClientStat is one row of the per-client rollup.

type Credential added in v0.23.0

type Credential struct {
	ID        uint              `json:"id" gorm:"primaryKey;autoIncrement"`
	CreatedAt time.Time         `json:"createdAt"`
	Context   string            `json:"context" gorm:"uniqueIndex:idx_credentials_context_name;not null"`
	Name      string            `json:"name" gorm:"uniqueIndex:idx_credentials_context_name;not null"`
	Secrets   map[string]string `json:"secrets" gorm:"serializer:json"`
	Encrypted bool              `json:"-"`
}

Credential stores secret environment variables for an Obot resource. List operations intentionally return Secrets keys with blank values; use RevealCredential to read values.

type Device added in v0.24.0

type Device struct {
	ID                 uint              `json:"id" gorm:"primaryKey;autoIncrement"`
	DeviceID           string            `json:"deviceID" gorm:"uniqueIndex;not null"`                                                   // client-computed, stable
	MDMConfigurationID uint              `json:"mdmConfigurationID" gorm:"index:idx_devices_configuration_enrolled,priority:1;not null"` // the configuration this device belongs to
	PublicKey          []byte            `json:"-"`                                                                                      // DER SubjectPublicKeyInfo (PKIX) of the identity key
	Hostname           string            `json:"hostname,omitempty"`
	OS                 string            `json:"os,omitempty"`
	OSVersion          string            `json:"osVersion,omitempty"`
	EnrolledAt         time.Time         `json:"enrolledAt" gorm:"index:idx_devices_configuration_enrolled,priority:2"`
	LastSeenAt         *time.Time        `json:"lastSeenAt,omitempty"`
	LatestScan         *DeviceLatestScan `json:"-" gorm:"-"` // derived from the device's latest scan, not stored
}

Device is one machine that belongs to a MDMConfiguration, identified by a stable, client-computed DeviceID.

PublicKey is the device's identity key, registered trust-on-first-use at enrollment. The device proves possession of it by signing short-lived JWTs that it presents directly when submitting scans; a request to bind a different key to an existing DeviceID is rejected (anti-takeover).

type DeviceEnrollmentKey added in v0.24.0

type DeviceEnrollmentKey struct {
	ID                 uint       `json:"id" gorm:"primaryKey;autoIncrement"`
	MDMConfigurationID uint       `json:"mdmConfigurationID" gorm:"index;not null"`
	Name               string     `json:"name,omitempty"` // optional, admin-provided
	HashedSecret       string     `json:"-"`              // bcrypt hash of the secret portion only
	CreatedBy          uint       `json:"createdBy"`
	CreatedAt          time.Time  `json:"createdAt"`
	LastUsedAt         *time.Time `json:"lastUsedAt,omitempty"`
	ExpiresAt          *time.Time `json:"expiresAt,omitempty"` // nil means no expiration
}

DeviceEnrollmentKey is one credential that authorizes enrolling a device into its configuration. A configuration can have several at once, added and removed independently. Deleting a key only stops it from enrolling new devices — it never affects already-enrolled devices (they authenticate with their own keys). Rotation is therefore: add a new key, distribute it, delete the old.

The credential format is: ode1-<configuration_id>-<key_id>-<secret> Lookup is by key ID (scoped to the configuration), then bcrypt verifies the secret.

type DeviceEnrollmentKeyCreateResponse added in v0.24.0

type DeviceEnrollmentKeyCreateResponse struct {
	DeviceEnrollmentKey
	EnrollmentCredential string `json:"enrollmentCredential"` // ode1-..., shown once
}

DeviceEnrollmentKeyCreateResponse is returned when minting a key. The full enrollment credential is only visible here.

type DeviceLatestScan added in v0.28.0

type DeviceLatestScan struct {
	DeviceScan
	MCPServerCount int64
	SkillCount     int64
	PluginCount    int64
	ClientCount    int64
}

DeviceLatestScan summarizes a device's latest scan for device lists: the scan envelope plus how many of each kind of observation it has, without loading the observations.

type DeviceScan added in v0.22.0

type DeviceScan struct {
	ID             uint      `json:"id" gorm:"primaryKey"`
	CreatedAt      time.Time `json:"createdAt" gorm:"index;index:idx_ds_user_time,priority:2;index:idx_ds_device_time,priority:2"`
	SubmittedBy    string    `json:"submittedBy" gorm:"index:idx_ds_user_time,priority:1"`
	DeviceID       string    `json:"deviceID" gorm:"index:idx_ds_device_time,priority:1"`
	Hostname       string    `json:"hostname"`
	Username       string    `json:"username"`
	OS             string    `json:"os"`
	Arch           string    `json:"arch"`
	ScannerVersion string    `json:"scannerVersion"`
	ScannedAt      time.Time `json:"scannedAt" gorm:"index"`

	MCPServers []DeviceScanMCPServer `json:"mcpServers,omitempty" gorm:"foreignKey:DeviceScanID;constraint:OnDelete:CASCADE"`
	Skills     []DeviceScanSkill     `json:"skills,omitempty"     gorm:"foreignKey:DeviceScanID;constraint:OnDelete:CASCADE"`
	Plugins    []DeviceScanPlugin    `json:"plugins,omitempty"    gorm:"foreignKey:DeviceScanID;constraint:OnDelete:CASCADE"`
	Files      []DeviceScanFile      `json:"files,omitempty"      gorm:"foreignKey:DeviceScanID;constraint:OnDelete:CASCADE"`
	Clients    []DeviceScanClient    `json:"clients,omitempty"    gorm:"foreignKey:DeviceScanID;constraint:OnDelete:CASCADE"`
}

DeviceScan is the parent envelope. Children (MCPServers, Skills, Plugins, Files) are GORM associations — db.Create(&scan) inserts everything atomically; db.Preload(...).First(...) loads them back.

Composite indexes:

  • idx_ds_user_time (submitted_by, created_at) — list scans for a user
  • idx_ds_device_time (device_id, created_at) — list scans for a device

CreatedAt also carries a standalone index. Retention cleanup filters on it alone, which neither composite can serve without a leading submitted_by or device_id value.

func DeviceScanFromManifest added in v0.22.0

func DeviceScanFromManifest(p types2.DeviceScanManifest) DeviceScan

DeviceScanFromManifest builds a gateway DeviceScan + its children from a submission manifest. Caller is responsible for setting SubmittedBy on the returned struct before passing it to InsertDeviceScan.

type DeviceScanClient added in v0.22.0

type DeviceScanClient struct {
	ID            uint      `json:"id" gorm:"primaryKey"`
	DeviceScanID  uint      `json:"deviceScanID" gorm:"index;not null"`
	CreatedAt     time.Time `json:"createdAt" gorm:"index"`
	Name          string    `json:"name" gorm:"index"`
	Version       string    `json:"version"`
	BinaryPath    string    `json:"binaryPath"`
	InstallPath   string    `json:"installPath"`
	ConfigPath    string    `json:"configPath"`
	HasMCPServers bool      `json:"hasMCPServers"`
	HasSkills     bool      `json:"hasSkills"`
	HasPlugins    bool      `json:"hasPlugins"`
}

DeviceScanClient is a per-scan record for an AI client observed on the device. Presence facts (BinaryPath, InstallPath, StateDir, Version) come from generic per-client detection. Has{MCPServers, Skills,Plugins} are roll-ups derived from observations attributed to this client name in the same scan.

type DeviceScanFile added in v0.22.0

type DeviceScanFile struct {
	ID           uint      `json:"id" gorm:"primaryKey"`
	DeviceScanID uint      `json:"deviceScanID" gorm:"index;not null"`
	CreatedAt    time.Time `json:"createdAt" gorm:"index"`
	Path         string    `json:"path" gorm:"index"`
	SizeBytes    int64     `json:"sizeBytes"`
	Oversized    bool      `json:"oversized"`
	Content      string    `json:"content" gorm:"type:text"`
}

type DeviceScanMCPServer added in v0.22.0

type DeviceScanMCPServer struct {
	ID           uint                        `json:"id" gorm:"primaryKey"`
	DeviceScanID uint                        `json:"deviceScanID" gorm:"index;not null"`
	CreatedAt    time.Time                   `json:"createdAt" gorm:"index"`
	Client       string                      `json:"client" gorm:"index"`
	Scope        string                      `json:"scope" gorm:"index"`
	ProjectPath  string                      `json:"projectPath" gorm:"index"`
	File         string                      `json:"file"`
	Name         string                      `json:"name" gorm:"index"`
	Transport    string                      `json:"transport" gorm:"index"`
	Command      string                      `json:"command"`
	Args         datatypes.JSONSlice[string] `json:"args"`
	URL          string                      `json:"url"`
	EnvKeys      datatypes.JSONSlice[string] `json:"envKeys"`
	HeaderKeys   datatypes.JSONSlice[string] `json:"headerKeys"`
	ConfigHash   string                      `json:"configHash" gorm:"index"`
}

DeviceScanMCPServer is one MCP server observation. Scope is derived at insert time from ProjectPath ("" → "global", non-empty → "project") and persisted denormalized so list queries hit a single table.

type DeviceScanPlugin added in v0.22.0

type DeviceScanPlugin struct {
	ID            uint                        `json:"id" gorm:"primaryKey"`
	DeviceScanID  uint                        `json:"deviceScanID" gorm:"index;not null"`
	CreatedAt     time.Time                   `json:"createdAt" gorm:"index"`
	Client        string                      `json:"client" gorm:"index"`
	Scope         string                      `json:"scope" gorm:"index"`
	ProjectPath   string                      `json:"projectPath" gorm:"index"`
	ConfigPath    string                      `json:"configPath"`
	Name          string                      `json:"name" gorm:"index"`
	PluginType    string                      `json:"pluginType" gorm:"index"`
	Version       string                      `json:"version"`
	Description   string                      `json:"description"`
	Author        string                      `json:"author"`
	Enabled       bool                        `json:"enabled"`
	Marketplace   string                      `json:"marketplace"`
	Files         datatypes.JSONSlice[string] `json:"files"`
	HasMCPServers bool                        `json:"hasMCPServers"`
	HasSkills     bool                        `json:"hasSkills"`
	HasRules      bool                        `json:"hasRules"`
	HasCommands   bool                        `json:"hasCommands"`
	HasHooks      bool                        `json:"hasHooks"`
}

type DeviceScanSkill added in v0.22.0

type DeviceScanSkill struct {
	ID           uint                        `json:"id" gorm:"primaryKey"`
	DeviceScanID uint                        `json:"deviceScanID" gorm:"index;not null"`
	CreatedAt    time.Time                   `json:"createdAt" gorm:"index"`
	Client       string                      `json:"client" gorm:"index"`
	Scope        string                      `json:"scope" gorm:"index"`
	ProjectPath  string                      `json:"projectPath" gorm:"index"`
	File         string                      `json:"file"`
	Name         string                      `json:"name" gorm:"index"`
	Description  string                      `json:"description"`
	HasScripts   bool                        `json:"hasScripts"`
	GitRemoteURL string                      `json:"gitRemoteURL" gorm:"index"`
	Files        datatypes.JSONSlice[string] `json:"files"`
}

type EgressAuditLog added in v0.27.0

type EgressAuditLog struct {
	ID                string          `json:"id" gorm:"primaryKey"`
	CreatedAt         time.Time       `json:"createdAt" gorm:"index"`
	UpdatedAt         time.Time       `json:"updatedAt" gorm:"index"`
	UserID            string          `json:"userID" gorm:"index"`
	ClaudeAccount     string          `json:"claudeAccount" gorm:"index"`
	EnvironmentID     string          `json:"environmentID" gorm:"index"`
	ClaudeSession     string          `json:"claudeSession" gorm:"index"`
	Actor             string          `json:"actor" gorm:"index"`
	Method            string          `json:"method"`
	Scheme            string          `json:"scheme"`
	Host              string          `json:"host" gorm:"index"`
	Path              string          `json:"path"`
	ResponseStatus    int             `json:"responseStatus" gorm:"index"`
	Outcome           string          `json:"outcome" gorm:"index"`
	DurationMs        int64           `json:"durationMs"`
	RequestBytes      int64           `json:"requestBytes"`
	ResponseBytes     int64           `json:"responseBytes"`
	RequestTruncated  bool            `json:"requestTruncated"`
	ResponseTruncated bool            `json:"responseTruncated"`
	RequestHeaders    json.RawMessage `json:"requestHeaders,omitempty"`
	ResponseHeaders   json.RawMessage `json:"responseHeaders,omitempty"`
	// Bodies are JSON-encoded byte slices (base64), including binary responses.
	RequestBody  json.RawMessage `json:"requestBody,omitempty"`
	ResponseBody json.RawMessage `json:"responseBody,omitempty"`
	// Finalized preserves transport status when capture and access logs arrive out of order.
	Finalized bool `json:"-"`
	Encrypted bool `json:"-"`
}

EgressAuditLog snapshots attribution so session cleanup cannot change history.

type EnforcementDecisionLog added in v0.25.0

type EnforcementDecisionLog struct {
	ID        uint      `json:"id" gorm:"primaryKey;autoIncrement"`
	CreatedAt time.Time `json:"createdAt" gorm:"index"`

	// Fields describing the device:
	MDMConfigurationID uint   `json:"mdmConfigurationID" gorm:"index"`
	DeviceID           string `json:"deviceID,omitempty" gorm:"index"`
	ClientIP           string `json:"clientIP,omitempty" gorm:"index"`

	// Fields describing the tool call:
	Agent      string `json:"agent,omitempty" gorm:"index"`
	Tool       string `json:"tool,omitempty" gorm:"index"`
	Kind       string `json:"kind,omitempty" gorm:"index"`
	ServerName string `json:"serverName,omitempty" gorm:"index"`
	ObotHosted bool   `json:"obotHosted,omitempty"`

	// Resolved server identity.
	ServerURL            string `json:"serverURL,omitempty"`
	ServerHostname       string `json:"serverHostname,omitempty"`
	ServerCommand        string `json:"serverCommand,omitempty"`
	ServerPackageSource  string `json:"serverPackageSource,omitempty"`
	ServerPackageName    string `json:"serverPackageName,omitempty"`
	ServerPackageVersion string `json:"serverPackageVersion,omitempty"`
	ServerConnector      string `json:"serverConnector,omitempty"`

	// Unresolved records that the device could not establish what the call
	// targeted, with UnresolvedReason naming the cause it reported. The row is
	// always a deny; these distinguish "we could not identify this" from "this
	// is identified and not allowlisted".
	Unresolved       bool   `json:"unresolved,omitempty"`
	UnresolvedReason string `json:"unresolvedReason,omitempty"`

	// Decision is the evaluator verdict: types.EnforcementDecisionAllow or
	// types.EnforcementDecisionDeny. Reason is the evaluator's human-readable
	// justification.
	Decision string `json:"decision" gorm:"index"`
	Reason   string `json:"reason,omitempty"`
}

EnforcementDecisionLog is one recorded allow/deny decision made by the enforcement decision endpoint for a device's tool call.

type Group added in v0.9.0

type Group struct {
	// ID is the globally unique identifier for the group.
	// Each auth provider should use a different prefix for their groups to avoid collisions with other providers.
	ID string `json:"id" gorm:"primaryKey;unique;index:idx_group_auth_provider_name,priority:4"`

	// AuthProviderName is the name of the auth provider that the group belongs to.
	// This is used to identify the auth provider that the group belongs to.
	AuthProviderName string `json:"authProviderName" gorm:"primaryKey;index:idx_group_auth_provider;index:idx_group_auth_provider_name,priority:1"`

	// AuthProviderNamespace is the namespace of the auth provider that the group belongs to.
	// Note: This is pretty much always "default", but we're keeping it here for parity with the Identity type.
	AuthProviderNamespace string `json:"authProviderNamespace" gorm:"primaryKey;index:idx_group_auth_provider;index:idx_group_auth_provider_name,priority:2"`

	// Name is the display name of the group.
	// Indexed because cached group listings are paged by keyset in (name, id) order.
	Name string `json:"name" gorm:"index:idx_group_auth_provider_name,priority:3"`

	// IconURL is the URL of the group's icon.
	IconURL *string `json:"iconURL"`
}

Group represents a group that users can belong to in an auth provider.

type GroupListResponse added in v0.25.2

type GroupListResponse struct {
	Items []Group `json:"items"`

	// NextCursor is the opaque position to pass back to fetch the following page. It is absent on
	// the last page, and its presence is the only indication that more results exist.
	NextCursor string `json:"nextCursor,omitempty"`

	// Source is where the items came from: GroupSourceProvider or GroupSourceCache.
	Source GroupSource `json:"source"`

	// Degraded is true when the auth provider could not be listed and the response fell back to
	// cached groups. It distinguishes a real failure from a provider that has no group support.
	Degraded bool `json:"degraded"`

	// Reset is true when the caller supplied a cursor that could not be honored, so these items are
	// the first page of a fresh listing rather than the page that was asked for.
	Reset bool `json:"reset,omitempty"`
}

GroupListResponse is the paginated response for a group listing.

type GroupMemberships added in v0.9.0

type GroupMemberships struct {
	// UserID is the ID of the user that is a member of the group.
	UserID uint `json:"userID" gorm:"primaryKey"`

	// GroupID is the globally unique identifier for the group. The primary key leads with UserID, so GroupID has its
	// own index for the queries that read or replace a group's members.
	GroupID string `json:"groupID" gorm:"primaryKey;index"`

	// CreatedAt is when the group membership was created.
	CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime"`
}

GroupMemberships represents a user's membership in a group.

type GroupRoleAssignment added in v0.15.0

type GroupRoleAssignment struct {
	// GroupName is the name of the auth provider group (used as primary key)
	GroupName string `json:"groupName" gorm:"primaryKey"`

	// CreatedAt is when the assignment was created
	CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime"`

	// UpdatedAt is when the assignment was last modified
	UpdatedAt time.Time `json:"updatedAt" gorm:"autoUpdateTime"`

	// Role is the role to assign to all members of the group
	Role types2.Role `json:"role" gorm:"not null"`

	// Description is an optional description of why this assignment exists
	Description string `json:"description"`
}

GroupRoleAssignment assigns a role to all members of an auth provider group.

type GroupSource added in v0.25.2

type GroupSource string

GroupSource names where a group listing came from.

const (
	// GroupSourceProvider means the listing came from the auth provider and is complete.
	GroupSourceProvider GroupSource = "provider"

	// GroupSourceCache means the listing came from the groups table, which holds the groups
	// observed during a user sign-in plus any resolved by ID for a policy, and is therefore
	// partial.
	GroupSourceCache GroupSource = "cache"
)

type Guardrail added in v0.28.0

type Guardrail struct {
	ID          string          `gorm:"primaryKey;type:text" json:"id"`
	CreatedAt   time.Time       `json:"created"`
	UpdatedAt   time.Time       `json:"updated"`
	Name        string          `gorm:"type:text;not null" json:"name"`
	Description string          `gorm:"type:text" json:"description,omitempty"`
	Type        string          `gorm:"type:text;not null" json:"type"`
	Config      json.RawMessage `json:"config,omitempty"`
}

Guardrail configures one checker. Sensitive settings are kept in the encrypted credential store, not here.

func (Guardrail) TableName added in v0.28.0

func (Guardrail) TableName() string

type GuardrailPolicy added in v0.28.0

type GuardrailPolicy struct {
	ID          string    `gorm:"primaryKey;type:text" json:"id"`
	CreatedAt   time.Time `json:"created"`
	UpdatedAt   time.Time `json:"updated"`
	Name        string    `gorm:"type:text;not null" json:"name"`
	Description string    `gorm:"type:text" json:"description,omitempty"`
	Enabled     bool      `gorm:"not null" json:"enabled"`
	// Target is llm (model requests and responses) or mcp (tool call arguments and results).
	Target string `gorm:"type:text;not null" json:"target"`
	// ApplyTo is input, output or both.
	ApplyTo string `gorm:"type:text;not null" json:"applyTo"`
	// Action is block, redact or log.
	Action string `gorm:"type:text;not null" json:"action"`
	// Condition is an optional CEL expression that must be true for the policy to apply.
	Condition string `gorm:"type:text" json:"condition,omitempty"`
	// SamplingRate is the percentage (1-100) of matching requests the policy checks.
	SamplingRate int `gorm:"not null" json:"samplingRate"`
	// InputScope is all (every message in the request) or latest (only messages since the
	// model last responded). Redacting policies always check every message.
	InputScope string `gorm:"type:text" json:"inputScope,omitempty"`
	// FailClosed blocks the request when a guardrail can't be evaluated.
	FailClosed bool `gorm:"not null" json:"failClosed"`
	// BlockMessage replaces the default message returned when the policy blocks.
	BlockMessage string   `gorm:"type:text" json:"blockMessage,omitempty"`
	GuardrailIDs []string `gorm:"serializer:json" json:"guardrailIDs"`
	// ProfileID is the gateway profile (a model access policy) the policy belongs to.
	ProfileID string `gorm:"type:text;index" json:"profileID"`
	// Subjects limit an MCP guardrail filter's policy to users and groups. They aren't stored:
	// stored policies apply through their profile.
	Subjects []GuardrailPolicySubject `gorm:"-" json:"-"`
}

GuardrailPolicy decides which model requests and responses are checked, by which guardrails, and what happens when a guardrail finds a problem. It applies to the users its gateway profile applies to. MCP guardrail filters are evaluated as policies too, in memory, with their own subjects.

func (GuardrailPolicy) TableName added in v0.28.0

func (GuardrailPolicy) TableName() string

type GuardrailPolicySubject added in v0.28.0

type GuardrailPolicySubject struct {
	Type string `json:"type"`
	ID   string `json:"id,omitempty"`
}

GuardrailPolicySubject limits an MCP guardrail filter to a user, a group or everyone.

type Identity

type Identity struct {
	AuthProviderName      string `json:"authProviderName" gorm:"primaryKey;index:idx_user_auth_id;index:idx_identities_group_lookup,priority:2"`
	AuthProviderNamespace string `json:"authProviderNamespace" gorm:"primaryKey;index:idx_user_auth_id;index:idx_identities_group_lookup,priority:1"`
	ProviderUsername      string `json:"providerUsername"`
	ProviderUserID        string `json:"providerUserID"`
	HashedProviderUserID  string `json:"hashedProviderUserID" gorm:"primaryKey"`
	ProviderGroupLookupID string `json:"providerGroupLookupID"`
	// HashedProviderGroupLookupID is the hash of ProviderGroupLookupID, which supports equality lookups without
	// decrypting. It is empty when ProviderGroupLookupID is. The index is not unique: lookup IDs may repeat in legacy
	// data.
	HashedProviderGroupLookupID string    `json:"hashedProviderGroupLookupID" gorm:"index:idx_identities_group_lookup,priority:3"`
	Email                       string    `json:"email"`
	HashedEmail                 string    `json:"hashedEmail"`
	UserID                      uint      `json:"userID" gorm:"index:idx_user_auth_id;index:idx_identities_user_id"`
	IconURL                     string    `json:"iconURL"`
	IconLastChecked             time.Time `json:"iconLastChecked"`
	Encrypted                   bool      `json:"encrypted"`

	// AuthProviderGroupsLastChecked is the last time the identity's auth provider groups were checked.
	AuthProviderGroupsLastChecked time.Time `json:"authProviderGroupsLastChecked"`

	// FirstSignInAt is when the identity first signed in through its auth provider. It is unset for an
	// identity that was created before anyone signed in with it, so an identity alone does not prove that its
	// user can sign in. The first sign-in of a user who is not disabled sets it, and nothing clears it.
	FirstSignInAt *time.Time `json:"firstSignInAt,omitempty"`

	// AuthProviderGroups is the set of auth provider groups that the identity is a member of.
	AuthProviderGroups []Group `json:"groups" gorm:"-"`
}

func (Identity) GetAuthProviderGroupIDs added in v0.9.0

func (i Identity) GetAuthProviderGroupIDs() []string

func (Identity) GroupLookupID added in v0.18.0

func (i Identity) GroupLookupID() string

type Image added in v0.7.0

type Image struct {
	ID        string    `json:"id" gorm:"primaryKey;autoIncrement:false"`
	CreatedAt time.Time `json:"createdAt"`
	Data      []byte    `json:"-" gorm:"type:bytea;not null"`
	MIMEType  string    `json:"mimeType" gorm:"type:varchar(100);not null"`
}

func (*Image) BeforeCreate added in v0.7.0

func (i *Image) BeforeCreate(_ *gorm.DB) error

BeforeCreate will set the ID to a UUID v4.

type LLMAuditLog added in v0.24.0

type LLMAuditLog struct {
	ID        string    `gorm:"primaryKey;type:text"`
	CreatedAt time.Time `` /* 628-byte string literal not displayed */
	Duration  int64
	UserID    string `gorm:"type:text;index:idx_llm_audit_user_created,priority:1"`
	APIKeyID  *uint  `gorm:"index:idx_llm_audit_api_key_created,priority:1"`
	// APIKeyRevoked is current lifecycle metadata populated when audit logs are read.
	// It is not persisted as part of the historical event snapshot.
	APIKeyRevoked bool `gorm:"-"`
	// APIKeyName is the event-time display value. Unnamed keys snapshot their
	// non-secret masked identifier instead of requiring an API-key table join.
	APIKeyName    string `gorm:"type:text"`
	ModelProvider string `gorm:"type:text;index:idx_llm_audit_provider_created,priority:1"`
	ModelID       string `gorm:"type:text"`
	// TargetModel is the requested model.
	TargetModel string `gorm:"type:text;index:idx_llm_audit_target_model_created,priority:1"`
	// ServedProvider and ServedModel are the provider and model that served the request, which
	// routing rules and fallbacks can make differ from TargetModel. ProviderKey names the
	// gateway key it was served with, and Fallback is true when a fallback served it.
	// ClaudeSubscription is true when the caller's Claude subscription paid for it instead,
	// with no gateway key.
	ServedProvider            string `gorm:"type:text;index:idx_llm_audit_served_provider_created,priority:1"`
	ServedModel               string `gorm:"type:text"`
	ProviderKey               string `gorm:"type:text"`
	Fallback                  bool   `gorm:"not null;default:false"`
	ClaudeSubscription        bool   `gorm:"not null;default:false"`
	ReasoningEffort           string `gorm:"type:text"`
	RequestPath               string `gorm:"type:text;index:idx_llm_audit_request_path_created,priority:1"`
	RequestMethod             string `gorm:"type:text"`
	RequestHeaders            json.RawMessage
	RequestBody               json.RawMessage
	PolicyModifiedRequestBody json.RawMessage
	MessagePolicyTriggered    bool `gorm:"not null;default:false;index:idx_llm_audit_message_policy_triggered_created,priority:1"`
	ResponseHeaders           json.RawMessage
	ResponseBody              json.RawMessage
	ResponseID                string `gorm:"type:text;index:idx_llm_audit_response_created,priority:1"`
	ResponseStatus            int    `gorm:"index:idx_llm_audit_response_status_created,priority:1"`
	Outcome                   string `gorm:"type:text;index:idx_llm_audit_outcome_created,priority:1"`
	Error                     string `gorm:"type:text"`
	InputTokens               int
	OutputTokens              int
	// CacheReadTokens and CacheWriteTokens are the input tokens read from and written to the
	// provider's prompt cache, and ReasoningTokens the output tokens spent reasoning; each is
	// part of InputTokens or OutputTokens.
	CacheReadTokens  int `gorm:"not null;default:0"`
	CacheWriteTokens int `gorm:"not null;default:0"`
	ReasoningTokens  int `gorm:"not null;default:0"`
	// Spend is what the request cost in USD, as recorded in token usage; 0 when the model has
	// no price.
	Spend           float64 `gorm:"not null;default:0"`
	RequestID       string  `gorm:"type:text"`
	UserAgent       string  `gorm:"type:text;index:idx_llm_audit_user_agent_created,priority:1"`
	ClientSessionID string  `gorm:"type:text;index:idx_llm_audit_client_session_created,priority:1"`
	ClientIP        string  `gorm:"type:text"`
	// GuardrailFindings say which guardrail policies found something and what they did, but
	// not what they found, so they are stored unencrypted.
	GuardrailFindings []types2.LLMAuditGuardrailFinding `gorm:"serializer:json"`
	Encrypted         bool
}

func (LLMAuditLog) TableName added in v0.24.0

func (LLMAuditLog) TableName() string

type LLMGatewayBudget added in v0.28.0

type LLMGatewayBudget struct {
	ID          string    `gorm:"primaryKey;type:text" json:"id"`
	CreatedAt   time.Time `json:"created"`
	UpdatedAt   time.Time `json:"updated"`
	Name        string    `gorm:"type:text;not null" json:"name"`
	Description string    `gorm:"type:text" json:"description,omitempty"`
	Enabled     bool      `gorm:"not null" json:"enabled"`
	// ProfileID is the gateway profile (a model access policy) the budget belongs to. It
	// applies to everyone the profile applies to.
	ProfileID string `gorm:"type:text;index" json:"profileID"`
	// PerUser gives every user of the profile their own allowance. Otherwise the limits are
	// one pool shared by all of them.
	PerUser bool `gorm:"not null" json:"perUser"`
	// ExemptAdmins leaves administrators unlimited by this budget.
	ExemptAdmins bool `gorm:"not null" json:"exemptAdmins"`
	// UserTokenLimits lets a user's personal daily token limits (set on the user) replace
	// this per-user budget's input and output token limits: a positive personal limit
	// replaces the amount, and a negative one removes the limit. This is how the daily
	// token quota treated personal limits, and the budget migrated from it keeps that.
	UserTokenLimits bool                    `gorm:"not null;default:false" json:"userTokenLimits"`
	Limits          []LLMGatewayBudgetLimit `gorm:"serializer:json" json:"limits"`
	// Models restricts the budget to these Model IDs. Empty means every model.
	Models []string `gorm:"serializer:json" json:"models,omitempty"`
}

LLMGatewayBudget limits LLM gateway usage for the users its profile applies to. Obot enforces budgets itself from usage it records in its own database, so limits hold exactly across every Obot replica.

func (LLMGatewayBudget) TableName added in v0.28.0

func (LLMGatewayBudget) TableName() string

type LLMGatewayBudgetLimit added in v0.28.0

type LLMGatewayBudgetLimit struct {
	// Metric is spend (USD), tokens, input_tokens, output_tokens or requests.
	Metric string  `json:"metric"`
	Amount float64 `json:"amount"`
	// Window is a count and unit: m (minutes), h, d, w or M (months), e.g. "1d" or "6h".
	Window string `json:"window"`
	// Calendar resets the window at calendar boundaries (the start of the hour, day, week
	// or month, in UTC) instead of rolling. Only single-unit windows can be calendar aligned.
	Calendar bool `json:"calendar,omitempty"`
}

LLMGatewayBudgetLimit caps one metric over a window.

type LLMGatewayBudgetUsage added in v0.28.0

type LLMGatewayBudgetUsage struct {
	ID           uint      `gorm:"primaryKey"`
	BudgetID     string    `` /* 152-byte string literal not displayed */
	UserID       string    `gorm:"type:text;not null;index:idx_llm_gateway_budget_usage_budget_user_created,priority:2"`
	CreatedAt    time.Time `` /* 139-byte string literal not displayed */
	Model        string    `gorm:"type:text"`
	InputTokens  int
	OutputTokens int
	TotalTokens  int
	Spend        float64
}

LLMGatewayBudgetUsage is one request's usage counted against one budget.

func (LLMGatewayBudgetUsage) TableName added in v0.28.0

func (LLMGatewayBudgetUsage) TableName() string

type LLMGatewaySettings added in v0.28.0

type LLMGatewaySettings struct {
	// SubscriptionPassthrough lets Claude Code users signed in with a Claude subscription use
	// it through the gateway: their Anthropic OAuth token is forwarded to Anthropic for Claude
	// models instead of a configured provider key.
	SubscriptionPassthrough bool `json:"subscriptionPassthrough"`
}

LLMGatewaySettings are the LLM gateway settings Obot enforces itself, as opposed to the engine's own configuration.

type LocalAgentToolCallAuditLogFields added in v0.24.0

type LocalAgentToolCallAuditLogFields struct {
	// Only index a column that queries filter or sort on with an operator an index can serve. The
	// free-text audit log search matches most of these columns by substring, which no B-tree index
	// helps, and every index is maintained on each audit log write.
	OccurredAt time.Time  `json:"occurredAt" gorm:"index"`
	StartedAt  *time.Time `json:"startedAt,omitempty"`

	// ActorType and ActorID are stamped from authenticated request context. They are never copied
	// from the client-reported event.
	ActorType types2.AuditLogActorType `json:"actorType"`
	ActorID   string                   `json:"actorID,omitempty"`

	ActionName string `json:"actionName" gorm:"index"`
	ActionKind string `json:"actionKind,omitempty" gorm:"index"`

	TargetType       types2.AuditLogTargetType `json:"targetType"`
	TargetName       string                    `json:"targetName"`
	TargetParentType types2.AuditLogTargetType `json:"targetParentType,omitempty"`
	TargetParentName string                    `json:"targetParentName,omitempty" gorm:"index"`

	OutcomeStatus types2.AuditLogOutcomeStatus `json:"outcomeStatus" gorm:"index"`
	OutcomeReason string                       `json:"outcomeReason,omitempty"`
	OutcomeError  string                       `json:"outcomeError,omitempty" gorm:"column:local_agent_error"`
	DurationMs    int64                        `json:"durationMs,omitempty" gorm:"index"`

	// IdempotencyKey deduplicates repeated submissions of the same completed audit entry.
	IdempotencyKey string `json:"idempotencyKey" gorm:"uniqueIndex"`
	// ToolUseID is the tool-use identifier from the agent runtime, when available.
	ToolUseID string `json:"toolUseID,omitempty"`
	SessionID string `json:"sessionID,omitempty" gorm:"index"`
	// TurnID identifies the conversation turn that produced this tool call.
	TurnID string `json:"turnID,omitempty"`

	AgentProvider  types2.LocalAgentProvider `json:"agentProvider" gorm:"index"`
	AgentVersion   string                    `json:"agentVersion,omitempty"`
	CLIName        string                    `json:"cliName,omitempty"`
	CLIVersion     string                    `json:"cliVersion"`
	Model          string                    `json:"model,omitempty"`
	ModelID        string                    `json:"modelID,omitempty"`
	PermissionMode string                    `json:"permissionMode,omitempty"`

	DeviceID           string `json:"deviceID,omitempty" gorm:"index"`
	DeviceDeploymentID uint   `json:"deviceDeploymentID,omitempty"`
	Hostname           string `json:"hostname,omitempty"`
	OS                 string `json:"os,omitempty"`
	Architecture       string `json:"architecture,omitempty"`
	LocalUsername      string `json:"localUsername,omitempty"`

	CWD               string                      `json:"cwd,omitempty"`
	GitRoot           string                      `json:"gitRoot,omitempty"`
	GitRemotes        datatypes.JSONSlice[string] `json:"gitRemotes,omitempty"`
	GitBranch         string                      `json:"gitBranch,omitempty"`
	GitCommit         string                      `json:"gitCommit,omitempty"`
	ReportedUserEmail string                      `json:"reportedUserEmail,omitempty"`

	// TranscriptPath is the local path to the agent transcript, if the client reported one.
	TranscriptPath string `json:"transcriptPath,omitempty"`

	RequestBody  json.RawMessage `json:"requestBody,omitempty" gorm:"column:local_agent_request_body"`
	ResponseBody json.RawMessage `json:"responseBody,omitempty" gorm:"column:local_agent_response_body"`
	// RawEvent preserves the original hook payload for debugging and future parsers.
	RawEvent json.RawMessage `json:"rawEvent,omitempty" gorm:"column:local_agent_raw_event"`
}

type LocalAuthSession added in v0.24.0

type LocalAuthSession struct {
	ID        string    `json:"-" gorm:"primaryKey"`
	CreatedAt time.Time `json:"createdAt"`
	ExpiresAt time.Time `json:"expiresAt" gorm:"index"`
	UserID    uint      `json:"userID" gorm:"index"`
}

LocalAuthSession is a login session created by the local auth provider. ID is the SHA-256 hash of the session token that is handed to the browser, so a database leak does not hand out usable sessions.

type LocalAuthUser added in v0.24.0

type LocalAuthUser struct {
	ID           uint      `json:"id" gorm:"primaryKey"`
	CreatedAt    time.Time `json:"createdAt"`
	UpdatedAt    time.Time `json:"updatedAt"`
	Email        string    `json:"email"`
	HashedEmail  string    `json:"-" gorm:"uniqueIndex"`
	PasswordHash string    `json:"-"`
	// RequirePasswordChange restricts this user's session to changing their password until they
	// have chosen a new one. It is set for initial and administrator-reset passwords.
	RequirePasswordChange bool       `json:"requirePasswordChange" gorm:"not null;default:false"`
	SetupTokenHash        string     `json:"-" gorm:"index;not null;default:''"`
	SetupTokenExpiresAt   *time.Time `json:"-"`
	// OwnerGrantedAt records when sign-in made the provisioned initial owner an Owner. The grant happens once, even
	// though the setup token stays usable until the password is set.
	OwnerGrantedAt *time.Time `json:"-"`
	Encrypted      bool       `json:"-"`
}

LocalAuthUser is a username/password user managed by the local auth provider. The email address is the login name and is also what identifies the user to the rest of Obot, so it is immutable: to change it, delete the user and create a new one.

type MCPAuditLog added in v0.8.0

type MCPAuditLog struct {
	ID         uint                      `json:"id" gorm:"primaryKey"`
	CreatedAt  time.Time                 `json:"createdAt" gorm:"index;index:idx_mcp_audit_api_key_created,priority:2;index:idx_mcp_audit_tool_calls_daily,priority:3"`
	SourceType types2.AuditLogSourceType `json:"sourceType" gorm:"index;default:mcp;index:idx_mcp_audit_tool_calls_daily,priority:1"`
	UserID     string                    `json:"userID" gorm:"index"`
	APIKeyID   *uint                     `json:"apiKeyID,omitempty" gorm:"index:idx_mcp_audit_api_key_created,priority:1"`
	// APIKeyRevoked is current lifecycle metadata populated when audit logs are read.
	// It is not persisted as part of the historical event snapshot.
	APIKeyRevoked bool `json:"apiKeyRevoked,omitempty" gorm:"-"`
	// APIKeyName is the event-time display value. Unnamed keys snapshot their
	// non-secret masked identifier instead of requiring an API-key table join.
	APIKeyName string `json:"apiKeyName,omitempty"`
	ClientIP   string `json:"clientIP" gorm:"index"`

	MCPFields                *MCPAuditLogFields                `json:"mcpFields,omitempty" gorm:"embedded"`
	LocalAgentToolCallFields *LocalAgentToolCallAuditLogFields `json:"localAgentToolCallFields,omitempty" gorm:"embedded"`
	Encrypted                bool                              `json:"encrypted"`
}

MCPAuditLog represents an audit log entry for MCP API calls

func NewLocalAgentToolCallAuditLogFromInput added in v0.24.0

func NewLocalAgentToolCallAuditLogFromInput(input types2.LocalAgentToolCallAuditLogInput, actorType types2.AuditLogActorType, actorID, clientIP string, deviceDeploymentID uint, createdAt time.Time) MCPAuditLog

func (*MCPAuditLog) MCP added in v0.24.0

func (a *MCPAuditLog) MCP() *MCPAuditLogFields

func (*MCPAuditLog) NormalizeMCPFields added in v0.24.0

func (a *MCPAuditLog) NormalizeMCPFields()

func (*MCPAuditLog) ValidateSourceFields added in v0.24.0

func (a *MCPAuditLog) ValidateSourceFields() error

type MCPAuditLogFields added in v0.24.0

type MCPAuditLogFields struct {
	APIKey                    string                                `json:"apiKey,omitempty"`
	MCPID                     string                                `json:"mcpID" gorm:"index;index:idx_mcp_audit_tool_calls_daily,priority:4"`
	PowerUserWorkspaceID      string                                `json:"powerUserWorkspaceID,omitempty" gorm:"index"`
	MCPServerDisplayName      string                                `json:"mcpServerDisplayName" gorm:"index"`
	MCPServerCatalogEntryName string                                `json:"mcpServerCatalogEntryName" gorm:"index"`
	ClientName                string                                `json:"clientName" gorm:"index"`
	ClientVersion             string                                `json:"clientVersion" gorm:"index"`
	CallType                  string                                `json:"callType" gorm:"index;index:idx_mcp_audit_tool_calls_daily,priority:2"`
	CallIdentifier            string                                `json:"callIdentifier,omitempty" gorm:"index"`
	RequestMutated            bool                                  `json:"requestMutated"`
	RequestBody               json.RawMessage                       `json:"requestBody,omitempty"`
	MutatedRequestBody        json.RawMessage                       `json:"mutatedRequestBody,omitempty"`
	ResponseMutated           bool                                  `json:"responseMutated"`
	ResponseBody              json.RawMessage                       `json:"responseBody,omitempty"`
	OriginalResponseBody      json.RawMessage                       `json:"originalResponseBody,omitempty"`
	ResponseStatus            int                                   `json:"responseStatus" gorm:"index"`
	Error                     string                                `json:"error,omitempty"`
	ProcessingTimeMs          int64                                 `json:"processingTimeMs" gorm:"index"`
	SessionID                 string                                `json:"sessionID,omitempty" gorm:"index"`
	WebhookStatuses           datatypes.JSONSlice[MCPWebhookStatus] `json:"webhookStatuses,omitempty"`
	ResponseReceived          bool                                  `json:"responseReceived"`
	// ProxyExchangeID is an internal identifier shared by the request and response
	// audit entries emitted for one proxied HTTP exchange. It is not MCP protocol data.
	ProxyExchangeID string `json:"-" gorm:"column:proxy_exchange_id;index"`

	// Additional metadata
	RequestID       string          `json:"requestID,omitempty" gorm:"index"`
	UserAgent       string          `json:"userAgent,omitempty"`
	RequestHeaders  json.RawMessage `json:"requestHeaders,omitempty"`
	ResponseHeaders json.RawMessage `json:"responseHeaders,omitempty"`
}

type MCPOAuthAttemptBudget added in v0.28.0

type MCPOAuthAttemptBudget struct {
	ID        string    `gorm:"primaryKey"`
	ExpiresAt time.Time `gorm:"index"`
	Starts    int
}

MCPOAuthAttemptBudget bounds repeated challenge/OAuth cycles independently of random tickets.

type MCPOAuthChallenge added in v0.28.0

type MCPOAuthChallenge struct {
	ID            string `gorm:"primaryKey"`
	CreatedAt     time.Time
	ExpiresAt     time.Time `gorm:"index"`
	UserID        string
	Namespace     string
	MCPID         string
	ClientID      string
	Resource      string
	AuthRequestID string
	Requirements  []v1.UpstreamOAuthRequirement `gorm:"serializer:json"`
}

MCPOAuthChallenge is a short-lived, single-transaction handoff, never a grant.

type MCPOAuthPendingState added in v0.17.0

type MCPOAuthPendingState struct {
	UpstreamChallenge string
	HashedState       string `gorm:"primaryKey"`
	State             string
	Verifier          string
	UserID            string `gorm:"index:idx_pending_user_mcp"`
	MCPID             string `gorm:"index:idx_pending_user_mcp"`
	URL               string

	// TunnelName is the MCPTunnel the server is reached through, if any. The callback's
	// code exchange goes through the same tunnel, since the token endpoint may be private.
	TunnelName         string
	ResourceURL        string
	OAuthAuthRequestID string
	ClientID           string
	ClientSecret       string
	AuthURL            string
	TokenURL           string
	AuthStyle          oauth2.AuthStyle
	RedirectURL        string
	Scopes             string
	Encrypted          bool
	CreatedAt          time.Time
}

type MCPOAuthToken added in v0.8.0

type MCPOAuthToken struct {
	oauth2.Endpoint
	ClientID     string
	ClientSecret string
	RedirectURL  string
	Scopes       string

	MCPID              string `gorm:"primaryKey"`
	UserID             string `gorm:"primaryKey"`
	URL                string
	OAuthAuthRequestID string `gorm:"index"`
	GrantID            string
	UpstreamChallenge  string
	AccessToken        string
	TokenType          string
	RefreshToken       string
	Expiry             time.Time
	ExpiresIn          int64

	Encrypted bool
}

type MCPPromptReadStats added in v0.8.0

type MCPPromptReadStats struct {
	PromptName string `json:"promptName"`
	ReadCount  int64  `json:"readCount"`
}

MCPPromptReadStats represents statistics for individual prompt reads

type MCPResourceReadStats added in v0.8.0

type MCPResourceReadStats struct {
	ResourceURI string `json:"resourceUri"`
	ReadCount   int64  `json:"readCount"`
}

MCPResourceReadStats represents statistics for individual resource reads

type MCPServerDetail added in v0.22.0

type MCPServerDetail struct {
	MCPServerStat
	EnvKeys    []string
	HeaderKeys []string
}

MCPServerDetail is the per-hash detail payload: an aggregated row plus the union of EnvKeys / HeaderKeys observed across every occurrence (those are deliberately excluded from the hash).

type MCPServerOccurrence added in v0.22.0

type MCPServerOccurrence struct {
	DeviceScanID uint      `gorm:"column:device_scan_id"`
	DeviceID     string    `gorm:"column:device_id"`
	Client       string    `gorm:"column:client"`
	Scope        string    `gorm:"column:scope"`
	ScannedAt    time.Time `gorm:"column:scanned_at"`
	ID           uint      `gorm:"column:id"`
}

MCPServerOccurrence is one device's latest-scan instance of a given ConfigHash.

type MCPServerStat added in v0.22.0

type MCPServerStat struct {
	ConfigHash       string                      `gorm:"column:config_hash"`
	Name             string                      `gorm:"column:name"`
	Transport        string                      `gorm:"column:transport"`
	Command          string                      `gorm:"column:command"`
	Args             datatypes.JSONSlice[string] `gorm:"-"`
	URL              string                      `gorm:"column:url"`
	DeviceCount      int64                       `gorm:"column:device_count"`
	UserCount        int64                       `gorm:"column:user_count"`
	ClientCount      int64                       `gorm:"column:client_count"`
	ObservationCount int64                       `gorm:"column:observation_count"`
}

MCPServerStat is one row of the device-fleet MCP aggregation: every DeviceScanMCPServer with the same ConfigHash, observed in any device's latest scan within the requested time window, collapses into a single entity. Identity fields (Name, Transport, Command, URL, Args) are constant within a ConfigHash group by construction. Args is loaded post-hoc because JSONB has no MAX() in Postgres.

type MCPToolCallStats added in v0.8.0

type MCPToolCallStats struct {
	ToolName  string                 `json:"-"`
	CallCount int64                  `json:"callCount"`
	Items     []MCPToolCallStatsItem `json:"items"`
}

MCPToolCallStats represents statistics for individual tool calls

type MCPToolCallStatsItem added in v0.8.0

type MCPToolCallStatsItem struct {
	ToolName         string    `json:"toolName"`
	CreatedAt        time.Time `json:"createdAt"`
	UserID           string    `json:"userID"`
	ProcessingTimeMs int64     `json:"processingTimeMs"`
	ResponseStatus   int       `json:"responseStatus"`
	Error            string    `json:"error"`
}

type MCPUsageStatItem added in v0.8.0

type MCPUsageStatItem struct {
	MCPID                     string                 `json:"mcpID"`
	MCPServerDisplayName      string                 `json:"mcpServerDisplayName"`
	MCPServerCatalogEntryName string                 `json:"mcpServerCatalogEntryName"`
	ToolCalls                 []MCPToolCallStats     `json:"toolCalls,omitempty"`
	ResourceReads             []MCPResourceReadStats `json:"resourceReads,omitempty"`
	PromptReads               []MCPPromptReadStats   `json:"promptReads,omitempty"`
}

MCPUsageStatItem represents usage statistics for MCP servers

type MCPUsageStatsList added in v0.8.0

type MCPUsageStatsList struct {
	TotalCalls  int64              `json:"totalCalls"`
	UniqueUsers int64              `json:"uniqueUsers"`
	TimeStart   time.Time          `json:"timeStart"`
	TimeEnd     time.Time          `json:"timeEnd"`
	Items       []MCPUsageStatItem `json:"items"`
}

type MCPWebhookStatus added in v0.8.0

type MCPWebhookStatus struct {
	Type    string `json:"type,omitempty"`
	URL     string `json:"url,omitempty"`
	Method  string `json:"method,omitempty"`
	Name    string `json:"name,omitempty"`
	Tool    string `json:"tool,omitempty"`
	Status  string `json:"status,omitempty"`
	Message string `json:"message,omitempty"`
}

type MDMAssetBundle added in v0.24.0

type MDMAssetBundle struct {
	Digest  string `json:"digest" gorm:"primaryKey;size:64"`
	Content []byte `json:"-" gorm:"not null"`
}

MDMAssetBundle is one immutable validated source snapshot, addressed by the lowercase SHA-256 of Content. Rendered configuration artifacts are stored in their own table rather than sharing a generic blob abstraction.

type MDMConfiguration added in v0.24.0

type MDMConfiguration struct {
	ID uint `json:"id" gorm:"primaryKey;autoIncrement"`

	// There may be no default before device management is configured, but there
	// can never be more than one. The backend assigns the first configuration as
	// the default; clients cannot change this field.
	IsDefault bool `json:"-" gorm:"not null;default:false;uniqueIndex:idx_mdm_configurations_default,where:is_default = true"`

	CreatedBy uint      `json:"createdBy"`
	CreatedAt time.Time `json:"createdAt"`

	// Name is a vestigial column retained so the pre-existing NOT NULL "name"
	// column keeps accepting inserts on databases created before the
	// configuration rework. It is not part of the public API and is stored
	// empty. The nullable "description" column from that same schema is left in
	// place; it is harmless and never read.
	Name string `json:"-" gorm:"not null"`

	// AssetDigest identifies the bundle against which Values were validated.
	// ObotSentryVersion is copied from that bundle's manifest when artifacts are
	// rendered, so the generated version is known without reopening the bundle.
	// Artifacts are loaded separately from their explicit table. ZIP bytes never
	// pass through the public configuration API.
	AssetDigest       string                     `json:"-" gorm:"size:64;index"`
	ObotSentryVersion string                     `json:"-" gorm:"size:64"`
	Values            string                     `json:"-" gorm:"type:text"`
	Artifacts         []MDMConfigurationArtifact `json:"-" gorm:"-"`

	EnforcementEnabled   bool                        `json:"enforcementEnabled,omitempty"`
	EnforcementAllowlist types2.EnforcementAllowlist `json:"-" gorm:"serializer:json"`
}

MDMConfiguration is a fleet grouping that devices enroll into. Enrollment is authorized by one or more DeviceEnrollmentKeys attached to it; a device belongs to the configuration itself, not to any particular key.

type MDMConfigurationArtifact added in v0.24.0

type MDMConfigurationArtifact struct {
	ID                 uint   `json:"id" gorm:"primaryKey;autoIncrement"`
	MDMConfigurationID uint   `json:"mdmConfigurationID" gorm:"not null;index;uniqueIndex:idx_mdm_configuration_artifact_slug,priority:1"`
	Slug               string `json:"slug" gorm:"not null;uniqueIndex:idx_mdm_configuration_artifact_slug,priority:2"`
	Platform           string `json:"platform"`
	OS                 string `json:"os"`
	Instructions       string `json:"instructions"`
	Digest             string `json:"digest" gorm:"size:64;not null"`
	Content            []byte `json:"-" gorm:"not null"`
}

MDMConfigurationArtifact stores one rendered download. The configuration relationship is maintained explicitly by the gateway client without a database foreign-key constraint.

type MDMConfigurationEnforcement added in v0.25.0

type MDMConfigurationEnforcement struct {
	Enabled   bool
	Allowlist types2.EnforcementAllowlist
}

type MessagePolicyViolation added in v0.19.0

type MessagePolicyViolation struct {
	ID                   uint            `json:"id" gorm:"primaryKey"`
	CreatedAt            time.Time       `json:"createdAt" gorm:"index"`
	UserID               string          `json:"userID" gorm:"index"`
	PolicyID             string          `json:"policyID" gorm:"index"`
	PolicyName           string          `json:"policyName" gorm:"index"`
	PolicyDefinition     string          `json:"policyDefinition"`
	Direction            string          `json:"direction" gorm:"index"`
	ViolationExplanation string          `json:"violationExplanation"`
	BlockedContent       json.RawMessage `json:"blockedContent,omitempty"`
	ProjectID            string          `json:"projectID" gorm:"index"`
	ThreadID             string          `json:"threadID" gorm:"index"`
	Encrypted            bool            `json:"encrypted"`
}

MessagePolicyViolation represents a record of a message policy violation.

type Migration added in v0.12.0

type Migration struct {
	Name string `gorm:"primaryKey"`
}

type Property added in v0.13.0

type Property struct {
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	Key       string    `json:"key" gorm:"primaryKey"`
	Value     string    `json:"value"`
	Encrypted bool      `json:"encrypted"`
}

type RunTokenActivity added in v0.8.0

type RunTokenActivity struct {
	ID         uint
	CreatedAt  time.Time `` /* 152-byte string literal not displayed */
	Name       string
	UserID     string `gorm:"index:idx_run_token_activity_user_created,priority:1"`
	Model      string
	APIKeyID   *uint  `gorm:"index:idx_run_token_activity_api_key_created,priority:1"`
	APIKeyName string `gorm:"type:text"`
	// Provider is the provider that served the request.
	Provider string `gorm:"type:text"`
	// Outcome is success, error or canceled, as for LLM audit logs. It is empty on records
	// made before outcomes were recorded, which were all successful requests.
	Outcome    string `gorm:"type:text"`
	DurationMs int64
	// Fallback is true when a fallback served the request.
	Fallback bool `gorm:"not null;default:false"`

	Usage TokenUsage `gorm:"embedded"`
}

RunTokenActivity is one LLM request and its usage. Every request sent to the LLM gateway has one, failed ones too (with no usage), so request counts and success rates can be reported from it.

type SCIMAddress added in v0.28.0

type SCIMAddress struct {
	Formatted     string `json:"formatted,omitempty"`
	StreetAddress string `json:"streetAddress,omitempty"`
	Locality      string `json:"locality,omitempty"`
	Region        string `json:"region,omitempty"`
	PostalCode    string `json:"postalCode,omitempty"`
	Country       string `json:"country,omitempty"`
	Type          string `json:"type,omitempty"`
	Primary       bool   `json:"primary,omitempty"`
}

SCIMAddress is one of a SCIM user's addresses.

type SCIMConnection added in v0.27.0

type SCIMConnection struct {
	// ID is the server-issued UUID of the connection, and the UID of its SCIM principal.
	ID        string    `json:"id" gorm:"primaryKey"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

	// AdapterType selects the provider-specific SCIM rules. It is recorded when the connection is created and never
	// changes.
	AdapterType string               `json:"adapterType" gorm:"not null"`
	Origin      SCIMConnectionOrigin `json:"origin" gorm:"not null"`

	// AuthProviderNamespace and AuthProviderName are the exact auth provider whose users and groups this connection
	// manages.
	AuthProviderNamespace string `json:"authProviderNamespace" gorm:"not null;uniqueIndex:idx_scim_connections_auth_provider"`
	AuthProviderName      string `json:"authProviderName" gorm:"not null;uniqueIndex:idx_scim_connections_auth_provider"`

	// GroupIDPrefix is the auth provider's group ID prefix, which groups created through SCIM keep.
	GroupIDPrefix string `json:"groupIDPrefix" gorm:"not null"`

	// Issuer is the identity provider's issuer URL, recorded when the connection was created.
	Issuer string `json:"issuer"`

	State SCIMConnectionState `json:"state" gorm:"not null"`

	// TokenVerifier is a hash of the current bearer token, and PreviousTokenVerifier a hash of the token it replaced,
	// which is still accepted until PreviousTokenExpiresAt or until it is revoked. Both are empty for a connection
	// that has no token yet. Tokens themselves are never stored.
	TokenVerifier          string     `json:"-"`
	TokenIssuedAt          *time.Time `json:"tokenIssuedAt,omitempty"`
	PreviousTokenVerifier  string     `json:"-"`
	PreviousTokenExpiresAt *time.Time `json:"previousTokenExpiresAt,omitempty"`

	// EnabledAt is when SCIM replaced login-time directory synchronization for the provider, and EnforcedAt when
	// sign-in started requiring a SCIM binding.
	EnabledAt  time.Time  `json:"enabledAt"`
	EnforcedAt *time.Time `json:"enforcedAt,omitempty"`

	// LastRequestAt is when the last authenticated SCIM request arrived, and LastSuccessAt when the last one
	// succeeded. They are recorded at most every few seconds, and show activity, not that the identity provider and
	// Obot are synchronized.
	LastRequestAt *time.Time `json:"lastRequestAt,omitempty"`
	LastSuccessAt *time.Time `json:"lastSuccessAt,omitempty"`
}

SCIMConnection connects one auth provider to an identity provider's SCIM client. Once it exists, SCIM replaces login-time directory synchronization for that provider, permanently. The installation has at most one.

func (SCIMConnection) HasToken added in v0.27.0

func (c SCIMConnection) HasToken() bool

HasToken reports whether the connection has a current bearer token. A connection without one answers every request with 401.

func (SCIMConnection) PreviousTokenAccepted added in v0.27.0

func (c SCIMConnection) PreviousTokenAccepted(now time.Time) bool

PreviousTokenAccepted reports whether the token that the last rotation replaced is still accepted.

func (SCIMConnection) TokenAccepted added in v0.27.0

func (c SCIMConnection) TokenAccepted(now time.Time) bool

TokenAccepted reports whether the current bearer token is still accepted.

func (SCIMConnection) TokenExpiresAt added in v0.27.0

func (c SCIMConnection) TokenExpiresAt() *time.Time

TokenExpiresAt returns when the current bearer token stops being accepted, or nil when the connection has none.

type SCIMConnectionOrigin added in v0.27.0

type SCIMConnectionOrigin string

SCIMConnectionOrigin is how a SCIM connection came to exist.

type SCIMConnectionState added in v0.27.0

type SCIMConnectionState string

SCIMConnectionState is how far a SCIM connection has taken over its auth provider's directory. Both transitions, from no connection to connected and from connected to enforced, are permanent.

type SCIMEnterpriseUser added in v0.28.0

type SCIMEnterpriseUser struct {
	EmployeeNumber string       `json:"employeeNumber,omitempty"`
	CostCenter     string       `json:"costCenter,omitempty"`
	Organization   string       `json:"organization,omitempty"`
	Division       string       `json:"division,omitempty"`
	Department     string       `json:"department,omitempty"`
	Manager        *SCIMManager `json:"manager,omitempty"`
}

SCIMEnterpriseUser holds the attributes of the enterprise User extension of RFC 7643 section 4.3.

type SCIMGroupBinding added in v0.27.0

type SCIMGroupBinding struct {
	// ID is the server-issued SCIM group ID.
	ID           string `gorm:"primaryKey"`
	ConnectionID string `` /* 177-byte string literal not displayed */
	// GroupID is the ID of the Obot group, which never changes.
	GroupID string `gorm:"not null;index:idx_scim_group_bindings_group,unique,where:retired_at IS NULL;index"`
	// NormalizedDisplayName is the trimmed, case-folded display name.
	NormalizedDisplayName string                 `gorm:"not null;index:idx_scim_group_bindings_name,unique,priority:2"`
	Origin                SCIMGroupBindingOrigin `gorm:"not null"`
	// ExternalID is the group's externalId as the identity provider last sent it, which is empty when it sent none.
	ExternalID string `gorm:"not null;default:'';index:idx_scim_group_bindings_external_id,priority:2"`

	// Revision counts the changes to the group and its memberships made through SCIM.
	Revision  int64 `gorm:"not null;default:0"`
	CreatedAt time.Time
	UpdatedAt time.Time
	RetiredAt *time.Time `gorm:"index"`
}

SCIMGroupBinding binds a SCIM group to an Obot group. Its ID is a random (version 4) UUID. A retired binding stays as a tombstone. The Obot group itself, and every reference to it, outlives the binding.

Each group has at most one unretired binding, and the normalized display names of a connection's unretired bindings are unique.

func (SCIMGroupBinding) Retired added in v0.27.0

func (b SCIMGroupBinding) Retired() bool

Retired reports whether the binding has been retired.

type SCIMGroupBindingOrigin added in v0.27.0

type SCIMGroupBindingOrigin string

SCIMGroupBindingOrigin is whether a group binding took over an existing group or created one.

type SCIMGroupSubjectCleanup added in v0.27.0

type SCIMGroupSubjectCleanup struct {
	GroupID string `gorm:"primaryKey"`
	// Namespace holds the access policies whose subjects are removed.
	Namespace string `gorm:"not null"`
	CreatedAt time.Time
	// ClaimedUntil is when a replica's claim to run the cleanup expires. A failed cleanup keeps its claim, so this is
	// also when it is retried.
	ClaimedUntil *time.Time
	Attempts     int `gorm:"not null;default:0"`
	LastError    string
}

SCIMGroupSubjectCleanup records a group that a SCIM DELETE deleted while SCIM was enforced, whose subjects in access policies are still to be removed. The policies live in the controller store, which cannot share the transaction that deleted the group.

type SCIMManager added in v0.28.0

type SCIMManager struct {
	Value string `json:"value,omitempty"`
	Ref   string `json:"$ref,omitempty"`
}

SCIMManager is a SCIM user's manager, as the identity provider identifies them. It is never resolved to a user.

type SCIMMultiValue added in v0.27.0

type SCIMMultiValue struct {
	Value   string `json:"value,omitempty"`
	Display string `json:"display,omitempty"`
	Type    string `json:"type,omitempty"`
	Primary bool   `json:"primary,omitempty"`
}

SCIMMultiValue is one value of a multi-valued SCIM attribute such as emails.

type SCIMName added in v0.27.0

type SCIMName struct {
	Formatted       string `json:"formatted,omitempty"`
	FamilyName      string `json:"familyName,omitempty"`
	GivenName       string `json:"givenName,omitempty"`
	MiddleName      string `json:"middleName,omitempty"`
	HonorificPrefix string `json:"honorificPrefix,omitempty"`
	HonorificSuffix string `json:"honorificSuffix,omitempty"`
}

SCIMName is the SCIM user's structured name.

type SCIMPendingGroupDeletion added in v0.27.0

type SCIMPendingGroupDeletion struct {
	GroupID      string `gorm:"primaryKey"`
	ConnectionID string `gorm:"not null;index"`
	// RunID identifies the deletion that placed the mark. A deletion deletes only the groups it marked itself, and
	// read the references of after marking them.
	RunID     string `gorm:"not null;default:''"`
	CreatedAt time.Time
}

SCIMPendingGroupDeletion marks a group that was selected for deletion because nothing references it. The mark is committed before the group is deleted, so that writers of group references can refuse new references to the group while its deletion completes. A mark expires a while after CreatedAt, by the database's clock, so that one a deletion left behind does not refuse references forever; the deletion then deletes nothing.

type SCIMReferenceWrite added in v0.27.0

type SCIMReferenceWrite struct {
	ID        string    `gorm:"primaryKey"`
	ExpiresAt time.Time `gorm:"not null;index"`
}

SCIMReferenceWrite records a write of new group references that is in progress. A deletion of unreferenced groups waits for the writes recorded when its marks committed, so that the references it reads afterwards include theirs, and every later write sees the marks. A write that never finished stops counting once it expires.

type SCIMRequestFailure added in v0.27.0

type SCIMRequestFailure struct {
	ID           uint   `gorm:"primaryKey"`
	ConnectionID string `gorm:"not null;index"`
	CreatedAt    time.Time
	Method       string
	// Resource is the request path below the connection's base URL.
	Resource  string
	Status    int
	SCIMType  string
	Detail    string
	Encrypted bool `gorm:"not null;default:false"`
}

SCIMRequestFailure records an authenticated SCIM request that failed, so administrators can see why provisioning tasks fail in the identity provider. Only the most recent failures of each connection are kept.

Detail can echo values from the request, such as a userName, so it is encrypted like users are.

type SCIMResourceType added in v0.27.0

type SCIMResourceType string

SCIMResourceType is the kind of resource a SCIM ID identifies.

type SCIMUserBinding added in v0.27.0

type SCIMUserBinding struct {
	// ID is the server-issued SCIM user ID. idx_scim_user_bindings_list serves the pages of a connection's users,
	// which are ordered by creation.
	ID           string `gorm:"primaryKey;index:idx_scim_user_bindings_list,priority:3,where:retired_at IS NULL"`
	ConnectionID string `` /* 298-byte string literal not displayed */
	UserID       uint   `gorm:"not null;index:idx_scim_user_bindings_user,unique,priority:2;index"`

	// HashedNativeUserID is the hash of the identity provider's immutable user ID, which the adapter derives from the
	// externalId. Which identity column it matches depends on the adapter's UserKey.
	HashedNativeUserID string `gorm:"not null;index:idx_scim_user_bindings_native,unique,priority:2"`
	// HashedUserName is the hash of the SCIM userName's comparison key, which SCIMUserNameKey returns.
	HashedUserName string `gorm:"not null;index:idx_scim_user_bindings_user_name,unique,priority:2"`

	ExternalID string
	UserName   string
	// Profile is the JSON-encoded SCIMUserProfile.
	Profile   string
	Encrypted bool `gorm:"not null;default:false"`

	// Active is the provisioned state the identity provider last sent.
	Active bool `gorm:"not null;default:false"`

	// Revision counts the changes to the binding.
	Revision  int64     `gorm:"not null;default:0"`
	CreatedAt time.Time `gorm:"index:idx_scim_user_bindings_list,priority:2"`
	UpdatedAt time.Time
	RetiredAt *time.Time `gorm:"index"`
}

SCIMUserBinding binds a SCIM user to an Obot user. Its ID is a random (version 4) UUID, like every SCIM ID this server issues, so SCIM IDs are unique across resource types. A retired binding stays as a tombstone, so that group writes that still mention it can recognize it.

Among a connection's unretired bindings, at most one has a given native user ID, at most one refers to a given Obot user, and at most one has a given case-folded userName.

ExternalID, UserName, and Profile hold data from the identity provider and are encrypted like users are. HashedNativeUserID and HashedUserName support equality lookups without decrypting.

func (SCIMUserBinding) Retired added in v0.27.0

func (b SCIMUserBinding) Retired() bool

Retired reports whether the binding has been retired.

type SCIMUserProfile added in v0.27.0

type SCIMUserProfile struct {
	Name              *SCIMName        `json:"name,omitempty"`
	DisplayName       string           `json:"displayName,omitempty"`
	NickName          string           `json:"nickName,omitempty"`
	ProfileURL        string           `json:"profileUrl,omitempty"`
	Title             string           `json:"title,omitempty"`
	UserType          string           `json:"userType,omitempty"`
	PreferredLanguage string           `json:"preferredLanguage,omitempty"`
	Locale            string           `json:"locale,omitempty"`
	Timezone          string           `json:"timezone,omitempty"`
	Emails            []SCIMMultiValue `json:"emails,omitempty"`
	PhoneNumbers      []SCIMMultiValue `json:"phoneNumbers,omitempty"`
	Addresses         []SCIMAddress    `json:"addresses,omitempty"`
	// EnterpriseUser holds the attributes of the enterprise User extension.
	EnterpriseUser *SCIMEnterpriseUser `json:"enterpriseUser,omitempty"`
}

SCIMUserProfile holds the supported SCIM user attributes that Obot's User cannot represent. The primary email and the display name are also projected onto the User.

func (SCIMUserProfile) ObotDisplayName added in v0.27.0

func (p SCIMUserProfile) ObotDisplayName() string

ObotDisplayName returns the name to show for the user in Obot: the display name, then the formatted name, then the given and family names. It is empty when the profile has none of them.

func (SCIMUserProfile) PrimaryEmail added in v0.27.0

func (p SCIMUserProfile) PrimaryEmail() string

PrimaryEmail returns the email marked primary, or the first email when none is.

type ServiceAccountAPIKey added in v0.21.0

type ServiceAccountAPIKey struct {
	ID                 uint       `gorm:"primaryKey;autoIncrement"`
	ServiceAccountName string     `gorm:"index;not null"`
	HashedSecret       string     `json:"-"`
	Token              string     `gorm:"-" json:"-"`
	CreatedAt          time.Time  `json:"createdAt"`
	ValidAfter         time.Time  `json:"validAfter"`
	RetireAfter        *time.Time `json:"retireAfter,omitempty"`
}

func (*ServiceAccountAPIKey) PlaintextToken added in v0.21.0

func (k *ServiceAccountAPIKey) PlaintextToken() string

type SkillDetail added in v0.22.0

type SkillDetail struct {
	SkillStat
	Description  string
	HasScripts   bool
	GitRemoteURL string
	Files        []string
}

SkillDetail is the per-skill detail payload: an aggregated row plus representative metadata pulled from a single canonical row in the latest-scan-per-device subset. Description / HasScripts / GitRemoteURL / Files come from one observation and are not guaranteed to be stable across observations sharing the same name.

type SkillOccurrence added in v0.22.0

type SkillOccurrence struct {
	DeviceScanID uint      `gorm:"column:device_scan_id"`
	DeviceID     string    `gorm:"column:device_id"`
	Client       string    `gorm:"column:client"`
	Scope        string    `gorm:"column:scope"`
	ProjectPath  string    `gorm:"column:project_path"`
	ScannedAt    time.Time `gorm:"column:scanned_at"`
	ID           uint      `gorm:"column:id"`
}

SkillOccurrence is one device's latest-scan instance of a given skill name.

type SkillStat added in v0.22.0

type SkillStat struct {
	Name             string `gorm:"column:name"`
	DeviceCount      int64  `gorm:"column:device_count"`
	UserCount        int64  `gorm:"column:user_count"`
	ObservationCount int64  `gorm:"column:observation_count"`
}

SkillStat is one row of the per-skill rollup.

type TempSetupUser added in v0.13.0

type TempSetupUser struct {
	ID                    uint        `json:"id" gorm:"primaryKey"`
	UserID                uint        `json:"userID" gorm:"index"`
	Username              string      `json:"username"`
	Email                 string      `json:"email"`
	Role                  types2.Role `json:"role"`
	IconURL               string      `json:"iconURL"`
	AuthProviderName      string      `json:"authProviderName"`
	AuthProviderNamespace string      `json:"authProviderNamespace"`
	CreatedAt             time.Time   `json:"createdAt"`
}

type TokenRequest

type TokenRequest struct {
	ID                    string `gorm:"primaryKey"`
	CreatedAt             time.Time
	UpdatedAt             time.Time
	Purpose               string    `gorm:"index"`
	DeviceCodeDigest      *string   `gorm:"uniqueIndex"`
	RequestExpiresAt      time.Time `gorm:"index"`
	DeviceCodeVerifiedAt  *time.Time
	State                 string `gorm:"index"`
	Name                  string
	Description           string
	Scopes                APIKeyScopes `gorm:"embedded"`
	Token                 string
	NoExpiration          bool
	ExpiresAt             time.Time
	CompletionRedirectURL string
	Error                 string
	TokenRetrieved        bool

	// OwnerUserID is the user who started a staged auth provider verification. Only they may open
	// the resulting login, so a verification cannot be picked up by another signed-in user.
	OwnerUserID *uint
}

type TokenUsage added in v0.24.0

type TokenUsage struct {
	// InputTokens is the total input: CacheReadTokens + CacheWriteTokens + uncached input.
	InputTokens int
	// CacheReadTokens is the cache-hit input tokens; a subset of InputTokens.
	CacheReadTokens int
	// CacheWriteTokens is the cache-write input tokens (5m + 1h); a subset of InputTokens
	// (Anthropic only).
	CacheWriteTokens int
	// OutputTokens is the total output, including ThinkingTokens.
	OutputTokens int
	// ThinkingTokens is the thinking/reasoning output tokens; a subset of OutputTokens.
	ThinkingTokens int
	// TotalTokens is InputTokens + OutputTokens.
	TotalTokens int

	// InputSpend is the total USD on InputTokens (each bucket at its own rate):
	// CacheReadSpend + CacheWriteSpend + uncached-input spend. 0 when unpriced.
	InputSpend float64
	// CacheReadSpend is the USD on CacheReadTokens; a subset of InputSpend.
	CacheReadSpend float64
	// CacheWriteSpend is the USD on CacheWriteTokens; a subset of InputSpend.
	CacheWriteSpend float64
	// OutputSpend is the USD on OutputTokens.
	OutputSpend float64
	// TotalSpend is InputSpend + OutputSpend.
	TotalSpend float64
}

TokenUsage is normalized token usage and spend.

type User

type User struct {
	ID             uint        `json:"id" gorm:"primaryKey"`
	CreatedAt      time.Time   `json:"createdAt"`
	DisplayName    string      `json:"displayName"`
	Username       string      `json:"username"`
	HashedUsername string      `json:"-" gorm:"unique"`
	Email          string      `json:"email"`
	HashedEmail    string      `json:"-"`
	Role           types2.Role `json:"role"`
	IconURL        string      `json:"iconURL"`
	Timezone       string      `json:"timezone"`

	// LastActiveDay is the time of the last request made by this user, currently at the 24 hour granularity.
	LastActiveDay          time.Time `json:"lastActiveDay"`
	Internal               bool      `json:"internal" gorm:"default:false"`
	DailyInputTokensLimit  int       `json:"dailyInputTokensLimit"`
	DailyOutputTokensLimit int       `json:"dailyOutputTokensLimit"`
	Encrypted              bool      `json:"encrypted"`
	// Soft delete fields
	DeletedAt        *time.Time `json:"deletedAt,omitempty"`
	OriginalEmail    string     `json:"-"`
	OriginalUsername string     `json:"-"`

	// Lifecycle fields. A disabled user keeps their account, identities, roles, memberships, and resources, but
	// is denied access. Unlike deletion, disabling is reversible. Only lifecycle operations write these fields;
	// see UserLifecycleColumns.
	DisabledAt     *time.Time         `json:"disabledAt,omitempty"`
	DisabledReason UserDisabledReason `json:"disabledReason,omitempty" gorm:"not null;default:''"`
}

func (User) ManagementSource added in v0.27.0

func (u User) ManagementSource() types2.UserManagementSource

ManagementSource returns what controls the user's lifecycle status, as far as the user row shows it. Only SCIM sets a disable reason, so a user with one is managed by SCIM. So is a user with a SCIM binding, which the row does not show, so callers that read the binding report SCIM for it.

func (User) Status added in v0.27.0

func (u User) Status() types2.UserStatus

Status returns the user's lifecycle status. Deletion takes precedence over disabling.

type UserDisabledReason added in v0.27.0

type UserDisabledReason string

UserDisabledReason records why a user is disabled.

const (
	// UserDisabledReasonSCIMInactive means the identity provider deprovisioned the user through SCIM.
	UserDisabledReasonSCIMInactive UserDisabledReason = "scim_inactive"
	// UserDisabledReasonSCIMUnprovisioned means SCIM was enforced for the user's auth provider before the
	// identity provider provisioned the user.
	UserDisabledReasonSCIMUnprovisioned UserDisabledReason = "scim_unprovisioned"
	// UserDisabledReasonSCIMDeleted means the identity provider deleted the user through SCIM. The user is deleted in
	// the same transaction, so the reason shows only until their data is cleaned up.
	UserDisabledReasonSCIMDeleted UserDisabledReason = "scim_deleted"
)

func (UserDisabledReason) Valid added in v0.27.0

func (r UserDisabledReason) Valid() bool

Valid reports whether r is a known disable reason.

type UserLifecycleEvent added in v0.27.0

type UserLifecycleEvent struct {
	// ID orders the events. idx_user_lifecycle_events_pending serves delivery, which reads the pending events in order.
	ID        uint                   `json:"id" gorm:"primaryKey;index:idx_user_lifecycle_events_pending,where:delivered_at IS NULL"`
	CreatedAt time.Time              `json:"createdAt"`
	UserID    uint                   `json:"userID" gorm:"index"`
	Type      UserLifecycleEventType `json:"type"`
	// GroupsRemoved is set on a reconcile event when the user left at least one group.
	GroupsRemoved bool `json:"groupsRemoved" gorm:"not null;default:false"`

	// ClaimedUntil is when a replica's claim to deliver the event expires, so that replicas rarely deliver the
	// same event at once. Delivery is idempotent, so an expired claim is safe to take over.
	ClaimedUntil *time.Time `json:"claimedUntil,omitempty"`
	DeliveredAt  *time.Time `json:"deliveredAt,omitempty" gorm:"index"`
	Attempts     int        `json:"attempts" gorm:"not null;default:0"`
	LastError    string     `json:"lastError,omitempty"`
}

UserLifecycleEvent is an outbox entry for work that must follow a committed change to a user, in a store the gateway database cannot share a transaction with. It is written in the same transaction as the change, and delivered after the commit until delivery succeeds.

type UserLifecycleEventType added in v0.27.0

type UserLifecycleEventType string

UserLifecycleEventType is the kind of work a UserLifecycleEvent records.

const (
	// UserLifecycleEventDisabled removes what a disabled user must not keep: their MCP OAuth refresh tokens.
	UserLifecycleEventDisabled UserLifecycleEventType = "disabled"
	// UserLifecycleEventReconcile recomputes what depends on a user's roles and, when the user left a group,
	// the resources that group granted.
	UserLifecycleEventReconcile UserLifecycleEventType = "reconcile"
	// UserLifecycleEventDeleted removes what a deleted user owns: their identities, sessions, API keys, agents,
	// vMCPs, and MCP servers.
	UserLifecycleEventDeleted UserLifecycleEventType = "deleted"
)

type UserQuery

type UserQuery struct {
	Username       string
	Email          string
	Role           types2.Role
	IncludeDeleted bool
}

func NewUserQuery

func NewUserQuery(u url.Values) UserQuery

func (UserQuery) Scope

func (q UserQuery) Scope(db *gorm.DB) *gorm.DB

Jump to

Keyboard shortcuts

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