api

package
v0.0.0-...-548cdc5 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 94 Imported by: 0

Documentation

Overview

Package api provides storage and HTTP handlers for the TMI service.

Package api provides storage and HTTP handlers for the TMI service.

Package api provides storage and HTTP handlers for the TMI service.

Package api provides primitives to interact with the openapi HTTP API.

Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.7.1 DO NOT EDIT.

Package api provides dialect-specific SQL helpers for cross-database compatibility. These helpers abstract database-specific SQL syntax differences that GORM doesn't automatically handle.

Package api implements the TMI HTTP API.

optimistic_locking.go provides shared helpers for the If-Match / version optimistic-locking contract introduced for T14 (#385). Mutable top-level entities (threat models, diagrams, projects, teams, assets, threats, documents, surveys) carry an integer Version column. PUT/PATCH callers pass the expected current version via the If-Match header (preferred) or a "version" body field (fallback). The repository layer then issues a versioned UPDATE; on a version mismatch handlers return 409 Conflict.

Rollout policy this release:

  • If neither If-Match nor body version is provided, the write proceeds but the response carries a Deprecation/Warning header.
  • When config RequireIfMatch is true (planned for the next release), missing If-Match returns 428 Precondition Required.

Oracle migration shape (#391, verified):

gorm-oracle v1.1.1 Migrator.AddColumn (oracle/migrator.go:298) emits a
SINGLE-statement ALTER TABLE for new columns:
  ALTER TABLE <table> ADD (<col> <DataType> DEFAULT 1 NOT NULL)
via FullDataTypeOf (oracle/migrator.go:615), which concatenates type +
default + NOT NULL in one clause.Expr. Oracle 12c+ / 19c ADB stores the
default in SYS.ECOL$ as metadata and synthesizes it for pre-existing
rows on read until they are rewritten, so the rollout does NOT take a
row-rewrite TM lock on threat_models / diagrams / assets / threats /
documents. If the gorm-oracle dependency is bumped, re-verify this
emission shape — the two-statement form (ADD + MODIFY NOT NULL) would
re-scan every row.

Package api — store-side helpers for the optimistic-locking contract (T14 / #385). Each Gorm-backed store for a versioned entity exposes a CheckAndBumpVersion method that delegates to the central helper. Handlers call this BEFORE issuing the entity-specific Update so concurrent writers race on a single CAS-style UPDATE: the first to commit wins, the loser gets ErrVersionMismatch.

Each store passes its model's TableName() to the central helper so Oracle (uppercase) and PostgreSQL (lowercase) identifier folding both resolve to the right table name without leaking schema knowledge here.

Package api provides storage and HTTP handlers for the TMI service.

Package api provides storage and HTTP handlers for the TMI service.

Package api provides storage and HTTP handlers for the TMI service.

api/timmy_entity_key.go

Index

Constants

View Source
const (
	ReasonTokenNotLinked            = "token_not_linked"
	ReasonTokenRefreshFailed        = "token_refresh_failed"
	ReasonTokenTransientFailure     = "token_transient_failure"
	ReasonPickerRegistrationInvalid = "picker_registration_invalid"
	ReasonNoAccessibleSource        = "no_accessible_source"
	ReasonSourceNotFound            = "source_not_found"
	ReasonFetchError                = "fetch_error"
	ReasonOther                     = "other"
	// ReasonMicrosoftNotShared is emitted when a SharePoint/OneDrive document
	// has not been shared with the TMI Entra application. The remediation
	// provides a copy-pasteable Graph API call the file owner can run to grant
	// per-file read access.
	ReasonMicrosoftNotShared = "microsoft_not_shared"
)

Reason codes for DocumentAccessDiagnostics.reason_code (stable API contract). tmi-ux localizes messages by these codes.

View Source
const (
	ReasonExtractionLimitCompressedSize   = "extraction_limit:compressed_size"
	ReasonExtractionLimitDecompressedSize = "extraction_limit:decompressed_size"
	ReasonExtractionLimitPartSize         = "extraction_limit:part_size"
	ReasonExtractionLimitPartCount        = "extraction_limit:part_count"
	ReasonExtractionLimitMarkdownSize     = "extraction_limit:markdown_size"
	ReasonExtractionLimitTimeout          = "extraction_limit:timeout"
	ReasonExtractionLimitXMLDepth         = "extraction_limit:xml_depth"
	ReasonExtractionLimitZipNested        = "extraction_limit:zip_nested"
	ReasonExtractionLimitZipPath          = "extraction_limit:zip_path"
	ReasonExtractionLimitCompressionRatio = "extraction_limit:compression_ratio"
	ReasonExtractionMalformed             = "extraction_malformed"
	ReasonExtractionUnsupported           = "extraction_unsupported"
	ReasonExtractionInternal              = "extraction_internal"
	// ReasonExtractionDeadLettered is emitted when an extraction job's worker
	// exhausted redelivery without ever publishing a result (e.g. the worker
	// crashed/OOMed mid-job). The job was dead-lettered to jobs.dlq and the
	// monolith marked it failed. Retry may succeed.
	ReasonExtractionDeadLettered = "extraction_dead_lettered"
)

Reason codes emitted by the OOXML extractor pipeline. tmi-ux localizes messages by these codes.

View Source
const (
	RemediationLinkAccount             = "link_account"
	RemediationRelinkAccount           = "relink_account"
	RemediationRepickFile              = "repick_file"
	RemediationShareWithServiceAccount = "share_with_service_account"
	RemediationRepickAfterShare        = "repick_after_share"
	RemediationRetry                   = "retry"
	RemediationContactOwner            = "contact_owner"
	// RemediationShareWithApplication is emitted for the microsoft_not_shared
	// reason. Params include drive_id, item_id, app_object_id, graph_call, and
	// graph_body so the file owner can paste the Graph snippet directly.
	RemediationShareWithApplication = "share_with_application"
)

Remediation actions for DocumentAccessDiagnostics.remediations[].action.

View Source
const (
	DefaultMaxActiveInvocations  = 3 // Allow 3 concurrent invocations per user by default
	DefaultMaxInvocationsPerHour = 10
)

Default quota values

View Source
const (
	// MaxIconLength is the maximum allowed length for icon strings
	MaxIconLength = 60
	// MaxAddonObjects is the maximum number of objects allowed in an add-on
	MaxAddonObjects = 100
	// MaxAddonDescriptionLength is the maximum allowed length for add-on descriptions
	// Consistent with ThreatBase.description maxLength in OpenAPI spec
	MaxAddonDescriptionLength = 2048
)
View Source
const (
	// MaxAddonParameters is the maximum number of parameters allowed per add-on
	MaxAddonParameters = 20
	// MaxAddonParameterEnumValues is the maximum number of enum values per parameter
	MaxAddonParameterEnumValues = 50
	// MaxAddonParameterNameLength is the maximum length for parameter names
	MaxAddonParameterNameLength = 128
	// MaxAddonParameterDescriptionLength is the maximum length for parameter descriptions
	MaxAddonParameterDescriptionLength = 512
	// MaxAddonParameterValueLength is the maximum length for enum values and default values
	MaxAddonParameterValueLength = 256
	// MaxAddonParameterMetadataKeyLength is the maximum length for metadata key names
	MaxAddonParameterMetadataKeyLength = 256
	// MaxStringValidationRegexLength is the maximum length for string_validation_regex patterns
	MaxStringValidationRegexLength = 256
	// MaxStringMaxLength is the upper bound for string_max_length constraint
	MaxStringMaxLength = 10000
)

Addon parameter validation constants

View Source
const (
	DefaultWebSocketDebounceDelay = 5 * time.Second
	DefaultRESTDebounceDelay      = 10 * time.Second
)

Default debounce delays

View Source
const (
	// EveryonePseudoGroup is a special group that matches all authenticated users
	// regardless of their identity provider or actual group memberships
	EveryonePseudoGroup = "everyone"

	// EveryonePseudoGroupUUID is the flag UUID used to represent the "everyone" pseudo-group
	// in the database. This allows storing "everyone" in a UUID column (subject_internal_uuid).
	// The zero UUID (all zeros) is used as it will never conflict with real user UUIDs.
	EveryonePseudoGroupUUID = "00000000-0000-0000-0000-000000000000"
)

Pseudo-group constants

View Source
const (
	// SecurityReviewersGroup is a built-in group for security engineers who triage survey responses and threat models.
	// Unlike pseudo-groups, this is a regular group that can have members managed via the admin API.
	// It uses the built-in provider ("tmi") and is auto-added to non-confidential survey responses and threat models.
	SecurityReviewersGroup = "security-reviewers"

	// SecurityReviewersGroupUUID is the well-known UUID for the Security Reviewers group.
	// This allows the group to be referenced before it's explicitly created in the database.
	SecurityReviewersGroupUUID = "00000000-0000-0000-0000-000000000001"

	// AdministratorsGroup is the group_name for the built-in Administrators group.
	// Users and groups that are members of this group have administrative privileges.
	AdministratorsGroup = "administrators"

	// AdministratorsGroupUUID is the well-known UUID for the Administrators built-in group.
	AdministratorsGroupUUID = "00000000-0000-0000-0000-000000000002"

	// ConfidentialProjectReviewersGroup is the group_name for the built-in
	// Confidential Project Reviewers group. Used for reviews of confidential
	// survey responses and threat models.
	ConfidentialProjectReviewersGroup = "confidential-project-reviewers"

	// ConfidentialProjectReviewersGroupUUID is the well-known UUID for the
	// Confidential Project Reviewers built-in group.
	ConfidentialProjectReviewersGroupUUID = "00000000-0000-0000-0000-000000000003"

	// TMIAutomationGroup is the group_name for the built-in TMI Automation group.
	// Automation/service accounts are added to this group to enable automated access to TMI objects.
	TMIAutomationGroup = "tmi-automation"

	// TMIAutomationGroupUUID is the well-known UUID for the TMI Automation built-in group.
	TMIAutomationGroupUUID = "00000000-0000-0000-0000-000000000004"

	// EmbeddingAutomationGroup is the group_name for the built-in Embedding Automation group.
	// Members can push pre-computed embeddings and read embedding provider config (including API keys).
	EmbeddingAutomationGroup = "embedding-automation"

	// EmbeddingAutomationGroupUUID is the well-known UUID for the Embedding Automation built-in group.
	EmbeddingAutomationGroupUUID = "00000000-0000-0000-0000-000000000005"
)

Built-in group constants

View Source
const (
	SortDirectionDESC = "DESC"
	SortDirectionASC  = "ASC"
)

Sort direction constants

View Source
const (
	PatchPathName        = "/name"
	PatchPathType        = "/type"
	PatchPathDescription = "/description"
	PatchPathURI         = "/uri"
	PatchPathStatus      = "/status"
)

JSON Patch path constants for common resource fields

View Source
const (
	ThreatModelCacheTTL = 10 * time.Minute // 10-15 minutes for threat models
	DiagramCacheTTL     = 2 * time.Minute  // 2-3 minutes for diagrams
	SubResourceCacheTTL = 5 * time.Minute  // 5-10 minutes for sub-resources
	AuthCacheTTL        = 15 * time.Minute // 15 minutes for authorization data
	MetadataCacheTTL    = 7 * time.Minute  // 5-10 minutes for metadata
	ListCacheTTL        = 5 * time.Minute  // 5 minutes for paginated lists
)

Cache TTL configurations based on the implementation plan

View Source
const (
	ProviderConfluence      = "confluence"
	ProviderGoogleDrive     = "google_drive"
	ProviderGoogleWorkspace = "google_workspace"
	ProviderHTTP            = "http"
	ProviderMicrosoft       = "microsoft"
	// ProviderOneDrive is the legacy name; retained as an alias until all wiring switches to ProviderMicrosoft.
	ProviderOneDrive = ProviderMicrosoft
)

Provider name constants

View Source
const (
	AccessStatusUnknown          = "unknown"
	AccessStatusAccessible       = "accessible"
	AccessStatusPendingAccess    = "pending_access"
	AccessStatusExtractionFailed = "extraction_failed"
)

Document access status constants

View Source
const (
	ContentTokenStatusActive        = "active"
	ContentTokenStatusFailedRefresh = "failed_refresh"
)

ContentTokenStatus constants for the Status field of ContentToken.

View Source
const (
	DialectPostgres  = "postgres"
	DialectOracle    = "oracle"
	DialectMySQL     = "mysql"
	DialectSQLServer = "sqlserver"
	DialectSQLite    = "sqlite"
)

Dialect names as returned by GORM's Dialector.Name()

View Source
const (
	// Threat Model Events
	EventThreatModelCreated = "threat_model.created"
	EventThreatModelUpdated = "threat_model.updated"
	EventThreatModelDeleted = "threat_model.deleted"

	// Diagram Events
	EventDiagramCreated = "diagram.created"
	EventDiagramUpdated = "diagram.updated"
	EventDiagramDeleted = "diagram.deleted"

	// Document Events
	EventDocumentCreated = "document.created"
	EventDocumentUpdated = "document.updated"
	EventDocumentDeleted = "document.deleted"

	// Note Events
	EventNoteCreated = "note.created"
	EventNoteUpdated = "note.updated"
	EventNoteDeleted = "note.deleted"

	// Repository Events
	EventRepositoryCreated = "repository.created"
	EventRepositoryUpdated = "repository.updated"
	EventRepositoryDeleted = "repository.deleted"

	// Asset Events
	EventAssetCreated = "asset.created"
	EventAssetUpdated = "asset.updated"
	EventAssetDeleted = "asset.deleted"

	// Threat Events
	EventThreatCreated = "threat.created"
	EventThreatUpdated = "threat.updated"
	EventThreatDeleted = "threat.deleted"

	// Metadata Events
	EventMetadataCreated = "metadata.created"
	EventMetadataUpdated = "metadata.updated"
	EventMetadataDeleted = "metadata.deleted"

	// Survey Events
	EventSurveyCreated = "survey.created"
	EventSurveyUpdated = "survey.updated"
	EventSurveyDeleted = "survey.deleted"

	// Survey Response Events
	EventSurveyResponseCreated = "survey_response.created"
	EventSurveyResponseUpdated = "survey_response.updated"
	EventSurveyResponseDeleted = "survey_response.deleted"

	// Team events
	EventTeamCreated = "team.created"
	EventTeamUpdated = "team.updated"
	EventTeamDeleted = "team.deleted"

	// Project events
	EventProjectCreated = "project.created"
	EventProjectUpdated = "project.updated"
	EventProjectDeleted = "project.deleted"

	// Addon Events
	EventAddonInvoked = "addon.invoked"

	// Document extraction outcome events (async pipeline, #347)
	EventDocumentExtractionCompleted = "document.extraction_completed"
	EventDocumentExtractionFailed    = "document.extraction_failed"

	// System audit events (T7, #395): emitted for every system_audit_entries
	// write (admin-write middleware and step-up adapter paths).
	EventSystemAuditAdminWrite = "system_audit.admin_write"
)

Event type constants for webhook emissions

View Source
const (
	// User API Quota limits
	MaxRequestsPerMinute = 10000  // Maximum API requests per minute per user
	MaxRequestsPerHour   = 600000 // Maximum API requests per hour per user

	// Webhook Quota limits
	MaxSubscriptions                 = 100   // Maximum webhook subscriptions per user
	MaxEventsPerMinute               = 1000  // Maximum webhook events per minute
	MaxSubscriptionRequestsPerMinute = 100   // Maximum subscription requests per minute
	MaxSubscriptionRequestsPerDay    = 10000 // Maximum subscription requests per day

	// Addon Invocation Quota limits
	MaxActiveInvocations  = 10   // Maximum concurrent active addon invocations
	MaxInvocationsPerHour = 1000 // Maximum addon invocations per hour
)

Quota ceiling constants define maximum allowed values for various quota types These limits prevent integer overflow and ensure system stability

View Source
const (
	GroupSortByGroupName  = "group_name"
	GroupSortByFirstUsed  = "first_used"
	GroupSortByLastUsed   = "last_used"
	GroupSortByUsageCount = "usage_count"
)

Group sort field constants used in GroupFilter.SortBy

View Source
const (
	// MaxPaginationLimit is the maximum allowed value for limit parameter
	MaxPaginationLimit = 1000
	// MaxPaginationOffset is the maximum allowed value for offset parameter
	MaxPaginationOffset = 1000000 // 1 million - reasonable for web UI pagination
)

Pagination validation constants

View Source
const (
	SettingsCacheTTL = 60 * time.Second // Short TTL for settings
	SettingsCacheKey = "tmi:settings:"
)

Cache TTL for system settings

View Source
const (
	SurveyStatusActive   = "active"
	SurveyStatusInactive = "inactive"
	SurveyStatusArchived = "archived"
)

Survey status constants (free-form strings matching ThreatModel pattern)

View Source
const (
	ResponseStatusDraft          = "draft"
	ResponseStatusSubmitted      = "submitted"
	ResponseStatusNeedsRevision  = "needs_revision"
	ResponseStatusReadyForReview = "ready_for_review"
	ResponseStatusReviewCreated  = "review_created"
)

Survey response status constants

View Source
const (
	// IndexTypeText is the index type for text content (assets, threats, diagrams, documents, notes)
	IndexTypeText = "text"

	// IndexTypeCode is the index type for code content (repositories)
	IndexTypeCode = "code"
)
View Source
const (
	DefaultMaxRequestsPerMinute = 1000  // Increased from 100 for fuzz testing
	DefaultMaxRequestsPerHour   = 60000 // Increased from 6000 for fuzz testing
)

Default user API quota values Note: These are set high for development and fuzz testing. In production, consider lowering these values and implementing tiered quotas per user role.

View Source
const (
	// MaxPreferencesSize is the maximum size in bytes for user preferences JSON
	MaxPreferencesSize = 1024 // 1KB

	// MaxPreferencesClients is the maximum number of client entries allowed
	MaxPreferencesClients = 20
)
View Source
const (
	DeliveryStatusPending    = "pending"
	DeliveryStatusInProgress = "in_progress"
	DeliveryStatusDelivered  = "delivered"
	DeliveryStatusFailed     = "failed"
)

Delivery status constants

View Source
const (
	DeliveryTTLActive    = 4 * time.Hour      // TTL for pending/in_progress records
	DeliveryTTLTerminal  = 7 * 24 * time.Hour // TTL for failed/delivered records
	DeliveryStaleTimeout = 15 * time.Minute   // inactivity timeout for in_progress records
)

Delivery TTL and timeout constants

View Source
const (
	DefaultMaxSubscriptions                 = 10
	DefaultMaxEventsPerMinute               = 12
	DefaultMaxSubscriptionRequestsPerMinute = 10
	DefaultMaxSubscriptionRequestsPerDay    = 20
)

Default quota values

View Source
const (
	AuthTypeTMI10 = "tmi-1.0"
)

Authorization type constants

View Source
const (
	BearerAuthScopes bearerAuthContextKey = "bearerAuth.Scopes"
)
View Source
const (
	// BuiltInProvider is the provider value for all TMI built-in groups and
	// the "everyone" pseudo-group. Replaces the former "*" wildcard.
	BuiltInProvider = "tmi"
)
View Source
const CacheEntityTypeSource = "source"

Cache entity type constant for sources

View Source
const (
	DefaultClientCredentialQuota = 10
)

Default quota value

View Source
const DefaultPruneInterval = 24 * time.Hour

DefaultPruneInterval is the default interval between pruning runs.

View Source
const DefaultSortOrderCreatedAtDesc = "created_at DESC"

Default sort order for list queries

View Source
const DefaultThreatModelFramework = "STRIDE"

Default threat model framework

View Source
const DefaultThreatModelStatus = "not_started"

DefaultThreatModelStatus is the initial status for newly created threat models. Matches the server-issued default advertised in the OpenAPI spec and the value that dashboard filters expect for "not yet started" work.

View Source
const DelegationTokenHeader = "X-TMI-Delegation-Token"

DelegationTokenHeader is the HTTP header that carries the per-attempt scoped delegation JWT for addon.invoked deliveries (T18, #358). Addons MUST use this token (not their own service-account credentials) when performing write-backs attributed to the invocation. The token's TTL matches the addon-invocation budget; if it expires, the addon's write-back is rejected and the invocation must be re-attempted. #nosec G101 — header name only; the token value comes from the delegation-token issuer at delivery time.

View Source
const (
	ErrMsgUserNotFound = "user not found"
)

Error message constants for resource lookup failures

View Source
const LogLevelDebugStr = "debug"

Log level string constant

View Source
const MaxConnectionsPerUser = 5

MaxConnectionsPerUser is the cap on simultaneous WebSocket connections held by a single user across all sessions on this hub. Set to zero to disable the cap.

View Source
const MaxParticipantsPerSession = 50

MaxParticipantsPerSession is the cap on clients inside one diagram session. Set to zero to disable the cap.

View Source
const (
	// OperatorSystemUserUUID is the well-known UUID for the synthetic Operator System
	// user record. This user owns the operator-pinned audit alert sink webhook
	// subscription (#395). It is seeded by seedOperatorSystemUser on every startup
	// and is never exposed via the API.
	OperatorSystemUserUUID = "00000000-0000-0000-0000-000000000001"
)

System user constants

View Source
const (
	ProtectedGroupEveryone = "everyone"
)

Protected group names that cannot be deleted

View Source
const SchemeWSS = "wss"

WebSocket scheme constant

View Source
const UnknownUserIdentity = "user=<unknown>"

Service account logging fallback

View Source
const VersionDeprecationLink = `true`

VersionDeprecationLink is emitted in the Deprecation header (RFC 8594) so clients have a stable signal they can scan for.

View Source
const VersionDeprecationMessage = `299 - "If-Match header (or body 'version') is required for PUT/PATCH; future releases will return 428 Precondition Required"`

VersionDeprecationMessage is emitted in the Warning response header when a caller omits both If-Match and the body version field. Per RFC 7234 the Warning header is "299 - <message>".

View Source
const WWWAuthenticateRealm = wwwauth.Realm

WWWAuthenticateRealm identifies the protection space for Bearer token authentication. This is a static value for TMI's API - all protected endpoints share the same realm.

Variables

View Source
var (
	ErrExtractionLimit = extract.ErrExtractionLimit
	ErrMalformed       = extract.ErrMalformed
	ErrUnsupported     = extract.ErrUnsupported
)

Sentinel-error re-exports.

View Source
var (
	NewContentExtractorRegistry = extract.NewContentExtractorRegistry
	NewDOCXExtractor            = extract.NewDOCXExtractor
	NewPPTXExtractor            = extract.NewPPTXExtractor
	NewXLSXExtractor            = extract.NewXLSXExtractor
	NewPDFExtractor             = extract.NewPDFExtractor
	NewHTMLExtractor            = extract.NewHTMLExtractor
	NewPlainTextExtractor       = extract.NewPlainTextExtractor
	NewTextChunker              = extract.NewTextChunker
)

Constructor re-exports.

View Source
var (
	ErrContentTokenNotFound  = fmt.Errorf("content token: %w", dberrors.ErrNotFound)
	ErrContentTokenDuplicate = fmt.Errorf("content token: %w", dberrors.ErrDuplicate)
)

Typed errors for content-token repository operations. Each wraps the corresponding dberrors sentinel so handlers can check either the entity-specific error or the generic category.

View Source
var (
	// GroupAdministrators is the built-in Administrators group.
	GroupAdministrators = BuiltInGroup{Name: AdministratorsGroup, UUID: uuid.MustParse(AdministratorsGroupUUID)}

	// GroupSecurityReviewers is the built-in Security Reviewers group.
	GroupSecurityReviewers = BuiltInGroup{Name: SecurityReviewersGroup, UUID: uuid.MustParse(SecurityReviewersGroupUUID)}

	// GroupConfidentialProjectReviewers is the built-in Confidential Project Reviewers group.
	GroupConfidentialProjectReviewers = BuiltInGroup{Name: ConfidentialProjectReviewersGroup, UUID: uuid.MustParse(ConfidentialProjectReviewersGroupUUID)}

	// GroupTMIAutomation is the built-in TMI Automation group.
	GroupTMIAutomation = BuiltInGroup{Name: TMIAutomationGroup, UUID: uuid.MustParse(TMIAutomationGroupUUID)}

	// GroupEmbeddingAutomation is the built-in Embedding Automation group.
	GroupEmbeddingAutomation = BuiltInGroup{Name: EmbeddingAutomationGroup, UUID: uuid.MustParse(EmbeddingAutomationGroupUUID)}
)
View Source
var (
	// Not-found errors
	ErrGroupNotFound          = fmt.Errorf("group: %w", dberrors.ErrNotFound)
	ErrMetadataNotFound       = fmt.Errorf("metadata: %w", dberrors.ErrNotFound)
	ErrGroupMemberNotFound    = fmt.Errorf("group member: %w", dberrors.ErrNotFound)
	ErrAssetNotFound          = fmt.Errorf("asset: %w", dberrors.ErrNotFound)
	ErrThreatNotFound         = fmt.Errorf("threat: %w", dberrors.ErrNotFound)
	ErrDocumentNotFound       = fmt.Errorf("document: %w", dberrors.ErrNotFound)
	ErrRepositoryNotFound     = fmt.Errorf("repository: %w", dberrors.ErrNotFound)
	ErrNoteNotFound           = fmt.Errorf("note: %w", dberrors.ErrNotFound)
	ErrTeamNotFound           = fmt.Errorf("team: %w", dberrors.ErrNotFound)
	ErrProjectNotFound        = fmt.Errorf("project: %w", dberrors.ErrNotFound)
	ErrTeamNoteNotFound       = fmt.Errorf("team note: %w", dberrors.ErrNotFound)
	ErrProjectNoteNotFound    = fmt.Errorf("project note: %w", dberrors.ErrNotFound)
	ErrSurveyNotFound         = fmt.Errorf("survey: %w", dberrors.ErrNotFound)
	ErrSurveyResponseNotFound = fmt.Errorf("survey response: %w", dberrors.ErrNotFound)
	ErrTimmySessionNotFound   = fmt.Errorf("timmy session: %w", dberrors.ErrNotFound)
	ErrAddonNotFound          = fmt.Errorf("addon: %w", dberrors.ErrNotFound)
	ErrAddonQuotaNotFound     = fmt.Errorf("addon quota: %w", dberrors.ErrNotFound)
	ErrUserAPIQuotaNotFound   = fmt.Errorf("user api quota: %w", dberrors.ErrNotFound)
	ErrWebhookNotFound        = fmt.Errorf("webhook subscription: %w", dberrors.ErrNotFound)
	ErrWebhookQuotaNotFound   = fmt.Errorf("webhook quota: %w", dberrors.ErrNotFound)
	ErrDenyListEntryNotFound  = fmt.Errorf("webhook url deny list entry: %w", dberrors.ErrNotFound)
	ErrTriageNoteNotFound     = fmt.Errorf("triage note: %w", dberrors.ErrNotFound)
	ErrTombstoneNotFound      = fmt.Errorf("tombstone: %w", dberrors.ErrNotFound)
	ErrUserNotFound           = fmt.Errorf("user: %w", dberrors.ErrNotFound)
	ErrThreatModelNotFound    = fmt.Errorf("threat model: %w", dberrors.ErrNotFound)
	ErrDiagramNotFound        = fmt.Errorf("diagram: %w", dberrors.ErrNotFound)
	ErrTicketNotFound         = fmt.Errorf("ticket: %w", dberrors.ErrNotFound)

	// Duplicate / conflict errors
	ErrGroupDuplicate       = fmt.Errorf("group: %w", dberrors.ErrDuplicate)
	ErrGroupMemberDuplicate = fmt.Errorf("group member: %w", dberrors.ErrDuplicate)
	ErrMetadataKeyExists    = fmt.Errorf("metadata key: %w", dberrors.ErrDuplicate)

	// Optimistic-locking error (T14 / #385). Returned by stores when a
	// versioned UPDATE fails because the caller's expected version does not
	// match the row's current version. Handlers map this to 409 Conflict.
	ErrVersionMismatch = errors.New("version mismatch")

	// Business-logic errors (not DB errors)
	ErrSelfMembership          = errors.New("a group cannot be a member of itself")
	ErrEveryoneGroup           = errors.New("the everyone group cannot be modified")
	ErrTeamHasProjects         = errors.New("cannot delete team: team has associated projects")
	ErrTeamSelfRelationship    = errors.New("a team cannot have a relationship with itself")
	ErrTeamRelationshipCycle   = errors.New("relationship would create a cycle")
	ErrTeamRelatedTeamNotFound = errors.New("related team not found")
	ErrProjectHasThreatModels  = errors.New("cannot delete project: it has associated threat models")
)

Repository error sentinels. Each wraps the corresponding dberrors sentinel so handlers can check either the entity-specific error or the generic category.

View Source
var (
	// Major version number
	VersionMajor = "1"
	// Minor version number
	VersionMinor = "5"
	// Patch version number
	VersionPatch = "0"
	// VersionPreRelease is the pre-release label (e.g., "rc.0", "beta.1"), empty for stable releases
	VersionPreRelease = ""
	// GitCommit is the git commit hash from build
	GitCommit = "development"
	// BuildDate is the build timestamp
	BuildDate = "unknown"
	// APIVersion is the API version string
	APIVersion = "v1"
)

These values are set during build time

View Source
var CommonValidators = NewValidatorRegistry()

Global validator registry instance

View Source
var ErrAccessDenied = errors.New("access denied")

ErrAccessDenied indicates an authorization failure

View Source
var ErrAliasSequenceMissing = errors.New("threat_model alias sequence missing")

ErrAliasSequenceMissing indicates the global ThreatModel alias sequence does not exist at NEXTVAL time — it was installed at startup (so useAliasSequence is on) but has since been dropped (schema drift / a DB reset under a running server). It is recoverable: GormThreatModelStore.Create reinstalls the sequence (idempotent, seeded above the current max alias) and retries the create once. The error chain also satisfies errors.Is(err, dberrors.ErrUndefinedObject).

View Source
var ErrAuthRequired = errors.New("delegated source: authentication required")

ErrAuthRequired indicates the caller has no valid token for this provider.

View Source
var ErrContentFeedbackTargetNotFound = errors.New("content feedback target not found")

ErrContentFeedbackTargetNotFound is returned by CreateWithTargetCheck when the target row does not exist (or does not belong to the named threat model) at the moment of the locked SELECT inside the create transaction.

View Source
var ErrContentOAuthStateNotFound = errors.New("content oauth state not found or expired")

ErrContentOAuthStateNotFound is returned when the OAuth state nonce is not found or has expired.

View Source
var ErrInvalidTableName = fmt.Errorf("invalid table name")

ErrInvalidTableName is returned when an invalid table name is provided

View Source
var ErrSafeHTTPBodyTooLarge = errors.New("safe_http: response body exceeds configured maximum")

ErrSafeHTTPBodyTooLarge is returned by Fetch when SafeFetchOptions.RejectIfBodyExceedsMax is set and the upstream declared a Content-Length larger than the configured MaxBodyBytes.

View Source
var ErrSafeHTTPRedirectBlocked = errors.New("safe_http: redirects are not allowed")

ErrSafeHTTPRedirectBlocked is returned indirectly when redirects are disallowed and the upstream tried to redirect; the caller observes a 3xx response with no body follow.

View Source
var ErrTransient = errors.New("delegated source: transient refresh failure")

ErrTransient indicates a temporary failure (5xx / network) during refresh.

View Source
var TMIObjectTypes = []string{
	"threat_model",
	"diagram",
	"asset",
	"threat",
	"document",
	"note",
	"repository",
	"metadata",
	"survey",
	"survey_response",
}

TMI object types taxonomy (valid values for objects field)

View Source
var TestFixtures struct {
	// Test users for authorization
	OwnerUser  string
	WriterUser string
	ReaderUser string

	// Owner field values
	Owner string

	// Test threat models
	ThreatModel   ThreatModel
	ThreatModelID string

	// Test diagrams
	Diagram     DfdDiagram
	DiagramID   string
	DiagramAuth []Authorization // Store authorization separately since it's not in the Diagram struct

	// Test flags
	Initialized bool
}
View Source
var TestUsers = struct {
	Owner    TestUserIdentity
	Writer   TestUserIdentity
	Reader   TestUserIdentity
	External TestUserIdentity
}{
	Owner: TestUserIdentity{
		Email:        "owner@example.com",
		ProviderID:   "owner-provider-id",
		InternalUUID: "owner-internal-uuid",
		IdP:          "tmi",
		Groups:       []string{},
	},
	Writer: TestUserIdentity{
		Email:        "writer@example.com",
		ProviderID:   "writer-provider-id",
		InternalUUID: "writer-internal-uuid",
		IdP:          "tmi",
		Groups:       []string{},
	},
	Reader: TestUserIdentity{
		Email:        "reader@example.com",
		ProviderID:   "reader-provider-id",
		InternalUUID: "reader-internal-uuid",
		IdP:          "tmi",
		Groups:       []string{},
	},
	External: TestUserIdentity{
		Email:        "external@example.com",
		ProviderID:   "external-provider-id",
		InternalUUID: "external-internal-uuid",
		IdP:          "tmi",
		Groups:       []string{},
	},
}

TestUsers provides standard test user identities

View Source
var ThreatModelPatchAllowList = PatchPathAllowList{
	MutablePaths: []string{
		"/name",
		"/description",
		"/issue_uri",
		"/metadata",
		"/threat_model_framework",
		"/source_code",
		"/sourceCode",
		"/repository_uri",
		"/project_id",
	},
	SecurityReviewerOnly: []string{
		"/status",
		"/security_reviewer",
	},

	OwnerCanClear: []string{
		"/security_reviewer",
	},
	OwnerOnly: []string{
		"/owner",
		"/authorization",
	},
}

ThreatModelPatchAllowList is the canonical allowlist for the /threat_models/{id} PATCH endpoint. Mirrors the writable fields of ThreatModelBase (api/api.go) plus the role-gated workflow and authorization fields.

Server-managed fields (id, created_at, modified_at, created_by, deleted_at, status_updated) and sub-resource collections (diagrams, documents, threats, notes, assets, repositories) are intentionally absent and therefore rejected by default.

is_confidential is also intentionally absent: it is set at creation and is read-only thereafter (escalating a non-confidential model to confidential after the fact would expose data to existing readers).

View Source
var ValidTableNames = map[string]bool{
	"users":                   true,
	"threat_models":           true,
	"diagrams":                true,
	"threats":                 true,
	"documents":               true,
	"metadata":                true,
	"client_credentials":      true,
	"webhook_subscriptions":   true,
	"webhook_quotas":          true,
	"webhook_url_deny_lists":  true,
	"addon_invocation_quotas": true,
	"addons":                  true,
	"user_api_quotas":         true,
	"group_members":           true,
	"threat_model_access":     true,
	"repositories":            true,
	"notes":                   true,
	"assets":                  true,
	"collaboration_sessions":  true,
	"session_participants":    true,
	"refresh_token_records":   true,
	"groups":                  true,
	"schema_migrations":       true,
}

ValidTableNames contains all valid table names for the TMI schema. This whitelist prevents SQL injection via table name parameters.

View Source
var ValidationConfigs = map[string]ValidationConfig{

	"threat_model_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "created_by", "owner",
			"diagrams", "documents", "threats", "sourceCode", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"authorization", "email_format", "no_html_injection", "string_length",
		}),
		Operation: "POST",
	},

	"threat_model_update": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "created_by",
			"diagrams", "documents", "threats", "sourceCode", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"authorization", "email_format", "no_html_injection", "string_length",
		}),
		AllowOwnerField: true,
		Operation:       "PUT",
	},

	"diagram_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"diagram_type", "no_html_injection", "string_length",
		}),
		Operation: "POST",
	},

	"diagram_update": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"diagram_type", "no_html_injection", "string_length",
		}),
		Operation: "PUT",
	},

	"document_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "url_format", "no_html_injection", "string_length",
		}), func(data any) error {

			doc, ok := data.(*Document)
			if !ok {
				return InvalidInputError("Invalid data type for document validation")
			}
			if doc.Name == "" {
				return InvalidInputError("Document name is required")
			}
			if doc.Uri == "" {
				return InvalidInputError("Document URI is required")
			}
			return nil
		}),
		Operation: "POST",
	},

	"document_update": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "url_format", "no_html_injection", "string_length",
		}), func(data any) error {

			doc, ok := data.(*Document)
			if !ok {
				return InvalidInputError("Invalid data type for document validation")
			}
			if doc.Name == "" {
				return InvalidInputError("Document name is required")
			}
			if doc.Uri == "" {
				return InvalidInputError("Document URI is required")
			}
			return nil
		}),
		Operation: "PUT",
	},

	"note_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "note_markdown", "string_length",
		}), func(data any) error {

			note, ok := data.(*Note)
			if !ok {
				return InvalidInputError("Invalid data type for note validation")
			}
			if note.Name == "" {
				return InvalidInputError("Note name is required")
			}
			if note.Content == "" {
				return InvalidInputError("Note content is required")
			}
			return nil
		}),
		Operation: "POST",
	},

	"note_update": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "note_markdown", "string_length",
		}), func(data any) error {

			note, ok := data.(*Note)
			if !ok {
				return InvalidInputError("Invalid data type for note validation")
			}
			if note.Name == "" {
				return InvalidInputError("Note name is required")
			}
			if note.Content == "" {
				return InvalidInputError("Note content is required")
			}
			return nil
		}),
		Operation: "PUT",
	},

	"triage_note_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "created_by", "modified_by",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"triage_note_markdown", "string_length",
		}), func(data any) error {
			note, ok := data.(*TriageNote)
			if !ok {
				return InvalidInputError("Invalid data type for triage note validation")
			}
			if note.Name == "" {
				return InvalidInputError("Triage note name is required")
			}
			if note.Content == "" {
				return InvalidInputError("Triage note content is required")
			}
			return nil
		}),
		Operation: "POST",
	},

	"repository_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "url_format", "no_html_injection", "string_length",
		}), func(data any) error {

			repository, ok := data.(*Repository)
			if !ok {
				return InvalidInputError("Invalid data type for repository validation")
			}
			if repository.Uri == "" {
				return InvalidInputError("Repository URI is required")
			}
			return nil
		}),
		Operation: "POST",
	},

	"repository_update": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "url_format", "no_html_injection", "string_length",
		}), func(data any) error {

			repository, ok := data.(*Repository)
			if !ok {
				return InvalidInputError("Invalid data type for repository validation")
			}
			if repository.Uri == "" {
				return InvalidInputError("Repository URI is required")
			}
			return nil
		}),
		Operation: "PUT",
	},

	"threat_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "threat_severity", "no_html_injection", "string_length", "score_precision",
		}), func(data any) error {

			threat, ok := data.(*Threat)
			if !ok {
				return InvalidInputError("Invalid data type for threat validation")
			}
			if threat.Name == "" {
				return InvalidInputError("Threat name is required")
			}
			return nil
		}),
		Operation: "POST",
	},

	"threat_update": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "threat_severity", "no_html_injection", "string_length", "score_precision",
		}), func(data any) error {

			threat, ok := data.(*Threat)
			if !ok {
				return InvalidInputError("Invalid data type for threat validation")
			}
			if threat.Name == "" {
				return InvalidInputError("Threat name is required")
			}
			return nil
		}),
		Operation: "PUT",
	},

	"metadata_create": {
		ProhibitedFields: []string{},
		CustomValidators: CommonValidators.GetValidators([]string{
			"metadata_key", "no_html_injection", "string_length",
		}),
		Operation: "POST",
	},

	"metadata_update": {
		ProhibitedFields: []string{},
		CustomValidators: CommonValidators.GetValidators([]string{
			"metadata_key", "no_html_injection", "string_length",
		}),
		Operation: "PUT",
	},

	"cell_create": {
		ProhibitedFields: []string{
			"id",
		},
		CustomValidators: []ValidatorFunc{ValidateUUIDFieldsFromStruct},
		Operation:        "POST",
	},

	"cell_update": {
		ProhibitedFields: []string{
			"id",
		},
		CustomValidators: []ValidatorFunc{ValidateUUIDFieldsFromStruct},
		Operation:        "PUT",
	},

	"asset_create": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "no_html_injection", "string_length",
		}), func(data any) error {

			asset, ok := data.(*Asset)
			if !ok {
				return InvalidInputError("Invalid data type for asset validation")
			}
			if asset.Name == "" {
				return InvalidInputError("Asset name is required")
			}
			if asset.Type == "" {
				return InvalidInputError("Asset type is required")
			}

			validTypes := map[AssetType]bool{
				"data": true, "hardware": true, "software": true,
				"infrastructure": true, "service": true, "personnel": true,
			}
			if !validTypes[asset.Type] {
				return InvalidInputError("Invalid asset type, must be one of: data, hardware, software, infrastructure, service, personnel")
			}

			if asset.Classification != nil && len(*asset.Classification) > 50 {
				return InvalidInputError("Asset classification array exceeds maximum of 50 items")
			}

			if asset.Sensitivity != nil && len(*asset.Sensitivity) > 128 {
				return InvalidInputError("Asset sensitivity exceeds maximum of 128 characters")
			}
			return nil
		}),
		Operation: "POST",
	},

	"asset_update": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at",
		},
		CustomValidators: append(CommonValidators.GetValidators([]string{
			"uuid_fields", "no_html_injection", "string_length",
		}), func(data any) error {

			asset, ok := data.(*Asset)
			if !ok {
				return InvalidInputError("Invalid data type for asset validation")
			}
			if asset.Name == "" {
				return InvalidInputError("Asset name is required")
			}
			if asset.Type == "" {
				return InvalidInputError("Asset type is required")
			}

			validTypes := map[AssetType]bool{
				"data": true, "hardware": true, "software": true,
				"infrastructure": true, "service": true, "personnel": true,
			}
			if !validTypes[asset.Type] {
				return InvalidInputError("Invalid asset type, must be one of: data, hardware, software, infrastructure, service, personnel")
			}

			if asset.Classification != nil && len(*asset.Classification) > 50 {
				return InvalidInputError("Asset classification array exceeds maximum of 50 items")
			}

			if asset.Sensitivity != nil && len(*asset.Sensitivity) > 128 {
				return InvalidInputError("Asset sensitivity exceeds maximum of 128 characters")
			}
			return nil
		}),
		Operation: "PUT",
	},

	"batch_patch": {
		ProhibitedFields: []string{},
		CustomValidators: []ValidatorFunc{},
		Operation:        "PATCH",
	},

	"batch_delete": {
		ProhibitedFields: []string{},
		CustomValidators: []ValidatorFunc{},
		Operation:        "DELETE",
	},

	"asset_patch": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"no_html_injection", "string_length",
		}),
		Operation: "PATCH",
	},

	"document_patch": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"no_html_injection", "string_length",
		}),
		Operation: "PATCH",
	},

	"note_patch": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"note_markdown", "string_length",
		}),
		Operation: "PATCH",
	},

	"repository_patch": {
		ProhibitedFields: []string{
			"id", "created_at", "modified_at", "alias",
		},
		CustomValidators: CommonValidators.GetValidators([]string{
			"no_html_injection", "string_length",
		}),
		Operation: "PATCH",
	},
}

ValidationConfigs defines validation rules for each endpoint

Functions

func AcceptHeaderValidation

func AcceptHeaderValidation() gin.HandlerFunc

AcceptHeaderValidation middleware validates that the Accept header is application/json Returns 406 Not Acceptable for unsupported media types SEM@29f63eb500c26288d0d3fe23737adf6fd94bdf9c: build middleware that rejects requests with unsupported Accept media types

func AcceptLanguageMiddleware

func AcceptLanguageMiddleware() gin.HandlerFunc

AcceptLanguageMiddleware handles Accept-Language headers gracefully SEM@a0b03d5d6a185b962cc24512bc65629f58b659da: parse the Accept-Language header and store the preferred language in context, defaulting to English

func AccessCheck

func AccessCheck(principal string, requiredRole Role, authData AuthorizationData) bool

AccessCheck performs core authorization logic Returns true if the principal has the required role for the given authorization data SEM@e28c0cfc627a2162c9550e53fb320facb734179e: check whether a principal string meets the required role against resource authorization data (pure)

func AccessCheckWithGroups

func AccessCheckWithGroups(user ResolvedUser, groups []string, requiredRole Role, authData AuthorizationData) bool

AccessCheckWithGroups performs authorization check with group support and SamePrincipal matching. Returns true if the user or one of their groups has the required role. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: check whether a resolved user or their groups meet the required role (pure)

func AccessCheckWithGroupsAndIdPLookup

func AccessCheckWithGroupsAndIdPLookup(user ResolvedUser, groups []string, requiredRole Role, authData AuthorizationData) bool

AccessCheckWithGroupsAndIdPLookup performs authorization check with group support and SamePrincipal matching. Returns true if the user or one of their groups has the required role. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: check whether a resolved user or their groups meet the required role using SamePrincipal matching (pure)

func AdminAuditMiddleware

func AdminAuditMiddleware(repo SystemAuditRepository, redactor Redactor, descriptors []auditDescriptor) gin.HandlerFunc

AdminAuditMiddleware writes a system_audit_entries row for every successful /admin/* write that has a descriptor entry. Audit-write failure is logged at Error level and does NOT fail the admin write (per spec §5).

Order: this middleware MUST run after StepUpMiddleware and after the JWT-validation middleware that populates userEmail/userIdP/userInternalUUID/ userID/userDisplayName on the Gin context. SEM@87d6f75bc3aecf3edd6c4103567546955c1afadf: Gin middleware that writes a system audit entry for every successful admin write operation (writes DB)

func AdministratorMiddleware

func AdministratorMiddleware() gin.HandlerFunc

AdministratorMiddleware creates a middleware that requires the user to be an administrator SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: authorize requests by rejecting non-administrator users before the handler runs

func AllocateNextAlias

func AllocateNextAlias(ctx context.Context, tx *gorm.DB, parentID, objectType string) (int32, error)

AllocateNextAlias atomically reserves the next alias value for the given (parentID, objectType) scope. MUST be called inside a transaction. The returned value is guaranteed unique within the scope so long as the calling transaction commits successfully.

For the ThreatModel global counter, pass parentID="__global__" and objectType="threat_model". For sub-objects, parentID is the parent ThreatModel UUID and objectType is one of "diagram", "threat", "asset", "repository", "note", "document".

The global ThreatModel scope is served from a DB sequence on PostgreSQL and Oracle (see #452); every other scope — and SQLite — uses the row-counter path below. Per-scope sub-object counters are naturally partitioned by their parent threat model and never became a global hot spot.

Note: on the row-counter path, if the calling transaction rolls back the counter UPDATE rolls back too — the alias is "released" and reused. On the sequence path the drawn value is gone (gap) whether or not the create commits. Both paths only ever yield committed, unique aliases. SEM@15d1523404ac67830fbe68f72a41c9683aa564b6: atomically reserve the next alias integer for a given parent/object-type scope within a transaction (reads DB)

func ApplyDiff

func ApplyDiff(state, diff []byte) ([]byte, error)

ApplyDiff applies a JSON Merge Patch (RFC 7396) to a state, producing a new state. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: apply a JSON Merge Patch to a state and return the resulting state (pure)

func ApplyOptimisticLock

func ApplyOptimisticLock(c *gin.Context, store VersionedStore, id string, bodyVersion *int) (newVersion int, present bool, err error)

ApplyOptimisticLock implements the handler-side flow:

  1. Resolve expectedVersion from If-Match header (preferred) or body "version" field (fallback).
  2. If neither is supplied, defer to RequireIfMatch(): either return a 428 RequestError or set Deprecation/Warning headers and return (0, false, nil).
  3. If a version is supplied, call store.CheckAndBumpVersion. On version mismatch return a 409 RequestError; on missing row return nil so the caller's existing not-found mapping fires.

On success the new version is returned so the handler can stamp the ETag response header before serializing the response body. SEM@3256ece0f5730b6c910aa6e61025555c7726a4a5: validate and apply a versioned compare-and-swap lock on a stored resource (reads DB)

func ApplyPatchOperations

func ApplyPatchOperations[T any](original T, operations []PatchOperation) (T, error)

ApplyPatchOperations applies JSON Patch operations to an entity and returns the modified entity SEM@08dc266da6e8cd180aa7274d8135e3c559663cfa: apply RFC 6902 JSON Patch operations to an entity, promoting replace to add for absent optional fields (pure)

func AssertAuthDataEqual

func AssertAuthDataEqual(t *testing.T, expected, actual *AuthorizationData)

AssertAuthDataEqual compares two AuthorizationData structs for equality SEM@e28c0cfc627a2162c9550e53fb320facb734179e: assert that two AuthorizationData values have the same owner and authorization entries (pure)

func AssertCORSHeaders

func AssertCORSHeaders(t *testing.T, headers http.Header, origin ...string)

AssertCORSHeaders verifies CORS headers are present when an allowed origin is set. The origin parameter is the expected reflected origin (or empty if no CORS headers expected). SEM@314b7ae8fe586a75ecee2e8fa7103d3193f15f7c: validate CORS response headers reflect the expected origin and required fields (pure)

func AssertDocumentEqual

func AssertDocumentEqual(d1, d2 Document) bool

AssertDocumentEqual compares two documents for testing equality SEM@d89d1545c4d3d1fc1bd631ae95995c7f60828240: compare two documents by name, description, and URI for test equality (pure)

func AssertHSTSHeader

func AssertHSTSHeader(t *testing.T, headers http.Header, expectPresent bool)

AssertHSTSHeader verifies that HSTS header is present and correctly configured SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: validate HSTS response header presence and value in tests (pure)

func AssertJSONErrorResponse

func AssertJSONErrorResponse(t *testing.T, w *httptest.ResponseRecorder, expectedStatus int, expectedError string)

AssertJSONErrorResponse verifies the response is a JSON error with expected status SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: validate HTTP error response has expected status, JSON content type, and error text (pure)

func AssertMetadataEqual

func AssertMetadataEqual(m1, m2 Metadata) bool

AssertMetadataEqual compares two metadata items for testing equality SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: compare two metadata items by key and value for test equality (pure)

func AssertRateLimitHeaders

func AssertRateLimitHeaders(t *testing.T, headers http.Header, remaining, limit int)

AssertRateLimitHeaders verifies rate limit headers are present with expected values SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: validate rate limit response headers match expected limit and remaining counts (pure)

func AssertRepositoryEqual

func AssertRepositoryEqual(r1, r2 Repository) bool

AssertRepositoryEqual compares two repositories for testing equality SEM@d89d1545c4d3d1fc1bd631ae95995c7f60828240: compare two repositories by name, description, URI, and type for test equality (pure)

func AssertSecurityHeaders

func AssertSecurityHeaders(t *testing.T, headers http.Header)

AssertSecurityHeaders verifies that all expected security headers are present SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: validate that a response includes all required security headers (pure)

func AssertThreatEqual

func AssertThreatEqual(t1, t2 Threat) bool

AssertThreatEqual compares two threats for testing equality SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: compare two threats by key fields for test equality (pure)

func AssignmentMap

func AssignmentMap(dialectName string, assignments map[string]any) map[string]any

AssignmentMap rewrites the keys of an OnConflict DoUpdates assignment map to the correct case for the database dialect. Use with clause.Assignments when you need to set explicit values (not just column names) on conflict. SEM@aa6d284f5df5c13ccb0001366a1f228490aba957: rewrite ON CONFLICT assignment map keys to dialect-correct column casing (pure)

func AuditRetentionDays

func AuditRetentionDays() int

AuditRetentionDays returns the configured audit-entry retention in days (AUDIT_RETENTION_DAYS, default 365). Exported because the append-only trigger installation derives its delete age floor from the same value, so the pruner cutoff and the trigger floor cannot drift (#453). SEM@bc84c37baf8f28057d9cb166b3a0e7d0cba90425: fetch the configured audit-entry retention period in days from the environment (pure)

func AuthFlowRateLimitMiddleware

func AuthFlowRateLimitMiddleware(server *Server) gin.HandlerFunc

AuthFlowRateLimitMiddleware creates middleware for multi-scope auth flow rate limiting (Tier 2) SEM@c70d49ed2d6089c24d05f8bc287ba5711c73abde: enforce multi-scope rate limits on auth flow endpoints, resetting the user limit after a successful token exchange

func AuthorizeIncludeDeleted

func AuthorizeIncludeDeleted(c *gin.Context) bool

AuthorizeIncludeDeleted checks whether the authenticated user has owner or admin role, which is required to use the include_deleted query parameter. Returns true if authorized. If not authorized, sends a 403 response and returns false. SEM@52360c4fb265990438f8595b7c8d0480a12f9979: authorize the include_deleted parameter for owner or admin role; send 403 if denied

func AuthzMiddleware

func AuthzMiddleware() gin.HandlerFunc

AuthzMiddleware is the unified declarative authorization gate. It looks up the AuthzRule for the matched route in the global AuthzTable and enforces public/role/ownership gates declared in the OpenAPI x-tmi-authz extension.

  • For routes with no rule (legacy paths not yet annotated): pass through. Existing resource middleware (ThreatModelMiddleware, DiagramMiddleware, etc.) takes over. This is the no-regression guarantee for paths the migration has not yet covered.

  • For routes with rule.Public=true: pass through regardless of identity. JWT middleware separately recognizes the path as public.

  • For routes with rule.Roles containing "admin": delegate to RequireAdministrator (api/auth_helpers.go), which returns 401/403 with consistent error format.

  • For routes with rule.Ownership in {reader, writer, owner}: extract the parent threat-model ID from the path, load lightweight ACL data, and enforce the role. This replaces the per-method switch in ThreatModelMiddleware for annotated routes (#365).

On any gate failure, the middleware aborts with the appropriate status code and response body. On allow, it sets the context key "authzCovered" = true so downstream resource middleware can short-circuit duplicate work. SEM@1c9f87f1ca746f8b265481c0a196627b2737787a: build the unified declarative authorization Gin middleware, failing closed if the AuthzTable cannot load

func AutomationMiddleware

func AutomationMiddleware() gin.HandlerFunc

AutomationMiddleware creates a middleware that requires the user to be a member of either the tmi-automation or embedding-automation group. This is the outer gate for all /automation/* routes. SEM@46ceafa6fa8deee41cbc5c929e3f60ca14fdd686: authorize requests to /automation/* routes, requiring tmi-automation or embedding-automation group membership

func BoundaryValueValidationMiddleware

func BoundaryValueValidationMiddleware() gin.HandlerFunc

BoundaryValueValidationMiddleware enhances validation of boundary values in JSON SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: parse JSON request bodies and log empty strings in likely-required fields without blocking the request

func BroadcastCollaborationStarted

func BroadcastCollaborationStarted(userID, diagramID, diagramName, threatModelID, threatModelName, sessionID string)

BroadcastCollaborationStarted notifies about a new collaboration session SEM@66b1e1515b82356913c8625edc8616772c3c70d3: notify all connected clients that a diagram collaboration session started (mutates shared state)

func BroadcastSystemAnnouncement

func BroadcastSystemAnnouncement(message string, severity string, actionRequired bool, actionURL string)

BroadcastSystemAnnouncement sends a system-wide announcement SEM@66b1e1515b82356913c8625edc8616772c3c70d3: dispatch a system-wide announcement to all connected notification clients (mutates shared state)

func BroadcastThreatModelCreated

func BroadcastThreatModelCreated(userID, threatModelID, threatModelName string)

BroadcastThreatModelCreated notifies all connected clients about a new threat model SEM@66b1e1515b82356913c8625edc8616772c3c70d3: notify all connected clients that a threat model was created (mutates shared state)

func BroadcastThreatModelDeleted

func BroadcastThreatModelDeleted(userID, threatModelID, threatModelName string)

BroadcastThreatModelDeleted notifies all connected clients about a deleted threat model SEM@66b1e1515b82356913c8625edc8616772c3c70d3: notify all connected clients that a threat model was deleted (mutates shared state)

func BroadcastThreatModelUpdated

func BroadcastThreatModelUpdated(userID, threatModelID, threatModelName string)

BroadcastThreatModelUpdated notifies all connected clients about an updated threat model SEM@66b1e1515b82356913c8625edc8616772c3c70d3: notify all connected clients that a threat model was updated (mutates shared state)

func CORS

func CORS(allowedOrigins []string, isDev bool) gin.HandlerFunc

CORS middleware to handle Cross-Origin Resource Sharing. In dev mode, any origin is reflected (permissive but spec-correct). In production, only origins in allowedOrigins are permitted. SEM@5d36fbba264b6e4f105d4eb316e4f509c58d7300: handle CORS preflight and set allowed-origin headers per environment mode

func CheckAndBumpVersion

func CheckAndBumpVersion(ctx context.Context, db *gorm.DB, tableName, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates the caller's expected version and increments the row's version by one. Returns the new version on success.

Errors:

  • dberrors.ErrNotFound if the row with id does not exist.
  • ErrVersionMismatch if the row exists but version != expected.
  • other GORM errors are returned wrapped via dberrors.Classify.

This is intended to be called BEFORE the entity's content UPDATE inside the same transaction. Concurrent writers race on this single UPDATE: the first to commit wins and the loser sees rows-affected = 0, which we map to ErrVersionMismatch (after a separate existence probe to distinguish 404 from 409).

tableName must be the physical DB table name (e.g. "threat_models"). On Oracle, GORM lowercases the WHERE column references; the column is "version" on both PostgreSQL and Oracle (case-insensitive identifier). SEM@9fa66a9bf47d32b91bc4119acc795e307691601a: atomically validate expected version and increment the row version in the DB (reads DB)

func CheckDiagramAccess

func CheckDiagramAccess(user ResolvedUser, groups []string, diagram DfdDiagram, requiredRole Role) error

CheckDiagramAccess checks if a user has required access to a diagram. Uses SamePrincipal for identity matching via GetUserRoleForDiagram. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: authorize a user against a required role on a diagram, returning an error if denied (reads DB)

func CheckHTMLInjection

func CheckHTMLInjection(value, fieldName string) error

CheckHTMLInjection is the unified HTML/XSS and template injection checker. It combines regex precision from the validation registry with broader pattern coverage from addon validation, providing consistent security checking. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: validate a field value for HTML/XSS and template injection patterns; reject if unsafe (pure)

func CheckOwnershipChanges

func CheckOwnershipChanges(operations []PatchOperation) (ownerChanging, authChanging bool)

CheckOwnershipChanges analyzes patch operations to determine if owner or authorization fields are being modified SEM@cdbe48c974fb76e1161972733b30bb0d1c02c3b1: detect whether patch operations modify the owner or authorization fields (pure)

func CheckResourceAccess

func CheckResourceAccess(subject string, resource any, requiredRole Role) (bool, error)

CheckResourceAccess is a utility function that checks if a subject has required access to a resource This function uses the basic AccessCheck and does NOT support group-based authorization. For group support (including "everyone" pseudo-group), use CheckResourceAccessWithGroups instead. Note: subject can be a user email or user ID, but group matching is not supported by this function. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: check whether a subject string meets the required role for a resource without group support (pure)

func CheckResourceAccessFromContext

func CheckResourceAccessFromContext(c *gin.Context, user ResolvedUser, resource any, requiredRole Role) (bool, error)

CheckResourceAccessFromContext checks resource access using user info from Gin context. This is a convenience function that builds a ResolvedUser from context fields and calls CheckResourceAccessWithGroups for group-aware authorization including "everyone" pseudo-group. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: authorize a user from Gin context against a resource, resolving groups from context (pure)

func CheckResourceAccessWithGroups

func CheckResourceAccessWithGroups(user ResolvedUser, groups []string, resource any, requiredRole Role) (bool, error)

CheckResourceAccessWithGroups checks if a user has required access to a resource with group support. This function supports group-based authorization including the "everyone" pseudo-group. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: authorize a user (with groups) against a resource's auth data for a required role (pure)

func CheckSubResourceAccess

func CheckSubResourceAccess(ctx context.Context, db *sql.DB, cache *CacheService, user ResolvedUser, groups []string, threatModelID string, requiredRole Role) (bool, error)

CheckSubResourceAccess validates if a user has the required access to a sub-resource. This function implements authorization inheritance with Redis caching for performance. Uses SamePrincipal for identity matching via AccessCheckWithGroups. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: authorize a user against a threat model's inherited permissions, with Redis cache (reads DB)

func CheckSubResourceAccessWithoutCache

func CheckSubResourceAccessWithoutCache(ctx context.Context, db *sql.DB, user ResolvedUser, groups []string, threatModelID string, requiredRole Role) (bool, error)

CheckSubResourceAccessWithoutCache validates sub-resource access without caching. This is useful for testing or when caching is not available. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: authorize a user against a threat model's inherited permissions, bypassing cache (reads DB)

func CheckThreatModelAccess

func CheckThreatModelAccess(user ResolvedUser, groups []string, threatModel ThreatModel, requiredRole Role) error

CheckThreatModelAccess checks if a user has required access to a threat model. Uses SamePrincipal for identity matching via AccessCheckWithGroups. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: authorize a user against a required role on a threat model, returning an error if denied (pure)

func CleanupTestFixtures

func CleanupTestFixtures(ctx context.Context) error

CleanupTestFixtures removes all test data from stores SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: remove all test data from stores after a test run (mutates shared state)

func Col

func Col(dialectName, column string) clause.Column

Col returns a clause.Column with the correct column name for the database dialect. Oracle requires uppercase column names because the oracle-samples/gorm-oracle driver doesn't consistently apply the NamingStrategy to column names in WHERE/ORDER BY clauses. SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: build a GORM clause.Column with dialect-correct column name casing (pure)

func ColumnMap

func ColumnMap(dialectName string, predicate map[string]any) map[string]any

ColumnMap rewrites the keys of a map-based WHERE predicate to the correct case for the database dialect. GORM emits map[string]any predicate keys verbatim through the quoter (it does NOT run them through the NamingStrategy the way it does struct-field queries), so a lowercase literal key produces a quoted-lowercase identifier that fails to match the uppercase column the Oracle GORM driver creates. Wrap every map-keyed Where/Not/Or predicate that uses literal column names in this helper:

db.Where(ColumnMap(db.Name(), map[string]any{"team_id": id}))

On non-Oracle dialects the map is returned unchanged. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: rewrite map-based WHERE predicate keys to dialect-correct column casing (pure)

func ColumnName

func ColumnName(dialectName, column string) string

ColumnName returns the column name in the correct case for the database dialect. Oracle requires uppercase column names because the oracle-samples/gorm-oracle driver doesn't consistently apply the NamingStrategy to column names in WHERE/ORDER BY clauses. SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: convert a column name to the correct case for the active database dialect (pure)

func ComputeReverseDiff

func ComputeReverseDiff(before, after []byte) ([]byte, error)

ComputeReverseDiff computes a JSON Merge Patch (RFC 7396) that transforms the 'after' state back to the 'before' state. This is the reverse diff stored in version snapshots for space efficiency. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: compute a JSON Merge Patch that reverts the after state back to before (pure)

func ContentTypeValidationMiddleware

func ContentTypeValidationMiddleware() gin.HandlerFunc

ContentTypeValidationMiddleware validates Content-Type header and rejects unsupported types SEM@c3d5e1776058ac335ccda141ec46f5a36de89f9f: validate request Content-Type against per-endpoint OpenAPI accepted types, rejecting unsupported media types

func ContextTimeout

func ContextTimeout(timeout time.Duration) gin.HandlerFunc

ContextTimeout adds a timeout to the request context SEM@386eea01f3b66c35027bf3ca762efbc291419e20: attach a deadline to the request context to enforce a per-request timeout

func ContextWithIncludeDeleted

func ContextWithIncludeDeleted(ctx context.Context) context.Context

ContextWithIncludeDeleted returns a context with include_deleted set SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: build a context that signals include-deleted queries are authorized (pure)

func CreateAddon

func CreateAddon(c *gin.Context)

CreateAddon creates a new add-on (admin only) SEM@15af4eb93978e65654702a2b47f0ebe20df650dc: handle POST /addons: validate and store a new addon, restricted to administrators (reads DB)

func CreateTestGinContext

func CreateTestGinContext(method, path string) (*gin.Context, *httptest.ResponseRecorder)

CreateTestGinContext creates a Gin context for testing with the given HTTP method and path SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: build a Gin context and response recorder for a given HTTP method and path (pure)

func CreateTestGinContextWithBody

func CreateTestGinContextWithBody(method, path, contentType string, body []byte) (*gin.Context, *httptest.ResponseRecorder)

CreateTestGinContextWithBody creates a Gin context with a request body SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: build a Gin context with a request body and content type for testing (pure)

func CurrentTime

func CurrentTime() time.Time

CurrentTime returns current time in UTC SEM@386eea01f3b66c35027bf3ca762efbc291419e20: return the current time in UTC (pure)

func CustomRecoveryMiddleware

func CustomRecoveryMiddleware() gin.HandlerFunc

CustomRecoveryMiddleware returns a Gin middleware that recovers from panics and returns appropriate error responses without exposing sensitive information SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: Gin middleware that recovers from panics and returns a 500 without exposing stack traces

func DateAddDays

func DateAddDays(dialectName string, days int) string

DateAddDays returns a dialect-specific expression for "now + N days". Useful for setting expiration dates or retry times.

Example usage:

updates := map[string]interface{}{
    "next_retry_at": gorm.Expr(DateAddDays(s.db.Dialector.Name(), retryDelayDays)),
}

SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a dialect-specific SQL expression for now plus N days (pure)

func DateAddMinutes

func DateAddMinutes(dialectName string, minutes int) string

DateAddMinutes returns a dialect-specific expression for "now + N minutes". Useful for setting short-term retry times. SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a dialect-specific SQL expression for now plus N minutes (pure)

func DateSubDays

func DateSubDays(dialectName, column string, days int) string

DateSubDays returns a dialect-specific WHERE clause for "column < now - N days". This handles the different date arithmetic syntax across databases.

Example usage:

result := s.db.Where("status IN ?", statuses).
    Where(DateSubDays(s.db.Dialector.Name(), "created_at", daysOld)).
    Delete(&SomeModel{})

SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a dialect-specific SQL WHERE clause for column < now minus N days (pure)

func DeleteAddon

func DeleteAddon(c *gin.Context)

DeleteAddon deletes an add-on (admin only) SEM@c9781319675ccc8efddf4bcf30faed097d0c028a: handle DELETE /addons/{id}: delete an addon, rejecting if active invocations exist (reads DB)

func DetailedRequestLoggingMiddleware

func DetailedRequestLoggingMiddleware() gin.HandlerFunc

DetailedRequestLoggingMiddleware logs request details at each stage SEM@053baa340d412aa135be32953dfcb6133af89b4d: log incoming request headers, body, and completion status with a unique request ID

func DiagramMiddleware

func DiagramMiddleware() gin.HandlerFunc

DiagramMiddleware creates middleware for diagram authorization SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: enforce role-based authorization on /diagrams/* routes and set diagram context

func DuplicateHeaderValidationMiddleware

func DuplicateHeaderValidationMiddleware() gin.HandlerFunc

DuplicateHeaderValidationMiddleware rejects requests with duplicate critical security headers Per RFC 7230 Section 3.2.2, duplicate headers are only allowed if the header is defined as a comma-separated list or is a known exception (like Set-Cookie). Duplicate security-critical headers can enable various attacks including request smuggling, authentication bypass, and cache poisoning. SEM@d86c7a3d58999ec91e9d2a8676d972f89424dad4: reject requests that supply duplicate security-critical headers such as Authorization or Content-Type

func EmbeddingAutomationMiddleware

func EmbeddingAutomationMiddleware() gin.HandlerFunc

EmbeddingAutomationMiddleware creates a middleware that requires the user to be a member of the embedding-automation group specifically. This is the inner gate for /automation/embeddings/* routes, layered inside AutomationMiddleware. SEM@46ceafa6fa8deee41cbc5c929e3f60ca14fdd686: authorize requests to /automation/embeddings/* routes, requiring embedding-automation group membership

func EnableThreatModelAliasSequence

func EnableThreatModelAliasSequence()

EnableThreatModelAliasSequence signals that the global ThreatModel alias sequence exists and AllocateNextAlias may draw the global alias from it. The server calls this once, after dbschema.InstallThreatModelAliasSequence succeeds on PostgreSQL or Oracle. SEM@15d1523404ac67830fbe68f72a41c9683aa564b6: enable DB-sequence-backed alias allocation for the global threat model scope (mutates shared state)

func EnforceIfMatchOrWarn

func EnforceIfMatchOrWarn(c *gin.Context) error

EnforceIfMatchOrWarn applies the rollout policy when the caller did not supply a version. When RequireIfMatch() is true, returns a 428 RequestError; otherwise sets the Deprecation/Warning headers and returns nil. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: return 428 when If-Match is required, or set deprecation warning headers when lenient

func EnrichAuthorizationEntry

func EnrichAuthorizationEntry(ctx context.Context, db *gorm.DB, auth *Authorization) error

EnrichAuthorizationEntry enriches a single Authorization entry by looking up missing fields from the users table. The caller must provide:

  • provider: REQUIRED - the identity provider name
  • EXACTLY ONE OF: provider_id (email/OAuth sub) OR email

The function will lookup the user in the database and fill in missing fields. For new users (not yet in database), it performs a sparse insert that will be completed when the user logs in via OAuth.

Group principals are skipped (no enrichment needed). SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: resolve a user by provider identity, performing a sparse insert for unknown users, and fill in missing authorization fields (reads DB)

func EnrichAuthorizationList

func EnrichAuthorizationList(ctx context.Context, db *gorm.DB, authList []Authorization) error

EnrichAuthorizationList enriches all authorization entries in a list SEM@383547f0bee568a092d84a1f830f227b74f6d723: enrich every authorization entry in a list, resolving user identity from the database (reads DB)

func EntityTypeToIndexType

func EntityTypeToIndexType(entityType string) string

EntityTypeToIndexType maps an entity type to its vector index type. Repositories go to the code index; everything else goes to the text index. SEM@37a05c9c7bcde023781ade490d31e55313f5a793: convert an entity type string to its search index type, mapping repositories to code index (pure)

func EnumNormalizerMiddleware

func EnumNormalizerMiddleware() gin.HandlerFunc

EnumNormalizerMiddleware normalizes enum values in query parameters and JSON request bodies to their canonical snake_case form before OpenAPI validation. This makes enum matching case-insensitive for API consumers. SEM@034968fa0e0ba8c15e9af9052b475f4d5dd72d50: normalize enum query params and JSON body fields to snake_case before validation

func ExtractOptionalUUID

func ExtractOptionalUUID(c *gin.Context, paramName string) (uuid.UUID, error)

ExtractOptionalUUID extracts and validates an optional UUID from a path parameter Returns the parsed UUID (or uuid.Nil if not present), and an error if parsing fails SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: parse and validate an optional UUID path parameter, returning uuid.Nil if absent (pure)

func ExtractRequiredUUIDs

func ExtractRequiredUUIDs(c *gin.Context, paramNames ...string) (map[string]uuid.UUID, error)

ExtractRequiredUUIDs extracts and validates multiple required UUID parameters Returns a map of parameter names to UUIDs, or an error with HTTP response already sent SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: parse and validate multiple required UUID path parameters, returning a name-to-UUID map (pure)

func ExtractUUID

func ExtractUUID(c *gin.Context, paramName string) (uuid.UUID, error)

ExtractUUID extracts and validates a UUID from a path parameter Returns the parsed UUID or an error with HTTP response already sent SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: parse and validate a required UUID path parameter, sending a 400 on failure (pure)

func FilterStackTraceFromBody

func FilterStackTraceFromBody(body string) string

FilterStackTraceFromBody filters out stack trace information from response bodies This is used by the request logger to prevent stack traces from being logged SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: redact or truncate stack trace content from a response body string before logging (pure)

func GenerateChangeSummary

func GenerateChangeSummary(originalJSON, modifiedJSON []byte) string

GenerateChangeSummary produces a human-readable summary of changes between two JSON states. Format: "field1: 'old' -> 'new', field2: added, field3: removed" SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: compute a human-readable field-level change summary between two JSON states (pure)

func GetAddon

func GetAddon(c *gin.Context)

GetAddon retrieves a single add-on by ID SEM@c9781319675ccc8efddf4bcf30faed097d0c028a: handle GET /addons/{id}: fetch and return a single addon by ID (reads DB)

func GetAllModels

func GetAllModels() []any

GetAllModels returns all GORM models for AutoMigrate This function is used by the server to run database migrations for non-postgres databases SEM@45a055dc8bd72a23aefc3c2edcf48d64d511ff36: return all GORM model instances for AutoMigrate (pure)

func GetDialectName

func GetDialectName(db *gorm.DB) string

GetDialectName is a convenience function to get the dialect name from a GORM DB instance. SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: fetch the GORM dialect name for a DB instance (pure)

func GetFieldErrorMessage

func GetFieldErrorMessage(field, operation string) string

GetFieldErrorMessage is the global function to get error messages SEM@63189587a90229342bc1d25023ec7a515412fb4f: fetch the contextual error message for a prohibited field from the global registry (pure)

func GetGroupUUIDsByNames

func GetGroupUUIDsByNames(ctx context.Context, db *gorm.DB, provider string, groupNames []string) ([]uuid.UUID, error)

GetGroupUUIDsByNames looks up group UUIDs from group names for a given provider. This is used by admin checks and auth adapters to convert JWT group claims to UUIDs. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch UUIDs for the named groups scoped to a provider (reads DB)

func GetOwnerInternalUUID

func GetOwnerInternalUUID(ctx context.Context, provider, providerID string) string

GetOwnerInternalUUID looks up the owner's internal UUID from provider and provider_id Returns the provider_id if lookup fails (fallback for tests/in-memory mode) SEM@f26a80b2c254e75f44d8b4302b64ff465d4a2ac5: resolve a user's internal UUID from provider and provider ID; falls back to provider ID on error (reads DB)

func GetProjectTeamID

func GetProjectTeamID(ctx context.Context, projectID string) (string, error)

GetProjectTeamID retrieves the team_id for a given project. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch the team ID that owns a given project (reads DB)

func GetPseudoGroupIdP

func GetPseudoGroupIdP(groupName string) *string

GetPseudoGroupIdP returns the appropriate IdP value for a pseudo-group Pseudo-groups are cross-IdP by design, so this returns nil SEM@6124bff108947c0b35d793f38a2bff9f438768ce: return nil IdP for a pseudo-group, indicating cross-provider scope (pure)

func GetSpec

func GetSpec() (swagger *openapi3.T, err error)

GetSpec returns the OpenAPI specification corresponding to the generated code in this file. External references in the spec are resolved through PathToRawSpec; externally-referenced files must be embedded in their corresponding Go packages (via the import-mapping feature). URL-based external refs are not supported.

func GetSpecJSON

func GetSpecJSON() ([]byte, error)

GetSpecJSON returns the raw JSON bytes of the embedded OpenAPI specification: decompressed but not unmarshaled. External references are not resolved here; the bytes are the spec exactly as embedded by codegen. The result is cached at package init time, so repeated calls are cheap.

func GetSwagger deprecated

func GetSwagger() (*openapi3.T, error)

GetSwagger returns the OpenAPI specification corresponding to the generated code in this file.

Deprecated: GetSwagger predates kin-openapi renaming openapi3.Swagger to openapi3.T. Use GetSpec instead. This wrapper is retained for backwards compatibility.

func GetTestUserRole

func GetTestUserRole(user string) string

GetTestUserRole returns the role for a given test user SEM@dff4dd105825de9e0bddf30a1b4cfc72f3acc18d: fetch the assigned role for a named test user, defaulting to unknown (pure)

func GetTestUsers

func GetTestUsers() map[string]string

GetTestUsers returns a map of test users with their roles SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: fetch a map of test user emails to their assigned roles (pure)

func GetUserAuthFieldsForAccessCheck

func GetUserAuthFieldsForAccessCheck(c *gin.Context) (providerUserID, internalUUID, provider string, groups []string)

GetUserAuthFieldsForAccessCheck extracts user identity fields from the Gin context using soft-failure semantics (empty strings on missing values). This is used by authorization middleware where missing fields don't prevent the access check - the authorization logic itself will deny access based on empty values. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: extract user identity fields from context with soft-failure semantics for authorization checks (pure)

func GetUserDisplayName

func GetUserDisplayName(c *gin.Context) string

GetUserDisplayName retrieves the user's display name from the context Returns the display name from JWT claims Returns empty string if not available (not an error) SEM@89d554e793900a75b5703e1d10c9d58f57ceadc6: fetch the authenticated user's display name from the Gin request context (pure)

func GetUserEmail

func GetUserEmail(c *gin.Context) (string, error)

GetUserEmail retrieves the user's email from the context This is set by the JWT middleware from the email claim Returns error if user is not authenticated or email is not available SEM@93f28e44afc91d0a7917b5dc1aaed9a52b00529a: fetch the authenticated user's email from the Gin request context (pure)

func GetUserFromContext

func GetUserFromContext(c *gin.Context) (*auth.User, error)

GetUserFromContext retrieves the full user object from the Gin context The user object is set by the JWT middleware after authentication Returns RequestError if user is not found or not authenticated SEM@89d554e793900a75b5703e1d10c9d58f57ceadc6: fetch the authenticated user from the Gin request context (pure)

func GetUserGroups

func GetUserGroups(c *gin.Context) []string

GetUserGroups retrieves the user's groups from the context Returns the groups array from the identity provider Returns empty array if no groups are present (not an error) SEM@89d554e793900a75b5703e1d10c9d58f57ceadc6: fetch the authenticated user's group memberships from the Gin request context (pure)

func GetUserIdentityForLogging

func GetUserIdentityForLogging(c *gin.Context) string

GetUserIdentityForLogging returns a formatted user identity string for logging that distinguishes between regular users and service accounts.

For regular users: returns "user={email}" For service accounts: returns "service_account=[Service Account] {name} (credential_id={id}, owner={email})" SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: format a loggable user identity string distinguishing service accounts from regular users (pure)

func GetUserInternalUUID

func GetUserInternalUUID(c *gin.Context) (string, error)

GetUserInternalUUID retrieves the user's internal UUID from the context This is the system-generated UUID for internal tracking (never exposed in JWT) Returns error if user is not authenticated or UUID is not available SEM@93f28e44afc91d0a7917b5dc1aaed9a52b00529a: fetch the authenticated user's internal system UUID from the Gin request context (pure)

func GetUserProvider

func GetUserProvider(c *gin.Context) (string, error)

GetUserProvider retrieves the user's OAuth provider from the context Returns the provider name (e.g., "tmi", "google", "github", "microsoft", "azure") Returns error if user is not authenticated or provider is not available SEM@93f28e44afc91d0a7917b5dc1aaed9a52b00529a: fetch the authenticated user's OAuth provider name from the Gin request context (pure)

func GetUserProviderID

func GetUserProviderID(c *gin.Context) (string, error)

GetUserProviderID retrieves the user's provider user ID from the context This is the OAuth provider's user ID (from JWT sub claim) Returns error if user is not authenticated or provider user ID is not available SEM@93f28e44afc91d0a7917b5dc1aaed9a52b00529a: fetch the authenticated user's provider subject ID from the Gin request context (pure)

func GetVersionString

func GetVersionString() string

GetVersionString returns the version as a formatted string SEM@6acba406c94a7bc4caaf713a960fd4f28bb3e6a7: format the application version as a human-readable string including commit and build date (pure)

func GetWebhookDeliveryStatus

func GetWebhookDeliveryStatus(c *gin.Context)

GetWebhookDeliveryStatus retrieves a webhook delivery record. Supports dual auth: JWT (admin, subscription owner, or addon invoker) or HMAC (webhook receiver). SEM@e64d904fcb8ba57e094190bac4395e83cec9abc1: fetch a webhook delivery record with dual HMAC or JWT authorization (reads DB)

func GinServerErrorHandler

func GinServerErrorHandler(c *gin.Context, err error, statusCode int)

GinServerErrorHandler converts parameter binding errors to TMI's error format This is used by the oapi-codegen generated server wrapper to handle parameter binding errors SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: convert a Gin parameter binding error into a typed TMI error response

func HSTSMiddleware

func HSTSMiddleware(tlsEnabled bool) gin.HandlerFunc

HSTSMiddleware adds Strict-Transport-Security header when TLS is enabled SEM@8bc458fb71c00d05590f369b09ca1dcf7de7819d: add Strict-Transport-Security header when TLS is enabled

func HandleRequestError

func HandleRequestError(c *gin.Context, err error)

HandleRequestError sends an appropriate HTTP error response SEM@6fb83b19171915a13ed7b703a35fc8b25209fa8c: dispatch an HTTP error response for a request error, setting appropriate headers (pure)

func HandleRestoreAsset

func HandleRestoreAsset(c *gin.Context, threatModelId, assetId string)

RestoreAsset restores a soft-deleted asset. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: restore a soft-deleted asset within its parent threat model (mutates shared state)

func HandleRestoreDiagram

func HandleRestoreDiagram(c *gin.Context, threatModelId, diagramId string)

RestoreDiagram restores a soft-deleted diagram. SEM@e4005658033b63171bdc1130fb523d996fbff9a7: restore a soft-deleted diagram within its parent threat model (mutates shared state)

func HandleRestoreDocument

func HandleRestoreDocument(c *gin.Context, threatModelId, documentId string)

RestoreDocument restores a soft-deleted document. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: restore a soft-deleted document within its parent threat model (mutates shared state)

func HandleRestoreNote

func HandleRestoreNote(c *gin.Context, threatModelId, noteId string)

RestoreNote restores a soft-deleted note. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: restore a soft-deleted note within its parent threat model (mutates shared state)

func HandleRestoreRepository

func HandleRestoreRepository(c *gin.Context, threatModelId, repositoryId string)

RestoreRepository restores a soft-deleted repository. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: restore a soft-deleted repository within its parent threat model (mutates shared state)

func HandleRestoreThreat

func HandleRestoreThreat(c *gin.Context, threatModelId, threatId string)

RestoreThreat restores a soft-deleted threat. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: restore a soft-deleted threat within its parent threat model (mutates shared state)

func HandleRestoreThreatModel

func HandleRestoreThreatModel(c *gin.Context, threatModelId string)

HandleRestoreThreatModel restores a soft-deleted threat model and all its children. SEM@b226389b316426e5d229ed94aa3a29dff80e46b1: restore a soft-deleted threat model and all its children, then emit audit record (mutates shared state)

func HeadMethodMiddleware

func HeadMethodMiddleware() gin.HandlerFunc

HeadMethodMiddleware returns Gin middleware that converts HEAD requests to GET before the handler chain, suppresses the response body, and restores the original HEAD method afterward. This allows OpenAPI validation middleware to match GET routes for HEAD requests while producing correct HEAD responses.

Certain protocol endpoints (OAuth authorize/callback, SAML login/SLO) are excluded from conversion because they involve redirects or other behavior that should not be altered. SEM@24f51bad50c8ca10a1308eb097fbe7cd4449e83a: Gin middleware that converts HEAD requests to GET, suppresses the response body, and sets Content-Length

func IPRateLimitMiddleware

func IPRateLimitMiddleware(server *Server) gin.HandlerFunc

IPRateLimitMiddleware creates middleware for IP-based rate limiting (Tier 1 - public discovery) SEM@c70d49ed2d6089c24d05f8bc287ba5711c73abde: enforce per-IP rate limits on public discovery endpoints, adding standard rate-limit response headers

func InitNotificationHub

func InitNotificationHub()

InitNotificationHub initializes the global notification hub SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: initialize and start the global notification hub if not already running (mutates shared state)

func InitSubResourceTestFixtures

func InitSubResourceTestFixtures()

InitSubResourceTestFixtures initializes comprehensive test fixtures for sub-resource testing SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: build and store the global sub-resource test fixtures including threat models, threats, documents, and diagrams (mutates shared state)

func InitTestFixtures

func InitTestFixtures()

InitTestFixtures initializes test data in stores SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: initialize in-memory stores with canonical test threat model and diagram fixtures (mutates shared state)

func InitializeEventEmitter

func InitializeEventEmitter(redisClient *redis.Client, streamKey string)

InitializeEventEmitter initializes the global event emitter SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: initialize the global event emitter with the given Redis client and stream key (mutates shared state)

func InitializeGormStores

func InitializeGormStores(db *gorm.DB, authService any, cache *CacheService, invalidator *CacheInvalidator)

InitializeGormStores initializes all stores with GORM implementations This is the only store initialization function - all databases use GORM SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: initialize all global GORM-backed stores and repositories using the provided DB, auth service, and cache (mutates shared state)

func InitializeMockStores

func InitializeMockStores()

InitializeMockStores creates simple mock stores for unit tests SEM@8fc3d262100f4b47c12ee2155e83e344babb1bd3: initialize global threat model and diagram stores with empty in-memory mocks (mutates shared state)

func InitializeQuotaCache

func InitializeQuotaCache(ttl time.Duration)

InitializeQuotaCache initializes the global quota cache SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: initialize the global quota cache singleton with the given TTL (mutates shared state)

func InsertDiagramForTest

func InsertDiagramForTest(id string, diagram DfdDiagram)

InsertDiagramForTest inserts a diagram with a specific ID directly into the store This is only for testing purposes SEM@66c07d60dcc389066ea6e3a699b4bd1ca24bfb65: store a diagram with a specific test ID, overriding the generated ID (reads DB)

func InvokeAddon

func InvokeAddon(c *gin.Context)

InvokeAddon invokes an add-on (authenticated users). Creates a WebhookDeliveryRecord and emits an addon.invoked event. SEM@00add3d4f7dc1c0a9cc072d7e6ca32ace4d03641: handle an addon invocation request, enforce rate limits, and enqueue a webhook delivery record (reads DB)

func IsConfidentialProjectReviewersGroup

func IsConfidentialProjectReviewersGroup(auth Authorization) bool

IsConfidentialProjectReviewersGroup checks if an authorization entry represents the Confidential Project Reviewers group SEM@65c402395f94917b986bab7e1b3f61ae0484c885: check whether an authorization entry represents the Confidential Project Reviewers built-in group (pure)

func IsContentOAuthPermanentFailure

func IsContentOAuthPermanentFailure(err error) bool

IsContentOAuthPermanentFailure returns true when err wraps a permanent OAuth failure (e.g. 4xx on refresh meaning the token is revoked or invalid). Permanent failures should not be retried; callers should mark the token as failed and ask the user to re-authorize. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: report whether an error signals a permanent, non-retryable OAuth failure (pure)

func IsGroupMember

func IsGroupMember(ctx context.Context, mc *MembershipContext, group BuiltInGroup) (bool, error)

IsGroupMember checks if the user described by mc is an effective member of the given built-in group. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: validate effective membership of a user in a built-in group (reads DB)

func IsGroupMemberFromContext

func IsGroupMemberFromContext(c *gin.Context, group BuiltInGroup) (bool, error)

IsGroupMemberFromContext is a convenience function that resolves the membership context from a Gin context and checks group membership in a single call. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: validate effective group membership by resolving membership context from a Gin request (reads DB)

func IsGroupMemberFromParams

func IsGroupMemberFromParams(ctx context.Context, memberStore GroupMemberRepository, userInternalUUID string, provider string, groupNames []string, group BuiltInGroup) (bool, error)

IsGroupMemberFromParams checks group membership using explicit parameters. This is used by cross-package adapters (e.g., auth package) that don't have a Gin context. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: validate effective group membership using explicit user UUID and group names without a Gin context (reads DB)

func IsIPv4

func IsIPv4(hostname string) bool

IsIPv4 checks if a string is an IPv4 address SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: check whether a string is a dotted-decimal IPv4 address (pure)

func IsIPv6

func IsIPv6(hostname string) bool

IsIPv6 checks if a string is an IPv6 address SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: check whether a string is an IPv6 address by presence of colons (pure)

func IsProjectTeamMemberOrAdmin

func IsProjectTeamMemberOrAdmin(ctx context.Context, projectID string, userInternalUUID string, c *gin.Context) (bool, error)

IsProjectTeamMemberOrAdmin checks if a user is a member of the team that owns the project, or an administrator. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: authorize whether a user belongs to the team that owns a project, or is an administrator (reads DB)

func IsPseudoGroup

func IsPseudoGroup(groupName string) bool

IsPseudoGroup checks if a group name is a recognized pseudo-group Pseudo-groups are special groups with predefined behavior that don't come from IdPs SEM@6124bff108947c0b35d793f38a2bff9f438768ce: validate whether a group name is a recognized built-in pseudo-group (pure)

func IsSecurityReviewersGroup

func IsSecurityReviewersGroup(auth Authorization) bool

IsSecurityReviewersGroup checks if an authorization entry represents the Security Reviewers group SEM@5998227fb120ee0575a994ea2c0ecb24f0e67109: check whether an authorization entry represents the Security Reviewers built-in group (pure)

func IsServiceAccountRequest

func IsServiceAccountRequest(c *gin.Context) bool

IsServiceAccountRequest returns true if the current request is from a service account SEM@b88f8e119b1c65b1b76832e46f22d2ebdb88d0ca: check whether the current request was authenticated as a service account (pure)

func IsTMIAutomationGroup

func IsTMIAutomationGroup(auth Authorization) bool

IsTMIAutomationGroup checks if an authorization entry represents the TMI Automation group SEM@ea27b9d824200a49ef32578459a76c5bca658108: check whether an authorization entry represents the TMI Automation built-in group (pure)

func IsTeamMemberOrAdmin

func IsTeamMemberOrAdmin(ctx context.Context, teamID string, userInternalUUID string, c *gin.Context) (bool, error)

IsTeamMemberOrAdmin checks if a user is a member of the specified team OR an administrator. Returns true if the user is authorized to access the team's resources. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: authorize whether a user is a team member or administrator (reads DB)

func IsTeamOwnerOrAdmin

func IsTeamOwnerOrAdmin(ctx context.Context, teamID string, userInternalUUID string, c *gin.Context) (bool, error)

IsTeamOwnerOrAdmin checks if a user is the creator/owner of a team or an administrator. Used for operations that require owner-level access (e.g., delete). SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: authorize whether a user is the team creator or administrator (reads DB)

func IsUserAdministrator

func IsUserAdministrator(c *gin.Context) (bool, error)

IsUserAdministrator checks if the authenticated user is an administrator Returns (isAdmin bool, error). Returns false if there's any error or if administrator check is not available. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: check whether the authenticated user belongs to the administrators group (reads DB)

func JSONErrorHandler

func JSONErrorHandler() gin.HandlerFunc

JSONErrorHandler middleware converts plain text error responses to JSON format This catches Gin framework errors that bypass application error handling It uses a buffered response writer to intercept responses before they're sent SEM@5d72468ae02763853a1bb7b148ece4292c8d3f99: intercept plain-text error responses and convert them to JSON format

func ListAddons

func ListAddons(c *gin.Context)

ListAddons retrieves add-ons with pagination SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: handle GET /addons: list addons with pagination and optional threat model filter (reads DB)

func LogRequest

func LogRequest(c *gin.Context, prefix string)

LogRequest logs debug information about the request SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: log request method, path, headers, and body at debug level

func MarshalAsyncMessage

func MarshalAsyncMessage(msg AsyncMessage) ([]byte, error)

Helper function to marshal AsyncMessage to JSON SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: validate and serialize an async message to JSON bytes (pure)

func MarshalAuditEntryResponse

func MarshalAuditEntryResponse(resp AuditEntryResponse) ([]byte, error)

MarshalAuditEntryResponse is a helper to serialize an AuditEntryResponse to JSON. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: serialize an audit entry response to JSON (pure)

func MethodNotAllowedHandler

func MethodNotAllowedHandler() gin.HandlerFunc

MethodNotAllowedHandler returns 405 for unsupported HTTP methods SEM@d86c7a3d58999ec91e9d2a8676d972f89424dad4: reject non-standard HTTP methods with 405 before routing proceeds

func MethodNotAllowedJSONHandler

func MethodNotAllowedJSONHandler() gin.HandlerFunc

MethodNotAllowedJSONHandler returns a Gin handler that responds with 405 Method Not Allowed in TMI's JSON error format. It is designed to be used with r.NoMethod() so Gin calls it when HandleMethodNotAllowed is true and the path exists but the requested HTTP method is not registered. Gin automatically sets the Allow header before invoking NoMethod handlers. SEM@81952f598eaf9b1599471d778c9fb82e7d2f2d7a: return 405 in TMI JSON error format when no route matches the requested HTTP method

func NewAdminAuditMiddleware

func NewAdminAuditMiddleware(repo SystemAuditRepository, redactor Redactor, reader SystemSettingReader) gin.HandlerFunc

NewAdminAuditMiddleware constructs AdminAuditMiddleware with the canonical descriptor set for all /admin/* write operations (#355). This is the preferred entry point for external callers (e.g. cmd/server/main.go) so that adminAuditDescriptors stays unexported. SEM@f44001bd271fd2fa66f717ac20086e48d444cd07: build AdminAuditMiddleware with the canonical descriptor set for all /admin/* write operations (pure)

func NewExtractedTextNoteDumper

func NewExtractedTextNoteDumper(notes NoteRepository, documents DocumentRepository) *extractedTextNoteDumper

NewExtractedTextNoteDumper builds a dumper. notes/documents must be non-nil. SEM@117032a3c5523a04e970f76a285e342169d5150c: build an extractedTextNoteDumper backed by note and document repositories (pure)

func NewPKCEVerifier

func NewPKCEVerifier() (string, error)

NewPKCEVerifier returns a 43-character code verifier per RFC 7636 §4.1. It is 32 random bytes encoded as base64url without padding. SEM@dc9b50bbe595fd2f030515ecf7ae1902b4fa8e7e: generate a cryptographically random PKCE code verifier (pure)

func NewReadCloser

func NewReadCloser(b []byte) *readCloser

SEM@386eea01f3b66c35027bf3ca762efbc291419e20: build an io.ReadCloser from a byte slice for body restoration (pure)

func NewStampedConfigProvider

func NewStampedConfigProvider(settings settingsReader) config.StampedConfigProvider

NewStampedConfigProvider builds a config.StampedConfigProvider that reads through the given settings reader (normally *SettingsService). SEM@07385154fa2286de1a8805dbf00575c0f52ce941: build a StampedConfigProvider backed by the given settings reader (pure)

func NormalizeColorPalette

func NormalizeColorPalette(palette *[]ColorPaletteEntry) (*[]ColorPaletteEntry, error)

NormalizeColorPalette validates and normalizes a color palette array. - Validates each color matches #RGB or #RRGGBB pattern - Expands 3-digit hex to 6-digit - Lowercases all color values - Rejects duplicate positions - Rejects more than 8 entries - Sorts entries by position - Returns nil for empty input (never returns an empty slice) SEM@3178cfdb4d9b95cb34c34db7f16dc14e46867342: validate, deduplicate, expand, lowercase, and sort a color palette up to 8 entries (pure)

func NormalizeDiagramCells

func NormalizeDiagramCells(cells []DfdDiagram_Cells_Item)

NormalizeDiagramCells normalizes all cells in a diagram This should be called for both REST API and WebSocket operations SEM@047735fbb921a2cd724d2f9af71dca52aeb8798b: normalize position and size fields for all cells in a diagram slice (pure)

func NormalizeEnumValue

func NormalizeEnumValue(value string) string

NormalizeEnumValue converts any case variant to canonical snake_case. e.g., "Critical" -> "critical", "OneSide" -> "one_side", "OK" -> "ok" SEM@034968fa0e0ba8c15e9af9052b475f4d5dd72d50: trim and convert an enum string value to snake_case (pure)

func NowGreaterThanColumn

func NowGreaterThanColumn(dialectName, column string) string

NowGreaterThanColumn returns a dialect-specific WHERE clause for "now > column". Useful for checking if a timestamp has passed (e.g., retry_at <= now means ready to retry). SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a dialect-specific SQL WHERE clause for now >= column (pure)

func NowLessThanColumn

func NowLessThanColumn(dialectName, column string) string

NowLessThanColumn returns a dialect-specific WHERE clause for "now < column". Useful for checking if a timestamp is in the future (e.g., retry_at > now means not yet ready). SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a dialect-specific SQL WHERE clause for now <= column (pure)

func OOXMLLimitsFromConfig

func OOXMLLimitsFromConfig(c config.ContentExtractorsConfig) extract.Limits

OOXMLLimitsFromConfig converts a validated ContentExtractorsConfig into the relocated extract.Limits value consumed by the OOXML extractors. Used by server wiring; tests can continue to use extract.DefaultLimits().

MaxXMLElementDepth and MaxCompressionRatio are server-only ceilings (not operator-tunable) and are populated with the const ceilings here so the extractors see consistent values regardless of caller. SEM@d1fd850907490887fd11a6ccd4a691326ede6e4e: convert operator content-extractor config to OOXML extractor limits with fixed security ceilings (pure)

func OTelSpanEnrichmentMiddleware

func OTelSpanEnrichmentMiddleware() gin.HandlerFunc

OTelSpanEnrichmentMiddleware adds TMI-specific attributes to the active OTel span. Must be placed after auth middleware so user context is available. SEM@71920f2fde60dd337c0e9ed3597bc6bb8194ef36: attach TMI-specific user, threat model, diagram, and request ID attributes to the active OTel span

func OpenAPIErrorHandler

func OpenAPIErrorHandler(c *gin.Context, message string, statusCode int)

OpenAPIErrorHandler converts OpenAPI validation errors to TMI's error format SEM@b01e07335548bf92e0c83fbddb8681759f35fdb7: convert an OpenAPI validation error into a typed TMI error response with correct HTTP status

func OrderByCol

func OrderByCol(dialectName, column string, desc bool) clause.OrderByColumn

OrderByCol returns a clause.OrderByColumn for use in ORDER BY clauses. Oracle requires uppercase column names. SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: build a GORM ORDER BY column with dialect-correct casing and direction (pure)

func PKCES256Challenge

func PKCES256Challenge(verifier string) string

PKCES256Challenge returns the S256 code challenge for the given verifier per RFC 7636 §4.2: BASE64URL(SHA256(ASCII(code_verifier))) without padding. SEM@dc9b50bbe595fd2f030515ecf7ae1902b4fa8e7e: compute the S256 PKCE code challenge from a verifier (pure)

func ParseIfMatchHeader

func ParseIfMatchHeader(c *gin.Context) (int, bool, error)

ParseIfMatchHeader extracts a non-negative integer version from the If-Match request header. Returns (version, true, nil) on success, (0, false, nil) if the header is absent, or (0, true, err) if the header is present but malformed.

Per RFC 7232 If-Match values are quoted ETags. We accept either a bare integer ("If-Match: 5") or a quoted integer (`If-Match: "5"`) for client convenience. The "*" wildcard form is intentionally rejected for now — callers should send an explicit version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: parse a non-negative integer version from the If-Match request header (pure)

func ParseRequestBody

func ParseRequestBody[T any](c *gin.Context) (T, error)

ParseRequestBody parses JSON request body into the specified type SEM@e890b588ef2cb844c92f6ddd0d56e797bb39b7e2: parse, validate, and deserialize a JSON request body into a typed value (pure)

func ParseUUIDOrNil

func ParseUUIDOrNil(s string) uuid.UUID

ParseUUIDOrNil parses a UUID string, returning a nil UUID on error SEM@09b9acb42bb2ed2bd519ff1f962213011e015b62: parse a UUID string and return uuid.Nil on parse failure (pure)

func PathParameterValidationMiddleware

func PathParameterValidationMiddleware() gin.HandlerFunc

PathParameterValidationMiddleware validates all path parameters for common issues SEM@a0b03d5d6a185b962cc24512bc65629f58b659da: validate all path parameters against injection, traversal, length, and null-byte attacks

func PathToRawSpec

func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error)

Constructs a synthetic filesystem for resolving external references when loading openapi specifications.

func PayloadTooLargeError

func PayloadTooLargeError(msg string) error

PayloadTooLargeError returns a 413 RequestError. SEM@72f2ef0deaad62ae1c2054ae42a059a253d123b7: build a 413 Payload Too Large request error (pure)

func PreserveCriticalFields

func PreserveCriticalFields[T any](modified, original T, preserveFields func(T, T) T) T

PreserveCriticalFields preserves critical fields that shouldn't change during patching SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: restore immutable fields on a patched entity using a caller-supplied field-copy function (pure)

func RateLimitMiddleware

func RateLimitMiddleware(server *Server) gin.HandlerFunc

RateLimitMiddleware creates a middleware that enforces API rate limiting SEM@c70d49ed2d6089c24d05f8bc287ba5711c73abde: enforce per-user API rate limits and set rate limit response headers, skipping public and auth endpoints

func RecordAuditCreate

func RecordAuditCreate(c *gin.Context, threatModelID, objectType, objectID string, entity any)

RecordAuditCreate records a "created" audit entry for a newly created entity. Call after the entity has been successfully created in the store. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: record a created audit entry for a newly created entity (mutates shared state)

func RecordAuditDelete

func RecordAuditDelete(c *gin.Context, threatModelID, objectType, objectID string, preState []byte)

RecordAuditDelete records a "deleted" audit entry for a deleted entity. preState should be obtained via SerializeForAudit before the deletion. Call after the entity has been successfully deleted from the store. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: record a deleted audit entry for a removed entity (mutates shared state)

func RecordAuditUpdate

func RecordAuditUpdate(c *gin.Context, changeType, threatModelID, objectType, objectID string, preState []byte, entity any)

RecordAuditUpdate records an "updated" or "patched" audit entry for a modified entity. preState should be obtained via SerializeForAudit before the mutation. Call after the entity has been successfully updated in the store. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: record an updated or patched audit entry when non-server fields change (mutates shared state)

func RegisterHEADRoutes

func RegisterHEADRoutes(r *gin.Engine)

RegisterHEADRoutes inspects all currently registered GET routes and adds a corresponding HEAD route for each one that is not in headExcludedPaths. This must be called after all GET routes have been registered so that:

  • Gin's HandleMethodNotAllowed=true does not return 405 for HEAD requests on GET-only routes (RFC 9110 §9.3.2 requires HEAD support).
  • HeadMethodMiddleware converts HEAD→GET so that OpenAPI validation and the actual handler see "GET", while the response body is suppressed.

Excluded paths (OAuth redirects, SAML redirects) are intentionally omitted because their redirect behaviour makes HEAD semantically incorrect. SEM@a729e8ec8c179ca5981e8e9cdc8d4290f627bd93: register HEAD routes for all eligible GET routes on the router (mutates shared state)

func RegisterHandlers

func RegisterHandlers(router gin.IRouter, si ServerInterface)

RegisterHandlers creates http.Handler with routing matching OpenAPI spec.

func RegisterHandlersWithOptions

func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions)

RegisterHandlersWithOptions creates http.Handler with additional options

func RequestTracingMiddleware

func RequestTracingMiddleware() gin.HandlerFunc

RequestTracingMiddleware provides comprehensive request tracing SEM@dff4dd105825de9e0bddf30a1b4cfc72f3acc18d: log method, path, status, latency, and request ID for every HTTP request

func RequireIfMatch

func RequireIfMatch() bool

RequireIfMatch reports whether missing If-Match should hard-fail with 428. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: report whether missing If-Match header should return 428 (pure)

func ResetSubResourceStores

func ResetSubResourceStores()

ResetSubResourceStores clears all sub-resource stores for testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: clear all sub-resource stores to a clean state between tests (mutates shared state)

func ResolveExpectedVersion

func ResolveExpectedVersion(c *gin.Context, bodyVersion *int) (int, bool, error)

ResolveExpectedVersion picks the expected version for a versioned write. Header wins over body. Returns (version, present, requestError).

  • If the header is present and valid, returns (n, true, nil).
  • If the header is present and malformed, returns (0, true, *RequestError).
  • If the header is absent and bodyVersion is non-nil, returns (*bodyVersion, true, nil).
  • If neither is provided, returns (0, false, nil) — caller decides whether to enforce per RequireIfMatch().

SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: resolve expected resource version from If-Match header or body fallback (pure)

func RespondWithBadRequest

func RespondWithBadRequest(c *gin.Context, errorDescription string)

RespondWithBadRequest sends a 400 Bad Request error response SEM@93f28e44afc91d0a7917b5dc1aaed9a52b00529a: send a 400 JSON error response with the given description

func RespondWithError

func RespondWithError(c *gin.Context, statusCode int, errorCode, errorDescription string)

RespondWithError sends a standardized error response matching the OpenAPI Error schema. Calls c.Abort() so downstream middleware in the chain do not overwrite the status. SEM@81952f598eaf9b1599471d778c9fb82e7d2f2d7a: send a structured JSON error response and abort the middleware chain

func RouteMatchingMiddleware

func RouteMatchingMiddleware() gin.HandlerFunc

RouteMatchingMiddleware logs which routes are being matched SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: log which route handler is matched for each incoming request

func RunMiddlewareTestCases

func RunMiddlewareTestCases(t *testing.T, middleware gin.HandlerFunc, testCases []MiddlewareTestCase)

RunMiddlewareTestCases executes a slice of test cases against a middleware SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: execute a batch of middleware test cases, asserting status, error text, and custom checks (pure)

func SAMLProviderOnlyMiddleware

func SAMLProviderOnlyMiddleware() gin.HandlerFunc

SAMLProviderOnlyMiddleware ensures the provider is a SAML provider (not OAuth) SEM@fb03bf4ae62f9d2e9e38b6a31882e902b0673586: reject requests whose path provider is not a SAML provider (pure)

func SafeFromEdge

func SafeFromEdge(item *DfdDiagram_Cells_Item, edge Edge) error

SafeFromEdge updates a DfdDiagram_Cells_Item with an Edge while preserving the edge's actual shape value. While "flow" is currently the only edge shape, this helper provides consistency with SafeFromNode and future-proofs against additional edge shapes. SEM@e0319b46956724d532b5b4f64b9f66b006e3a0a9: update a diagram cell union item with an edge while preserving its actual shape discriminator (pure)

func SafeFromNode

func SafeFromNode(item *DfdDiagram_Cells_Item, node Node) error

SafeFromNode updates a DfdDiagram_Cells_Item with a Node while preserving the node's actual shape value. The generated FromNode() method hardcodes the shape to a fixed discriminator value (due to oapi-codegen limitation where multiple discriminator values map to the same type), which corrupts the shape field. This helper bypasses that by marshaling the node directly and storing the raw bytes via UnmarshalJSON. SEM@e0319b46956724d532b5b4f64b9f66b006e3a0a9: update a diagram cell union item with a node while preserving its actual shape discriminator (pure)

func SafeParseInt

func SafeParseInt(s string, fallback int) int

SafeParseInt safely parses an integer string with a fallback value Does not return errors - uses fallback for any parsing failure SEM@e7454256ce7abf612c8dc53c5b39f9f7ad67a011: parse a non-negative integer string with overflow protection, returning a fallback on failure (pure)

func SamePrincipal

func SamePrincipal(a, b ResolvedUser) bool

SamePrincipal returns true if two ResolvedUser values represent the same person. Pure in-memory comparison, no DB access. Both arguments should ideally be fully resolved (via GetAuthenticatedUser or ResolveUser) before calling.

Algorithm: 1. If both have InternalUUID: match on UUID (warn if provider fields conflict) 2. If both have Provider AND ProviderID: match on (provider, provider_id) 3. Otherwise: return false (insufficient information)

Email is NEVER used for identity comparison. SEM@4c02975792d1bdeac3eeb81454da517814040317: compare two resolved users for identity equality using UUID then provider ID; never uses email (pure)

func SameProviderMiddleware

func SameProviderMiddleware() gin.HandlerFunc

SameProviderMiddleware ensures the authenticated user is from the same provider as specified in the path SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: authorize requests where the user's identity provider matches the path provider parameter (pure)

func SanitizeDiagramCellMetadata

func SanitizeDiagramCellMetadata(cells []DfdDiagram_Cells_Item) error

SanitizeDiagramCellMetadata sanitizes metadata values in all cells of a diagram. Processes both Node and Edge cell types. Returns an error if any value fails validation. Uses the shape discriminator to determine cell type, preventing node corruption that can occur when AsNode() fails (e.g., position validation) and the code falls through to AsEdge(), which rewrites nodes with edge-specific fields. SEM@7bac1ed632ff8929eff543daec4372c53d51283a: sanitize metadata values in all diagram cells using the shape discriminator to avoid type corruption (pure)

func SanitizeMarkdownContent

func SanitizeMarkdownContent(content string) string

SanitizeMarkdownContent applies the bluemonday HTML sanitization policy to a markdown content string. Safe HTML (per the allowlist) is preserved; dangerous elements and attributes are stripped. SEM@d6557548645ee87e8fe5910b447499fc633fbe6b: sanitize a markdown string by stripping disallowed HTML elements and attributes (pure)

func SanitizeMetadataSlice

func SanitizeMetadataSlice(metadata *[]Metadata) error

SanitizeMetadataSlice sanitizes all values in a metadata slice using SanitizePlainText. Returns an error if any value fails template injection validation after sanitization. SEM@6c2ed16a87725c4d8e764cde607ac1e06704e3ac: sanitize all values in a metadata slice and validate against HTML injection (pure)

func SanitizeOptionalString

func SanitizeOptionalString(s *string) *string

SanitizeOptionalString sanitizes an optional string field using SanitizePlainText. Returns nil if input is nil. Use for *string fields like Description, IssueUri, Mitigation. SEM@0c74197df2eb6b51a91fa4592766476fdf09f984: sanitize an optional string field, returning nil if input is nil (pure)

func SanitizePatchOperations

func SanitizePatchOperations(operations []PatchOperation, paths []string)

SanitizePatchOperations sanitizes string values in JSON Patch operations for the specified field paths using SanitizePlainText. Only "replace" and "add" operations are sanitized. SEM@0c74197df2eb6b51a91fa4592766476fdf09f984: sanitize string values in JSON Patch replace and add operations at specified paths (pure)

func SanitizePlainText

func SanitizePlainText(s string) string

SanitizePlainText strips ALL HTML tags from a string, leaving only text content. Use this for plain-text fields (e.g., metadata values) that should never contain HTML. Unlike SanitizeMarkdownContent, this does not preserve any HTML elements. HTML entities are decoded first so that entity-encoded tags (e.g., &lt;script&gt;) become real tags before sanitization strips them. The result is then unescaped again so that legitimate text like "0.0.0.0/0 -> NAT" is stored verbatim rather than as "0.0.0.0/0 -&gt; NAT". SEM@b8c2e635d7ace355cadeed6d3b0b853b2c950f75: strip all HTML from a plain-text field, decoding entities first to prevent bypass (pure)

func SecurityHeaders

func SecurityHeaders() gin.HandlerFunc

SecurityHeaders middleware adds security headers to all responses SEM@a1d7f44f9fbf44b654abfc81c5b3770eb540ecb0: attach OWASP security headers (CSP, X-Frame-Options, etc.) to every response

func SerializeForAudit

func SerializeForAudit(entity any) ([]byte, error)

SerializeForAudit marshals an entity to JSON, stripping server-managed and bulky derived fields (like SVG images) from the snapshot. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: serialize an entity to JSON, stripping server-managed fields for audit snapshots (pure)

func SetETagHeader

func SetETagHeader(c *gin.Context, version int)

SetETagHeader writes the ETag response header for a versioned entity. Per RFC 7232 ETag values are double-quoted opaque tokens; we use the integer version as the value. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: write the versioned ETag response header for a resource (pure)

func SetFullUserContext

func SetFullUserContext(c *gin.Context, email, userID, internalUUID, idp string, groups []string)

SetFullUserContext sets complete user authentication context including groups and IdP SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: store full user identity fields including IdP and groups into a Gin context for testing (mutates shared state)

func SetGlobalAuthServiceForEvents

func SetGlobalAuthServiceForEvents(authService AuthService)

SetGlobalAuthServiceForEvents sets the global auth service for event owner lookups SEM@f26a80b2c254e75f44d8b4302b64ff465d4a2ac5: register the global auth service used for owner UUID lookups during event emission (mutates shared state)

func SetGlobalDelegationTokenIssuer

func SetGlobalDelegationTokenIssuer(issuer DelegationTokenIssuer)

SetGlobalDelegationTokenIssuer sets the global delegation-token issuer. Safe to call once at startup from cmd/server/main.go. SEM@e6be8a8f816c564356a656ac18f3693ac7f10369: register the delegation token issuer at startup (mutates shared state)

func SetRequireIfMatch

func SetRequireIfMatch(v bool)

SetRequireIfMatch updates the optimistic-locking enforcement flag. Called once during server initialization from the loaded config. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: store the global If-Match enforcement flag at server startup (mutates shared state)

func SetTeamAuthDB

func SetTeamAuthDB(db *gorm.DB)

SetTeamAuthDB sets the GORM database handle for team authorization. SEM@8c7929da791c778ff88713684c47aa2a10911bba: register the GORM database handle for team authorization queries (mutates shared state)

func SetUserContext

func SetUserContext(c *gin.Context, email, userID string, role Role)

SetUserContext sets authentication context on a Gin context SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: store email, user ID, and role into a Gin context for testing (mutates shared state)

func SetWWWAuthenticateHeader

func SetWWWAuthenticateHeader(c *gin.Context, errType WWWAuthenticateError, description string)

SetWWWAuthenticateHeader sets a RFC 6750 compliant WWW-Authenticate header. The header value is built by the shared internal/wwwauth package so the RFC 6750 format lives in one place.

Parameters:

  • c: Gin context
  • errType: Error type (invalid_request, invalid_token, insufficient_scope) or empty for basic challenge
  • description: Human-readable error description (optional, ignored if errType is empty)

SEM@fcd7743e746718c31b33ef56fb3ba2f8ccf669c7: set the WWW-Authenticate response header for a given error type (pure)

func SetupOpenAPIValidation

func SetupOpenAPIValidation() (gin.HandlerFunc, error)

SetupOpenAPIValidation creates and returns OpenAPI validation middleware SEM@74d36522781dcfd28cfc8f5f32ed5cd9dd62a25e: build and return a Gin middleware that validates requests against the OpenAPI spec, skipping WebSocket routes

func SetupStoresWithFixtures

func SetupStoresWithFixtures(ctx context.Context) error

SetupStoresWithFixtures initializes stores with test fixtures SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: initialize stores with pre-built test fixtures, running fixture setup if not yet done (mutates shared state)

func ShouldAudit

func ShouldAudit(originalJSON, modifiedJSON []byte) bool

ShouldAudit returns true if the change between original and modified JSON includes changes to non-server-managed fields. Returns false if the only differences are in server-managed fields (id, timestamps, etc.). SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: report whether two JSON states differ on non-server-managed fields (pure)

func StepUpMiddleware

func StepUpMiddleware(window time.Duration, table StepUpRouteTable) gin.HandlerFunc

StepUpMiddleware enforces auth_time freshness on routes resolved as step-up-required by the provided table. Window is read once at construction; changes require a server restart.

Behavior (#355):

  • Route not in table or not flagged required: pass through.
  • userAuthTime missing or older than window: 401 with WWW-Authenticate: Bearer error="insufficient_user_authentication", max_age=<seconds>. (Per draft-ietf-oauth-step-up-authn-challenge.)
  • Fresh enough: pass through.

Order: this middleware MUST run after AuthzMiddleware so non-admins get 403 (not 401) when they hit an admin route they can't reach. See spec "Request flow for a gated admin write". SEM@e005ee4f6bf927c842fe7fae5363929a8ad0d794: enforce recent re-authentication for routes that require step-up auth (pure)

func StrictFormBind

func StrictFormBind(c *gin.Context, target any, allowedFields map[string]bool) string

StrictFormBind binds form-urlencoded request body to the target struct. For form data, we validate against a whitelist of allowed fields.

allowedFields is a map of field names that are permitted. Returns an error message if unknown fields are present, or empty string on success. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: bind form data to a struct, rejecting fields not in the allowed list (pure)

func StrictJSONBind

func StrictJSONBind(c *gin.Context, target any) string

StrictJSONBind binds JSON request body to the target struct, rejecting unknown fields. This prevents mass assignment vulnerabilities where attackers send undeclared fields that might be accidentally processed.

Returns an error message suitable for the client if binding fails, or empty string on success. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: parse and bind JSON body to a struct, rejecting unknown fields (pure)

func StrictJSONValidationMiddleware

func StrictJSONValidationMiddleware() gin.HandlerFunc

StrictJSONValidationMiddleware validates JSON syntax strictly, rejecting: - Trailing garbage after valid JSON (e.g., `{"name":"test"}bla`) - Duplicate keys in objects (RFC 8259 recommends unique keys) This ensures all handlers receive well-formed JSON regardless of which binding method they use (ShouldBindJSON vs ParseRequestBody). SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: reject JSON request bodies that contain trailing garbage or duplicate object keys

func SystemAuditRetentionDays

func SystemAuditRetentionDays() int

SystemAuditRetentionDays returns the configured system-audit retention in days (SYSTEM_AUDIT_RETENTION_DAYS, default 365), clamped to a 90-day minimum. Exported because the append-only trigger installation derives its delete age floor from the same value (#400). SEM@f01a64c2e8171748ed345be12c73a8e143fd32e3: fetch the configured system-audit retention period in days, clamped to a 90-day evidence minimum (pure)

func ThreatModelMiddleware

func ThreatModelMiddleware() gin.HandlerFunc

ThreatModelMiddleware creates middleware for threat model authorization SEM@8fa90ed6c2a4a20c3a5b7d508736a882e9c647a0: enforce threat model authorization for unannotated routes, delegating to legacy logic

func TimmyEnabledMiddleware

func TimmyEnabledMiddleware(reader TimmyConfigReader) gin.HandlerFunc

TimmyEnabledMiddleware checks Timmy configuration per request and gates access to Timmy endpoints. When Timmy is disabled, all /chat/sessions and /admin/timmy/ paths return 404. When enabled but not fully configured, those paths return 503. All other paths pass through unaffected. SEM@97d90c492e6b6921c50b9c6e84de6ad5ece1dbb2: gate Timmy endpoints with 404/503 when Timmy is disabled or misconfigured

func TombstoneRetentionDays

func TombstoneRetentionDays() int

TombstoneRetentionDays returns the configured tombstone retention in days (TOMBSTONE_RETENTION_DAYS, default 30). See AuditRetentionDays. SEM@bc84c37baf8f28057d9cb166b3a0e7d0cba90425: fetch the configured tombstone retention period in days from the environment (pure)

func TransferEncodingValidationMiddleware

func TransferEncodingValidationMiddleware() gin.HandlerFunc

TransferEncodingValidationMiddleware rejects requests with Transfer-Encoding header Transfer-Encoding (especially chunked) is not supported by this API Returns 400 Bad Request instead of 501 Not Implemented for better HTTP semantics SEM@16ece52d11c25cd6671ef7ab6e426844f1fdb35a: reject requests that include a Transfer-Encoding header with 400

func TruncateTable

func TruncateTable(dialectName, tableName string) (string, error)

TruncateTable returns a dialect-specific SQL statement to truncate a table. Note: This bypasses GORM's soft delete and foreign key checks. Use with caution, primarily for test cleanup. Returns ErrInvalidTableName if the table name is not in the allowed whitelist. SEM@2bbbcc69cdb6c6b415fb186b43b57e5a2de961d2: build a dialect-specific TRUNCATE statement after validating the table name (pure)

func UUIDValidationMiddleware

func UUIDValidationMiddleware() gin.HandlerFunc

UUIDValidationMiddleware validates UUID path parameters SEM@a0b03d5d6a185b962cc24512bc65629f58b659da: validate UUID-typed path parameters and abort with 400 on malformed values

func UnicodeNormalizationMiddleware

func UnicodeNormalizationMiddleware() gin.HandlerFunc

UnicodeNormalizationMiddleware normalizes Unicode in request bodies and rejects problematic characters SEM@445f237f7a35ca185cf03ef25426c1a97b1a1917: normalize JSON request bodies to NFC and reject dangerous Unicode characters

func UpdateTimestamps

func UpdateTimestamps[T WithTimestamps](entity T, isNew bool) T

UpdateTimestamps updates the timestamps on an entity SEM@a37a0039279be689bb07be2113fe86024a410a4b: set created_at and modified_at to a microsecond-truncated UTC now on an entity (pure)

func UpdateWebhookDeliveryStatus

func UpdateWebhookDeliveryStatus(c *gin.Context)

UpdateWebhookDeliveryStatus updates the status of a webhook delivery (HMAC authenticated). SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: update a webhook delivery status via HMAC-authenticated callback, resetting timeouts on success (mutates shared state)

func UserIDFromContext

func UserIDFromContext(ctx context.Context) (string, bool)

UserIDFromContext reads the user identifier set by JWT middleware or tests. Returns ("", false) when no user ID is present or it is empty. SEM@910d076563691e5e679e89d83c82fdca8d04f2b3: fetch the authenticated user identifier from a context (pure)

func ValidateAddonDescription

func ValidateAddonDescription(description string) error

ValidateAddonDescription validates the add-on description for XSS and length SEM@c3818ab211091946cfe831b51f278e1a29914219: validate an add-on description for length and XSS content (pure)

func ValidateAddonName

func ValidateAddonName(name string) error

ValidateAddonName validates the add-on name for XSS and length SEM@c3818ab211091946cfe831b51f278e1a29914219: validate an add-on name for length and XSS content (pure)

func ValidateAddonParameters

func ValidateAddonParameters(params []AddonParameter) error

ValidateAddonParameters validates parameter definitions at addon creation time SEM@15af4eb93978e65654702a2b47f0ebe20df650dc: validate the full add-on parameter definitions list for duplicates and type constraints (pure)

func ValidateAndParseRequest

func ValidateAndParseRequest[T any](c *gin.Context, config ValidationConfig) (*T, error)

ValidateAndParseRequest provides unified request validation and parsing SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: parse and validate a JSON request body against prohibited fields, required fields, and custom validators (pure)

func ValidateAuthorizationEntries

func ValidateAuthorizationEntries(authList []Authorization) error

ValidateAuthorizationEntries validates individual authorization entries Note: This function is intended for ENRICHED entries where ProviderId has been populated For sparse/pre-enrichment validation, use ValidateSparseAuthorizationEntries SEM@e28c0cfc627a2162c9550e53fb320facb734179e: validate that all enriched authorization entries have a non-empty provider ID (pure)

func ValidateAuthorizationEntriesFromStruct

func ValidateAuthorizationEntriesFromStruct(data any) error

ValidateAuthorizationEntriesFromStruct is the public wrapper for the validator SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: public wrapper that validates authorization entries on an arbitrary struct (pure)

func ValidateAuthorizationEntriesWithFormat

func ValidateAuthorizationEntriesWithFormat(authList []Authorization) error

ValidateAuthorizationEntriesWithFormat validates authorization entries with format checking Note: This function is intended for ENRICHED entries where ProviderId has been populated SEM@e28c0cfc627a2162c9550e53fb320facb734179e: validate enriched authorization entries checking provider ID length and role values (pure)

func ValidateAuthorizationWithPseudoGroups

func ValidateAuthorizationWithPseudoGroups(authList []Authorization) error

ValidateAuthorizationWithPseudoGroups validates authorization entries and applies pseudo-group specific rules SEM@6124bff108947c0b35d793f38a2bff9f438768ce: validate authorization entries applying pseudo-group-specific rules (pure)

func ValidateDiagramType

func ValidateDiagramType(data any) error

ValidateDiagramType validates diagram type field SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate that a struct's Type field equals the only supported diagram type DFD-1.0.0 (pure)

func ValidateDuplicateSubjects

func ValidateDuplicateSubjects(authList []Authorization) error

ValidateDuplicateSubjects checks for duplicate subjects in authorization list. Should be called BEFORE enrichment to catch obvious client mistakes.

This validation is intentionally lenient - it only catches cases where the API caller specified the exact same user with the exact same identifiers multiple times. It does NOT catch cases where the same user is specified with different identifiers (e.g., once by email, once by provider_id) because those are resolved later during enrichment and database save, where ON CONFLICT gracefully handles them.

Duplicate Detection Logic: A user subject A is a duplicate of user subject B if:

Case 1: Both have provider_id values

  • (A.provider == B.provider) AND (A.provider_id == B.provider_id)
  • This identifies the same OAuth/SAML user identity

Case 2: Both lack provider_id values

  • (A.provider == B.provider) AND (A.provider_id is empty) AND (B.provider_id is empty) AND (A.email == B.email)
  • This identifies the same user by email when OAuth sub is not yet known

For group principals, always use (provider, provider_id) as the unique key.

Note: internal_uuid is never present in API requests/responses, so we cannot use it for duplicate detection. The database ON CONFLICT clauses handle internal_uuid resolution gracefully, allowing the same user to be specified multiple ways without error. SEM@1a54e88429506603e24f26cbaaadfc8a810ec63b: validate that no authorization list contains duplicate principal identifiers (pure)

func ValidateEmailFields

func ValidateEmailFields(data any) error

ValidateEmailFields validates email format in struct fields SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate email format in all email-tagged struct fields via reflection (pure)

func ValidateIcon

func ValidateIcon(icon string) error

ValidateIcon validates an icon string against Material Symbols or FontAwesome formats SEM@5c62a84f1cb794382a7efdc627ec1fc36d86af7c: validate an icon string against Material Symbols and FontAwesome formats (pure)

func ValidateInvocationData

func ValidateInvocationData(data map[string]interface{}, params []AddonParameter) error

ValidateInvocationData validates invocation data against declared addon parameters SEM@15af4eb93978e65654702a2b47f0ebe20df650dc: validate add-on invocation data map against declared parameter definitions (pure)

func ValidateJSONStringFields

func ValidateJSONStringFields(c *gin.Context, fields ...string) string

ValidateJSONStringFields checks that the specified fields in a JSON request body are string types (not numbers, booleans, objects, or arrays). This prevents type coercion where Go's json.Unmarshal silently converts e.g. numeric 123 to string "123". The body bytes are read from the gin context and restored for subsequent binding. Returns an error message if any field has the wrong type, or empty string on success. SEM@5b38b9a109d5e10e1a9a58a35a692f19c30a0ed5: validate that named JSON fields are string type, not number or boolean (pure)

func ValidateMarkdownContent

func ValidateMarkdownContent(_ string) error

ValidateMarkdownContent validates a markdown content string. HTML tags are allowed and will be sanitized by bluemonday in the handler layer before storage. Template-like patterns (${, {{, <%, etc.) are permitted in markdown content because these fields store free-text data that may legitimately contain such syntax (e.g., Terraform references, shell variables, code examples). TMI does not evaluate templates in stored content, so SSTI is not a concern here. SEM@bb3f5b6b781f2930614631116234cf58a7ee562f: no-op validator; markdown content is sanitized at the handler layer, not here (pure)

func ValidateMetadataKey

func ValidateMetadataKey(data any) error

ValidateMetadataKey validates metadata key format (no spaces, special chars) SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate metadata key fields contain only alphanumeric, underscore, or hyphen characters (pure)

func ValidateNoDuplicateEntries

func ValidateNoDuplicateEntries(data any) error

ValidateNoDuplicateEntries validates that slice fields don't contain duplicates SEM@24dcbaf59ea6bfe4e66c3f1fbc4863c809cfdc0e: validate that slice fields tagged unique contain no duplicate entries (pure)

func ValidateNoHTMLInjection

func ValidateNoHTMLInjection(data any) error

ValidateNoHTMLInjection prevents HTML/script injection in text fields. Uses the unified CheckHTMLInjection checker for consistent pattern coverage. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: reject struct string fields containing HTML or script injection patterns (pure)

func ValidateNoteMarkdown

func ValidateNoteMarkdown(data any) error

ValidateNoteMarkdown validates Note.Content field for dangerous HTML. This validator is specifically designed for Note objects that contain Markdown content. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate a Note's content field as markdown; delegates to shared markdown validator (pure)

func ValidateNumericRange

func ValidateNumericRange(value any, minVal, maxVal int64, fieldName string) error

ValidateNumericRange validates that a numeric value is within the specified range Handles int, int32, int64, float32, float64 SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate that a numeric value falls within a declared min/max range; reject NaN/infinity (pure)

func ValidateObjects

func ValidateObjects(objects []string) error

ValidateObjects validates that all object types are in the TMI taxonomy SEM@e890b588ef2cb844c92f6ddd0d56e797bb39b7e2: validate that all object type strings belong to the TMI taxonomy (pure)

func ValidatePatchAuthorization

func ValidatePatchAuthorization(operations []PatchOperation, userRole Role) error

ValidatePatchAuthorization validates that the user has permission to perform the patch operations SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: validate that the caller's role permits the requested ownership or authorization changes (pure)

func ValidatePatchedEntity

func ValidatePatchedEntity[T any](original, patched T, userName string, validator func(T, T, string) error) error

ValidatePatchedEntity validates that the patched entity meets business rules SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: run a caller-supplied validator against the patched entity and map failures to 400 errors (pure)

func ValidateQuotaValue

func ValidateQuotaValue(value int, minVal int, maxVal int, fieldName string) error

ValidateQuotaValue validates that a quota value is within acceptable bounds SEM@7cd4e086ca351285b214de56af06e83e3a2a8807: validate a quota integer falls within declared minimum and maximum bounds (pure)

func ValidateReferenceURIPatchOperations

func ValidateReferenceURIPatchOperations(validator *URIValidator, operations []PatchOperation, uriPaths []string) error

ValidateReferenceURIPatchOperations is the reference-mode counterpart of ValidateURIPatchOperations: it validates URI values in JSON Patch operations using ValidateReference (no DNS/IP checks). Use for stored-only fields like issue_uri. SEM@f34985e914fe8d55039296cf4302878c88329818: validate URI values in JSON Patch add/replace operations using reference-mode checks (pure)

func ValidateResourceAccess

func ValidateResourceAccess(requiredRole Role) gin.HandlerFunc

ValidateResourceAccess is a Gin middleware-compatible function for authorization checks SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: build a Gin middleware that enforces a required role on the request's resource

func ValidateRoleFields

func ValidateRoleFields(data any) error

ValidateRoleFields validates role format in struct fields SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate role fields are one of the allowed role values via reflection (pure)

func ValidateScorePrecision

func ValidateScorePrecision(data any) error

ValidateScorePrecision validates that score fields have at most 1 decimal place This matches the OpenAPI spec constraint: multipleOf: 0.1 SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate that the score field has at most one decimal place (pure)

func ValidateSecurityReviewerProtection

func ValidateSecurityReviewerProtection(proposedAuthList []Authorization, securityReviewer *User) error

ValidateSecurityReviewerProtection checks that the security reviewer still has owner role in the proposed authorization list. Returns an error if the security reviewer's owner access would be removed or downgraded. SEM@b11d5634ea0de9c46ce45bd4660b0bb604404f15: validate that a proposed authorization list preserves the security reviewer's owner role (pure)

func ValidateSparseAuthorizationEntries

func ValidateSparseAuthorizationEntries(authList []Authorization) error

ValidateSparseAuthorizationEntries validates authorization entries BEFORE enrichment Requires: provider + (provider_id OR email) Does NOT require: display_name (response-only field) Note: Call StripResponseOnlyAuthFields() before this function if the authorization data came from a client that may have included response-only fields SEM@6b85a6fabc237d03c99bf64a10eb26dfeaf09d3b: validate pre-enrichment authorization entries requiring provider and at least one identifier (pure)

func ValidateStringLengths

func ValidateStringLengths(data any) error

ValidateStringLengths validates string field lengths based on struct tags SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate struct string fields against maxlength struct tags via reflection (pure)

func ValidateSubResourceAccess

func ValidateSubResourceAccess(db *sql.DB, cache *CacheService, requiredRole Role) gin.HandlerFunc

ValidateSubResourceAccess creates middleware for sub-resource authorization with caching This middleware validates access to sub-resources (threats, documents, sources) by inheriting permissions from their parent threat model SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: enforce inherited threat-model authorization for sub-resource routes at a given role level

func ValidateSubResourceAccessOwner

func ValidateSubResourceAccessOwner(db *sql.DB, cache *CacheService) gin.HandlerFunc

ValidateSubResourceAccessOwner creates middleware for owner-only sub-resource access SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build sub-resource authorization middleware requiring owner role

func ValidateSubResourceAccessReader

func ValidateSubResourceAccessReader(db *sql.DB, cache *CacheService) gin.HandlerFunc

ValidateSubResourceAccessReader creates middleware for read-only sub-resource access SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build sub-resource authorization middleware requiring reader role

func ValidateSubResourceAccessWriter

func ValidateSubResourceAccessWriter(db *sql.DB, cache *CacheService) gin.HandlerFunc

ValidateSubResourceAccessWriter creates middleware for write sub-resource access SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build sub-resource authorization middleware requiring writer role

func ValidateTableName

func ValidateTableName(tableName string) error

ValidateTableName checks if a table name is in the allowed whitelist. Returns ErrInvalidTableName if the table name is not whitelisted. SEM@2bbbcc69cdb6c6b415fb186b43b57e5a2de961d2: validate a table name against the allowed whitelist; reject unknown names (pure)

func ValidateThreatSeverity

func ValidateThreatSeverity(data any) error

ValidateThreatSeverity is a no-op validator that accepts any severity value Severity is now a free-form string field per the OpenAPI schema SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: no-op validator; severity is a free-form string requiring no constraint (pure)

func ValidateTriageNoteMarkdown

func ValidateTriageNoteMarkdown(data any) error

ValidateTriageNoteMarkdown validates TriageNote.Content field for dangerous HTML. This validator uses the same shared markdown validation as Note objects. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate a TriageNote's content field as markdown; delegates to shared markdown validator (pure)

func ValidateURIPatchOperations

func ValidateURIPatchOperations(validator *URIValidator, operations []PatchOperation, uriPaths []string) error

ValidateURIPatchOperations validates URI values in JSON Patch operations. Only "replace" and "add" operations for the specified paths are validated. Returns nil if validator is nil. SEM@f34985e914fe8d55039296cf4302878c88329818: validate URI values in JSON Patch add/replace operations against full URI rules (pure)

func ValidateURLFields

func ValidateURLFields(data any) error

ValidateURLFields validates URL format in struct fields SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate HTTP/HTTPS URL format in all url-tagged struct fields via reflection (pure)

func ValidateUUID

func ValidateUUID(s string, fieldName string) (uuid.UUID, error)

ValidateUUID validates that a string is a valid UUID format SEM@e7454256ce7abf612c8dc53c5b39f9f7ad67a011: validate a string as a UUID and return the parsed value; reject empty or malformed input (pure)

func ValidateUUIDFieldsFromStruct

func ValidateUUIDFieldsFromStruct(data any) error

Enhanced UUID validation with better error messages SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate UUID string and pointer fields in a struct are non-nil and well-formed (pure)

func ValidateUnicodeContent

func ValidateUnicodeContent(value, fieldName string) error

ValidateUnicodeContent checks for problematic Unicode that might slip through middleware. Delegates to the consolidated unicodecheck package for consistent character detection. Uses context-aware zero-width checking and threshold-based combining mark detection to support international text while blocking attacks. SEM@445f237f7a35ca185cf03ef25426c1a97b1a1917: validate a field value for dangerous Unicode: zero-width chars, bidi overrides, and Zalgo marks (pure)

func ValidateUserIdentity

func ValidateUserIdentity(u User) error

ValidateUserIdentity validates that a User struct contains at least one valid identifier SEM@e236ac749d0a1d6016793e5992c930397b838d76: validate that a User has at least one identifier and a plausible email format (pure)

func VerifySignature

func VerifySignature(payload []byte, signature string, secret string) bool

VerifySignature verifies the HMAC signature of a request. Delegates to the consolidated crypto package. SEM@ca61a567c4babc9270ee913396aaa4fb530505a3: validate HMAC signature of a webhook payload against a shared secret (pure)

func VersionRetentionDays

func VersionRetentionDays() int

VersionRetentionDays returns the configured version-snapshot retention in days (VERSION_RETENTION_DAYS, default 90). See AuditRetentionDays. SEM@bc84c37baf8f28057d9cb166b3a0e7d0cba90425: fetch the configured version-snapshot retention period in days from the environment (pure)

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID returns a new context carrying the given user ID. Used by middleware and tests to attach a user id to request contexts. SEM@910d076563691e5e679e89d83c82fdca8d04f2b3: build a context carrying a user identifier (pure)

Types

type APIRateLimiter

type APIRateLimiter struct {
	SlidingWindowRateLimiter
	// contains filtered or unexported fields
}

APIRateLimiter implements rate limiting for general API operations using Redis SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: sliding-window API rate limiter backed by Redis and a per-user quota store

func NewAPIRateLimiter

func NewAPIRateLimiter(redisClient *redis.Client, quotaStore UserAPIQuotaStoreInterface) *APIRateLimiter

NewAPIRateLimiter creates a new API rate limiter SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: build an API rate limiter from a Redis client and quota store (pure)

func (*APIRateLimiter) CheckRateLimit

func (r *APIRateLimiter) CheckRateLimit(ctx context.Context, userID string) (bool, int, error)

CheckRateLimit checks if a user has exceeded their rate limit Returns allowed (bool), retryAfter (seconds), and error SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: validate a user's per-minute and per-hour request quotas against Redis sliding windows (reads DB)

func (*APIRateLimiter) GetRateLimitInfo

func (r *APIRateLimiter) GetRateLimitInfo(ctx context.Context, userID string) (limit int, remaining int, resetAt int64, err error)

GetRateLimitInfo returns current rate limit status for a user SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: fetch the current rate limit, remaining requests, and reset time for a user (reads DB)

type APIReranker

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

APIReranker calls an HTTP reranker endpoint compatible with Cohere/Jina/vLLM. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: HTTP reranker client compatible with Cohere/Jina/vLLM rerank endpoints (pure)

func NewAPIReranker

func NewAPIReranker(baseURL, model, apiKey string, topK int, validator *URIValidator, timeout time.Duration) *APIReranker

NewAPIReranker creates an APIReranker. validator MUST be non-nil and is used to validate the reranker endpoint URL against scheme/SSRF allowlist rules before each call. timeout sets the per-request overall timeout (0 → 120s). SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build an APIReranker with SSRF-safe HTTP client and configurable timeout (pure)

func (*APIReranker) Rerank

func (r *APIReranker) Rerank(ctx context.Context, query string, documents []string) ([]RerankResult, error)

Rerank sends documents to the reranker API and returns them ordered by relevance. Returns nil, nil when documents is empty. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: fetch document relevance scores from the reranker API and return results sorted by score descending

type AccessDiagnosticsDiag

type AccessDiagnosticsDiag struct {
	ReasonCode   string                  `json:"reason_code"`
	ReasonDetail *string                 `json:"reason_detail,omitempty"`
	Remediations []AccessRemediationDiag `json:"remediations"`
}

AccessDiagnosticsDiag is the builder's internal representation of access_diagnostics. See AccessRemediationDiag. SEM@b04bada4485747c502b780806fa3deba2fd822fa: internal representation of access diagnostics containing reason code and remediation list (pure)

func BuildAccessDiagnostics

func BuildAccessDiagnostics(ctx BuilderContext) *AccessDiagnosticsDiag

BuildAccessDiagnostics returns a diagnostic object given the builder context, or nil when there is no diagnostic to report (empty ReasonCode). SEM@da7b9edd86863da63512f8216a886a429b2b6f9e: build an access diagnostics object with reason-specific remediations from the builder context (pure)

type AccessPoller

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

AccessPoller periodically checks documents with "pending_access" status. SEM@d994c2f113f9e0997f83a0815018638cc94111f7: background service that periodically checks pending-access documents and transitions them to accessible (mutates shared state)

func NewAccessPoller

func NewAccessPoller(
	sources *ContentSourceRegistry,
	documentStore DocumentRepository,
	interval time.Duration,
	maxAge time.Duration,
) *AccessPoller

NewAccessPoller creates a new background access poller. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build an AccessPoller with a polling interval and max document age (pure)

func (*AccessPoller) SetAsyncExtraction

func (p *AccessPoller) SetAsyncExtraction(publisher *ExtractionPublisher, decider func(context.Context) bool)

SetAsyncExtraction injects the async extraction publisher and decider into the poller. When the decider returns true AND publisher is non-nil, pollOnce routes extraction through the worker pipeline (fetch bytes + publish job) instead of running inline extraction. The document is left in pending_access; the result-consumer transitions it to accessible when the worker completes.

Pass nil publisher or a nil decider to keep the inline path. Lifecycle: must be called BEFORE Start. SEM@d994c2f113f9e0997f83a0815018638cc94111f7: inject an async extraction publisher and decider to route polling through the worker pipeline (mutates shared state)

func (*AccessPoller) SetContentPipeline

func (p *AccessPoller) SetContentPipeline(pipeline *ContentPipeline)

SetContentPipeline injects a content pipeline so the poller can attempt extraction once a document transitions to accessible. When extraction fails, the poller classifies the failure and persists the access_status + reason_code via UpdateAccessStatusWithDiagnostics. Optional — when omitted, the poller updates to AccessStatusAccessible without attempting extraction (legacy behavior).

Lifecycle: same as SetLinkedProviderChecker; must be called BEFORE Start. SEM@a3a8b3e82371d176bbcdfb7444b4ac361b0f8ace: inject a content pipeline to attempt extraction on document access transition (mutates shared state)

func (*AccessPoller) SetLinkedProviderChecker

func (p *AccessPoller) SetLinkedProviderChecker(c LinkedProviderChecker)

SetLinkedProviderChecker injects a LinkedProviderChecker so the poller can dispatch picker-attached documents to their delegated source via FindSourceForDocument. Optional — when omitted, the poller behaves as before (URL-based dispatch only).

Lifecycle: must be called BEFORE Start. Calling SetLinkedProviderChecker after Start races with the poll goroutine reading the field; in production wiring (cmd/server/main.go) the checker is configured during init alongside the rest of the poller setup. SEM@d330121ff53e262b1d2c0ff6713294e41f615330: inject a linked provider checker for picker-aware document dispatch (mutates shared state)

func (*AccessPoller) Start

func (p *AccessPoller) Start()

Start begins the background polling loop. SEM@7f13559c1b4f9930b12898ca3e23b47987cae72c: launch the background polling goroutine (mutates shared state)

func (*AccessPoller) Stop

func (p *AccessPoller) Stop()

Stop signals the poller to stop. Safe to call more than once; subsequent calls are no-ops. The goroutine exits asynchronously; callers that need synchronous teardown should wait on a done channel (not exposed here because the common pattern is fire-and-forget from the holder). SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: signal the polling goroutine to stop; idempotent (mutates shared state)

type AccessRemediation

type AccessRemediation struct {
	Action AccessRemediationAction `json:"action"`

	// Params Action-specific parameters. Examples: `service_account_email`, `provider_id`, `user_email` (for `share_with_service_account`); `drive_id`, `item_id`, `app_object_id`, `graph_call`, `graph_body` (for `share_with_application`).
	Params map[string]interface{} `json:"params"`
}

AccessRemediation A suggested client- or user-facing action to resolve a document access problem. Ordered list: the first remediation in `DocumentAccessDiagnostics.remediations` is the recommended next step.

type AccessRemediationAction

type AccessRemediationAction string

AccessRemediationAction defines model for AccessRemediation.Action.

const (
	ContactOwner            AccessRemediationAction = "contact_owner"
	LinkAccount             AccessRemediationAction = "link_account"
	RelinkAccount           AccessRemediationAction = "relink_account"
	RepickAfterShare        AccessRemediationAction = "repick_after_share"
	RepickFile              AccessRemediationAction = "repick_file"
	Retry                   AccessRemediationAction = "retry"
	ShareWithApplication    AccessRemediationAction = "share_with_application"
	ShareWithServiceAccount AccessRemediationAction = "share_with_service_account"
)

Defines values for AccessRemediationAction.

func (AccessRemediationAction) Valid

func (e AccessRemediationAction) Valid() bool

Valid indicates whether the value is a known member of the AccessRemediationAction enum.

type AccessRemediationDiag

type AccessRemediationDiag struct {
	Action string                 `json:"action"`
	Params map[string]interface{} `json:"params"`
}

AccessRemediationDiag is the builder's internal representation of a single remediation. The API-wire type is regenerated from OpenAPI in Phase 8; this internal type is converted at the handler boundary. SEM@b04bada4485747c502b780806fa3deba2fd822fa: internal representation of a single access remediation action with typed parameters (pure)

type AccessRequester

type AccessRequester interface {
	RequestAccess(ctx context.Context, uri string) error
}

AccessRequester programmatically requests access to a URI (e.g., share request email). SEM@789146ae6555f1667678ed835a68faac5b22ad30: interface for programmatically requesting access to a URI

type AccessTracker

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

AccessTracker records threat model access times with in-memory debouncing. It uses a sync.Map to avoid writing to the database more than once per debounce window per threat model. SEM@b9bf86932f146b39c22ae499fe2f193dfba4659b: debounced tracker that updates threat model last-accessed timestamps in the DB (mutates shared state)

var GlobalAccessTracker *AccessTracker

GlobalAccessTracker is initialized at server startup and used by ThreatModelMiddleware.

func NewAccessTracker

func NewAccessTracker(db *gorm.DB) *AccessTracker

NewAccessTracker creates an AccessTracker with the default 1-minute debounce. SEM@b9bf86932f146b39c22ae499fe2f193dfba4659b: build an AccessTracker with the default one-minute debounce window (pure)

func NewAccessTrackerWithDebounce

func NewAccessTrackerWithDebounce(db *gorm.DB, debounce time.Duration) *AccessTracker

NewAccessTrackerWithDebounce creates an AccessTracker with a custom debounce duration (for testing). SEM@b9bf86932f146b39c22ae499fe2f193dfba4659b: build an AccessTracker with a custom debounce duration (pure)

func (*AccessTracker) RecordAccess

func (at *AccessTracker) RecordAccess(threatModelID string)

RecordAccess updates last_accessed_at for a threat model, debouncing writes. The DB update runs in a fire-and-forget goroutine to avoid adding latency. SEM@f8417a5cf7ccccd973f67a4a09364e8065dddf5f: update last_accessed_at for a threat model, skipping writes within the debounce window (reads DB)

func (*AccessTracker) Reset

func (at *AccessTracker) Reset()

Reset clears the debounce map. Used in tests. SEM@b9bf86932f146b39c22ae499fe2f193dfba4659b: clear the debounce map for testing (mutates shared state)

type AccessValidator

type AccessValidator interface {
	ValidateAccess(ctx context.Context, uri string) (accessible bool, err error)
}

AccessValidator checks whether a source can access a URI without downloading it. SEM@789146ae6555f1667678ed835a68faac5b22ad30: interface for probing URI accessibility without downloading content

type AddGroupMemberJSONRequestBody

type AddGroupMemberJSONRequestBody = AddGroupMemberRequest

AddGroupMemberJSONRequestBody defines body for AddGroupMember for application/json ContentType.

type AddGroupMemberRequest

type AddGroupMemberRequest struct {
	// MemberGroupInternalUuid Internal UUID of the group to add as a member (required when subject_type is group)
	MemberGroupInternalUuid *openapi_types.UUID `json:"member_group_internal_uuid,omitempty"`

	// Notes Optional notes about this membership
	Notes *string `json:"notes,omitempty"`

	// SubjectType Type of member to add: user or group
	SubjectType *AddGroupMemberRequestSubjectType `json:"subject_type,omitempty"`

	// UserInternalUuid Internal UUID of the user to add to the group
	UserInternalUuid *openapi_types.UUID `json:"user_internal_uuid,omitempty"`
}

AddGroupMemberRequest Request to add a user or group to a group. Provide user_internal_uuid for user members or member_group_internal_uuid for group members.

type AddGroupMemberRequestSubjectType

type AddGroupMemberRequestSubjectType string

AddGroupMemberRequestSubjectType Type of member to add: user or group

const (
	AddGroupMemberRequestSubjectTypeGroup AddGroupMemberRequestSubjectType = "group"
	AddGroupMemberRequestSubjectTypeUser  AddGroupMemberRequestSubjectType = "user"
)

Defines values for AddGroupMemberRequestSubjectType.

func (AddGroupMemberRequestSubjectType) Valid

Valid indicates whether the value is a known member of the AddGroupMemberRequestSubjectType enum.

type Addon

type Addon struct {
	ID            uuid.UUID        `json:"id"`
	CreatedAt     time.Time        `json:"created_at"`
	Name          string           `json:"name"`
	WebhookID     uuid.UUID        `json:"webhook_id"`
	Description   string           `json:"description,omitempty"`
	Icon          string           `json:"icon,omitempty"`
	Objects       []string         `json:"objects,omitempty"`
	ThreatModelID *uuid.UUID       `json:"threat_model_id,omitempty"`
	Parameters    []AddonParameter `json:"parameters,omitempty"`
}

Addon represents an add-on in the system SEM@15af4eb93978e65654702a2b47f0ebe20df650dc: domain model for an add-on linking a webhook to optional threat model parameters (pure)

type AddonInvocationQuota

type AddonInvocationQuota struct {
	// CreatedAt Creation timestamp
	CreatedAt time.Time `json:"created_at"`

	// MaxActiveInvocations Maximum concurrent active addon invocations
	MaxActiveInvocations int `json:"max_active_invocations"`

	// MaxInvocationsPerHour Maximum addon invocations per hour
	MaxInvocationsPerHour int `json:"max_invocations_per_hour"`

	// ModifiedAt Last modification timestamp
	ModifiedAt time.Time `json:"modified_at"`

	// OwnerId User ID
	OwnerId openapi_types.UUID `json:"owner_id"`
}

AddonInvocationQuota Addon invocation quota for a user

type AddonInvocationQuotaDatabaseStore

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

AddonInvocationQuotaDatabaseStore implements AddonInvocationQuotaStore using PostgreSQL SEM@afdb1506d3879a33daeab641ffec090578a2814b: database-backed implementation of AddonInvocationQuotaStore (pure)

func NewAddonInvocationQuotaDatabaseStore

func NewAddonInvocationQuotaDatabaseStore(db *sql.DB) *AddonInvocationQuotaDatabaseStore

NewAddonInvocationQuotaDatabaseStore creates a new database-backed quota store SEM@afdb1506d3879a33daeab641ffec090578a2814b: build a database-backed addon invocation quota store (pure)

func (*AddonInvocationQuotaDatabaseStore) Count

Count returns the total number of addon invocation quotas SEM@df41a3866f5824f0f8fb588edb04475095615bcf: return the total number of custom addon invocation quota records (reads DB)

func (*AddonInvocationQuotaDatabaseStore) Delete

Delete removes quota for a user (reverts to defaults) SEM@c1e5f4b740482faedb4383dcf3a2224c8525dd35: delete a user's custom addon invocation quota, reverting them to system defaults (mutates shared state)

func (*AddonInvocationQuotaDatabaseStore) Get

Get retrieves quota for a user, returns error if not found SEM@afdb1506d3879a33daeab641ffec090578a2814b: fetch the addon invocation quota for a specific user; error if not found (reads DB)

func (*AddonInvocationQuotaDatabaseStore) GetOrDefault

GetOrDefault retrieves quota for a user, or returns defaults if not set SEM@9214f003590204e62d98bd62c10b96602d3ef503: fetch the addon invocation quota for a user, returning system defaults when none is set (reads DB)

func (*AddonInvocationQuotaDatabaseStore) List

List retrieves all addon invocation quotas with pagination SEM@c1e5f4b740482faedb4383dcf3a2224c8525dd35: list all custom addon invocation quotas with pagination (reads DB)

func (*AddonInvocationQuotaDatabaseStore) Set

Set creates or updates quota for a user SEM@9214f003590204e62d98bd62c10b96602d3ef503: upsert an addon invocation quota for a user (mutates shared state)

type AddonInvocationQuotaStore

type AddonInvocationQuotaStore interface {
	// Get retrieves quota for a user, returns error if not found
	Get(ctx context.Context, ownerID uuid.UUID) (*AddonInvocationQuota, error)

	// GetOrDefault retrieves quota for a user, or returns defaults if not set
	GetOrDefault(ctx context.Context, ownerID uuid.UUID) (*AddonInvocationQuota, error)

	// List retrieves all custom quotas (non-default) with pagination
	List(ctx context.Context, offset, limit int) ([]*AddonInvocationQuota, error)

	// Count returns the total number of custom quotas
	Count(ctx context.Context) (int, error)

	// Set creates or updates quota for a user
	Set(ctx context.Context, quota *AddonInvocationQuota) error

	// Delete removes quota for a user (reverts to defaults)
	Delete(ctx context.Context, ownerID uuid.UUID) error
}

AddonInvocationQuotaStore defines the interface for quota storage operations SEM@503212a05958ba0c15d423fab4dbceb92b747ed9: interface for CRUD operations on per-user addon invocation quota records (pure)

var GlobalAddonInvocationQuotaStore AddonInvocationQuotaStore

GlobalAddonInvocationQuotaStore is the global singleton for quota storage

type AddonParameter

type AddonParameter struct {
	// DefaultValue Default value if not provided by user
	DefaultValue *string `json:"default_value,omitempty"`

	// Description Human-readable description for UI display
	Description *string `json:"description,omitempty"`

	// EnumValues Allowed values (applicable when type is 'enum')
	EnumValues *[]string `json:"enum_values,omitempty"`

	// MetadataKey Metadata key name to auto-populate from TMI object (applicable when type is 'metadata_key')
	MetadataKey *string `json:"metadata_key,omitempty"`

	// Name Parameter name (used as key in invocation data payload)
	Name string `json:"name"`

	// NumberMax Maximum allowed value (applicable when type is 'number')
	NumberMax *float32 `json:"number_max,omitempty"`

	// NumberMin Minimum allowed value (applicable when type is 'number')
	NumberMin *float32 `json:"number_min,omitempty"`

	// Required Whether the parameter must be provided on invocation
	Required *bool `json:"required,omitempty"`

	// StringMaxLength Maximum string length (applicable when type is 'string')
	StringMaxLength *int `json:"string_max_length,omitempty"`

	// StringValidationRegex Regular expression for string validation (applicable when type is 'string')
	StringValidationRegex *string `json:"string_validation_regex,omitempty"`

	// Type Parameter type determining client UI control
	Type AddonParameterType `json:"type"`
}

AddonParameter Typed parameter declaration for an add-on, used to drive client UI generation

type AddonParameterType

type AddonParameterType string

AddonParameterType Parameter type determining client UI control

const (
	AddonParameterTypeBoolean     AddonParameterType = "boolean"
	AddonParameterTypeEnum        AddonParameterType = "enum"
	AddonParameterTypeMetadataKey AddonParameterType = "metadata_key"
	AddonParameterTypeNumber      AddonParameterType = "number"
	AddonParameterTypeString      AddonParameterType = "string"
)

Defines values for AddonParameterType.

func (AddonParameterType) Valid

func (e AddonParameterType) Valid() bool

Valid indicates whether the value is a known member of the AddonParameterType enum.

type AddonQuotaUpdate

type AddonQuotaUpdate struct {
	// MaxActiveInvocations Maximum concurrent active addon invocations
	MaxActiveInvocations int `json:"max_active_invocations"`

	// MaxInvocationsPerHour Maximum addon invocations per hour
	MaxInvocationsPerHour int `json:"max_invocations_per_hour"`
}

AddonQuotaUpdate Configuration update for addon invocation quotas

type AddonRateLimiter

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

AddonRateLimiter provides rate limiting for add-on invocations SEM@afdb1506d3879a33daeab641ffec090578a2814b: enforce per-user concurrent and hourly invocation quotas for add-on calls via Redis

var GlobalAddonRateLimiter *AddonRateLimiter

GlobalAddonRateLimiter is the global singleton for rate limiting

func NewAddonRateLimiter

func NewAddonRateLimiter(redis *db.RedisDB, quotaStore AddonInvocationQuotaStore) *AddonRateLimiter

NewAddonRateLimiter creates a new rate limiter SEM@afdb1506d3879a33daeab641ffec090578a2814b: build an AddonRateLimiter wired to a Redis client and quota store (pure)

func (*AddonRateLimiter) CheckActiveInvocationLimit

func (rl *AddonRateLimiter) CheckActiveInvocationLimit(ctx context.Context, userID uuid.UUID) error

CheckActiveInvocationLimit checks if user has reached their concurrent invocation limit SEM@ca61a567c4babc9270ee913396aaa4fb530505a3: validate that a user has not exceeded their concurrent add-on invocation quota (reads Redis)

func (*AddonRateLimiter) CheckHourlyRateLimit

func (rl *AddonRateLimiter) CheckHourlyRateLimit(ctx context.Context, userID uuid.UUID) error

CheckHourlyRateLimit checks if user has exceeded hourly invocation limit using sliding window SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: validate that a user has not exceeded their hourly add-on invocation quota using a sliding window (reads Redis)

func (*AddonRateLimiter) RecordInvocation

func (rl *AddonRateLimiter) RecordInvocation(ctx context.Context, userID uuid.UUID) error

RecordInvocation records a new invocation in the sliding window SEM@914adca66ed5ce0bcfa6a1233361a298648ccf00: record an add-on invocation in the user's hourly sliding-window rate-limit key (mutates shared state)

type AddonResponse

type AddonResponse struct {
	// CreatedAt Creation timestamp
	CreatedAt time.Time `json:"created_at"`

	// Description Add-on description
	Description *string `json:"description,omitempty"`

	// Icon Icon identifier
	Icon *string `json:"icon,omitempty"`

	// Id Add-on identifier
	Id openapi_types.UUID `json:"id"`

	// Name Display name
	Name string `json:"name"`

	// Objects Supported TMI object types
	Objects *[]string `json:"objects,omitempty"`

	// Parameters Typed parameter declarations for client UI generation. Each parameter defines a name, type, and type-specific configuration that clients use to render appropriate input controls.
	Parameters *[]AddonParameter `json:"parameters,omitempty"`

	// ThreatModelId Threat model scope (if scoped)
	ThreatModelId *openapi_types.UUID `json:"threat_model_id,omitempty"`

	// WebhookId Associated webhook subscription ID
	WebhookId openapi_types.UUID `json:"webhook_id"`
}

AddonResponse Addon details including configuration and status

type AddonStore

type AddonStore interface {
	// Create creates a new add-on
	Create(ctx context.Context, addon *Addon) error

	// Get retrieves an add-on by ID
	Get(ctx context.Context, id uuid.UUID) (*Addon, error)

	// List retrieves add-ons with pagination, optionally filtered by threat model
	List(ctx context.Context, limit, offset int, threatModelID *uuid.UUID) ([]Addon, int, error)

	// Delete removes an add-on by ID
	Delete(ctx context.Context, id uuid.UUID) error

	// GetByWebhookID retrieves all add-ons associated with a webhook
	GetByWebhookID(ctx context.Context, webhookID uuid.UUID) ([]Addon, error)

	// CountActiveInvocations counts pending/in_progress invocations for an add-on
	// This will be used to block deletion when active invocations exist
	// Returns count of active invocations
	CountActiveInvocations(ctx context.Context, addonID uuid.UUID) (int, error)

	// DeleteByWebhookID deletes all add-ons associated with a webhook
	// Returns the count of deleted add-ons
	DeleteByWebhookID(ctx context.Context, webhookID uuid.UUID) (int, error)
}

AddonStore defines the interface for add-on storage operations SEM@0752a420273337759ce2f45c2aeb1671409c30b0: storage interface for add-on CRUD, listing, and invocation count operations

var GlobalAddonStore AddonStore

GlobalAddonStore is the global singleton for add-on storage

type AdminContext

type AdminContext struct {
	Email        string
	InternalUUID *uuid.UUID
	Provider     string
	GroupNames   []string
	GroupUUIDs   []uuid.UUID
}

AdminContext contains the authenticated administrator's information SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: carrier for the authenticated administrator's identity and group membership (pure)

func RequireAdministrator

func RequireAdministrator(c *gin.Context) (*AdminContext, error)

RequireAdministrator checks if the current user is an administrator. Service account tokens (client credentials grant) are always rejected — administrative operations require interactive (PKCE) authentication. Returns an AdminContext if authorized, or nil with error response sent. SEM@1c9f87f1ca746f8b265481c0a196627b2737787a: authorize the current user as an administrator and return their admin context (reads DB)

type AdminGroup

type AdminGroup struct {
	// Description Group description
	Description *string `json:"description,omitempty"`

	// FirstUsed First time this group was referenced
	FirstUsed time.Time `json:"first_used"`

	// GroupName Provider-assigned group name
	GroupName string `json:"group_name"`

	// InternalUuid Internal system UUID for the group
	InternalUuid openapi_types.UUID `json:"internal_uuid"`

	// LastUsed Last time this group was referenced
	LastUsed time.Time `json:"last_used"`

	// MemberCount Number of members in the group from IdP (enriched, if available)
	MemberCount *int `json:"member_count,omitempty"`

	// Name Human-readable group name
	Name *string `json:"name,omitempty"`

	// Provider OAuth/SAML provider identifier, or "tmi" for TMI built-in groups
	Provider string `json:"provider"`

	// UsageCount Number of times this group has been referenced
	UsageCount int `json:"usage_count"`

	// UsedInAdminGrants Whether this group is used in any admin grants (enriched)
	UsedInAdminGrants *bool `json:"used_in_admin_grants,omitempty"`

	// UsedInAuthorizations Whether this group is used in any authorizations (enriched)
	UsedInAuthorizations *bool `json:"used_in_authorizations,omitempty"`
}

AdminGroup Group object with administrative fields and enriched data

type AdminGroupListResponse

type AdminGroupListResponse struct {
	// Groups List of groups
	Groups []AdminGroup `json:"groups"`

	// Limit Maximum number of results returned
	Limit int `json:"limit"`

	// Offset Number of results skipped
	Offset int `json:"offset"`

	// Total Total number of groups matching the filter
	Total int `json:"total"`
}

AdminGroupListResponse Paginated list of groups for administrative management

type AdminUser

type AdminUser struct {
	// ActiveThreatModels Number of active threat models owned by user (enriched)
	ActiveThreatModels *int `json:"active_threat_models,omitempty"`

	// Automation Whether this is an automation/service account. Server-managed: set to true only when an automation account is created via the admin API. Nullable; null and false are equivalent.
	Automation *bool `json:"automation,omitempty"`

	// CreatedAt Account creation timestamp
	CreatedAt time.Time `json:"created_at"`

	// Email User email address
	Email openapi_types.Email `json:"email"`

	// EmailVerified Whether the email has been verified
	EmailVerified bool `json:"email_verified"`

	// Groups List of group names the user belongs to (enriched)
	Groups *[]string `json:"groups,omitempty"`

	// InternalUuid Internal system UUID for the user
	InternalUuid openapi_types.UUID `json:"internal_uuid"`

	// IsAdmin Whether the user has administrator privileges (enriched)
	IsAdmin *bool `json:"is_admin,omitempty"`

	// LastLogin Last login timestamp
	LastLogin *time.Time `json:"last_login,omitempty"`

	// ModifiedAt Last modification timestamp
	ModifiedAt time.Time `json:"modified_at"`

	// Name User display name
	Name string `json:"name"`

	// Provider OAuth/SAML provider identifier
	Provider string `json:"provider"`

	// ProviderUserId Provider-assigned user identifier
	ProviderUserId string `json:"provider_user_id"`
}

AdminUser User object with administrative fields and enriched data

type AdminUserListResponse

type AdminUserListResponse struct {
	// Limit Maximum number of results returned
	Limit int `json:"limit"`

	// Offset Number of results skipped
	Offset int `json:"offset"`

	// Total Total number of users matching the filter
	Total int `json:"total"`

	// Users List of users
	Users []AdminUser `json:"users"`
}

AdminUserListResponse Paginated list of users for administrative management

type AlertingBootstrap

type AlertingBootstrap struct {
	Enabled bool
	URL     string
	Secret  string
}

AlertingBootstrap holds the alerting configuration values needed to upsert the operator-pinned audit alert sink webhook subscription (#395). SEM@13c4215bf8e204da342579717f97f7393bb5fe2f: configuration for the operator-pinned audit alert sink webhook subscription

type ApiInfo

type ApiInfo struct {
	Api struct {
		// Specification URL to the API specification
		Specification string `json:"specification"`

		// Version API version
		Version string `json:"version"`
	} `json:"api"`

	// Health Detailed health status of system components. Only present when status is DEGRADED.
	Health *struct {
		// Database Health status of a system component
		Database *ComponentHealth `json:"database,omitempty"`

		// Redis Health status of a system component
		Redis *ComponentHealth `json:"redis,omitempty"`
	} `json:"health,omitempty"`
	Operator *struct {
		// Contact Operator contact information from environment variables
		Contact string `json:"contact"`

		// Name Operator name from environment variables
		Name string `json:"name"`
	} `json:"operator,omitempty"`
	Service struct {
		// Build Current build number
		Build string `json:"build"`

		// Name Name of the service
		Name string `json:"name"`
	} `json:"service"`
	Status struct {
		// Code Status code indicating system health: OK (all components healthy), DEGRADED (server up but database or Redis unhealthy), ERROR (critical failure)
		Code ApiInfoStatusCode `json:"code"`

		// Time Current server time in UTC, formatted as RFC 3339
		Time time.Time `json:"time"`
	} `json:"status"`
}

ApiInfo API information response for the root endpoint

type ApiInfoHandler

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

ApiInfoHandler handles requests to the root endpoint SEM@7193f12546f4e4755ee3b2271543ba2fc6b329f0: HTTP handler type for serving API root endpoint responses

func NewApiInfoHandler

func NewApiInfoHandler(server *Server) *ApiInfoHandler

NewApiInfoHandler creates a new handler for API info SEM@7193f12546f4e4755ee3b2271543ba2fc6b329f0: build an ApiInfoHandler bound to the given server instance (pure)

func (*ApiInfoHandler) GetApiInfo

func (h *ApiInfoHandler) GetApiInfo(c *gin.Context)

GetApiInfo returns service, API, and operator information SEM@82a3444e3d58a2e4d97fabaf3b6cbf06d6e7c800: handle root endpoint: return service info, version, health status, and operator details as JSON or HTML

type ApiInfoStatusCode

type ApiInfoStatusCode string

ApiInfoStatusCode Status code indicating system health: OK (all components healthy), DEGRADED (server up but database or Redis unhealthy), ERROR (critical failure)

const (
	ApiInfoStatusCodeDegraded ApiInfoStatusCode = "degraded"
	ApiInfoStatusCodeError    ApiInfoStatusCode = "error"
	ApiInfoStatusCodeOk       ApiInfoStatusCode = "ok"
)

Defines values for ApiInfoStatusCode.

func (ApiInfoStatusCode) Valid

func (e ApiInfoStatusCode) Valid() bool

Valid indicates whether the value is a known member of the ApiInfoStatusCode enum.

type Asset

type Asset struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// Classification Classification tags for the asset
	Classification *[]string `json:"classification,omitempty"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Criticality Criticality level of the asset
	Criticality *string `json:"criticality,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of the asset
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the asset
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Asset name
	Name string `binding:"required" json:"name"`

	// Sensitivity Sensitivity label for the asset
	Sensitivity *string `json:"sensitivity,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Type of asset
	Type AssetType `binding:"required" json:"type"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

Asset defines model for Asset.

type AssetBase

type AssetBase struct {
	// Classification Classification tags for the asset
	Classification *[]string `json:"classification,omitempty"`

	// Criticality Criticality level of the asset
	Criticality *string `json:"criticality,omitempty"`

	// Description Description of the asset
	Description *string `json:"description,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Name Asset name
	Name string `binding:"required" json:"name"`

	// Sensitivity Sensitivity label for the asset
	Sensitivity *string `json:"sensitivity,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Type of asset
	Type AssetBaseType `binding:"required" json:"type"`
}

AssetBase Base fields for Asset (user-writable only)

type AssetBaseType

type AssetBaseType string

AssetBaseType Type of asset

const (
	AssetBaseTypeData           AssetBaseType = "data"
	AssetBaseTypeHardware       AssetBaseType = "hardware"
	AssetBaseTypeInfrastructure AssetBaseType = "infrastructure"
	AssetBaseTypePersonnel      AssetBaseType = "personnel"
	AssetBaseTypeService        AssetBaseType = "service"
	AssetBaseTypeSoftware       AssetBaseType = "software"
)

Defines values for AssetBaseType.

func (AssetBaseType) Valid

func (e AssetBaseType) Valid() bool

Valid indicates whether the value is a known member of the AssetBaseType enum.

type AssetId

type AssetId = openapi_types.UUID

AssetId defines model for AssetId.

type AssetInput

type AssetInput = AssetBase

AssetInput Base fields for Asset (user-writable only)

type AssetRepository

type AssetRepository interface {
	// CRUD operations
	Create(ctx context.Context, asset *Asset, threatModelID string) error
	Get(ctx context.Context, id string) (*Asset, error)
	Update(ctx context.Context, asset *Asset, threatModelID string) error
	Delete(ctx context.Context, id string) error
	SoftDelete(ctx context.Context, id string) error
	Restore(ctx context.Context, id string) error
	HardDelete(ctx context.Context, id string) error
	GetIncludingDeleted(ctx context.Context, id string) (*Asset, error)
	Patch(ctx context.Context, id string, operations []PatchOperation) (*Asset, error)

	// List operations with pagination
	List(ctx context.Context, threatModelID string, offset, limit int) ([]Asset, error)
	// Count returns total number of assets for a threat model
	Count(ctx context.Context, threatModelID string) (int, error)

	// Bulk operations
	BulkCreate(ctx context.Context, assets []Asset, threatModelID string) error

	// Cache management
	InvalidateCache(ctx context.Context, id string) error
	WarmCache(ctx context.Context, threatModelID string) error
}

AssetRepository defines the interface for asset operations with caching support SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: contract for CRUD, patch, bulk, and cache operations on threat-model assets (pure)

var GlobalAssetRepository AssetRepository

type AssetSubResourceHandler

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

AssetSubResourceHandler provides handlers for asset sub-resource operations SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: handler struct grouping asset sub-resource operations for threat models (reads DB)

func NewAssetSubResourceHandler

func NewAssetSubResourceHandler(assetStore AssetRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *AssetSubResourceHandler

NewAssetSubResourceHandler creates a new asset sub-resource handler SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build an AssetSubResourceHandler with the given store, database, cache, and invalidator (pure)

func (*AssetSubResourceHandler) BulkCreateAssets

func (h *AssetSubResourceHandler) BulkCreateAssets(c *gin.Context)

BulkCreateAssets creates multiple assets in a single request POST /threat_models/{threat_model_id}/assets/bulk SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: handle POST /threat_models/{id}/assets/bulk: validate and store multiple assets atomically (reads DB)

func (*AssetSubResourceHandler) BulkUpdateAssets

func (h *AssetSubResourceHandler) BulkUpdateAssets(c *gin.Context)

BulkUpdateAssets updates or creates multiple assets (upsert operation) PUT /threat_models/{threat_model_id}/assets/bulk SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: handle PUT /threat_models/{id}/assets/bulk: replace multiple assets in a single operation (reads DB)

func (*AssetSubResourceHandler) CreateAsset

func (h *AssetSubResourceHandler) CreateAsset(c *gin.Context)

CreateAsset creates a new asset in a threat model POST /threat_models/{threat_model_id}/assets SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: handle POST /threat_models/{id}/assets: validate and store a new asset (reads DB)

func (*AssetSubResourceHandler) DeleteAsset

func (h *AssetSubResourceHandler) DeleteAsset(c *gin.Context)

DeleteAsset deletes an asset DELETE /threat_models/{threat_model_id}/assets/{asset_id} SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: handle DELETE /threat_models/{id}/assets/{asset_id}: remove an asset by ID (reads DB)

func (*AssetSubResourceHandler) GetAsset

func (h *AssetSubResourceHandler) GetAsset(c *gin.Context)

GetAsset retrieves a specific asset by ID GET /threat_models/{threat_model_id}/assets/{asset_id} SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: handle GET /threat_models/{id}/assets/{asset_id}: fetch a single asset by ID (reads DB)

func (*AssetSubResourceHandler) GetAssets

func (h *AssetSubResourceHandler) GetAssets(c *gin.Context)

GetAssets retrieves all assets for a threat model with pagination GET /threat_models/{threat_model_id}/assets SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: handle GET /threat_models/{id}/assets: list paginated assets for a threat model (reads DB)

func (*AssetSubResourceHandler) PatchAsset

func (h *AssetSubResourceHandler) PatchAsset(c *gin.Context)

PatchAsset applies JSON patch operations to an asset PATCH /threat_models/{threat_model_id}/assets/{asset_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: handle PATCH /threat_models/{id}/assets/{asset_id}: apply JSON Patch operations to an asset (reads DB)

func (*AssetSubResourceHandler) UpdateAsset

func (h *AssetSubResourceHandler) UpdateAsset(c *gin.Context)

UpdateAsset updates an existing asset PUT /threat_models/{threat_model_id}/assets/{asset_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: handle PUT /threat_models/{id}/assets/{asset_id}: replace an asset with validated data (reads DB)

type AssetType

type AssetType string

AssetType Type of asset

const (
	AssetTypeData           AssetType = "data"
	AssetTypeHardware       AssetType = "hardware"
	AssetTypeInfrastructure AssetType = "infrastructure"
	AssetTypePersonnel      AssetType = "personnel"
	AssetTypeService        AssetType = "service"
	AssetTypeSoftware       AssetType = "software"
)

Defines values for AssetType.

func (AssetType) Valid

func (e AssetType) Valid() bool

Valid indicates whether the value is a known member of the AssetType enum.

type AsyncMessage

type AsyncMessage interface {
	GetMessageType() MessageType
	Validate() error
}

AsyncMessage is the base interface for all WebSocket messages SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: base interface for all WebSocket messages requiring type and validation (pure)

func ParseAsyncMessage

func ParseAsyncMessage(data []byte) (AsyncMessage, error)

Message Parser utility to parse incoming WebSocket messages SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: parse and validate an incoming WebSocket message into its concrete async message type (pure)

type AsyncParticipant

type AsyncParticipant struct {
	User         User      `json:"user"`
	Permissions  string    `json:"permissions"`
	LastActivity time.Time `json:"last_activity"`
}

AsyncParticipant represents a participant in the AsyncAPI format SEM@df0585645a37c72fb1ecbeafbfd7644df9718c29: struct representing a session participant with role and last-activity timestamp (pure)

type AuditActor

type AuditActor struct {
	// DisplayName User display name at the time of the action
	DisplayName string `json:"display_name"`

	// Email User email at the time of the action
	Email string `json:"email"`

	// Provider Identity provider (e.g., google, github, tmi)
	Provider string `json:"provider"`

	// ProviderId Provider-specific user identifier
	ProviderId string `json:"provider_id"`
}

AuditActor Denormalized user information stored with audit entries. Persists after user deletion.

type AuditActorEmail

type AuditActorEmail = openapi_types.Email

AuditActorEmail defines model for AuditActorEmail.

type AuditActorProvider

type AuditActorProvider = string

AuditActorProvider defines model for AuditActorProvider.

type AuditAround

type AuditAround = openapi_types.UUID

AuditAround defines model for AuditAround.

type AuditChangeType

type AuditChangeType string

AuditChangeType defines model for AuditChangeType.

const (
	AuditChangeTypeCreated    AuditChangeType = "created"
	AuditChangeTypeDeleted    AuditChangeType = "deleted"
	AuditChangeTypePatched    AuditChangeType = "patched"
	AuditChangeTypeRestored   AuditChangeType = "restored"
	AuditChangeTypeRolledBack AuditChangeType = "rolled_back"
	AuditChangeTypeUpdated    AuditChangeType = "updated"
)

Defines values for AuditChangeType.

func (AuditChangeType) Valid

func (e AuditChangeType) Valid() bool

Valid indicates whether the value is a known member of the AuditChangeType enum.

type AuditContext

type AuditContext struct {
	ActorUserID string
	ActorEmail  string
}

AuditContext contains the actor information for audit logs SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: actor identity (user ID and email) extracted for audit log entries (pure)

func ExtractAuditContext

func ExtractAuditContext(c *gin.Context) *AuditContext

ExtractAuditContext extracts actor information from the Gin context SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: extract the authenticated actor's identity from a Gin request context (pure)

type AuditCursor

type AuditCursor = string

AuditCursor defines model for AuditCursor.

type AuditDebouncer

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

AuditDebouncer buffers rapid mutations to the same entity and coalesces them into a single audit entry after a period of inactivity. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: coalesces rapid mutations on the same entity into a single deferred audit record (mutates shared state)

var GlobalAuditDebouncer *AuditDebouncer

func NewAuditDebouncer

func NewAuditDebouncer(auditService AuditServiceInterface) *AuditDebouncer

NewAuditDebouncer creates a new debouncer with the given audit service. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: build an AuditDebouncer with default WebSocket and REST debounce delays (pure)

func (*AuditDebouncer) FlushAll

func (d *AuditDebouncer) FlushAll()

FlushAll flushes all pending audit entries immediately. Should be called during server shutdown or WebSocket session end. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: flush all pending debounced audit entries immediately, e.g. on server shutdown (reads DB)

func (*AuditDebouncer) FlushEntity

func (d *AuditDebouncer) FlushEntity(objectType, objectID string)

FlushEntity flushes the pending audit entry for a specific entity immediately. Useful when a WebSocket session for a diagram ends. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: flush the pending audit entry for a specific entity immediately (reads DB)

func (*AuditDebouncer) PendingCount

func (d *AuditDebouncer) PendingCount() int

PendingCount returns the number of pending (un-flushed) audit entries. Useful for testing. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: return the number of buffered audit entries awaiting flush (pure)

func (*AuditDebouncer) RecordOrBuffer

func (d *AuditDebouncer) RecordOrBuffer(ctx context.Context, params AuditParams, isWebSocket bool)

RecordOrBuffer either buffers a mutation for debouncing or records it immediately. Use isWebSocket=true for WebSocket cell operations (shorter delay), isWebSocket=false for REST auto-save operations (longer delay). SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: buffer a mutation audit event and reset its debounce timer, or start a new buffer (mutates shared state)

type AuditEntry

type AuditEntry struct {
	// Actor Denormalized user information stored with audit entries. Persists after user deletion.
	Actor AuditActor `json:"actor"`

	// ChangeSummary Human-readable summary of what changed
	ChangeSummary *string `json:"change_summary,omitempty"`

	// ChangeType Type of mutation
	ChangeType AuditEntryChangeType `json:"change_type"`

	// CreatedAt When the mutation occurred
	CreatedAt time.Time `json:"created_at"`

	// Id Unique identifier for the audit entry
	Id openapi_types.UUID `json:"id"`

	// ObjectId ID of the entity that was mutated
	ObjectId openapi_types.UUID `json:"object_id"`

	// ObjectType Type of the entity that was mutated
	ObjectType AuditEntryObjectType `json:"object_type"`

	// ThreatModelId ID of the threat model this audit entry belongs to
	ThreatModelId openapi_types.UUID `json:"threat_model_id"`

	// Version Version number. Null if the version snapshot has been pruned and rollback is no longer available.
	Version *int `json:"version,omitempty"`
}

AuditEntry An entry in the audit trail recording a mutation to an entity

type AuditEntryChangeType

type AuditEntryChangeType string

AuditEntryChangeType Type of mutation

const (
	AuditEntryChangeTypeCreated    AuditEntryChangeType = "created"
	AuditEntryChangeTypeDeleted    AuditEntryChangeType = "deleted"
	AuditEntryChangeTypePatched    AuditEntryChangeType = "patched"
	AuditEntryChangeTypeRestored   AuditEntryChangeType = "restored"
	AuditEntryChangeTypeRolledBack AuditEntryChangeType = "rolled_back"
	AuditEntryChangeTypeUpdated    AuditEntryChangeType = "updated"
)

Defines values for AuditEntryChangeType.

func (AuditEntryChangeType) Valid

func (e AuditEntryChangeType) Valid() bool

Valid indicates whether the value is a known member of the AuditEntryChangeType enum.

type AuditEntryId

type AuditEntryId = openapi_types.UUID

AuditEntryId defines model for AuditEntryId.

type AuditEntryObjectType

type AuditEntryObjectType string

AuditEntryObjectType Type of the entity that was mutated

const (
	AuditEntryObjectTypeAsset       AuditEntryObjectType = "asset"
	AuditEntryObjectTypeDiagram     AuditEntryObjectType = "diagram"
	AuditEntryObjectTypeDocument    AuditEntryObjectType = "document"
	AuditEntryObjectTypeNote        AuditEntryObjectType = "note"
	AuditEntryObjectTypeRepository  AuditEntryObjectType = "repository"
	AuditEntryObjectTypeThreat      AuditEntryObjectType = "threat"
	AuditEntryObjectTypeThreatModel AuditEntryObjectType = "threat_model"
)

Defines values for AuditEntryObjectType.

func (AuditEntryObjectType) Valid

func (e AuditEntryObjectType) Valid() bool

Valid indicates whether the value is a known member of the AuditEntryObjectType enum.

type AuditEntryResponse

type AuditEntryResponse struct {
	ID            string             `json:"id"`
	ThreatModelID string             `json:"threat_model_id"`
	ObjectType    string             `json:"object_type"`
	ObjectID      string             `json:"object_id"`
	Version       *int               `json:"version"` // nil means version snapshot has been pruned
	ChangeType    string             `json:"change_type"`
	Actor         InternalAuditActor `json:"actor"`
	ChangeSummary *string            `json:"change_summary"`
	CreatedAt     time.Time          `json:"created_at"`
}

AuditEntryResponse represents an audit entry as returned by the service layer. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: audit trail entry returned by the service layer, including actor and change metadata (pure)

type AuditFieldPath

type AuditFieldPath = string

AuditFieldPath defines model for AuditFieldPath.

type AuditFilters

type AuditFilters struct {
	ObjectType    *string
	ObjectID      *string
	ChangeType    *string
	ActorEmail    *string
	ActorProvider *string // admin cross-TM queries (#398)
	ThreatModelID *string // admin cross-TM queries (#398); per-TM reads still pass the scoped WHERE
	After         *time.Time
	Before        *time.Time
}

AuditFilters defines filtering criteria for querying audit entries. SEM@b7db260b5211c371fc74a10f72dfcd61bf7d1090: filtering criteria for querying audit entries by object, actor, or time range (pure)

type AuditHTTPMethod

type AuditHTTPMethod string

AuditHTTPMethod defines model for AuditHTTPMethod.

const (
	AuditHTTPMethodDELETE AuditHTTPMethod = "DELETE"
	AuditHTTPMethodPATCH  AuditHTTPMethod = "PATCH"
	AuditHTTPMethodPOST   AuditHTTPMethod = "POST"
	AuditHTTPMethodPUT    AuditHTTPMethod = "PUT"
)

Defines values for AuditHTTPMethod.

func (AuditHTTPMethod) Valid

func (e AuditHTTPMethod) Valid() bool

Valid indicates whether the value is a known member of the AuditHTTPMethod enum.

type AuditHandler

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

AuditHandler provides handlers for audit trail and rollback operations. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: handler struct holding the audit service for audit trail HTTP endpoints

func NewAuditHandler

func NewAuditHandler(auditService AuditServiceInterface) *AuditHandler

NewAuditHandler creates a new audit handler. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: build an AuditHandler wired to the given audit service (pure)

func (*AuditHandler) GetAssetAuditTrail

func (h *AuditHandler) GetAssetAuditTrail(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, params GetAssetAuditTrailParams)

GetAssetAuditTrail lists audit entries for a specific asset. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: list audit entries for a specific asset, delegating to the sub-resource audit handler (reads DB)

func (*AuditHandler) GetAuditEntry

func (h *AuditHandler) GetAuditEntry(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

GetAuditEntry returns a single audit entry. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: fetch a single audit entry by ID, validating it belongs to the given threat model (reads DB)

func (*AuditHandler) GetDiagramAuditTrail

func (h *AuditHandler) GetDiagramAuditTrail(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, params GetDiagramAuditTrailParams)

GetDiagramAuditTrail lists audit entries for a specific diagram. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: list audit entries for a specific diagram, delegating to the sub-resource audit handler (reads DB)

func (*AuditHandler) GetDocumentAuditTrail

func (h *AuditHandler) GetDocumentAuditTrail(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, params GetDocumentAuditTrailParams)

GetDocumentAuditTrail lists audit entries for a specific document. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: list audit entries for a specific document, delegating to the sub-resource audit handler (reads DB)

func (*AuditHandler) GetNoteAuditTrail

func (h *AuditHandler) GetNoteAuditTrail(c *gin.Context, threatModelId ThreatModelId, noteId NoteId, params GetNoteAuditTrailParams)

GetNoteAuditTrail lists audit entries for a specific note. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: list audit entries for a specific note, delegating to the sub-resource audit handler (reads DB)

func (*AuditHandler) GetRepositoryAuditTrail

func (h *AuditHandler) GetRepositoryAuditTrail(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, params GetRepositoryAuditTrailParams)

GetRepositoryAuditTrail lists audit entries for a specific repository. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: list audit entries for a specific repository, delegating to the sub-resource audit handler (reads DB)

func (*AuditHandler) GetThreatAuditTrail

func (h *AuditHandler) GetThreatAuditTrail(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, params GetThreatAuditTrailParams)

GetThreatAuditTrail lists audit entries for a specific threat. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: list audit entries for a specific threat, delegating to the sub-resource audit handler (reads DB)

func (*AuditHandler) GetThreatModelAuditTrail

func (h *AuditHandler) GetThreatModelAuditTrail(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelAuditTrailParams)

GetThreatModelAuditTrail lists audit entries for a threat model and all sub-objects. SEM@24454e2885191ae61007ef13d2194c563ebe6d37: list paginated audit entries for a threat model and its sub-objects (reads DB)

func (*AuditHandler) RollbackToVersion

func (h *AuditHandler) RollbackToVersion(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

RollbackToVersion restores an entity to a previous version. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: restore a threat model entity to a prior version snapshot and record the rollback (mutates shared state)

type AuditLogger

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

AuditLogger provides standardized audit logging for admin operations SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: structured audit logger for recording admin actions with actor context (pure)

func NewAuditLogger

func NewAuditLogger() *AuditLogger

NewAuditLogger creates a new audit logger SEM@a5548be4c61d9f98ed2f3edd998abd909cd5f4ab: build an AuditLogger backed by the global structured logger (pure)

func (*AuditLogger) LogAction

func (a *AuditLogger) LogAction(ctx *AuditContext, action string, details map[string]any)

LogAction logs an audit event with standardized format SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: emit a structured audit log entry for an action with actor and detail fields (pure)

func (*AuditLogger) LogCreate

func (a *AuditLogger) LogCreate(ctx *AuditContext, entityType string, entityID string, details map[string]any)

LogCreate logs an entity creation event SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: emit an audit log entry recording creation of a named entity (pure)

func (*AuditLogger) LogDelete

func (a *AuditLogger) LogDelete(ctx *AuditContext, entityType string, entityID string, details map[string]any)

LogDelete logs an entity deletion event SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: emit an audit log entry recording deletion of a named entity (pure)

func (*AuditLogger) LogGroupMemberAdded

func (a *AuditLogger) LogGroupMemberAdded(ctx *AuditContext, groupUUID string, userUUID string, userEmail string)

LogGroupMemberAdded logs a group member addition event SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: emit an audit log entry recording a user being added to a group (pure)

func (*AuditLogger) LogGroupMemberRemoved

func (a *AuditLogger) LogGroupMemberRemoved(ctx *AuditContext, groupUUID string, userUUID string)

LogGroupMemberRemoved logs a group member removal event SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: emit an audit log entry recording a user being removed from a group (pure)

func (*AuditLogger) LogUpdate

func (a *AuditLogger) LogUpdate(ctx *AuditContext, entityType string, entityID string, changes []string)

LogUpdate logs an entity update event SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: emit an audit log entry recording which fields of an entity were updated (pure)

func (*AuditLogger) LogUserDeletion

func (a *AuditLogger) LogUserDeletion(ctx *AuditContext, provider string, providerUserID string, email string, transferred int, deleted int)

LogUserDeletion logs a user deletion event with transfer and deletion counts SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: emit an audit log entry for an admin user deletion with transfer and deletion counts (pure)

type AuditObjectType

type AuditObjectType string

AuditObjectType defines model for AuditObjectType.

const (
	AuditObjectTypeAsset       AuditObjectType = "asset"
	AuditObjectTypeDiagram     AuditObjectType = "diagram"
	AuditObjectTypeDocument    AuditObjectType = "document"
	AuditObjectTypeNote        AuditObjectType = "note"
	AuditObjectTypeRepository  AuditObjectType = "repository"
	AuditObjectTypeThreat      AuditObjectType = "threat"
	AuditObjectTypeThreatModel AuditObjectType = "threat_model"
)

Defines values for AuditObjectType.

func (AuditObjectType) Valid

func (e AuditObjectType) Valid() bool

Valid indicates whether the value is a known member of the AuditObjectType enum.

type AuditPageLimit

type AuditPageLimit = int

AuditPageLimit defines model for AuditPageLimit.

type AuditParams

type AuditParams struct {
	ThreatModelID string
	ObjectType    string
	ObjectID      string
	ChangeType    string // "created", "updated", "patched", "deleted", "rolled_back"
	Actor         InternalAuditActor
	PreviousState []byte  // full JSON of entity before mutation; nil for "created"
	CurrentState  []byte  // full JSON of entity after mutation; nil for "deleted"
	ChangeSummary *string // human-readable summary of what changed
}

AuditParams contains the parameters for recording an audit entry. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: parameters for recording a single mutation in the audit trail (pure)

type AuditPathPrefix

type AuditPathPrefix = string

AuditPathPrefix defines model for AuditPathPrefix.

type AuditPruner

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

AuditPruner runs periodic cleanup of expired audit entries and version snapshots. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: background scheduler that periodically deletes expired audit entries and snapshots

func NewAuditPruner

func NewAuditPruner(auditService AuditServiceInterface) *AuditPruner

NewAuditPruner creates a new pruner for the given audit service. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: build an AuditPruner for the given audit service with the default 24-hour interval (pure)

func (*AuditPruner) Start

func (p *AuditPruner) Start()

Start begins the background pruning goroutine. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: start the background pruning goroutine (mutates shared state)

func (*AuditPruner) Stop

func (p *AuditPruner) Stop()

Stop gracefully stops the pruning goroutine. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: cancel the background pruning goroutine (mutates shared state)

type AuditServiceInterface

type AuditServiceInterface interface {
	// RecordMutation records a mutation in the audit trail and creates a version snapshot.
	// The service internally computes reverse diffs and determines checkpoint intervals.
	RecordMutation(ctx context.Context, params AuditParams) error

	// GetThreatModelAuditTrailKeyset retrieves audit entries for a threat model and
	// its sub-objects using bidirectional keyset pagination ordered
	// (created_at DESC, id DESC). Returns (rows, total, prev, next) where total is
	// the filtered count ignoring the cursor (#457).
	GetThreatModelAuditTrailKeyset(ctx context.Context, threatModelID string, limit int, cursor *auditCursor, filters *AuditFilters) ([]AuditEntryResponse, int, *string, *string, error)

	// GetObjectAuditTrail retrieves audit entries for a specific object.
	GetObjectAuditTrail(ctx context.Context, objectType, objectID string, offset, limit int) ([]AuditEntryResponse, int, error)

	// GetAuditEntry retrieves a single audit entry by ID.
	GetAuditEntry(ctx context.Context, entryID string) (*AuditEntryResponse, error)

	// GetSnapshot reconstructs the full entity state at a given audit entry's version.
	// Returns the full JSON by finding the nearest checkpoint and applying diffs.
	// Returns an error if the version snapshot has been pruned.
	GetSnapshot(ctx context.Context, entryID string) ([]byte, error)

	// PruneAuditEntries removes audit entries older than the configured retention period.
	// Returns the number of entries pruned.
	PruneAuditEntries(ctx context.Context) (int, error)

	// PruneVersionSnapshots removes version snapshots outside the configured retention window.
	// Always stops at checkpoint boundaries to ensure remaining diffs can be reconstructed.
	// Audit entries are immutable and keep their version numbers; rollback to a pruned
	// version returns an error (the handler maps it to 410 Gone).
	// Returns the number of snapshots pruned.
	PruneVersionSnapshots(ctx context.Context) (int, error)

	// PruneOrphanedVersionSnapshots removes version snapshots whose referenced
	// entity no longer exists (e.g. children orphaned by the threat-model
	// hard-delete cascade, which removes the rows but not their snapshots, #458).
	// Only snapshots aged past the append-only delete floor are removed; younger
	// orphans are left for a later cycle. Returns the number of snapshots removed.
	PruneOrphanedVersionSnapshots(ctx context.Context) (int, error)

	// PurgeTombstones hard-deletes entities that have been soft-deleted for longer than
	// the tombstone retention period. Also cleans up associated metadata and version snapshots.
	// Audit entries are append-only and are never deleted.
	// Returns the number of entities purged.
	PurgeTombstones(ctx context.Context) (int, error)

	// PruneSystemAuditEntries removes system audit entries older than the
	// configured retention period (SYSTEM_AUDIT_RETENTION_DAYS, default 365,
	// minimum 90). Returns the number of entries pruned.
	PruneSystemAuditEntries(ctx context.Context) (int, error)

	// ListAuditEntriesAdmin lists audit entries across ALL threat models with
	// bidirectional keyset pagination. Returns (rows, total, prev, next) (#464).
	ListAuditEntriesAdmin(ctx context.Context, limit int, cursor *auditCursor, filters *AuditFilters) ([]AuditEntryResponse, int, *string, *string, error)
	// AroundAuditEntriesAdmin returns a page of `limit` entries centered on
	// anchorID. Returns errAuditAnchorNotFound for an unknown id (#464).
	AroundAuditEntriesAdmin(ctx context.Context, limit int, anchorID string, filters *AuditFilters) ([]AuditEntryResponse, int, *string, *string, error)
}

AuditServiceInterface defines operations for audit trail and version management. SEM@24454e2885191ae61007ef13d2194c563ebe6d37: contract for recording mutations, querying audit trails, and pruning version snapshots

var GlobalAuditService AuditServiceInterface

Audit trail and versioning

type AuditThreatModelId

type AuditThreatModelId = openapi_types.UUID

AuditThreatModelId defines model for AuditThreatModelId.

type AuthFlowRateLimiter

type AuthFlowRateLimiter struct {
	SlidingWindowRateLimiter
}

AuthFlowRateLimiter implements multi-scope rate limiting for OAuth/SAML auth flows SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: enforce sliding-window rate limits on OAuth/SAML auth flows across session, IP, and user scopes (mutates shared state)

func NewAuthFlowRateLimiter

func NewAuthFlowRateLimiter(redisClient *redis.Client) *AuthFlowRateLimiter

NewAuthFlowRateLimiter creates a new auth flow rate limiter SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: build an AuthFlowRateLimiter backed by a Redis client (pure)

func (*AuthFlowRateLimiter) CheckRateLimit

func (r *AuthFlowRateLimiter) CheckRateLimit(ctx context.Context, sessionID string, ipAddress string, userIdentifier string) (*RateLimitResult, error)

CheckRateLimit checks all three scopes and returns the most restrictive result. Scopes are evaluated most-specific-first: session (100/min), user identifier (50/min), IP (100/min). SEM@2ba330fcb59eb085d8f877fe8f75f90af9b69071: check all three auth-flow rate limit scopes and return the most restrictive result (reads DB)

func (*AuthFlowRateLimiter) CheckRateLimitForTokenEndpoint

func (r *AuthFlowRateLimiter) CheckRateLimitForTokenEndpoint(ctx context.Context, sessionID string, ipAddress string, userIdentifier string) (*RateLimitResult, error)

CheckRateLimitForTokenEndpoint checks rate limits for the token endpoint Uses the same per-IP limit as other auth endpoints SEM@c70d49ed2d6089c24d05f8bc287ba5711c73abde: check rate limits for the token endpoint using the standard per-IP limit (reads DB)

func (*AuthFlowRateLimiter) ResetUserRateLimit

func (r *AuthFlowRateLimiter) ResetUserRateLimit(ctx context.Context, userIdentifier string)

ResetUserRateLimit clears the user identifier rate limit counter. Called after a successful login so that prior failed/exploratory attempts don't lock a legitimate user out for the remainder of the hour window. SEM@c70d49ed2d6089c24d05f8bc287ba5711c73abde: clear the user-scoped rate limit counter after a successful login (mutates shared state)

type AuthService

type AuthService interface {
	GetProviders(c *gin.Context)
	GetSAMLProviders(c *gin.Context)
	Authorize(c *gin.Context)
	StepUp(c *gin.Context)
	Callback(c *gin.Context)
	Exchange(c *gin.Context)
	Token(c *gin.Context)
	Refresh(c *gin.Context)
	Logout(c *gin.Context)
	RevokeToken(c *gin.Context)
	MeLogout(c *gin.Context)
	Me(c *gin.Context)
	IsValidProvider(idp string) bool
	GetProviderGroupsFromCache(ctx context.Context, idp string) ([]string, error)
}

AuthService placeholder - we'll need to create this interface to avoid circular deps SEM@3b3ce007aac967644943c133123d85a9a1525644: interface defining auth endpoints and provider utilities the server delegates to (pure)

var GlobalAuthServiceForEvents AuthService

Global auth service for owner UUID lookups

type AuthServiceAdapter

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

AuthServiceAdapter adapts the auth package's Handlers to implement our AuthService interface SEM@0f62047e453da0091b22aafd9f8f959f3d083927: adapter bridging the auth package's Handlers to the API's AuthService interface (pure)

func NewAuthServiceAdapter

func NewAuthServiceAdapter(handlers *auth.Handlers) *AuthServiceAdapter

NewAuthServiceAdapter creates a new adapter for auth handlers SEM@0f62047e453da0091b22aafd9f8f959f3d083927: build an AuthServiceAdapter wrapping the given auth Handlers (pure)

func (*AuthServiceAdapter) Authorize

func (a *AuthServiceAdapter) Authorize(c *gin.Context)

Authorize delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: delegate the OAuth authorization request to auth.Handlers

func (*AuthServiceAdapter) Callback

func (a *AuthServiceAdapter) Callback(c *gin.Context)

Callback delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: delegate the OAuth callback request to auth.Handlers

func (*AuthServiceAdapter) Exchange

func (a *AuthServiceAdapter) Exchange(c *gin.Context)

Exchange delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: delegate the authorization code exchange request to auth.Handlers

func (*AuthServiceAdapter) GetJWKS

func (a *AuthServiceAdapter) GetJWKS(c *gin.Context)

GetJWKS delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: fetch the public key set (JWKS) for JWT verification (pure)

func (*AuthServiceAdapter) GetOAuthAuthorizationServerMetadata

func (a *AuthServiceAdapter) GetOAuthAuthorizationServerMetadata(c *gin.Context)

GetOAuthAuthorizationServerMetadata delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: fetch the RFC 8414 authorization server metadata document (pure)

func (*AuthServiceAdapter) GetOAuthProtectedResourceMetadata

func (a *AuthServiceAdapter) GetOAuthProtectedResourceMetadata(c *gin.Context)

GetOAuthProtectedResourceMetadata delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: fetch the RFC 9728 protected resource metadata document (pure)

func (*AuthServiceAdapter) GetOpenIDConfiguration

func (a *AuthServiceAdapter) GetOpenIDConfiguration(c *gin.Context)

GetOpenIDConfiguration delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: fetch the OIDC discovery document for this server (pure)

func (*AuthServiceAdapter) GetProviderGroupsFromCache

func (a *AuthServiceAdapter) GetProviderGroupsFromCache(ctx context.Context, idp string) ([]string, error)

GetProviderGroupsFromCache retrieves all unique groups for a provider from cached user sessions SEM@d510ee7a8017fc630e79a21b9480e4f975482b47: fetch all unique cached group names for an identity provider (reads DB)

func (*AuthServiceAdapter) GetProviders

func (a *AuthServiceAdapter) GetProviders(c *gin.Context)

GetProviders delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: delegate the list-OAuth-providers request to auth.Handlers

func (*AuthServiceAdapter) GetSAMLMetadata

func (a *AuthServiceAdapter) GetSAMLMetadata(c *gin.Context, providerID string)

GetSAMLMetadata delegates to auth handlers for SAML metadata SEM@2fbab585a899780eb5d718ec784b7c730c732113: fetch SAML SP metadata XML for a given provider

func (*AuthServiceAdapter) GetSAMLProviders

func (a *AuthServiceAdapter) GetSAMLProviders(c *gin.Context)

GetSAMLProviders delegates to auth handlers SEM@f2053af9d1a8c6b42c543c9406c5fb607c9c7d69: delegate the list-SAML-providers request to auth.Handlers

func (*AuthServiceAdapter) GetService

func (a *AuthServiceAdapter) GetService() *auth.Service

GetService returns the underlying auth service for advanced operations SEM@bd740ab90ce24a669adc1fa8b8153efbd33bac10: fetch the underlying auth service instance (pure)

func (*AuthServiceAdapter) InitiateSAMLLogin

func (a *AuthServiceAdapter) InitiateSAMLLogin(c *gin.Context, providerID string, clientCallback *string)

InitiateSAMLLogin delegates to auth handlers to start SAML authentication SEM@2fbab585a899780eb5d718ec784b7c730c732113: dispatch a SAML authentication redirect to the identity provider

func (*AuthServiceAdapter) IntrospectToken

func (a *AuthServiceAdapter) IntrospectToken(c *gin.Context)

IntrospectToken delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: validate a bearer token and return its active status and claims (reads DB)

func (*AuthServiceAdapter) IsValidProvider

func (a *AuthServiceAdapter) IsValidProvider(idp string) bool

IsValidProvider checks if the given provider ID is configured and enabled SEM@0eb4bf778ed84abb8fa3d433bf42cc7928258257: validate that an OAuth provider ID is configured and enabled (pure)

func (*AuthServiceAdapter) IssueForInvocation

func (a *AuthServiceAdapter) IssueForInvocation(
	ctx context.Context,
	invokerInternalUUID string,
	addonID, deliveryID, threatModelID uuid.UUID,
) (string, error)

IssueForInvocation implements DelegationTokenIssuer (api/delegation_token_issuer.go) by loading the invoker from the auth user store and asking auth.Service to mint a scoped delegation JWT (auth/delegation_token.go). Used by the webhook delivery worker to attach a per-attempt token to every addon.invoked delivery (T18, #358). SEM@e6be8a8f816c564356a656ac18f3693ac7f10369: issue a delegated addon invocation token for the given invoking user

func (*AuthServiceAdapter) Logout

func (a *AuthServiceAdapter) Logout(c *gin.Context)

Logout delegates to auth handlers (deprecated - use RevokeToken or MeLogout) SEM@e01a24e0b115a4483cccea13af361c6ede9d62a5: delegate a logout request to auth.Handlers.MeLogout (deprecated endpoint)

func (*AuthServiceAdapter) Me

func (a *AuthServiceAdapter) Me(c *gin.Context)

Me delegates to auth handlers, with fallback user lookup if needed SEM@23ecc252aaf49b08f2030803b81a91d5727c7d25: fetch the authenticated user from context or by provider ID and return user profile

func (*AuthServiceAdapter) MeLogout

func (a *AuthServiceAdapter) MeLogout(c *gin.Context)

MeLogout delegates to auth handlers for self-logout SEM@e01a24e0b115a4483cccea13af361c6ede9d62a5: delegate a self-logout request to auth.Handlers

func (*AuthServiceAdapter) ProcessSAMLLogout

func (a *AuthServiceAdapter) ProcessSAMLLogout(c *gin.Context, providerID string, samlRequest string)

ProcessSAMLLogout delegates to auth handlers for SAML logout SEM@2fbab585a899780eb5d718ec784b7c730c732113: validate a SAML logout request and invalidate the user's sessions

func (*AuthServiceAdapter) ProcessSAMLResponse

func (a *AuthServiceAdapter) ProcessSAMLResponse(c *gin.Context, providerID string, samlResponse string, relayState string)

ProcessSAMLResponse delegates to auth handlers to process SAML assertion SEM@2fbab585a899780eb5d718ec784b7c730c732113: validate a SAML assertion and issue a token pair for the authenticated user

func (*AuthServiceAdapter) Refresh

func (a *AuthServiceAdapter) Refresh(c *gin.Context)

Refresh delegates to auth handlers SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: delegate a token refresh request to auth.Handlers

func (*AuthServiceAdapter) RevokeToken

func (a *AuthServiceAdapter) RevokeToken(c *gin.Context)

RevokeToken delegates to auth handlers for RFC 7009 token revocation SEM@e01a24e0b115a4483cccea13af361c6ede9d62a5: delegate an RFC 7009 token revocation request to auth.Handlers

func (*AuthServiceAdapter) StepUp

func (a *AuthServiceAdapter) StepUp(c *gin.Context)

StepUp delegates to auth.Handlers.StepUp (#397). SEM@3b3ce007aac967644943c133123d85a9a1525644: delegate a step-up authentication request to auth.Handlers

func (*AuthServiceAdapter) Token

func (a *AuthServiceAdapter) Token(c *gin.Context)

Token delegates to auth handlers (supports all grant types and content types) SEM@9af9f8a9f8a6ebe7f9c56c6b1de45cebf7fbd5b1: delegate a token request supporting all grant types to auth.Handlers

type AuthServiceGetter

type AuthServiceGetter interface {
	GetService() *auth.Service
}

AuthServiceGetter defines an interface for getting the auth service SEM@35d3e17459ee0834e412739eaa604652b815d559: interface for retrieving the auth service instance (pure)

type AuthTestHelper

type AuthTestHelper struct {
	DB               *sql.DB
	Cache            *CacheService
	CacheInvalidator *CacheInvalidator
	TestContext      context.Context
}

AuthTestHelper provides utilities for testing authorization functionality with caching SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: test helper struct bundling DB, cache, and invalidator for authorization test scenarios (pure)

func NewAuthTestHelper

func NewAuthTestHelper(db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *AuthTestHelper

NewAuthTestHelper creates a new authorization test helper SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build an AuthTestHelper wiring DB, cache, and invalidator for authorization tests (pure)

func (*AuthTestHelper) CleanupTestAuth

func (h *AuthTestHelper) CleanupTestAuth(t *testing.T, threatModelIDs []string)

CleanupTestAuth cleans up test authorization data SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: invalidate cache entries for the given threat model IDs to clean up after authorization tests

func (*AuthTestHelper) CreateTestGinContext

func (h *AuthTestHelper) CreateTestGinContext(userEmail string, threatModelID string) (*gin.Context, *httptest.ResponseRecorder)

CreateTestGinContext creates a Gin context for testing with authentication SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build a Gin test context pre-populated with user email and threat model ID (pure)

func (*AuthTestHelper) SetupTestAuthorizationData

func (h *AuthTestHelper) SetupTestAuthorizationData() []AuthTestScenario

SetupTestAuthorizationData creates test authorization data for various scenarios SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the canonical set of authorization test scenarios covering owner, writer, reader, and external users (pure)

func (*AuthTestHelper) SetupTestThreatModel

func (h *AuthTestHelper) SetupTestThreatModel(t *testing.T, owner string, authList []Authorization) string

SetupTestThreatModel creates a test threat model with authorization for testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: register a test threat model with a given owner and authorization list, returning its UUID (pure)

func (*AuthTestHelper) TestCacheInvalidation

func (h *AuthTestHelper) TestCacheInvalidation(t *testing.T, threatModelID string)

TestCacheInvalidation tests that cache is properly invalidated when authorization changes SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: verify that invalidating the cache clears previously stored authorization data

func (*AuthTestHelper) TestCheckSubResourceAccess

func (h *AuthTestHelper) TestCheckSubResourceAccess(t *testing.T, scenarios []AuthTestScenario)

TestCheckSubResourceAccess tests the CheckSubResourceAccess function with caching SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: run CheckSubResourceAccess against a set of scenarios and assert expected access outcomes

func (*AuthTestHelper) TestGetInheritedAuthData

func (h *AuthTestHelper) TestGetInheritedAuthData(t *testing.T, scenarios []AuthTestScenario)

TestGetInheritedAuthData tests the GetInheritedAuthData function with various scenarios SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: run GetInheritedAuthData against a set of scenarios and assert access and cache behavior

func (*AuthTestHelper) TestValidateSubResourceAccess

func (h *AuthTestHelper) TestValidateSubResourceAccess(t *testing.T, scenarios []AuthTestScenario)

TestValidateSubResourceAccess tests the middleware function SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: exercise the sub-resource access middleware against scenarios and assert allow or block behavior

func (*AuthTestHelper) VerifyAuthorizationInheritance

func (h *AuthTestHelper) VerifyAuthorizationInheritance(t *testing.T, threatModelID, subResourceID string)

VerifyAuthorizationInheritance verifies that sub-resource authorization inherits from threat model SEM@9109f507bb812a13798dcd3c74f0dc11531d370e: assert that sub-resource access correctly inherits each authorized user's role from the parent threat model

type AuthTestScenario

type AuthTestScenario struct {
	Description      string
	User             string
	ThreatModelID    string
	ExpectedAccess   bool
	ExpectedRole     Role
	ShouldCache      bool
	ExpectedCacheHit bool
}

AuthTestScenario defines a test scenario for authorization testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: struct defining expected access, role, and cache behavior for a single authorization test case (pure)

type AuthTokenResponse

type AuthTokenResponse struct {
	// AccessToken JWT access token
	AccessToken string `json:"access_token"`

	// ExpiresIn Access token expiration time in seconds
	ExpiresIn int `json:"expires_in"`

	// RefreshToken Refresh token for obtaining new access tokens
	RefreshToken string `json:"refresh_token"`

	// TokenType Token type
	TokenType AuthTokenResponseTokenType `json:"token_type"`
}

AuthTokenResponse JWT token response for authentication endpoints

type AuthTokenResponseTokenType

type AuthTokenResponseTokenType string

AuthTokenResponseTokenType Token type

const (
	Bearer AuthTokenResponseTokenType = "bearer"
)

Defines values for AuthTokenResponseTokenType.

func (AuthTokenResponseTokenType) Valid

func (e AuthTokenResponseTokenType) Valid() bool

Valid indicates whether the value is a known member of the AuthTokenResponseTokenType enum.

type AuthUser

type AuthUser struct {
	Email     string    `json:"email"`
	Name      string    `json:"name"`
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
}

AuthUser represents authenticated user information SEM@386eea01f3b66c35027bf3ca762efbc291419e20: represent an authenticated user's identity and access token (pure)

type Authorization

type Authorization struct {
	// DisplayName Human-readable display name for UI presentation
	DisplayName *string `json:"display_name,omitempty"`

	// Email Email address (required for users, optional for groups)
	Email *openapi_types.Email `json:"email,omitempty"`

	// PrincipalType Type of principal: user (individual) or group
	PrincipalType AuthorizationPrincipalType `json:"principal_type"`

	// Provider Identity provider name (e.g., "google", "github", "microsoft", "tmi"). Use "tmi" for TMI built-in groups.
	Provider string `json:"provider"`

	// ProviderId Provider-assigned identifier. For users: provider_user_id (e.g., email or OAuth sub). For groups: group_name.
	ProviderId string `json:"provider_id"`

	// Role Role: reader (view), writer (edit), owner (full control)
	Role AuthorizationRole `binding:"required" json:"role"`
}

Authorization defines model for Authorization.

func ApplyOwnershipTransferRule

func ApplyOwnershipTransferRule(authList []Authorization, originalOwner, newOwner string) []Authorization

ApplyOwnershipTransferRule applies the business rule that when ownership changes, the original owner should be preserved in the authorization list with owner role SEM@5bacd53eee87984ab4d2aab453afb59913aa79dc: ensure the original owner retains the owner role when ownership is transferred (pure)

func ApplySecurityReviewerRule

func ApplySecurityReviewerRule(authList []Authorization, securityReviewer *User) []Authorization

ApplySecurityReviewerRule ensures the security reviewer is in the authorization list with owner role. If the security reviewer is already present, their role is upgraded to owner. If not present, they are appended with owner role. SEM@b11d5634ea0de9c46ce45bd4660b0bb604404f15: ensure the assigned security reviewer holds the owner role in the authorization list (pure)

func ConfidentialProjectReviewersAuthorization

func ConfidentialProjectReviewersAuthorization() Authorization

ConfidentialProjectReviewersAuthorization returns an Authorization entry for the Confidential Project Reviewers group with owner role. This is used to auto-add Confidential Project Reviewers to confidential survey responses and threat models. SEM@192fb026aa596416ded7413d23092ccd1733ad90: build an Authorization entry granting the Confidential Project Reviewers group owner role (pure)

func DeduplicateAuthorizationList

func DeduplicateAuthorizationList(authList []Authorization) []Authorization

DeduplicateAuthorizationList removes duplicate authorization entries, keeping the last occurrence. This mimics database ON CONFLICT behavior where the latest value wins.

Deduplication uses the same logic as ValidateDuplicateSubjects: - For groups: (provider, provider_id) - For users with provider_id: (provider, provider_id) - For users without provider_id: (provider, email)

When duplicates are found, the LAST occurrence is kept (latest wins), which matches the behavior of applying multiple PATCH operations where the final role should be used. SEM@1a54e88429506603e24f26cbaaadfc8a810ec63b: remove duplicate authorization entries keeping the last occurrence for each principal (pure)

func ExtractOwnershipChangesFromOperations

func ExtractOwnershipChangesFromOperations(operations []PatchOperation) (newOwner string, newAuth []Authorization, hasOwnerChange, hasAuthChange bool)

ExtractOwnershipChangesFromOperations extracts owner and authorization changes from patch operations SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: extract owner and authorization changes from a list of JSON Patch operations (pure)

func NormalizePseudoGroupAuthorization

func NormalizePseudoGroupAuthorization(auth Authorization) Authorization

NormalizePseudoGroupAuthorization ensures pseudo-group authorization entries have the correct Provider value (BuiltInProvider for cross-provider pseudo-groups) SEM@192fb026aa596416ded7413d23092ccd1733ad90: normalize a single authorization entry to set the built-in provider for pseudo-groups (pure)

func NormalizePseudoGroupAuthorizationList

func NormalizePseudoGroupAuthorizationList(authList []Authorization) []Authorization

NormalizePseudoGroupAuthorizationList applies normalization to a list of authorization entries SEM@6124bff108947c0b35d793f38a2bff9f438768ce: normalize a list of authorization entries to set the built-in provider for pseudo-groups (pure)

func SecurityReviewersAuthorization

func SecurityReviewersAuthorization() Authorization

SecurityReviewersAuthorization returns an Authorization entry for the Security Reviewers group with owner role. This is used to auto-add Security Reviewers to non-confidential survey responses and threat models. SEM@192fb026aa596416ded7413d23092ccd1733ad90: build an Authorization entry granting the Security Reviewers group owner role (pure)

func StripResponseOnlyAuthFields

func StripResponseOnlyAuthFields(authList []Authorization) []Authorization

StripResponseOnlyAuthFields strips response-only fields from authorization entries This should be called before validation to allow clients to send back authorization data they received from the server (which includes response-only fields) SEM@49c5b6ee85e3d61e46787ef99d00ad8cbc637806: clear response-only fields from authorization entries before processing client input (pure)

func TMIAutomationAuthorization

func TMIAutomationAuthorization() Authorization

TMIAutomationAuthorization returns an Authorization entry for the TMI Automation group with writer role. This is used to auto-add the TMI Automation group to all new threat models and survey responses. SEM@192fb026aa596416ded7413d23092ccd1733ad90: build an Authorization entry granting the TMI Automation group writer role (pure)

type AuthorizationData

type AuthorizationData struct {
	Type          string          `json:"type"`
	Owner         User            `json:"owner"`
	Authorization []Authorization `json:"authorization"`
}

AuthorizationData represents abstracted authorization data for any resource SEM@e28c0cfc627a2162c9550e53fb320facb734179e: struct holding the owner and authorization list for any access-controlled resource (pure)

func ExtractAuthData

func ExtractAuthData(resource any) (AuthorizationData, error)

ExtractAuthData extracts authorization data from threat models or diagrams This is a generic helper that works with any struct that has Owner and Authorization fields SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: extract normalized AuthorizationData from a threat model or diagram resource (pure)

func GetInheritedAuthData

func GetInheritedAuthData(ctx context.Context, db *sql.DB, threatModelID string) (*AuthorizationData, error)

GetInheritedAuthData retrieves authorization data for a threat model from the database This function implements authorization inheritance by fetching threat model permissions that apply to all sub-resources within that threat model SEM@d73e23609ca9cefd9ef2feb0e43d87e4286ea6d6: fetch a threat model's owner and access list from the DB as AuthorizationData (reads DB)

func GetTestAuthorizationData

func GetTestAuthorizationData(scenario string) *AuthorizationData

GetTestAuthorizationData returns test authorization data for a specific scenario SEM@e28c0cfc627a2162c9550e53fb320facb734179e: return a canned AuthorizationData fixture for a named test scenario (pure)

type AuthorizationDeniedMessage

type AuthorizationDeniedMessage struct {
	MessageType         MessageType `json:"message_type"`
	OriginalOperationID string      `json:"original_operation_id"`
	Reason              string      `json:"reason"`
}

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: server-to-client WebSocket message rejecting an operation due to insufficient authorization (pure)

func (AuthorizationDeniedMessage) GetMessageType

func (m AuthorizationDeniedMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for AuthorizationDeniedMessage (pure)

func (AuthorizationDeniedMessage) Validate

func (m AuthorizationDeniedMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate an AuthorizationDeniedMessage has correct type, UUID operation ID, and reason (pure)

type AuthorizationPrincipalType

type AuthorizationPrincipalType string

AuthorizationPrincipalType Type of principal: user (individual) or group

const (
	AuthorizationPrincipalTypeGroup AuthorizationPrincipalType = "group"
	AuthorizationPrincipalTypeUser  AuthorizationPrincipalType = "user"
)

Defines values for AuthorizationPrincipalType.

func (AuthorizationPrincipalType) Valid

func (e AuthorizationPrincipalType) Valid() bool

Valid indicates whether the value is a known member of the AuthorizationPrincipalType enum.

type AuthorizationRole

type AuthorizationRole string

AuthorizationRole Role: reader (view), writer (edit), owner (full control)

const (
	AuthorizationRoleOwner  AuthorizationRole = "owner"
	AuthorizationRoleReader AuthorizationRole = "reader"
	AuthorizationRoleWriter AuthorizationRole = "writer"
)

Defines values for AuthorizationRole.

func (AuthorizationRole) Valid

func (e AuthorizationRole) Valid() bool

Valid indicates whether the value is a known member of the AuthorizationRole enum.

type AuthorizeContentTokenJSONBody

type AuthorizeContentTokenJSONBody struct {
	// ClientCallback Client URL to redirect back to after the content-OAuth callback completes. Must match the server-side allow list.
	ClientCallback string `json:"client_callback"`
}

AuthorizeContentTokenJSONBody defines parameters for AuthorizeContentToken.

type AuthorizeContentTokenJSONRequestBody

type AuthorizeContentTokenJSONRequestBody AuthorizeContentTokenJSONBody

AuthorizeContentTokenJSONRequestBody defines body for AuthorizeContentToken for application/json ContentType.

type AuthorizeOAuthProviderParams

type AuthorizeOAuthProviderParams struct {
	// Idp OAuth provider identifier. Defaults to 'tmi' provider in non-production builds if not specified.
	Idp *IdpQueryParam `form:"idp,omitempty" json:"idp,omitempty"`

	// ClientCallback Client callback URL where TMI should redirect after successful OAuth completion with tokens in URL fragment (#access_token=...). If not provided, tokens are returned as JSON response. Per OAuth 2.0 implicit flow spec, tokens are in fragments to prevent logging.
	ClientCallback *ClientCallbackQueryParam `form:"client_callback,omitempty" json:"client_callback,omitempty"`

	// State CSRF protection state parameter. Recommended for security. Will be included in the callback response.
	State *StateQueryParam `form:"state,omitempty" json:"state,omitempty"`

	// LoginHint User identity hint for TMI OAuth provider. Allows specifying a desired user identity for testing and automation. Only supported by the TMI provider (ignored by production providers like Google, GitHub, etc.). Valid characters: letters, digits, periods, underscores, percent signs, plus signs, and hyphens.
	LoginHint *LoginHintQueryParam `form:"login_hint,omitempty" json:"login_hint,omitempty"`

	// Scope OAuth 2.0 scope parameter. For OpenID Connect, must include "openid". Supports "profile" and "email" scopes. Other scopes are silently ignored. Space-separated values.
	Scope ScopeQueryParam `form:"scope" json:"scope"`

	// CodeChallenge PKCE code challenge (RFC 7636) - Base64url-encoded SHA256 hash of the code_verifier. Must be 43-128 characters using unreserved characters [A-Za-z0-9-._~]. The server associates this with the authorization code for later verification during token exchange.
	CodeChallenge CodeChallengeQueryParam `form:"code_challenge" json:"code_challenge"`

	// CodeChallengeMethod PKCE code challenge method (RFC 7636) - Specifies the transformation applied to the code_verifier. Only "S256" (SHA256) is supported for security. The "plain" method is not supported.
	CodeChallengeMethod AuthorizeOAuthProviderParamsCodeChallengeMethod `form:"code_challenge_method" json:"code_challenge_method"`
}

AuthorizeOAuthProviderParams defines parameters for AuthorizeOAuthProvider.

type AuthorizeOAuthProviderParamsCodeChallengeMethod

type AuthorizeOAuthProviderParamsCodeChallengeMethod string

AuthorizeOAuthProviderParamsCodeChallengeMethod defines parameters for AuthorizeOAuthProvider.

const (
	AuthorizeOAuthProviderParamsCodeChallengeMethodS256 AuthorizeOAuthProviderParamsCodeChallengeMethod = "S256"
)

Defines values for AuthorizeOAuthProviderParamsCodeChallengeMethod.

func (AuthorizeOAuthProviderParamsCodeChallengeMethod) Valid

Valid indicates whether the value is a known member of the AuthorizeOAuthProviderParamsCodeChallengeMethod enum.

type AuthzRoleName

type AuthzRoleName string

AuthzRoleName is a named role gate. Defined values for slice 1: admin. Future slices register security_reviewer, automation, confidential_reviewer. SEM@e2de7c62a484c8859b1f6760addcf1b628ec49bb: enum of named role gates checked during authorization (pure)

const (
	RoleAuthzAdmin                AuthzRoleName = "admin"
	RoleAuthzSecurityReviewer     AuthzRoleName = "security_reviewer"
	RoleAuthzAutomation           AuthzRoleName = "automation"
	RoleAuthzConfidentialReviewer AuthzRoleName = "confidential_reviewer"
)

type AuthzRule

type AuthzRule struct {
	Ownership        Ownership
	Roles            []AuthzRoleName
	Public           bool
	Audit            string           // "required" | "optional" | ""
	SubjectAuthority SubjectAuthority // "" (any) | "invoker" | "service_account"
}

AuthzRule is the per-operation declaration sourced from x-tmi-authz. SEM@e6be8a8f816c564356a656ac18f3693ac7f10369: per-operation authorization declaration parsed from the x-tmi-authz OpenAPI extension (pure)

type AuthzTable

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

AuthzTable indexes rules by (method, normalized-path-template). Lookups against concrete request paths use template matching (e.g. /admin/users/abc -> /admin/users/{id}). SEM@7a41ed9e2527d8cce054328a84a5d9fec9804ee1: index of authorization rules keyed by HTTP method and path template (pure)

func LoadGlobalAuthzTable

func LoadGlobalAuthzTable() (*AuthzTable, error)

LoadGlobalAuthzTable parses the embedded OpenAPI spec once and caches the resulting AuthzTable. Subsequent calls return the cached value. Errors from the first call are persisted and re-returned on every subsequent call. SEM@e2de7c62a484c8859b1f6760addcf1b628ec49bb: parse the embedded OpenAPI spec into a cached global AuthzTable; return cached result on subsequent calls (mutates shared state)

func (*AuthzTable) Lookup

func (t *AuthzTable) Lookup(method, requestPath string) (AuthzRule, bool)

Lookup matches a concrete request path against the table's templates and returns the rule for (method, matched-template). Matching mirrors the strategy in findPathItem (api/openapi_middleware.go): exact match wins, otherwise the template with the most literal segments wins. SEM@7a41ed9e2527d8cce054328a84a5d9fec9804ee1: match a concrete request path against stored templates and return the authorization rule for the operation (pure)

type AutomationQueryParam

type AutomationQueryParam = bool

AutomationQueryParam defines model for AutomationQueryParam.

type BadRequest

type BadRequest = Error

BadRequest Standard error response format

type BaseContentOAuthProvider

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

BaseContentOAuthProvider is the default implementation; providers with provider-specific userinfo / scope semantics can wrap it. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: default OAuth provider implementation backed by SafeHTTPClient (struct)

func NewBaseContentOAuthProvider

func NewBaseContentOAuthProvider(id string, cfg config.ContentOAuthProviderConfig, validator *URIValidator) *BaseContentOAuthProvider

NewBaseContentOAuthProvider creates a new BaseContentOAuthProvider routing outbound OAuth calls through SafeHTTPClient with a 30s overall timeout and a 1 MiB body cap. validator MUST be non-nil; in production it is built from the operator's content_oauth allowlist (typically equal to the authorization/token URL hosts). SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build a BaseContentOAuthProvider with a 30s timeout and 1 MiB body cap (pure)

func (*BaseContentOAuthProvider) AuthorizationURL

func (p *BaseContentOAuthProvider) AuthorizationURL(state, pkceChallenge, redirectURI string) string

AuthorizationURL builds the authorization URL with PKCE and state parameters. It respects any existing query string in cfg.AuthURL and appends any provider configured ExtraAuthorizeParams (e.g. Atlassian's audience=api.atlassian.com). Standard parameters always win if a provider misconfigures an extra with the same key. SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: build the PKCE authorization URL with state, scopes, and provider-specific extra params (pure)

func (*BaseContentOAuthProvider) ExchangeCode

func (p *BaseContentOAuthProvider) ExchangeCode(ctx context.Context, code, pkceVerifier, redirectURI string) (*ContentOAuthTokenResponse, error)

ExchangeCode exchanges an authorization code for tokens using the authorization_code grant. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: exchange an authorization code for an access and refresh token via authorization_code grant

func (*BaseContentOAuthProvider) FetchAccountInfo

func (p *BaseContentOAuthProvider) FetchAccountInfo(ctx context.Context, accessToken string) (string, string, error)

FetchAccountInfo fetches the account id and label from the provider's userinfo endpoint. Returns empty strings (not an error) if UserinfoURL is not configured. The account id is taken from the first non-empty of: sub, id, account_id. The label is taken from the first non-empty of: email, username, name. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: fetch the provider account ID and label from the userinfo endpoint (reads DB)

func (*BaseContentOAuthProvider) ID

ID returns the provider identifier. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: return the provider's identifier string (pure)

func (*BaseContentOAuthProvider) Refresh

Refresh exchanges a refresh token for new tokens using the refresh_token grant. On 4xx responses (e.g., invalid_grant), an errContentOAuthPermanent is returned. On 5xx responses, a plain transient error is returned. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: exchange a refresh token for new tokens; permanent failures return a non-retryable error

func (*BaseContentOAuthProvider) RequiredScopes

func (p *BaseContentOAuthProvider) RequiredScopes() []string

RequiredScopes returns the scopes required by this provider. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: return the OAuth scopes required by this provider (pure)

func (*BaseContentOAuthProvider) Revoke

func (p *BaseContentOAuthProvider) Revoke(ctx context.Context, token string) error

Revoke revokes the given token via RFC 7009. If no RevocationURL is configured, this is a no-op and returns nil. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: revoke a token at the provider via RFC 7009; no-op when no revocation URL is configured

type BaseDiagram

type BaseDiagram struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// AutoGenerated True when the diagram was created by an automation/service-account principal. Sticky from creation.
	AutoGenerated *bool `json:"auto_generated,omitempty"`

	// ColorPalette Custom color palette for diagram elements, ordered by position
	ColorPalette *[]ColorPaletteEntry `json:"color_palette,omitempty"`

	// CreatedAt Creation timestamp (ISO3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Optional description of the diagram
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the diagram (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// Image Image data with version information
	Image *struct {
		// Svg BASE64 encoded SVG representation of the diagram, used for thumbnails and reports
		Svg *[]byte `json:"svg,omitempty"`

		// UpdateVector Version of the diagram when this SVG was generated. If not provided when svg is updated, will be auto-set to BaseDiagram.update_vector
		UpdateVector *int64 `json:"update_vector,omitempty"`
	} `json:"image,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Key-value pairs for additional diagram metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (ISO3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name of the diagram
	Name string `json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Type of diagram with version
	Type BaseDiagramType `json:"type"`

	// UpdateVector Server-managed monotonic version counter, incremented on each diagram update
	UpdateVector *int64 `json:"update_vector,omitempty"`
}

BaseDiagram Base diagram object with common properties - used for API responses

type BaseDiagramInput

type BaseDiagramInput struct {
	// ColorPalette Custom color palette for diagram elements, ordered by position
	ColorPalette *[]ColorPaletteEntry `json:"color_palette,omitempty"`

	// Description Optional description of the diagram
	Description *string `json:"description,omitempty"`

	// Image Image data with version information
	Image *struct {
		// Svg BASE64 encoded SVG representation of the diagram, used for thumbnails and reports
		Svg *[]byte `json:"svg,omitempty"`

		// UpdateVector Version of the diagram when this SVG was generated. If not provided when svg is updated, will be auto-set to BaseDiagram.update_vector
		UpdateVector *int64 `json:"update_vector,omitempty"`
	} `json:"image,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Key-value pairs for additional diagram metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// Name Name of the diagram
	Name string `json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Type of diagram with version
	Type BaseDiagramInputType `json:"type"`
}

BaseDiagramInput Base diagram input for PUT/PATCH requests - excludes readOnly server-managed fields

type BaseDiagramInputType

type BaseDiagramInputType string

BaseDiagramInputType Type of diagram with version

const (
	BaseDiagramInputTypeDFD100 BaseDiagramInputType = "DFD-1.0.0"
)

Defines values for BaseDiagramInputType.

func (BaseDiagramInputType) Valid

func (e BaseDiagramInputType) Valid() bool

Valid indicates whether the value is a known member of the BaseDiagramInputType enum.

type BaseDiagramType

type BaseDiagramType string

BaseDiagramType Type of diagram with version

const (
	BaseDiagramTypeDFD100 BaseDiagramType = "DFD-1.0.0"
)

Defines values for BaseDiagramType.

func (BaseDiagramType) Valid

func (e BaseDiagramType) Valid() bool

Valid indicates whether the value is a known member of the BaseDiagramType enum.

type BoundedExtractor

type BoundedExtractor = extract.BoundedExtractor

Type aliases re-exporting pkg/extract into the api package. The extractor logic was relocated to pkg/extract during Component Platform Plan 2 (#347) so the sandboxed worker can link it without pulling in Gin/GORM. These aliases keep the monolith's many call sites unchanged.

type BuilderContext

type BuilderContext struct {
	ReasonCode   string
	ReasonDetail string

	// ProviderID is the provider relevant to the error (e.g. "google_workspace"),
	// used to populate remediation params.
	ProviderID string

	// Caller context (the user viewing the document, not necessarily the owner).
	CallerUserEmail       string
	CallerLinkedProviders map[string]bool // provider_id -> has-active-token

	// Config-sourced values for specific remediations.
	ServiceAccountEmail string

	// Owner context (optional; used for contact_owner remediation).
	DocumentOwnerEmail string

	// MicrosoftDriveID, MicrosoftItemID, and MicrosoftApplicationObjectID are
	// populated for the share_with_application remediation. The handler
	// resolves drive/item ids from picker metadata or the Graph /shares/{id}
	// lookup done during ValidateAccess; the application object id is the
	// TMI Entra app's object id, configured at startup.
	MicrosoftDriveID             string
	MicrosoftItemID              string
	MicrosoftApplicationObjectID string
}

BuilderContext carries everything the builder needs to assemble a diagnostics object. Empty fields are treated as "not applicable" — the builder tolerates missing context. SEM@fe4cf07a3a2b954860a8df90ba211cb0919d71de: context struct carrying caller, owner, and provider info for building access diagnostic remediations (pure)

type BuiltInGroup

type BuiltInGroup struct {
	Name string
	UUID uuid.UUID
}

BuiltInGroup represents a well-known TMI group used as an authorization fixture. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: well-known TMI authorization group with a fixed name and UUID (pure)

type BulkCreateAdminSurveyMetadataJSONBody

type BulkCreateAdminSurveyMetadataJSONBody = []Metadata

BulkCreateAdminSurveyMetadataJSONBody defines parameters for BulkCreateAdminSurveyMetadata.

type BulkCreateAdminSurveyMetadataJSONRequestBody

type BulkCreateAdminSurveyMetadataJSONRequestBody = BulkCreateAdminSurveyMetadataJSONBody

BulkCreateAdminSurveyMetadataJSONRequestBody defines body for BulkCreateAdminSurveyMetadata for application/json ContentType.

type BulkCreateDiagramMetadataJSONBody

type BulkCreateDiagramMetadataJSONBody = []Metadata

BulkCreateDiagramMetadataJSONBody defines parameters for BulkCreateDiagramMetadata.

type BulkCreateDiagramMetadataJSONRequestBody

type BulkCreateDiagramMetadataJSONRequestBody = BulkCreateDiagramMetadataJSONBody

BulkCreateDiagramMetadataJSONRequestBody defines body for BulkCreateDiagramMetadata for application/json ContentType.

type BulkCreateDocumentMetadataJSONBody

type BulkCreateDocumentMetadataJSONBody = []Metadata

BulkCreateDocumentMetadataJSONBody defines parameters for BulkCreateDocumentMetadata.

type BulkCreateDocumentMetadataJSONRequestBody

type BulkCreateDocumentMetadataJSONRequestBody = BulkCreateDocumentMetadataJSONBody

BulkCreateDocumentMetadataJSONRequestBody defines body for BulkCreateDocumentMetadata for application/json ContentType.

type BulkCreateIntakeSurveyResponseMetadataJSONBody

type BulkCreateIntakeSurveyResponseMetadataJSONBody = []Metadata

BulkCreateIntakeSurveyResponseMetadataJSONBody defines parameters for BulkCreateIntakeSurveyResponseMetadata.

type BulkCreateIntakeSurveyResponseMetadataJSONRequestBody

type BulkCreateIntakeSurveyResponseMetadataJSONRequestBody = BulkCreateIntakeSurveyResponseMetadataJSONBody

BulkCreateIntakeSurveyResponseMetadataJSONRequestBody defines body for BulkCreateIntakeSurveyResponseMetadata for application/json ContentType.

type BulkCreateNoteMetadataJSONBody

type BulkCreateNoteMetadataJSONBody = []Metadata

BulkCreateNoteMetadataJSONBody defines parameters for BulkCreateNoteMetadata.

type BulkCreateNoteMetadataJSONRequestBody

type BulkCreateNoteMetadataJSONRequestBody = BulkCreateNoteMetadataJSONBody

BulkCreateNoteMetadataJSONRequestBody defines body for BulkCreateNoteMetadata for application/json ContentType.

type BulkCreateProjectMetadataJSONBody

type BulkCreateProjectMetadataJSONBody = []Metadata

BulkCreateProjectMetadataJSONBody defines parameters for BulkCreateProjectMetadata.

type BulkCreateProjectMetadataJSONRequestBody

type BulkCreateProjectMetadataJSONRequestBody = BulkCreateProjectMetadataJSONBody

BulkCreateProjectMetadataJSONRequestBody defines body for BulkCreateProjectMetadata for application/json ContentType.

type BulkCreateRepositoryMetadataJSONBody

type BulkCreateRepositoryMetadataJSONBody = []Metadata

BulkCreateRepositoryMetadataJSONBody defines parameters for BulkCreateRepositoryMetadata.

type BulkCreateRepositoryMetadataJSONRequestBody

type BulkCreateRepositoryMetadataJSONRequestBody = BulkCreateRepositoryMetadataJSONBody

BulkCreateRepositoryMetadataJSONRequestBody defines body for BulkCreateRepositoryMetadata for application/json ContentType.

type BulkCreateTeamMetadataJSONBody

type BulkCreateTeamMetadataJSONBody = []Metadata

BulkCreateTeamMetadataJSONBody defines parameters for BulkCreateTeamMetadata.

type BulkCreateTeamMetadataJSONRequestBody

type BulkCreateTeamMetadataJSONRequestBody = BulkCreateTeamMetadataJSONBody

BulkCreateTeamMetadataJSONRequestBody defines body for BulkCreateTeamMetadata for application/json ContentType.

type BulkCreateThreatMetadataJSONBody

type BulkCreateThreatMetadataJSONBody = []Metadata

BulkCreateThreatMetadataJSONBody defines parameters for BulkCreateThreatMetadata.

type BulkCreateThreatMetadataJSONRequestBody

type BulkCreateThreatMetadataJSONRequestBody = BulkCreateThreatMetadataJSONBody

BulkCreateThreatMetadataJSONRequestBody defines body for BulkCreateThreatMetadata for application/json ContentType.

type BulkCreateThreatModelAssetMetadataJSONBody

type BulkCreateThreatModelAssetMetadataJSONBody = []Metadata

BulkCreateThreatModelAssetMetadataJSONBody defines parameters for BulkCreateThreatModelAssetMetadata.

type BulkCreateThreatModelAssetMetadataJSONRequestBody

type BulkCreateThreatModelAssetMetadataJSONRequestBody = BulkCreateThreatModelAssetMetadataJSONBody

BulkCreateThreatModelAssetMetadataJSONRequestBody defines body for BulkCreateThreatModelAssetMetadata for application/json ContentType.

type BulkCreateThreatModelAssetsJSONBody

type BulkCreateThreatModelAssetsJSONBody = []AssetBase

BulkCreateThreatModelAssetsJSONBody defines parameters for BulkCreateThreatModelAssets.

type BulkCreateThreatModelAssetsJSONRequestBody

type BulkCreateThreatModelAssetsJSONRequestBody = BulkCreateThreatModelAssetsJSONBody

BulkCreateThreatModelAssetsJSONRequestBody defines body for BulkCreateThreatModelAssets for application/json ContentType.

type BulkCreateThreatModelDocumentsJSONBody

type BulkCreateThreatModelDocumentsJSONBody = []Document

BulkCreateThreatModelDocumentsJSONBody defines parameters for BulkCreateThreatModelDocuments.

type BulkCreateThreatModelDocumentsJSONRequestBody

type BulkCreateThreatModelDocumentsJSONRequestBody = BulkCreateThreatModelDocumentsJSONBody

BulkCreateThreatModelDocumentsJSONRequestBody defines body for BulkCreateThreatModelDocuments for application/json ContentType.

type BulkCreateThreatModelMetadataJSONBody

type BulkCreateThreatModelMetadataJSONBody = []Metadata

BulkCreateThreatModelMetadataJSONBody defines parameters for BulkCreateThreatModelMetadata.

type BulkCreateThreatModelMetadataJSONRequestBody

type BulkCreateThreatModelMetadataJSONRequestBody = BulkCreateThreatModelMetadataJSONBody

BulkCreateThreatModelMetadataJSONRequestBody defines body for BulkCreateThreatModelMetadata for application/json ContentType.

type BulkCreateThreatModelRepositoriesJSONBody

type BulkCreateThreatModelRepositoriesJSONBody = []Repository

BulkCreateThreatModelRepositoriesJSONBody defines parameters for BulkCreateThreatModelRepositories.

type BulkCreateThreatModelRepositoriesJSONRequestBody

type BulkCreateThreatModelRepositoriesJSONRequestBody = BulkCreateThreatModelRepositoriesJSONBody

BulkCreateThreatModelRepositoriesJSONRequestBody defines body for BulkCreateThreatModelRepositories for application/json ContentType.

type BulkCreateThreatModelThreatsJSONBody

type BulkCreateThreatModelThreatsJSONBody = []Threat

BulkCreateThreatModelThreatsJSONBody defines parameters for BulkCreateThreatModelThreats.

type BulkCreateThreatModelThreatsJSONRequestBody

type BulkCreateThreatModelThreatsJSONRequestBody = BulkCreateThreatModelThreatsJSONBody

BulkCreateThreatModelThreatsJSONRequestBody defines body for BulkCreateThreatModelThreats for application/json ContentType.

type BulkDeleteThreatModelThreatsParams

type BulkDeleteThreatModelThreatsParams struct {
	// ThreatIds Comma-separated list of threat IDs to delete (UUID format)
	ThreatIds ThreatIdsQueryParam `form:"threat_ids" json:"threat_ids"`
}

BulkDeleteThreatModelThreatsParams defines parameters for BulkDeleteThreatModelThreats.

type BulkPatchRequest

type BulkPatchRequest struct {
	// Patches Array of patch operations, each targeting a specific threat by ID
	Patches []struct {
		// Id ID of the threat to patch
		Id openapi_types.UUID `json:"id"`

		// Operations JSON Patch document as defined in RFC 6902
		Operations JsonPatchDocument `json:"operations"`
	} `json:"patches"`
}

BulkPatchRequest Request body for bulk patching multiple threats

type BulkPatchThreatModelThreatsJSONRequestBody

type BulkPatchThreatModelThreatsJSONRequestBody = BulkPatchRequest

BulkPatchThreatModelThreatsJSONRequestBody defines body for BulkPatchThreatModelThreats for application/json ContentType.

type BulkReplaceAdminSurveyMetadataJSONBody

type BulkReplaceAdminSurveyMetadataJSONBody = []Metadata

BulkReplaceAdminSurveyMetadataJSONBody defines parameters for BulkReplaceAdminSurveyMetadata.

type BulkReplaceAdminSurveyMetadataJSONRequestBody

type BulkReplaceAdminSurveyMetadataJSONRequestBody = BulkReplaceAdminSurveyMetadataJSONBody

BulkReplaceAdminSurveyMetadataJSONRequestBody defines body for BulkReplaceAdminSurveyMetadata for application/json ContentType.

type BulkReplaceDiagramMetadataJSONBody

type BulkReplaceDiagramMetadataJSONBody = []Metadata

BulkReplaceDiagramMetadataJSONBody defines parameters for BulkReplaceDiagramMetadata.

type BulkReplaceDiagramMetadataJSONRequestBody

type BulkReplaceDiagramMetadataJSONRequestBody = BulkReplaceDiagramMetadataJSONBody

BulkReplaceDiagramMetadataJSONRequestBody defines body for BulkReplaceDiagramMetadata for application/json ContentType.

type BulkReplaceDocumentMetadataJSONBody

type BulkReplaceDocumentMetadataJSONBody = []Metadata

BulkReplaceDocumentMetadataJSONBody defines parameters for BulkReplaceDocumentMetadata.

type BulkReplaceDocumentMetadataJSONRequestBody

type BulkReplaceDocumentMetadataJSONRequestBody = BulkReplaceDocumentMetadataJSONBody

BulkReplaceDocumentMetadataJSONRequestBody defines body for BulkReplaceDocumentMetadata for application/json ContentType.

type BulkReplaceIntakeSurveyResponseMetadataJSONBody

type BulkReplaceIntakeSurveyResponseMetadataJSONBody = []Metadata

BulkReplaceIntakeSurveyResponseMetadataJSONBody defines parameters for BulkReplaceIntakeSurveyResponseMetadata.

type BulkReplaceIntakeSurveyResponseMetadataJSONRequestBody

type BulkReplaceIntakeSurveyResponseMetadataJSONRequestBody = BulkReplaceIntakeSurveyResponseMetadataJSONBody

BulkReplaceIntakeSurveyResponseMetadataJSONRequestBody defines body for BulkReplaceIntakeSurveyResponseMetadata for application/json ContentType.

type BulkReplaceNoteMetadataJSONBody

type BulkReplaceNoteMetadataJSONBody = []Metadata

BulkReplaceNoteMetadataJSONBody defines parameters for BulkReplaceNoteMetadata.

type BulkReplaceNoteMetadataJSONRequestBody

type BulkReplaceNoteMetadataJSONRequestBody = BulkReplaceNoteMetadataJSONBody

BulkReplaceNoteMetadataJSONRequestBody defines body for BulkReplaceNoteMetadata for application/json ContentType.

type BulkReplaceProjectMetadataJSONBody

type BulkReplaceProjectMetadataJSONBody = []Metadata

BulkReplaceProjectMetadataJSONBody defines parameters for BulkReplaceProjectMetadata.

type BulkReplaceProjectMetadataJSONRequestBody

type BulkReplaceProjectMetadataJSONRequestBody = BulkReplaceProjectMetadataJSONBody

BulkReplaceProjectMetadataJSONRequestBody defines body for BulkReplaceProjectMetadata for application/json ContentType.

type BulkReplaceRepositoryMetadataJSONBody

type BulkReplaceRepositoryMetadataJSONBody = []Metadata

BulkReplaceRepositoryMetadataJSONBody defines parameters for BulkReplaceRepositoryMetadata.

type BulkReplaceRepositoryMetadataJSONRequestBody

type BulkReplaceRepositoryMetadataJSONRequestBody = BulkReplaceRepositoryMetadataJSONBody

BulkReplaceRepositoryMetadataJSONRequestBody defines body for BulkReplaceRepositoryMetadata for application/json ContentType.

type BulkReplaceTeamMetadataJSONBody

type BulkReplaceTeamMetadataJSONBody = []Metadata

BulkReplaceTeamMetadataJSONBody defines parameters for BulkReplaceTeamMetadata.

type BulkReplaceTeamMetadataJSONRequestBody

type BulkReplaceTeamMetadataJSONRequestBody = BulkReplaceTeamMetadataJSONBody

BulkReplaceTeamMetadataJSONRequestBody defines body for BulkReplaceTeamMetadata for application/json ContentType.

type BulkReplaceThreatMetadataJSONBody

type BulkReplaceThreatMetadataJSONBody = []Metadata

BulkReplaceThreatMetadataJSONBody defines parameters for BulkReplaceThreatMetadata.

type BulkReplaceThreatMetadataJSONRequestBody

type BulkReplaceThreatMetadataJSONRequestBody = BulkReplaceThreatMetadataJSONBody

BulkReplaceThreatMetadataJSONRequestBody defines body for BulkReplaceThreatMetadata for application/json ContentType.

type BulkReplaceThreatModelAssetMetadataJSONBody

type BulkReplaceThreatModelAssetMetadataJSONBody = []Metadata

BulkReplaceThreatModelAssetMetadataJSONBody defines parameters for BulkReplaceThreatModelAssetMetadata.

type BulkReplaceThreatModelAssetMetadataJSONRequestBody

type BulkReplaceThreatModelAssetMetadataJSONRequestBody = BulkReplaceThreatModelAssetMetadataJSONBody

BulkReplaceThreatModelAssetMetadataJSONRequestBody defines body for BulkReplaceThreatModelAssetMetadata for application/json ContentType.

type BulkReplaceThreatModelMetadataJSONBody

type BulkReplaceThreatModelMetadataJSONBody = []Metadata

BulkReplaceThreatModelMetadataJSONBody defines parameters for BulkReplaceThreatModelMetadata.

type BulkReplaceThreatModelMetadataJSONRequestBody

type BulkReplaceThreatModelMetadataJSONRequestBody = BulkReplaceThreatModelMetadataJSONBody

BulkReplaceThreatModelMetadataJSONRequestBody defines body for BulkReplaceThreatModelMetadata for application/json ContentType.

type BulkUpdateThreatModelThreatsJSONBody

type BulkUpdateThreatModelThreatsJSONBody = []ThreatBulkUpdateItem

BulkUpdateThreatModelThreatsJSONBody defines parameters for BulkUpdateThreatModelThreats.

type BulkUpdateThreatModelThreatsJSONRequestBody

type BulkUpdateThreatModelThreatsJSONRequestBody = BulkUpdateThreatModelThreatsJSONBody

BulkUpdateThreatModelThreatsJSONRequestBody defines body for BulkUpdateThreatModelThreats for application/json ContentType.

type BulkUpsertAdminSurveyMetadataJSONBody

type BulkUpsertAdminSurveyMetadataJSONBody = []Metadata

BulkUpsertAdminSurveyMetadataJSONBody defines parameters for BulkUpsertAdminSurveyMetadata.

type BulkUpsertAdminSurveyMetadataJSONRequestBody

type BulkUpsertAdminSurveyMetadataJSONRequestBody = BulkUpsertAdminSurveyMetadataJSONBody

BulkUpsertAdminSurveyMetadataJSONRequestBody defines body for BulkUpsertAdminSurveyMetadata for application/json ContentType.

type BulkUpsertDiagramMetadataJSONBody

type BulkUpsertDiagramMetadataJSONBody = []Metadata

BulkUpsertDiagramMetadataJSONBody defines parameters for BulkUpsertDiagramMetadata.

type BulkUpsertDiagramMetadataJSONRequestBody

type BulkUpsertDiagramMetadataJSONRequestBody = BulkUpsertDiagramMetadataJSONBody

BulkUpsertDiagramMetadataJSONRequestBody defines body for BulkUpsertDiagramMetadata for application/json ContentType.

type BulkUpsertDocumentMetadataJSONBody

type BulkUpsertDocumentMetadataJSONBody = []Metadata

BulkUpsertDocumentMetadataJSONBody defines parameters for BulkUpsertDocumentMetadata.

type BulkUpsertDocumentMetadataJSONRequestBody

type BulkUpsertDocumentMetadataJSONRequestBody = BulkUpsertDocumentMetadataJSONBody

BulkUpsertDocumentMetadataJSONRequestBody defines body for BulkUpsertDocumentMetadata for application/json ContentType.

type BulkUpsertIntakeSurveyResponseMetadataJSONBody

type BulkUpsertIntakeSurveyResponseMetadataJSONBody = []Metadata

BulkUpsertIntakeSurveyResponseMetadataJSONBody defines parameters for BulkUpsertIntakeSurveyResponseMetadata.

type BulkUpsertIntakeSurveyResponseMetadataJSONRequestBody

type BulkUpsertIntakeSurveyResponseMetadataJSONRequestBody = BulkUpsertIntakeSurveyResponseMetadataJSONBody

BulkUpsertIntakeSurveyResponseMetadataJSONRequestBody defines body for BulkUpsertIntakeSurveyResponseMetadata for application/json ContentType.

type BulkUpsertNoteMetadataJSONBody

type BulkUpsertNoteMetadataJSONBody = []Metadata

BulkUpsertNoteMetadataJSONBody defines parameters for BulkUpsertNoteMetadata.

type BulkUpsertNoteMetadataJSONRequestBody

type BulkUpsertNoteMetadataJSONRequestBody = BulkUpsertNoteMetadataJSONBody

BulkUpsertNoteMetadataJSONRequestBody defines body for BulkUpsertNoteMetadata for application/json ContentType.

type BulkUpsertProjectMetadataJSONRequestBody

type BulkUpsertProjectMetadataJSONRequestBody = BulkPatchRequest

BulkUpsertProjectMetadataJSONRequestBody defines body for BulkUpsertProjectMetadata for application/json ContentType.

type BulkUpsertRepositoryMetadataJSONBody

type BulkUpsertRepositoryMetadataJSONBody = []Metadata

BulkUpsertRepositoryMetadataJSONBody defines parameters for BulkUpsertRepositoryMetadata.

type BulkUpsertRepositoryMetadataJSONRequestBody

type BulkUpsertRepositoryMetadataJSONRequestBody = BulkUpsertRepositoryMetadataJSONBody

BulkUpsertRepositoryMetadataJSONRequestBody defines body for BulkUpsertRepositoryMetadata for application/json ContentType.

type BulkUpsertTeamMetadataJSONRequestBody

type BulkUpsertTeamMetadataJSONRequestBody = BulkPatchRequest

BulkUpsertTeamMetadataJSONRequestBody defines body for BulkUpsertTeamMetadata for application/json ContentType.

type BulkUpsertThreatMetadataJSONBody

type BulkUpsertThreatMetadataJSONBody = []Metadata

BulkUpsertThreatMetadataJSONBody defines parameters for BulkUpsertThreatMetadata.

type BulkUpsertThreatMetadataJSONRequestBody

type BulkUpsertThreatMetadataJSONRequestBody = BulkUpsertThreatMetadataJSONBody

BulkUpsertThreatMetadataJSONRequestBody defines body for BulkUpsertThreatMetadata for application/json ContentType.

type BulkUpsertThreatModelAssetMetadataJSONBody

type BulkUpsertThreatModelAssetMetadataJSONBody = []Metadata

BulkUpsertThreatModelAssetMetadataJSONBody defines parameters for BulkUpsertThreatModelAssetMetadata.

type BulkUpsertThreatModelAssetMetadataJSONRequestBody

type BulkUpsertThreatModelAssetMetadataJSONRequestBody = BulkUpsertThreatModelAssetMetadataJSONBody

BulkUpsertThreatModelAssetMetadataJSONRequestBody defines body for BulkUpsertThreatModelAssetMetadata for application/json ContentType.

type BulkUpsertThreatModelAssetsJSONBody

type BulkUpsertThreatModelAssetsJSONBody = []Asset

BulkUpsertThreatModelAssetsJSONBody defines parameters for BulkUpsertThreatModelAssets.

type BulkUpsertThreatModelAssetsJSONRequestBody

type BulkUpsertThreatModelAssetsJSONRequestBody = BulkUpsertThreatModelAssetsJSONBody

BulkUpsertThreatModelAssetsJSONRequestBody defines body for BulkUpsertThreatModelAssets for application/json ContentType.

type BulkUpsertThreatModelDocumentsJSONBody

type BulkUpsertThreatModelDocumentsJSONBody = []Document

BulkUpsertThreatModelDocumentsJSONBody defines parameters for BulkUpsertThreatModelDocuments.

type BulkUpsertThreatModelDocumentsJSONRequestBody

type BulkUpsertThreatModelDocumentsJSONRequestBody = BulkUpsertThreatModelDocumentsJSONBody

BulkUpsertThreatModelDocumentsJSONRequestBody defines body for BulkUpsertThreatModelDocuments for application/json ContentType.

type BulkUpsertThreatModelMetadataJSONBody

type BulkUpsertThreatModelMetadataJSONBody = []Metadata

BulkUpsertThreatModelMetadataJSONBody defines parameters for BulkUpsertThreatModelMetadata.

type BulkUpsertThreatModelMetadataJSONRequestBody

type BulkUpsertThreatModelMetadataJSONRequestBody = BulkUpsertThreatModelMetadataJSONBody

BulkUpsertThreatModelMetadataJSONRequestBody defines body for BulkUpsertThreatModelMetadata for application/json ContentType.

type BulkUpsertThreatModelRepositoriesJSONBody

type BulkUpsertThreatModelRepositoriesJSONBody = []Repository

BulkUpsertThreatModelRepositoriesJSONBody defines parameters for BulkUpsertThreatModelRepositories.

type BulkUpsertThreatModelRepositoriesJSONRequestBody

type BulkUpsertThreatModelRepositoriesJSONRequestBody = BulkUpsertThreatModelRepositoriesJSONBody

BulkUpsertThreatModelRepositoriesJSONRequestBody defines body for BulkUpsertThreatModelRepositories for application/json ContentType.

type CVSSScore

type CVSSScore struct {
	// Score CVSS score (0.0-10.0)
	Score float32 `json:"score"`

	// Vector CVSS vector string (e.g., CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
	Vector string `json:"vector"`
}

CVSSScore CVSS vector and score pair

type CacheInvalidator

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

CacheInvalidator handles complex cache invalidation scenarios SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: Redis-backed cache invalidation coordinator for entity and paginated-list caches

func NewCacheInvalidator

func NewCacheInvalidator(redis *db.RedisDB, cache *CacheService) *CacheInvalidator

NewCacheInvalidator creates a new cache invalidator SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build a CacheInvalidator wired to Redis and a CacheService (pure)

func (*CacheInvalidator) BulkInvalidate

func (ci *CacheInvalidator) BulkInvalidate(ctx context.Context, events []InvalidationEvent) error

BulkInvalidate handles bulk cache invalidation for multiple entities SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: process a batch of invalidation events grouped by strategy (mutates shared state)

func (*CacheInvalidator) GetInvalidationPattern

func (ci *CacheInvalidator) GetInvalidationPattern(entityType, entityID, parentType, parentID string) []string

GetInvalidationPattern returns cache key patterns that would be affected by an entity change SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: return Redis key patterns affected by a change to the given entity and parent (pure)

func (*CacheInvalidator) InvalidateAllRelatedCaches

func (ci *CacheInvalidator) InvalidateAllRelatedCaches(ctx context.Context, threatModelID string) error

InvalidateAllRelatedCaches performs comprehensive cache invalidation for a threat model SEM@b226389b316426e5d229ed94aa3a29dff80e46b1: evict all caches for a threat model and its sub-resource lists (mutates shared state)

func (*CacheInvalidator) InvalidatePermissionRelatedCaches

func (ci *CacheInvalidator) InvalidatePermissionRelatedCaches(ctx context.Context, threatModelID string) error

InvalidatePermissionRelatedCaches invalidates caches when permissions change SEM@b226389b316426e5d229ed94aa3a29dff80e46b1: evict auth data and threat model caches when threat model permissions change (mutates shared state)

func (*CacheInvalidator) InvalidateSubResourceChange

func (ci *CacheInvalidator) InvalidateSubResourceChange(ctx context.Context, event InvalidationEvent) error

InvalidateSubResourceChange handles cache invalidation when a sub-resource changes SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: dispatch a cache invalidation event according to its strategy (mutates shared state)

type CacheService

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

CacheService provides caching functionality for sub-resources SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: Redis-backed cache for threat model sub-resources and authorization data (pure)

var GlobalCacheService *CacheService

GlobalCacheService is the package-level cache service instance, set during server initialization. Used by middleware and store methods that don't have dependency-injected cache references. Nil-safe: all callers check for nil before use.

func NewCacheService

func NewCacheService(redis *db.RedisDB) *CacheService

NewCacheService creates a new cache service instance SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build a CacheService wired to a Redis connection and key builder (pure)

func (*CacheService) CacheAsset

func (cs *CacheService) CacheAsset(ctx context.Context, asset *Asset) error

CacheAsset caches an asset SEM@f2c738b899d06c4246bd8283b568260c596d5168: store an asset in Redis with sub-resource TTL (mutates shared state)

func (*CacheService) CacheAuthData

func (cs *CacheService) CacheAuthData(ctx context.Context, threatModelID string, authData AuthorizationData) error

CacheAuthData caches authorization data for a threat model SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: store authorization data for a threat model in Redis with auth TTL (mutates shared state)

func (*CacheService) CacheCells

func (cs *CacheService) CacheCells(ctx context.Context, diagramID string, cells []Cell) error

CacheCells caches diagram cells collection SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: store a diagram's cells collection in Redis with diagram TTL (mutates shared state)

func (*CacheService) CacheDocument

func (cs *CacheService) CacheDocument(ctx context.Context, document *Document) error

CacheDocument caches a document SEM@98c83c6a9092288eead710533517e486c44239b2: store a document in Redis with sub-resource TTL (mutates shared state)

func (*CacheService) CacheList

func (cs *CacheService) CacheList(ctx context.Context, entityType, parentID string, offset, limit int, data any) error

CacheList caches a paginated list result SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: store a paginated list result in Redis keyed by entity type, parent, and page params (mutates shared state)

func (*CacheService) CacheMetadata

func (cs *CacheService) CacheMetadata(ctx context.Context, entityType, entityID string, metadata []Metadata) error

CacheMetadata caches metadata collection for an entity SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: store a metadata collection for an entity in Redis with metadata TTL (mutates shared state)

func (*CacheService) CacheMiddlewareAuth

func (cs *CacheService) CacheMiddlewareAuth(ctx context.Context, threatModelID string, data MiddlewareAuthData) error

CacheMiddlewareAuth caches lightweight auth data for middleware SEM@2ec29b7908cd546e20f3bbf1ad51b2c76e52c70d: store lightweight middleware auth data for a threat model in Redis with auth TTL (mutates shared state)

func (*CacheService) CacheNote

func (cs *CacheService) CacheNote(ctx context.Context, note *Note) error

CacheNote caches a note SEM@bc24b01d8fe51390e6178a0cbe35e701f76556ce: store a note in Redis with sub-resource TTL (mutates shared state)

func (*CacheService) CacheRepository

func (cs *CacheService) CacheRepository(ctx context.Context, repository *Repository) error

CacheRepository caches a repository code entry SEM@98c83c6a9092288eead710533517e486c44239b2: store a repository entry in Redis with sub-resource TTL (mutates shared state)

func (*CacheService) CacheThreat

func (cs *CacheService) CacheThreat(ctx context.Context, threat *Threat) error

CacheThreat caches an individual threat with write-through strategy SEM@98c83c6a9092288eead710533517e486c44239b2: store a threat in Redis with sub-resource TTL (mutates shared state)

func (*CacheService) CacheThreatModelResponse

func (cs *CacheService) CacheThreatModelResponse(ctx context.Context, id string, tm *ThreatModel) error

CacheThreatModelResponse caches a full threat model API response SEM@b226389b316426e5d229ed94aa3a29dff80e46b1: store a full threat model API response in Redis with threat-model TTL (mutates shared state)

func (*CacheService) GetCachedAsset

func (cs *CacheService) GetCachedAsset(ctx context.Context, assetID string) (*Asset, error)

GetCachedAsset retrieves a cached asset SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch a cached asset from Redis, returning nil on cache miss (reads DB)

func (*CacheService) GetCachedAuthData

func (cs *CacheService) GetCachedAuthData(ctx context.Context, threatModelID string) (*AuthorizationData, error)

GetCachedAuthData retrieves cached authorization data SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch cached authorization data for a threat model from Redis, returning nil on miss (reads DB)

func (*CacheService) GetCachedCells

func (cs *CacheService) GetCachedCells(ctx context.Context, diagramID string) ([]Cell, error)

GetCachedCells retrieves cached diagram cells SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch cached diagram cells from Redis, returning nil on cache miss (reads DB)

func (*CacheService) GetCachedDocument

func (cs *CacheService) GetCachedDocument(ctx context.Context, documentID string) (*Document, error)

GetCachedDocument retrieves a cached document SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch a cached document from Redis, returning nil on cache miss (reads DB)

func (*CacheService) GetCachedList

func (cs *CacheService) GetCachedList(ctx context.Context, entityType, parentID string, offset, limit int, result any) error

GetCachedList retrieves a cached paginated list result SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch a cached paginated list from Redis, deserializing into result; nil error on miss (reads DB)

func (*CacheService) GetCachedMetadata

func (cs *CacheService) GetCachedMetadata(ctx context.Context, entityType, entityID string) ([]Metadata, error)

GetCachedMetadata retrieves cached metadata for an entity SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch cached metadata for an entity from Redis, returning nil on cache miss (reads DB)

func (*CacheService) GetCachedMiddlewareAuth

func (cs *CacheService) GetCachedMiddlewareAuth(ctx context.Context, threatModelID string) (*MiddlewareAuthData, error)

GetCachedMiddlewareAuth retrieves cached middleware auth data SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch cached middleware auth data for a threat model from Redis, returning nil on miss (reads DB)

func (*CacheService) GetCachedNote

func (cs *CacheService) GetCachedNote(ctx context.Context, noteID string) (*Note, error)

GetCachedNote retrieves a cached note SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch a cached note from Redis, returning nil on cache miss (reads DB)

func (*CacheService) GetCachedRepository

func (cs *CacheService) GetCachedRepository(ctx context.Context, repositoryID string) (*Repository, error)

GetCachedRepository retrieves a cached repository code entry SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch a cached repository entry from Redis, returning nil on cache miss (reads DB)

func (*CacheService) GetCachedThreat

func (cs *CacheService) GetCachedThreat(ctx context.Context, threatID string) (*Threat, error)

GetCachedThreat retrieves a cached threat SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch a cached threat from Redis, returning nil on cache miss (reads DB)

func (*CacheService) GetCachedThreatModelResponse

func (cs *CacheService) GetCachedThreatModelResponse(ctx context.Context, id string) (*ThreatModel, error)

GetCachedThreatModelResponse retrieves a cached threat model response SEM@1f8a861705b8907dc184e3db47d54cbe24222ef9: fetch a cached full threat model response from Redis, returning nil on cache miss (reads DB)

func (*CacheService) InvalidateAuthData

func (cs *CacheService) InvalidateAuthData(ctx context.Context, threatModelID string) error

InvalidateAuthData removes authorization data cache SEM@2ec29b7908cd546e20f3bbf1ad51b2c76e52c70d: delete authorization and middleware auth cache entries for a threat model from Redis (mutates shared state)

func (*CacheService) InvalidateEntity

func (cs *CacheService) InvalidateEntity(ctx context.Context, entityType, entityID string) error

InvalidateEntity removes an entity from cache SEM@cdbe48c974fb76e1161972733b30bb0d1c02c3b1: delete a typed entity from Redis cache by entity type and ID (mutates shared state)

func (*CacheService) InvalidateMetadata

func (cs *CacheService) InvalidateMetadata(ctx context.Context, entityType, entityID string) error

InvalidateMetadata removes metadata cache for an entity SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: delete metadata cache for an entity from Redis (mutates shared state)

func (*CacheService) InvalidateMiddlewareAuth

func (cs *CacheService) InvalidateMiddlewareAuth(ctx context.Context, threatModelID string) error

InvalidateMiddlewareAuth invalidates middleware auth cache for a threat model SEM@2ec29b7908cd546e20f3bbf1ad51b2c76e52c70d: delete middleware auth cache entry for a threat model from Redis (mutates shared state)

func (*CacheService) InvalidateThreatModelResponse

func (cs *CacheService) InvalidateThreatModelResponse(ctx context.Context, id string) error

InvalidateThreatModelResponse invalidates the response cache for a threat model SEM@b226389b316426e5d229ed94aa3a29dff80e46b1: delete the response cache entry for a threat model from Redis (mutates shared state)

type CacheTestHelper

type CacheTestHelper struct {
	Cache       *CacheService
	Invalidator *CacheInvalidator
	RedisClient *db.RedisDB
	TestContext context.Context
	KeyBuilder  *db.RedisKeyBuilder
}

CacheTestHelper provides utilities for testing Redis cache functionality SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: test utility bundling a CacheService, invalidator, and Redis client for cache integration tests (pure)

func NewCacheTestHelper

func NewCacheTestHelper(cache *CacheService, invalidator *CacheInvalidator, redisClient *db.RedisDB) *CacheTestHelper

NewCacheTestHelper creates a new cache test helper SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build a CacheTestHelper wiring together the cache service, invalidator, and Redis client (pure)

func (*CacheTestHelper) CacheTestDocument

func (h *CacheTestHelper) CacheTestDocument(t *testing.T, document *Document)

CacheTestDocument caches a document for testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: store a document into the test cache, failing the test on error

func (*CacheTestHelper) CacheTestRepository

func (h *CacheTestHelper) CacheTestRepository(t *testing.T, repository *Repository)

CacheTestRepository caches a repository for testing SEM@98c83c6a9092288eead710533517e486c44239b2: store a repository into the test cache, failing the test on error

func (*CacheTestHelper) CacheTestThreat

func (h *CacheTestHelper) CacheTestThreat(t *testing.T, threat *Threat)

CacheTestThreat caches a threat for testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: store a threat in the Redis cache for test setup (mutates shared state)

func (*CacheTestHelper) ClearAllTestCache

func (h *CacheTestHelper) ClearAllTestCache(t *testing.T)

ClearAllTestCache clears all test cache data SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: delete all test cache entries across every entity-type namespace (mutates shared state)

func (*CacheTestHelper) ClearDocumentCache

func (h *CacheTestHelper) ClearDocumentCache(t *testing.T, documentID string)

ClearDocumentCache clears document cache for testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: delete a document's Redis cache entry by ID for test isolation (mutates shared state)

func (*CacheTestHelper) ClearRepositoryCache

func (h *CacheTestHelper) ClearRepositoryCache(t *testing.T, repositoryID string)

ClearRepositoryCache clears repository cache for testing SEM@98c83c6a9092288eead710533517e486c44239b2: delete a repository's Redis cache entry by ID for test isolation (mutates shared state)

func (*CacheTestHelper) ClearThreatCache

func (h *CacheTestHelper) ClearThreatCache(t *testing.T, threatID string)

ClearThreatCache clears threat cache for testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: delete a threat's Redis cache entry by ID for test isolation (mutates shared state)

func (*CacheTestHelper) GetCacheStats

func (h *CacheTestHelper) GetCacheStats(t *testing.T) map[string]any

GetCacheStats returns cache statistics for testing SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: fetch raw Redis INFO stats for cache performance inspection (reads DB)

func (*CacheTestHelper) SetupTestCache

func (h *CacheTestHelper) SetupTestCache(t *testing.T)

SetupTestCache initializes cache with test data SEM@98c83c6a9092288eead710533517e486c44239b2: populate the Redis cache with standard sub-resource test fixtures (mutates shared state)

func (*CacheTestHelper) TestCacheAuthOperations

func (h *CacheTestHelper) TestCacheAuthOperations(t *testing.T, threatModelID string)

TestCacheAuthOperations tests caching operations for authorization data SEM@d628c72c0cdb096a8e1e541018253b05694edeab: validate authorization data cache store, retrieval, and full invalidation (pure)

func (*CacheTestHelper) TestCacheConsistency

func (h *CacheTestHelper) TestCacheConsistency(t *testing.T, threatModelID string)

TestCacheConsistency tests cache consistency across operations SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: validate that overwriting a cached threat reflects the updated value (reads DB)

func (*CacheTestHelper) TestCacheDocumentOperations

func (h *CacheTestHelper) TestCacheDocumentOperations(t *testing.T, scenarios []CacheTestScenario)

TestCacheDocumentOperations tests caching operations for documents SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: validate document cache hit, miss, and invalidation across test scenarios (pure)

func (*CacheTestHelper) TestCacheInvalidationStrategies

func (h *CacheTestHelper) TestCacheInvalidationStrategies(t *testing.T, threatModelID string)

TestCacheInvalidationStrategies tests different invalidation strategies SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: validate immediate cache invalidation across multiple entity-type strategies (pure)

func (*CacheTestHelper) TestCacheMetadataOperations

func (h *CacheTestHelper) TestCacheMetadataOperations(t *testing.T, entityType, entityID string)

TestCacheMetadataOperations tests caching operations for metadata SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: validate metadata cache store, retrieval, and invalidation for an entity (pure)

func (*CacheTestHelper) TestCacheRepositoryOperations

func (h *CacheTestHelper) TestCacheRepositoryOperations(t *testing.T, scenarios []CacheTestScenario)

TestCacheRepositoryOperations tests caching operations for repositories SEM@98c83c6a9092288eead710533517e486c44239b2: validate repository cache hit, miss, and invalidation across test scenarios (pure)

func (*CacheTestHelper) TestCacheTTLBehavior

func (h *CacheTestHelper) TestCacheTTLBehavior(t *testing.T, scenarios []CacheTestScenario)

TestCacheTTLBehavior tests TTL behavior for cached items SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: validate that cached entries expire after their configured TTL (reads DB)

func (*CacheTestHelper) TestCacheThreatOperations

func (h *CacheTestHelper) TestCacheThreatOperations(t *testing.T, scenarios []CacheTestScenario)

TestCacheThreatOperations tests caching operations for threats SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: validate threat cache hit, miss, and invalidation across test scenarios (pure)

func (*CacheTestHelper) VerifyCacheMetrics

func (h *CacheTestHelper) VerifyCacheMetrics(t *testing.T, expectedHitRatio float64)

VerifyCacheMetrics verifies cache performance metrics SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: validate that the cache service is responsive by performing a read-write probe (reads DB)

type CacheTestScenario

type CacheTestScenario struct {
	Description     string
	EntityType      string
	EntityID        string
	ThreatModelID   string
	ExpectedHit     bool
	ExpectedMiss    bool
	TTL             time.Duration
	ShouldExpire    bool
	InvalidateAfter bool
}

CacheTestScenario defines a test scenario for cache testing SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: declarative specification of a single cache test case including hit/miss/TTL/invalidation expectations (pure)

func SetupCacheTestScenarios

func SetupCacheTestScenarios() []CacheTestScenario

SetupCacheTestScenarios returns common cache test scenarios SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the standard set of hit, miss, invalidation, and TTL cache test scenarios (pure)

type CacheWarmer

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

CacheWarmer handles proactive cache warming for frequently accessed data SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: proactively populate the cache with frequently accessed threat model data on a schedule (mutates shared state)

func NewCacheWarmer

func NewCacheWarmer(
	db *sql.DB,
	cache *CacheService,
	threatStore ThreatRepository,
	documentStore DocumentRepository,
	repositoryStore RepositoryRepository,
	metadataStore MetadataRepository,
) *CacheWarmer

NewCacheWarmer creates a new cache warmer instance SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a CacheWarmer wired to the given cache service and entity repositories (pure)

func (*CacheWarmer) DisableWarming

func (cw *CacheWarmer) DisableWarming()

DisableWarming disables cache warming SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: disable proactive cache warming (mutates shared state)

func (*CacheWarmer) EnableWarming

func (cw *CacheWarmer) EnableWarming()

EnableWarming enables cache warming SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: enable proactive cache warming (mutates shared state)

func (*CacheWarmer) GetWarmingStats

func (cw *CacheWarmer) GetWarmingStats() WarmingStats

GetWarmingStats returns current warming statistics SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: return a snapshot of cache warming statistics (pure)

func (*CacheWarmer) IsWarmingEnabled

func (cw *CacheWarmer) IsWarmingEnabled() bool

IsWarmingEnabled returns whether cache warming is enabled SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: report whether proactive cache warming is currently enabled (pure)

func (*CacheWarmer) SetWarmingInterval

func (cw *CacheWarmer) SetWarmingInterval(interval time.Duration)

SetWarmingInterval configures the proactive warming interval SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: update the proactive cache warming interval (mutates shared state)

func (*CacheWarmer) StartProactiveWarming

func (cw *CacheWarmer) StartProactiveWarming(ctx context.Context) error

StartProactiveWarming starts the proactive cache warming process SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: start the background cache warming loop on a configured interval (mutates shared state)

func (*CacheWarmer) StopProactiveWarming

func (cw *CacheWarmer) StopProactiveWarming()

StopProactiveWarming stops the proactive cache warming process SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: stop the background cache warming goroutine and disable warming (mutates shared state)

func (*CacheWarmer) WarmFrequentlyAccessedData

func (cw *CacheWarmer) WarmFrequentlyAccessedData(ctx context.Context) error

WarmFrequentlyAccessedData warms cache with frequently accessed data SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: warm cache with recent threat models, auth data, and metadata in one pass (reads DB)

func (*CacheWarmer) WarmOnDemandRequest

func (cw *CacheWarmer) WarmOnDemandRequest(ctx context.Context, request WarmingRequest) error

WarmOnDemandRequest handles on-demand cache warming requests SEM@cdbe48c974fb76e1161972733b30bb0d1c02c3b1: dispatch a targeted cache warm for a specific entity based on request type (reads DB)

func (*CacheWarmer) WarmThreatModelData

func (cw *CacheWarmer) WarmThreatModelData(ctx context.Context, threatModelID string) error

WarmThreatModelData warms cache with all data for a specific threat model SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: concurrently warm threats, documents, sources, and auth data for a threat model (reads DB)

type Cell

type Cell struct {
	// Data Flexible data storage compatible with X6, with reserved metadata namespace
	Data *Cell_Data `json:"data,omitempty"`

	// Id Unique identifier of the cell (UUID)
	Id openapi_types.UUID `json:"id"`

	// Shape Shape type identifier that determines cell structure and behavior
	Shape string `json:"shape"`
}

Cell Base schema for all diagram cells (nodes and edges). Contains common properties shared by Node and Edge types.

type CellIdQueryParam

type CellIdQueryParam = openapi_types.UUID

CellIdQueryParam defines model for CellIdQueryParam.

type CellOperation

type CellOperation struct {
	ID        string                 `json:"id"`
	Operation string                 `json:"operation"`
	Data      *DfdDiagram_Cells_Item `json:"data,omitempty"` // Union type: Node | Edge
}

CellOperation represents a single cell operation (add/update/remove) SEM@be6cc4edcc9140493267132a7d584481845e0dfe: single add/update/remove operation targeting a diagram cell by UUID (pure)

func (CellOperation) Validate

func (op CellOperation) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a CellOperation has UUID id, valid operation type, and consistent cell data (pure)

type CellOperationProcessor

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

CellOperationProcessor processes cell operations with validation and conflict detection SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: data type that validates and applies cell operations against a diagram store (pure)

func NewCellOperationProcessor

func NewCellOperationProcessor(store DiagramStoreInterface) *CellOperationProcessor

NewCellOperationProcessor creates a new cell operation processor SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: build a CellOperationProcessor bound to the given diagram store (pure)

func (*CellOperationProcessor) ProcessCellOperations

func (cop *CellOperationProcessor) ProcessCellOperations(diagramID string, operation CellPatchOperation) (*OperationValidationResult, error)

ProcessCellOperations processes a batch of cell operations with full validation SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: validate and persist a batch of cell patch operations, saving the diagram if state changed (mutates shared state)

type CellPatchOperation

type CellPatchOperation struct {
	Type  string          `json:"type"`
	Cells []CellOperation `json:"cells"`
}

CellPatchOperation mirrors REST PATCH operations for cells with batch support SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: batch patch payload for one or more diagram cell operations (pure)

func ConvertJSONPatchToCellOperations

func ConvertJSONPatchToCellOperations(operations []PatchOperation) (*CellPatchOperation, error)

ConvertJSONPatchToCellOperations converts standard JSON Patch operations to CellPatchOperation format This enables code reuse between REST PATCH endpoints and WebSocket operations SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: convert JSON Patch operations targeting cells into the WebSocket CellPatchOperation format (pure)

func (CellPatchOperation) Validate

func (op CellPatchOperation) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a CellPatchOperation has patch type and at least one valid cell operation (pure)

type Cell_Data

type Cell_Data struct {
	// UnderscoreMetadata Reserved namespace for structured business metadata
	UnderscoreMetadata *[]Metadata `json:"_metadata,omitempty"`

	// DataAssets References to Asset IDs associated with this cell. Each UUID must reference an existing Asset in the same threat model.
	DataAssets *[]openapi_types.UUID `json:"data_assets,omitempty"`

	// SecurityBoundary Indicates whether this cell represents a security boundary in the threat model
	SecurityBoundary     *bool                  `json:"security_boundary,omitempty"`
	AdditionalProperties map[string]interface{} `json:"-"`
}

Cell_Data Flexible data storage compatible with X6, with reserved metadata namespace

func (Cell_Data) Get

func (a Cell_Data) Get(fieldName string) (value interface{}, found bool)

Getter for additional properties for Cell_Data. Returns the specified element and whether it was found

func (Cell_Data) MarshalJSON

func (a Cell_Data) MarshalJSON() ([]byte, error)

Override default JSON handling for Cell_Data to handle AdditionalProperties

func (*Cell_Data) Set

func (a *Cell_Data) Set(fieldName string, value interface{})

Setter for additional properties for Cell_Data

func (*Cell_Data) UnmarshalJSON

func (a *Cell_Data) UnmarshalJSON(b []byte) error

Override default JSON handling for Cell_Data to handle AdditionalProperties

type ChallengeQueryParam

type ChallengeQueryParam = string

ChallengeQueryParam defines model for ChallengeQueryParam.

type ChangePresenterMessage

type ChangePresenterMessage struct {
	MessageType    MessageType `json:"message_type"`
	InitiatingUser User        `json:"initiating_user"`
	NewPresenter   User        `json:"new_presenter"`
}

SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: server-to-client WebSocket event announcing presenter role transfer to all participants (pure)

func (ChangePresenterMessage) GetMessageType

func (m ChangePresenterMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for ChangePresenterMessage (pure)

func (ChangePresenterMessage) Validate

func (m ChangePresenterMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a ChangePresenterMessage has correct type and provider IDs for both users (pure)

type ChangePresenterRequest

type ChangePresenterRequest struct {
	MessageType  MessageType `json:"message_type"`
	NewPresenter User        `json:"new_presenter"`
}

ChangePresenterRequest is sent by client to change presenter SEM@4c26178bb9014e2fcc62e1a29307dad2c36b6ada: client-to-server WebSocket request to transfer the presenter role to another user (pure)

func (ChangePresenterRequest) GetMessageType

func (m ChangePresenterRequest) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for ChangePresenterRequest (pure)

func (ChangePresenterRequest) Validate

func (m ChangePresenterRequest) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a ChangePresenterRequest has correct type and identifiable new presenter (pure)

type ChangePresenterRequestHandler

type ChangePresenterRequestHandler struct{}

ChangePresenterRequestHandler handles change presenter request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: handle a change_presenter_request WebSocket message for presenter role transfer (pure)

func (*ChangePresenterRequestHandler) HandleMessage

func (h *ChangePresenterRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: dispatch a change presenter WebSocket message to the diagram session (mutates shared state)

func (*ChangePresenterRequestHandler) MessageType

func (h *ChangePresenterRequestHandler) MessageType() string

SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: return the change_presenter_request message type discriminator (pure)

type ClientCallbackQueryParam

type ClientCallbackQueryParam = string

ClientCallbackQueryParam defines model for ClientCallbackQueryParam.

type ClientConfig

type ClientConfig struct {
	// ContentProviders Content providers the server has configured. Order matches server-side registration order.
	ContentProviders *[]ContentProvider `json:"content_providers,omitempty"`

	// Features Feature flags indicating enabled functionality
	Features *struct {
		// SamlEnabled Whether SAML authentication is enabled
		SamlEnabled *bool `json:"saml_enabled,omitempty"`

		// WebhooksEnabled Whether webhook subscriptions are enabled
		WebhooksEnabled *bool `json:"webhooks_enabled,omitempty"`

		// WebsocketEnabled Whether WebSocket collaboration is enabled
		WebsocketEnabled *bool `json:"websocket_enabled,omitempty"`
	} `json:"features,omitempty"`

	// Limits System limits and quotas
	Limits *struct {
		// MaxDiagramParticipants Maximum participants per collaboration session
		MaxDiagramParticipants *int `json:"max_diagram_participants,omitempty"`

		// MaxFileUploadMb Maximum file upload size in megabytes
		MaxFileUploadMb *int `json:"max_file_upload_mb,omitempty"`
	} `json:"limits,omitempty"`

	// Operator Operator information
	Operator *struct {
		// Contact Contact information for the operator
		Contact *string `json:"contact,omitempty"`

		// Jurisdiction Legal jurisdiction under which the service operates
		Jurisdiction *string `json:"jurisdiction,omitempty"`

		// Name Name of the service operator
		Name *string `json:"name,omitempty"`
	} `json:"operator,omitempty"`

	// Ui UI configuration defaults
	Ui *struct {
		// DefaultTheme Default UI theme
		DefaultTheme *ClientConfigUiDefaultTheme `json:"default_theme,omitempty"`
	} `json:"ui,omitempty"`
}

ClientConfig Client configuration for tmi-ux and other client applications

type ClientConfigUiDefaultTheme

type ClientConfigUiDefaultTheme string

ClientConfigUiDefaultTheme Default UI theme

const (
	Auto  ClientConfigUiDefaultTheme = "auto"
	Dark  ClientConfigUiDefaultTheme = "dark"
	Light ClientConfigUiDefaultTheme = "light"
)

Defines values for ClientConfigUiDefaultTheme.

func (ClientConfigUiDefaultTheme) Valid

func (e ClientConfigUiDefaultTheme) Valid() bool

Valid indicates whether the value is a known member of the ClientConfigUiDefaultTheme enum.

type ClientCredentialInfo

type ClientCredentialInfo struct {
	// ClientId OAuth 2.0 client ID (format: tmi_cc_*)
	ClientId string `json:"client_id"`

	// CreatedAt Creation timestamp (ISO 8601)
	CreatedAt time.Time `json:"created_at"`

	// Description Optional description of the credential's purpose
	Description *string `json:"description,omitempty"`

	// ExpiresAt Optional expiration timestamp (ISO 8601)
	ExpiresAt *time.Time `json:"expires_at,omitempty"`

	// Id Unique identifier for the credential
	Id openapi_types.UUID `json:"id"`

	// IsActive Whether the credential is active
	IsActive bool `json:"is_active"`

	// LastUsedAt Last time this credential was used (ISO 8601)
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`

	// ModifiedAt Last modification timestamp (ISO 8601)
	ModifiedAt time.Time `json:"modified_at"`

	// Name Human-readable name for the credential
	Name string `json:"name"`
}

ClientCredentialInfo Client credential information without the secret

type ClientCredentialInfoInternal

type ClientCredentialInfoInternal struct {
	ID          uuid.UUID  `json:"id"`
	ClientID    string     `json:"client_id"`
	Name        string     `json:"name"`
	Description string     `json:"description"`
	IsActive    bool       `json:"is_active"`
	LastUsedAt  *time.Time `json:"last_used_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	ModifiedAt  time.Time  `json:"modified_at"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
}

ClientCredentialInfoInternal represents a client credential without the secret (internal type) SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: client credential metadata without the secret for listing responses (pure)

type ClientCredentialQuotaStore

type ClientCredentialQuotaStore interface {
	// GetClientCredentialQuota retrieves the maximum number of credentials allowed for a user
	GetClientCredentialQuota(ctx context.Context, userUUID uuid.UUID) (int, error)

	// GetClientCredentialCount retrieves the current number of active credentials for a user
	GetClientCredentialCount(ctx context.Context, userUUID uuid.UUID) (int, error)

	// CheckClientCredentialQuota verifies if a user can create a new credential
	CheckClientCredentialQuota(ctx context.Context, userUUID uuid.UUID) error
}

ClientCredentialQuotaStore defines the interface for client credential quota operations SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: interface for fetching and enforcing per-user client credential quota limits (pure)

var GlobalClientCredentialQuotaStore ClientCredentialQuotaStore

GlobalClientCredentialQuotaStore is the global singleton for client credential quota

type ClientCredentialResponse

type ClientCredentialResponse struct {
	// ClientId OAuth 2.0 client ID (format: tmi_cc_*)
	ClientId string `json:"client_id"`

	// ClientSecret OAuth 2.0 client secret - ONLY returned at creation time, cannot be retrieved later
	ClientSecret string `json:"client_secret"`

	// CreatedAt Creation timestamp (ISO 8601)
	CreatedAt time.Time `json:"created_at"`

	// Description Optional description of the credential's purpose
	Description *string `json:"description,omitempty"`

	// ExpiresAt Optional expiration timestamp (ISO 8601)
	ExpiresAt *time.Time `json:"expires_at,omitempty"`

	// Id Unique identifier for the credential
	Id openapi_types.UUID `json:"id"`

	// Name Human-readable name for the credential
	Name string `json:"name"`
}

ClientCredentialResponse Response from creating a client credential. WARNING: The client_secret is ONLY returned once and cannot be retrieved later.

type ClientCredentialService

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

ClientCredentialService handles client credential generation and management SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: service for creating, listing, and revoking machine-to-machine client credentials (reads DB)

func NewClientCredentialService

func NewClientCredentialService(authService *auth.Service) *ClientCredentialService

NewClientCredentialService creates a new client credential service SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: build a ClientCredentialService from an auth service (pure)

func (*ClientCredentialService) Create

Create generates a new client credential for the specified owner The client_secret is only returned once and cannot be retrieved later (GitHub PAT pattern) SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: generate and store a new bcrypt-hashed client credential, returning the plaintext secret once (reads DB)

func (*ClientCredentialService) Deactivate

func (s *ClientCredentialService) Deactivate(ctx context.Context, credID uuid.UUID, ownerUUID uuid.UUID) error

Deactivate soft-deletes a client credential (sets is_active = false) SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: soft-disable a client credential by marking it inactive (reads DB)

func (*ClientCredentialService) Delete

func (s *ClientCredentialService) Delete(ctx context.Context, credID uuid.UUID, ownerUUID uuid.UUID) error

Delete permanently deletes a client credential SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: permanently delete a client credential by ID and owner (reads DB)

func (*ClientCredentialService) List

List retrieves all client credentials for the specified owner (without secrets) SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: list all client credentials for an owner, excluding secrets (reads DB)

type CodeChallengeMethodQueryParam

type CodeChallengeMethodQueryParam string

CodeChallengeMethodQueryParam defines model for CodeChallengeMethodQueryParam.

const (
	CodeChallengeMethodQueryParamS256 CodeChallengeMethodQueryParam = "S256"
)

Defines values for CodeChallengeMethodQueryParam.

func (CodeChallengeMethodQueryParam) Valid

Valid indicates whether the value is a known member of the CodeChallengeMethodQueryParam enum.

type CodeChallengeQueryParam

type CodeChallengeQueryParam = string

CodeChallengeQueryParam defines model for CodeChallengeQueryParam.

type CodeQueryParam

type CodeQueryParam = string

CodeQueryParam RFC 6749 §A.11 authorization-code = 1*VSCHAR; VSCHAR = %x20-7E. Microsoft codes can exceed 1500 chars and contain *, !, $.

type CollaborationInviteData

type CollaborationInviteData struct {
	DiagramID       string `json:"diagram_id"`
	DiagramName     string `json:"diagram_name,omitempty"`
	ThreatModelID   string `json:"threat_model_id"`
	ThreatModelName string `json:"threat_model_name,omitempty"`
	InviterEmail    string `json:"inviter_email"`
	Role            string `json:"role"` // viewer, writer
}

CollaborationInviteData contains data for collaboration invitations SEM@66b1e1515b82356913c8625edc8616772c3c70d3: payload for collaboration invitation notifications including inviter and role (pure)

type CollaborationNotificationData

type CollaborationNotificationData struct {
	DiagramID       string `json:"diagram_id"`
	DiagramName     string `json:"diagram_name,omitempty"`
	ThreatModelID   string `json:"threat_model_id"`
	ThreatModelName string `json:"threat_model_name,omitempty"`
	SessionID       string `json:"session_id,omitempty"`
}

CollaborationNotificationData contains data for collaboration notifications SEM@66b1e1515b82356913c8625edc8616772c3c70d3: payload for diagram collaboration session start/end notifications (pure)

type CollaborationSession

type CollaborationSession struct {
	// DiagramId Unique identifier of the associated diagram (UUID)
	DiagramId openapi_types.UUID `json:"diagram_id"`

	// DiagramName Name of the associated diagram
	DiagramName string `json:"diagram_name"`

	// Host User hosting the collaboration session
	Host *User `json:"host,omitempty"`

	// Participants List of active participants
	Participants []Participant `json:"participants"`

	// Presenter User currently presenting (may be null if no active presenter)
	Presenter *User `json:"presenter,omitempty"`

	// SessionId Unique identifier for the session (UUID)
	SessionId *openapi_types.UUID `json:"session_id,omitempty"`

	// ThreatModelId Unique identifier of the associated threat model (UUID)
	ThreatModelId openapi_types.UUID `json:"threat_model_id"`

	// ThreatModelName Name of the associated threat model
	ThreatModelName string `json:"threat_model_name"`

	// WebsocketUrl WebSocket URL for real-time updates
	WebsocketUrl string `json:"websocket_url"`
}

CollaborationSession Details of an active collaboration session for a diagram

type ColorPaletteEntry

type ColorPaletteEntry struct {
	// Color Hex color value (#RGB or #RRGGBB), stored as lowercase #RRGGBB
	Color string `json:"color"`

	// Position Display order position (1-8)
	Position int `json:"position"`
}

ColorPaletteEntry A color entry in a diagram color palette with explicit position for ordering

type CommonValidatorRegistry

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

CommonValidatorRegistry provides a centralized registry of reusable validators SEM@4fa1d37f07fd36467dea01526b97410523474271: named registry mapping validator keys to reusable ValidatorFunc instances (pure)

func NewValidatorRegistry

func NewValidatorRegistry() *CommonValidatorRegistry

NewValidatorRegistry creates a new validator registry with common validators SEM@869fcafe6842b187f8cfe8e7cf65ca47021b8418: build a validator registry pre-loaded with all standard domain validators (pure)

func (*CommonValidatorRegistry) Get

Get retrieves a validator by name SEM@4fa1d37f07fd36467dea01526b97410523474271: fetch a named validator function from the registry (pure)

func (*CommonValidatorRegistry) GetValidators

func (r *CommonValidatorRegistry) GetValidators(names []string) []ValidatorFunc

GetValidators returns multiple validators by names SEM@4fa1d37f07fd36467dea01526b97410523474271: fetch multiple validator functions by name from the registry (pure)

func (*CommonValidatorRegistry) Register

func (r *CommonValidatorRegistry) Register(name string, validator ValidatorFunc)

Register adds a validator to the registry SEM@4fa1d37f07fd36467dea01526b97410523474271: store a named validator function in the registry (mutates shared state)

type Component

type Component struct {
	ID       string         `json:"id"`
	Type     string         `json:"type" binding:"required"`
	Data     map[string]any `json:"data"`
	Metadata []MetadataItem `json:"metadata,omitempty"`
}

Component represents a diagram component SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: represent a typed diagram component with associated metadata (pure)

type ComponentHealth

type ComponentHealth struct {
	// LatencyMs Response latency in milliseconds
	LatencyMs *int64 `json:"latency_ms,omitempty"`

	// Message Human-readable status message or error description
	Message *string `json:"message,omitempty"`

	// Status Component health status
	Status ComponentHealthStatus `json:"status"`
}

ComponentHealth Health status of a system component

type ComponentHealthResult

type ComponentHealthResult struct {
	Status    ComponentHealthStatus
	LatencyMs int64
	Message   string
}

ComponentHealthResult holds health check results for a single component SEM@5775fac65ab5239fc263439d133089dda83af787: health probe result for a single infrastructure component with status, latency, and message (pure)

func (ComponentHealthResult) ToAPIComponentHealth

func (r ComponentHealthResult) ToAPIComponentHealth() *ComponentHealth

ToAPIComponentHealth converts a ComponentHealthResult to the API ComponentHealth type SEM@5775fac65ab5239fc263439d133089dda83af787: convert a ComponentHealthResult to its API DTO (pure)

type ComponentHealthStatus

type ComponentHealthStatus string

ComponentHealthStatus Component health status

const (
	ComponentHealthStatusHealthy   ComponentHealthStatus = "healthy"
	ComponentHealthStatusUnhealthy ComponentHealthStatus = "unhealthy"
	ComponentHealthStatusUnknown   ComponentHealthStatus = "unknown"
)

Defines values for ComponentHealthStatus.

func (ComponentHealthStatus) Valid

func (e ComponentHealthStatus) Valid() bool

Valid indicates whether the value is a known member of the ComponentHealthStatus enum.

type ConcurrencyLimiter

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

ConcurrencyLimiter caps simultaneous extractions per user. Capacity is looked up on first acquire and cached per-user for the lifetime of the process (override changes don't resize the existing semaphore — known limitation, see design spec). The lookup callback is invoked while the internal mutex is held, so callers must supply a fast (cached) lookup. SEM@d1fd850907490887fd11a6ccd4a691326ede6e4e: per-user weighted semaphore pool capping simultaneous content extractions (mutates shared state)

func NewConcurrencyLimiter

func NewConcurrencyLimiter(fallback int, lookup func(ctx context.Context, userID string) (int, error)) *ConcurrencyLimiter

NewConcurrencyLimiter is the public constructor used by server wiring. fallback is the per-user concurrency cap used when no override is set; lookup is called on first acquire per user to fetch the override value. A nil lookup means "always use fallback". Values outside (0, config.MaxPerUserConcurrency] are clamped to the safe default of 2. SEM@d1fd850907490887fd11a6ccd4a691326ede6e4e: build a ConcurrencyLimiter with a fallback cap and optional per-user override lookup (pure)

type ConfigProvider

type ConfigProvider interface {
	GetMigratableSettings() []MigratableSetting
}

ConfigProvider provides access to migratable settings from configuration SEM@600cc6a8afb0ea9ee0881874c4e9197f9d5288e7: interface for supplying migratable settings from application config

type ConfigProviderAdapter

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

ConfigProviderAdapter adapts config.Config to implement the ConfigProvider interface SEM@f25790d896e8e128807a3c9a0a517fcbe6f710fe: adapter bridging app config to the API migratable-settings interface (pure)

func NewConfigProviderAdapter

func NewConfigProviderAdapter(cfg *config.Config) *ConfigProviderAdapter

NewConfigProviderAdapter creates a new ConfigProviderAdapter SEM@f25790d896e8e128807a3c9a0a517fcbe6f710fe: build a ConfigProviderAdapter wrapping the given config (pure)

func (*ConfigProviderAdapter) GetMigratableSettings

func (a *ConfigProviderAdapter) GetMigratableSettings() []MigratableSetting

GetMigratableSettings returns migratable settings from the config SEM@33a84a2f45e6081d58584c7c6233564fb6bbf063: convert config migratable settings to API-layer MigratableSetting values (pure)

type ConfirmIdentityLinkJSONBody

type ConfirmIdentityLinkJSONBody struct {
	// Token Pending identity link token from the callback redirect
	Token string `json:"token"`
}

ConfirmIdentityLinkJSONBody defines parameters for ConfirmIdentityLink.

type ConfirmIdentityLinkJSONRequestBody

type ConfirmIdentityLinkJSONRequestBody ConfirmIdentityLinkJSONBody

ConfirmIdentityLinkJSONRequestBody defines body for ConfirmIdentityLink for application/json ContentType.

type Conflict

type Conflict = Error

Conflict Standard error response format

type ConfluenceContentOAuthProvider

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

ConfluenceContentOAuthProvider wraps BaseContentOAuthProvider to upgrade the account label using Atlassian's /oauth/token/accessible-resources endpoint. The base provider's /me call already populates account_id and a reasonable fallback label (email or display name); this wrapper additionally sets the label to the first matched site URL when accessible-resources returns one or more entries, which is more useful for users with multiple Atlassian instances.

Authorization URL, token exchange, refresh, revoke, and required-scopes behavior are all delegated to the base provider unchanged. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: Confluence OAuth provider that enriches account info with Atlassian accessible-resources site URL

func NewConfluenceContentOAuthProvider

func NewConfluenceContentOAuthProvider(base *BaseContentOAuthProvider, validator *URIValidator) *ConfluenceContentOAuthProvider

NewConfluenceContentOAuthProvider wraps base with Confluence-specific account-info enrichment. validator MUST be non-nil and is used to validate outbound calls to api.atlassian.com (or operator-overridden test stubs). SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build a ConfluenceContentOAuthProvider wrapping a base provider with SSRF-validated HTTP client (pure)

func (*ConfluenceContentOAuthProvider) AuthorizationURL

func (p *ConfluenceContentOAuthProvider) AuthorizationURL(state, pkceChallenge, redirectURI string) string

AuthorizationURL delegates to the base provider, which appends any configured ExtraAuthorizeParams (e.g. audience=api.atlassian.com). SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: build the Confluence OAuth authorization URL, delegating to the base provider (pure)

func (*ConfluenceContentOAuthProvider) ExchangeCode

func (p *ConfluenceContentOAuthProvider) ExchangeCode(ctx context.Context, code, pkceVerifier, redirectURI string) (*ContentOAuthTokenResponse, error)

ExchangeCode delegates to the base provider. SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: exchange an authorization code for Confluence OAuth tokens via the base provider

func (*ConfluenceContentOAuthProvider) FetchAccountInfo

func (p *ConfluenceContentOAuthProvider) FetchAccountInfo(ctx context.Context, accessToken string) (string, string, error)

FetchAccountInfo first calls the base /me endpoint for the canonical account_id, then calls accessible-resources to upgrade the label to the first site URL when available. Errors during the accessible-resources call are logged and ignored — the base label is still returned, so the row can still be linked. SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: fetch Atlassian account ID and upgrade the label to the first accessible site URL

func (*ConfluenceContentOAuthProvider) ID

ID returns the wrapped provider's id (always "confluence" in practice; the registry chooses this implementation by id). SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: return the provider identifier from the wrapped base provider (pure)

func (*ConfluenceContentOAuthProvider) Refresh

Refresh delegates to the base provider. SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: refresh a Confluence OAuth access token via the base provider

func (*ConfluenceContentOAuthProvider) RequiredScopes

func (p *ConfluenceContentOAuthProvider) RequiredScopes() []string

RequiredScopes delegates to the base provider. Operators must include "offline_access" in required_scopes for refresh tokens to be issued. SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: return the OAuth scopes required for Confluence access, delegating to the base provider (pure)

func (*ConfluenceContentOAuthProvider) Revoke

Revoke delegates to the base provider. Atlassian 3LO has no public RFC 7009 revocation endpoint, so operator config typically leaves revocation_url empty; the base provider treats that as a no-op. SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: revoke a Confluence OAuth token via the base provider (no-op if revocation URL is unconfigured)

type ContentAuthorizationURL

type ContentAuthorizationURL struct {
	// AuthorizationUrl Provider authorization URL to which the client must navigate the user.
	AuthorizationUrl string `json:"authorization_url"`

	// ExpiresAt Timestamp after which the associated server-side state nonce is no longer valid (ISO 8601).
	ExpiresAt time.Time `json:"expires_at"`
}

ContentAuthorizationURL OAuth authorization URL plus expiry of the associated server-side state.

type ContentExtractor

type ContentExtractor = extract.ContentExtractor

Type aliases re-exporting pkg/extract into the api package. The extractor logic was relocated to pkg/extract during Component Platform Plan 2 (#347) so the sandboxed worker can link it without pulling in Gin/GORM. These aliases keep the monolith's many call sites unchanged.

type ContentExtractorRegistry

type ContentExtractorRegistry = extract.ContentExtractorRegistry

Type aliases re-exporting pkg/extract into the api package. The extractor logic was relocated to pkg/extract during Component Platform Plan 2 (#347) so the sandboxed worker can link it without pulling in Gin/GORM. These aliases keep the monolith's many call sites unchanged.

type ContentFeedback

type ContentFeedback struct {
	ClientId      string             `json:"client_id"`
	ClientVersion *string            `json:"client_version,omitempty"`
	CreatedAt     time.Time          `json:"created_at"`
	CreatedBy     openapi_types.UUID `json:"created_by"`

	// FalsePositiveReason Allowed only when sentiment='down' and target_type='threat'
	FalsePositiveReason *ContentFeedbackFalsePositiveReason `json:"false_positive_reason,omitempty"`

	// FalsePositiveSubreason Allowed only when false_positive_reason has subreasons; must be a valid subreason for the chosen reason
	FalsePositiveSubreason *ContentFeedbackFalsePositiveSubreason `json:"false_positive_subreason,omitempty"`
	Id                     openapi_types.UUID                     `json:"id"`

	// Screenshot Optional viewport screenshot captured by the client at submission time. Data URL form (e.g. `data:image/jpeg;base64,...`). Used as support context.
	Screenshot *string                  `json:"screenshot,omitempty"`
	Sentiment  ContentFeedbackSentiment `json:"sentiment"`

	// TargetField Required iff target_type is 'threat_classification'; identifies the field of the threat (e.g. 'cwe', 'severity')
	TargetField *string `json:"target_field,omitempty"`

	// TargetId ID of the targeted artifact (note/diagram/threat). For threat_classification, the threat ID.
	TargetId openapi_types.UUID `json:"target_id"`

	// TargetType Type of artifact the feedback targets
	TargetType    ContentFeedbackTargetType `json:"target_type"`
	ThreatModelId openapi_types.UUID        `json:"threat_model_id"`
	Verbatim      *string                   `json:"verbatim,omitempty"`
}

ContentFeedback defines model for ContentFeedback.

type ContentFeedbackFalsePositiveReason

type ContentFeedbackFalsePositiveReason string

ContentFeedbackFalsePositiveReason Allowed only when sentiment='down' and target_type='threat'

const (
	ContentFeedbackFalsePositiveReasonAlreadyRemediated     ContentFeedbackFalsePositiveReason = "already_remediated"
	ContentFeedbackFalsePositiveReasonDetectionMisfired     ContentFeedbackFalsePositiveReason = "detection_misfired"
	ContentFeedbackFalsePositiveReasonDetectionRuleFlawed   ContentFeedbackFalsePositiveReason = "detection_rule_flawed"
	ContentFeedbackFalsePositiveReasonDuplicate             ContentFeedbackFalsePositiveReason = "duplicate"
	ContentFeedbackFalsePositiveReasonIntendedBehavior      ContentFeedbackFalsePositiveReason = "intended_behavior"
	ContentFeedbackFalsePositiveReasonOutOfScope            ContentFeedbackFalsePositiveReason = "out_of_scope"
	ContentFeedbackFalsePositiveReasonRealButMitigated      ContentFeedbackFalsePositiveReason = "real_but_mitigated"
	ContentFeedbackFalsePositiveReasonRealButNotExploitable ContentFeedbackFalsePositiveReason = "real_but_not_exploitable"
)

Defines values for ContentFeedbackFalsePositiveReason.

func (ContentFeedbackFalsePositiveReason) Valid

Valid indicates whether the value is a known member of the ContentFeedbackFalsePositiveReason enum.

type ContentFeedbackFalsePositiveSubreason

type ContentFeedbackFalsePositiveSubreason string

ContentFeedbackFalsePositiveSubreason Allowed only when false_positive_reason has subreasons; must be a valid subreason for the chosen reason

const (
	ContentFeedbackFalsePositiveSubreasonCodeDoesNotExist            ContentFeedbackFalsePositiveSubreason = "code_does_not_exist"
	ContentFeedbackFalsePositiveSubreasonComponentOutsideThreatModel ContentFeedbackFalsePositiveSubreason = "component_outside_threat_model"
	ContentFeedbackFalsePositiveSubreasonNeedsTuning                 ContentFeedbackFalsePositiveSubreason = "needs_tuning"
	ContentFeedbackFalsePositiveSubreasonNotARealRisk                ContentFeedbackFalsePositiveSubreason = "not_a_real_risk"
	ContentFeedbackFalsePositiveSubreasonSanctionedByDesign          ContentFeedbackFalsePositiveSubreason = "sanctioned_by_design"
	ContentFeedbackFalsePositiveSubreasonTriggerConditionsNotMet     ContentFeedbackFalsePositiveSubreason = "trigger_conditions_not_met"
)

Defines values for ContentFeedbackFalsePositiveSubreason.

func (ContentFeedbackFalsePositiveSubreason) Valid

Valid indicates whether the value is a known member of the ContentFeedbackFalsePositiveSubreason enum.

type ContentFeedbackHandler

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

ContentFeedbackHandler bundles the three /threat_models/{id}/feedback endpoints. SEM@7c8a034d9bad3f82041f085b04149f654fb31db3: handler bundle for create, fetch, and list content feedback endpoints on a threat model

func NewContentFeedbackHandler

func NewContentFeedbackHandler(repo ContentFeedbackRepository, db *gorm.DB) *ContentFeedbackHandler

NewContentFeedbackHandler constructs the handler. SEM@7c8a034d9bad3f82041f085b04149f654fb31db3: build a ContentFeedbackHandler wiring together a feedback repository and DB (pure)

func (*ContentFeedbackHandler) Create

func (h *ContentFeedbackHandler) Create(c *gin.Context)

Create handles POST /threat_models/{threat_model_id}/feedback. SEM@1c63bfe9bdfd225380a2a4e2960fef14b3437996: store user feedback for a threat model target, validating input and checking target existence (reads DB)

func (*ContentFeedbackHandler) Get

func (h *ContentFeedbackHandler) Get(c *gin.Context)

Get handles GET /threat_models/{threat_model_id}/feedback/{feedback_id}. SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: fetch a single content feedback entry scoped to a threat model (reads DB)

func (*ContentFeedbackHandler) List

func (h *ContentFeedbackHandler) List(c *gin.Context)

List handles GET /threat_models/{threat_model_id}/feedback. SEM@7c8a034d9bad3f82041f085b04149f654fb31db3: list paginated content feedback entries for a threat model with optional filters (reads DB)

type ContentFeedbackInput

type ContentFeedbackInput struct {
	ClientId      string  `json:"client_id"`
	ClientVersion *string `json:"client_version,omitempty"`

	// FalsePositiveReason Allowed only when sentiment='down' and target_type='threat'
	FalsePositiveReason *ContentFeedbackInputFalsePositiveReason `json:"false_positive_reason,omitempty"`

	// FalsePositiveSubreason Allowed only when false_positive_reason has subreasons; must be a valid subreason for the chosen reason
	FalsePositiveSubreason *ContentFeedbackInputFalsePositiveSubreason `json:"false_positive_subreason,omitempty"`

	// Screenshot Optional viewport screenshot captured by the client at submission time. Data URL form (e.g. `data:image/jpeg;base64,...`). Used as support context.
	Screenshot *string                       `json:"screenshot,omitempty"`
	Sentiment  ContentFeedbackInputSentiment `json:"sentiment"`

	// TargetField Required iff target_type is 'threat_classification'; identifies the field of the threat (e.g. 'cwe', 'severity')
	TargetField *string `json:"target_field,omitempty"`

	// TargetId ID of the targeted artifact (note/diagram/threat). For threat_classification, the threat ID.
	TargetId openapi_types.UUID `json:"target_id"`

	// TargetType Type of artifact the feedback targets
	TargetType ContentFeedbackInputTargetType `json:"target_type"`
	Verbatim   *string                        `json:"verbatim,omitempty"`
}

ContentFeedbackInput defines model for ContentFeedbackInput.

type ContentFeedbackInputFalsePositiveReason

type ContentFeedbackInputFalsePositiveReason string

ContentFeedbackInputFalsePositiveReason Allowed only when sentiment='down' and target_type='threat'

const (
	ContentFeedbackInputFalsePositiveReasonAlreadyRemediated     ContentFeedbackInputFalsePositiveReason = "already_remediated"
	ContentFeedbackInputFalsePositiveReasonDetectionMisfired     ContentFeedbackInputFalsePositiveReason = "detection_misfired"
	ContentFeedbackInputFalsePositiveReasonDetectionRuleFlawed   ContentFeedbackInputFalsePositiveReason = "detection_rule_flawed"
	ContentFeedbackInputFalsePositiveReasonDuplicate             ContentFeedbackInputFalsePositiveReason = "duplicate"
	ContentFeedbackInputFalsePositiveReasonIntendedBehavior      ContentFeedbackInputFalsePositiveReason = "intended_behavior"
	ContentFeedbackInputFalsePositiveReasonOutOfScope            ContentFeedbackInputFalsePositiveReason = "out_of_scope"
	ContentFeedbackInputFalsePositiveReasonRealButMitigated      ContentFeedbackInputFalsePositiveReason = "real_but_mitigated"
	ContentFeedbackInputFalsePositiveReasonRealButNotExploitable ContentFeedbackInputFalsePositiveReason = "real_but_not_exploitable"
)

Defines values for ContentFeedbackInputFalsePositiveReason.

func (ContentFeedbackInputFalsePositiveReason) Valid

Valid indicates whether the value is a known member of the ContentFeedbackInputFalsePositiveReason enum.

type ContentFeedbackInputFalsePositiveSubreason

type ContentFeedbackInputFalsePositiveSubreason string

ContentFeedbackInputFalsePositiveSubreason Allowed only when false_positive_reason has subreasons; must be a valid subreason for the chosen reason

const (
	ContentFeedbackInputFalsePositiveSubreasonCodeDoesNotExist            ContentFeedbackInputFalsePositiveSubreason = "code_does_not_exist"
	ContentFeedbackInputFalsePositiveSubreasonComponentOutsideThreatModel ContentFeedbackInputFalsePositiveSubreason = "component_outside_threat_model"
	ContentFeedbackInputFalsePositiveSubreasonNeedsTuning                 ContentFeedbackInputFalsePositiveSubreason = "needs_tuning"
	ContentFeedbackInputFalsePositiveSubreasonNotARealRisk                ContentFeedbackInputFalsePositiveSubreason = "not_a_real_risk"
	ContentFeedbackInputFalsePositiveSubreasonSanctionedByDesign          ContentFeedbackInputFalsePositiveSubreason = "sanctioned_by_design"
	ContentFeedbackInputFalsePositiveSubreasonTriggerConditionsNotMet     ContentFeedbackInputFalsePositiveSubreason = "trigger_conditions_not_met"
)

Defines values for ContentFeedbackInputFalsePositiveSubreason.

func (ContentFeedbackInputFalsePositiveSubreason) Valid

Valid indicates whether the value is a known member of the ContentFeedbackInputFalsePositiveSubreason enum.

type ContentFeedbackInputSentiment

type ContentFeedbackInputSentiment string

ContentFeedbackInputSentiment defines model for ContentFeedbackInput.Sentiment.

const (
	ContentFeedbackInputSentimentDown ContentFeedbackInputSentiment = "down"
	ContentFeedbackInputSentimentUp   ContentFeedbackInputSentiment = "up"
)

Defines values for ContentFeedbackInputSentiment.

func (ContentFeedbackInputSentiment) Valid

Valid indicates whether the value is a known member of the ContentFeedbackInputSentiment enum.

type ContentFeedbackInputTargetType

type ContentFeedbackInputTargetType string

ContentFeedbackInputTargetType Type of artifact the feedback targets

const (
	ContentFeedbackInputTargetTypeDiagram              ContentFeedbackInputTargetType = "diagram"
	ContentFeedbackInputTargetTypeNote                 ContentFeedbackInputTargetType = "note"
	ContentFeedbackInputTargetTypeThreat               ContentFeedbackInputTargetType = "threat"
	ContentFeedbackInputTargetTypeThreatClassification ContentFeedbackInputTargetType = "threat_classification"
)

Defines values for ContentFeedbackInputTargetType.

func (ContentFeedbackInputTargetType) Valid

Valid indicates whether the value is a known member of the ContentFeedbackInputTargetType enum.

type ContentFeedbackListFilter

type ContentFeedbackListFilter struct {
	TargetType          string
	TargetID            string
	Sentiment           string
	FalsePositiveReason string
}

ContentFeedbackListFilter controls ContentFeedbackRepository.List. Zero/empty fields are ignored. SEM@87c89d0c54dceab6486f4f612415b28f2d4b30db: filter parameters for listing content feedback entries (pure)

type ContentFeedbackRepository

type ContentFeedbackRepository interface {
	// Create inserts a feedback row without verifying target existence.
	// Prefer CreateWithTargetCheck for handler paths that take user input.
	Create(ctx context.Context, fb *models.ContentFeedback) error
	// CreateWithTargetCheck verifies the target row exists in the threat model
	// and inserts the feedback row in a single transaction with a row lock on
	// the target. This closes the SELECT-then-INSERT TOCTOU window where a
	// concurrent delete of the target could leave a feedback row pointing at a
	// non-existent entity.
	//
	// Returns ErrTargetNotFound if the target row does not exist (or does not
	// belong to the threat model) at the moment of the locked SELECT.
	CreateWithTargetCheck(ctx context.Context, fb *models.ContentFeedback, target ContentFeedbackTargetRef) error
	Get(ctx context.Context, id string) (*models.ContentFeedback, error)
	List(ctx context.Context, threatModelID string, filter ContentFeedbackListFilter, offset, limit int) ([]models.ContentFeedback, error)
	Count(ctx context.Context, threatModelID string, filter ContentFeedbackListFilter) (int64, error)
}

ContentFeedbackRepository defines persistence for content_feedback rows. SEM@1c63bfe9bdfd225380a2a4e2960fef14b3437996: persistence interface for creating, fetching, listing, and counting content feedback rows

var GlobalContentFeedbackRepository ContentFeedbackRepository

type ContentFeedbackSentiment

type ContentFeedbackSentiment string

ContentFeedbackSentiment defines model for ContentFeedback.Sentiment.

const (
	ContentFeedbackSentimentDown ContentFeedbackSentiment = "down"
	ContentFeedbackSentimentUp   ContentFeedbackSentiment = "up"
)

Defines values for ContentFeedbackSentiment.

func (ContentFeedbackSentiment) Valid

func (e ContentFeedbackSentiment) Valid() bool

Valid indicates whether the value is a known member of the ContentFeedbackSentiment enum.

type ContentFeedbackTargetRef

type ContentFeedbackTargetRef struct {
	Table         string
	TargetID      string
	ThreatModelID string
}

ContentFeedbackTargetRef identifies the row that a feedback entry refers to. Table is the GORM table name (e.g., "threats", "notes", "diagrams"). SEM@1c63bfe9bdfd225380a2a4e2960fef14b3437996: identify the target row a feedback entry refers to by table, ID, and threat model (pure)

type ContentFeedbackTargetType

type ContentFeedbackTargetType string

ContentFeedbackTargetType Type of artifact the feedback targets

const (
	ContentFeedbackTargetTypeDiagram              ContentFeedbackTargetType = "diagram"
	ContentFeedbackTargetTypeNote                 ContentFeedbackTargetType = "note"
	ContentFeedbackTargetTypeThreat               ContentFeedbackTargetType = "threat"
	ContentFeedbackTargetTypeThreatClassification ContentFeedbackTargetType = "threat_classification"
)

Defines values for ContentFeedbackTargetType.

func (ContentFeedbackTargetType) Valid

func (e ContentFeedbackTargetType) Valid() bool

Valid indicates whether the value is a known member of the ContentFeedbackTargetType enum.

type ContentOAuthCallbackParams

type ContentOAuthCallbackParams struct {
	// State Opaque nonce that binds this callback to a server-side authorize request.
	State *string `form:"state,omitempty" json:"state,omitempty"`

	// Code Authorization code returned by the provider when authorization succeeds.
	Code *string `form:"code,omitempty" json:"code,omitempty"`

	// Error Error code reported by the provider when authorization fails.
	Error *string `form:"error,omitempty" json:"error,omitempty"`
}

ContentOAuthCallbackParams defines parameters for ContentOAuthCallback.

type ContentOAuthHandlers

type ContentOAuthHandlers struct {
	Cfg           config.ContentOAuthConfig
	Registry      *ContentOAuthProviderRegistry
	StateStore    *ContentOAuthStateStore
	Tokens        ContentTokenRepository
	CallbackAllow *auth.ClientCallbackAllowList
	// Documents is used by Delete for the picker un-link cascade.
	// Nil is allowed — cascade is skipped when nil.
	Documents DocumentRepository
	// UserLookup extracts the caller's internal user UUID from the Gin context.
	// It returns ("", false) when no authenticated user is present.
	// This indirection keeps the handler independent of the specific auth
	// middleware implementation and makes it easy to stub in tests.
	UserLookup func(c *gin.Context) (userID string, ok bool)
}

ContentOAuthHandlers holds the dependencies for the /me/content_tokens/* and /oauth2/content_callback endpoints. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: handler dependencies for content-token OAuth endpoints (struct)

func (*ContentOAuthHandlers) AdminDelete

func (h *ContentOAuthHandlers) AdminDelete(c *gin.Context)

AdminDelete handles DELETE /admin/users/:user_id/content_tokens/:provider_id. Deletes the token and attempts provider-side revocation (best-effort). Returns 204 whether or not the row existed (idempotent). Admin-role enforcement is applied by middleware at route registration time. SEM@02f6179e32b8858ace90c56dab8a84249a32eef8: delete a user's content OAuth token for a provider and attempt provider revocation (reads DB)

func (*ContentOAuthHandlers) AdminList

func (h *ContentOAuthHandlers) AdminList(c *gin.Context)

AdminList handles GET /admin/users/:user_id/content_tokens. Returns 200 with {"content_tokens": [...]} for the path user. Admin-role enforcement is applied by middleware at route registration time. SEM@02f6179e32b8858ace90c56dab8a84249a32eef8: list all content OAuth tokens for a given user as an admin (reads DB)

func (*ContentOAuthHandlers) Authorize

func (h *ContentOAuthHandlers) Authorize(c *gin.Context)

Authorize handles POST /me/content_tokens/:provider_id/authorize. Validates the provider and client_callback, generates PKCE, stores state in Redis, and returns {authorization_url, expires_at}. SEM@462c9c5f31b3e00796bfbcea980a74ada200f7f7: initiate a PKCE OAuth flow for a content provider and return the authorization URL (mutates shared state)

func (*ContentOAuthHandlers) Callback

func (h *ContentOAuthHandlers) Callback(c *gin.Context)

Callback handles GET /oauth2/content_callback. This is a public endpoint (no auth middleware). It completes the OAuth authorization code flow, stores the resulting token, and redirects to the client_callback URL with status=success or status=error. SEM@462c9c5f31b3e00796bfbcea980a74ada200f7f7: complete the OAuth code exchange, persist the content token, and redirect to the client callback

func (*ContentOAuthHandlers) Delete

func (h *ContentOAuthHandlers) Delete(c *gin.Context)

Delete handles DELETE /me/content_tokens/:provider_id. Deletes the token and attempts provider-side revocation (best-effort). Returns 204 whether or not the row existed (idempotent). SEM@f80dc196a824e779553730fd0cdca2eeaebef4d7: delete a content token and best-effort revoke it at the provider, with picker un-link cascade (mutates shared state)

func (*ContentOAuthHandlers) List

func (h *ContentOAuthHandlers) List(c *gin.Context)

List handles GET /me/content_tokens. Returns 200 with {"content_tokens": ContentTokenInfo} or 401 if not authenticated. SEM@462c9c5f31b3e00796bfbcea980a74ada200f7f7: list all content tokens for the authenticated user (reads DB)

func (*ContentOAuthHandlers) RevokeUserTokens

func (h *ContentOAuthHandlers) RevokeUserTokens(ctx context.Context, userID string)

RevokeUserTokens is a best-effort sweep of all content tokens belonging to userID. For each token it finds, it attempts provider-side revocation. Failures are logged at Warn level but never block or propagate — user deletion must always succeed regardless of provider availability.

This method satisfies the auth.UserContentTokenRevoker interface and is intended to be called via the pre-user-delete hook registered on auth.Service. The sweep MUST happen before the user row (and its FK-cascaded child rows) is deleted so that the token data is still accessible. SEM@cd187b523b66aef0fa87861d3a929c2017787b86: best-effort sweep and revoke all content OAuth tokens for a user before deletion (reads DB)

type ContentOAuthProvider

type ContentOAuthProvider interface {
	ID() string
	AuthorizationURL(state, pkceChallenge, redirectURI string) string
	ExchangeCode(ctx context.Context, code, pkceVerifier, redirectURI string) (*ContentOAuthTokenResponse, error)
	Refresh(ctx context.Context, refreshToken string) (*ContentOAuthTokenResponse, error)
	Revoke(ctx context.Context, token string) error
	RequiredScopes() []string
	// FetchAccountInfo is provider-specific; if UserinfoURL is configured, it
	// returns the external account id + label. Returns empty values if unavailable.
	FetchAccountInfo(ctx context.Context, accessToken string) (accountID, label string, err error)
}

ContentOAuthProvider is the interface each delegated content provider implements. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: interface for delegated content OAuth providers covering auth, token exchange, refresh, and revoke

type ContentOAuthProviderRegistry

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

ContentOAuthProviderRegistry is a thread-safe registry mapping provider id to a ContentOAuthProvider instance. SEM@95c7b93f8264174c0c95a133b5e0fc17b05d6594: thread-safe registry mapping provider ID to a ContentOAuthProvider (struct)

func LoadContentOAuthRegistryFromConfig

func LoadContentOAuthRegistryFromConfig(cfg config.ContentOAuthConfig, validator *URIValidator) (*ContentOAuthProviderRegistry, error)

LoadContentOAuthRegistryFromConfig builds a ContentOAuthProviderRegistry from the given config, registering an appropriate ContentOAuthProvider for each enabled entry. Providers with Enabled == false are skipped.

Provider-specific implementations are selected by id when they need to override BaseContentOAuthProvider behavior (e.g. Confluence augments FetchAccountInfo with the matched accessible-resources site URL). All other ids fall back to BaseContentOAuthProvider.

validator is the URIValidator used to gate outbound OAuth and userinfo/accessible-resources calls. It MUST be non-nil; in production it is built from the operator's content_oauth allowlist. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build and populate a ContentOAuthProviderRegistry from config, skipping disabled providers

func NewContentOAuthProviderRegistry

func NewContentOAuthProviderRegistry() *ContentOAuthProviderRegistry

NewContentOAuthProviderRegistry creates a new, empty ContentOAuthProviderRegistry. SEM@95c7b93f8264174c0c95a133b5e0fc17b05d6594: build an empty, thread-safe ContentOAuthProviderRegistry (pure)

func (*ContentOAuthProviderRegistry) Get

Get returns the provider with the given id, and whether it was found. It is safe to call concurrently. SEM@95c7b93f8264174c0c95a133b5e0fc17b05d6594: fetch a registered content OAuth provider by ID; returns false when not found (pure)

func (*ContentOAuthProviderRegistry) IDs

IDs returns a snapshot of the registered provider ids. The order of the returned slice is not guaranteed. SEM@95c7b93f8264174c0c95a133b5e0fc17b05d6594: list all registered provider IDs as an unordered snapshot (pure)

func (*ContentOAuthProviderRegistry) Register

Register adds or replaces the provider in the registry. It is safe to call concurrently. SEM@95c7b93f8264174c0c95a133b5e0fc17b05d6594: register or replace a content OAuth provider by its ID (mutates shared state)

type ContentOAuthStatePayload

type ContentOAuthStatePayload struct {
	UserID           string    `json:"user_id"`
	ProviderID       string    `json:"provider_id"`
	ClientCallback   string    `json:"client_callback"`
	PKCECodeVerifier string    `json:"pkce_code_verifier"`
	CreatedAt        time.Time `json:"created_at"`
}

ContentOAuthStatePayload holds the data associated with a pending OAuth authorization flow. SEM@0ee4fc6b79c5a6c5a7dade501546a8eec4509aed: data held in a pending content OAuth authorization state nonce (pure)

type ContentOAuthStateStore

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

ContentOAuthStateStore stores short-lived OAuth state nonces in Redis. SEM@0ee4fc6b79c5a6c5a7dade501546a8eec4509aed: Redis-backed store for short-lived content OAuth state nonces

func NewContentOAuthStateStore

func NewContentOAuthStateStore(rdb redis.UniversalClient) *ContentOAuthStateStore

NewContentOAuthStateStore creates a new ContentOAuthStateStore backed by the given Redis client. SEM@0ee4fc6b79c5a6c5a7dade501546a8eec4509aed: build a ContentOAuthStateStore backed by the given Redis client (pure)

func (*ContentOAuthStateStore) Consume

Consume retrieves and atomically deletes the payload for the given nonce. Returns ErrContentOAuthStateNotFound if the nonce does not exist or has expired. SEM@0ee4fc6b79c5a6c5a7dade501546a8eec4509aed: atomically fetch and delete an OAuth state payload by nonce; error if absent or expired (reads DB)

func (*ContentOAuthStateStore) Put

Put stores the payload under a freshly generated nonce and returns the nonce. The entry expires after ttl. SEM@0ee4fc6b79c5a6c5a7dade501546a8eec4509aed: store an OAuth state payload under a new random nonce with a TTL; return the nonce (reads DB)

type ContentOAuthTokenResponse

type ContentOAuthTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	Scope        string `json:"scope"`
}

ContentOAuthTokenResponse is the token payload returned by exchange/refresh. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: token payload returned by a content OAuth exchange or refresh (pure)

func (*ContentOAuthTokenResponse) ExpiresAt

func (r *ContentOAuthTokenResponse) ExpiresAt() *time.Time

ExpiresAt returns the computed absolute expiry time, or nil if ExpiresIn is zero. SEM@c97401fa0a66697da085fd38b4dff4f6898f6831: compute the absolute expiry time from ExpiresIn seconds; nil when no expiry (pure)

type ContentPipeline

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

ContentPipeline orchestrates Source -> Extractor for URI-based content. SEM@117032a3c5523a04e970f76a285e342169d5150c: orchestrates fetching and text extraction from external content sources

func NewContentPipeline

func NewContentPipeline(
	sources *ContentSourceRegistry,
	extractors *ContentExtractorRegistry,
	matcher *URLPatternMatcher,
) *ContentPipeline

NewContentPipeline creates a new pipeline. SEM@d98d9d1c0d122ade355ea522b49b132e523ebf52: build a ContentPipeline without concurrency limiting (pure)

func NewContentPipelineWithLimiter

func NewContentPipelineWithLimiter(
	sources *ContentSourceRegistry,
	extractors *ContentExtractorRegistry,
	matcher *URLPatternMatcher,
	limiter *ConcurrencyLimiter,
	limits PipelineLimits,
) *ContentPipeline

NewContentPipelineWithLimiter wires a per-user concurrency limiter and a pipeline-level wall-clock budget into the existing pipeline. The legacy NewContentPipeline constructor remains for callers that don't need either. SEM@9d853db42745838f38cf03567f0d9e14a212c576: build a ContentPipeline with concurrency limiting and wall-clock budget (pure)

func RebuildPipelineWithSources

func RebuildPipelineWithSources(base *ContentPipeline, sources *ContentSourceRegistry) *ContentPipeline

RebuildPipelineWithSources creates a new ContentPipeline that reuses all settings from base (extractor registry, URL pattern matcher, concurrency limiter, pipeline limits, and the extracted-text dumper) but replaces the content source registry. This is used by ContentSourceHolder to build a fresh pipeline whenever the source registry is rebuilt at runtime, without reconstructing the extractor stack. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: build a new ContentPipeline reusing base settings but with a different source registry (pure)

func (*ContentPipeline) Extract

func (p *ContentPipeline) Extract(ctx context.Context, uri string) (ExtractedContent, error)

Extract fetches bytes from the appropriate source and extracts text. SEM@d1fd850907490887fd11a6ccd4a691326ede6e4e: fetch and extract text from a URI using the matching source and extractor

func (*ContentPipeline) ExtractForDocument

func (p *ContentPipeline) ExtractForDocument(ctx context.Context, doc Document) (ExtractedContent, error)

ExtractForDocument is a document-aware variant of Extract. It runs the usual fetch + extract pipeline, and on success — if a dev/test-only dumper is configured — also persists the extracted markdown as a Note on the document's parent threat model. Note creation failures are logged but do not affect the returned ExtractedContent or error: the dump hook is strictly an inspection aid and must not change the production behavior of the pipeline. SEM@117032a3c5523a04e970f76a285e342169d5150c: extract content for a document and optionally dump the result as a note

func (*ContentPipeline) FetchForPublish

func (p *ContentPipeline) FetchForPublish(ctx context.Context, uri string) ([]byte, string, error)

FetchForPublish performs only the fetch step (FindSource + Fetch) of the pipeline and returns the raw bytes and content-type. It does NOT run any extractor. This is the seam used by the async extraction path to obtain bytes for publishing to the worker pipeline; the worker performs the actual extraction. The same per-user concurrency limiter that guards Extract is also applied here so that concurrent fetch-for-publish calls are subject to the same cap. SEM@d994c2f113f9e0997f83a0815018638cc94111f7: fetch raw content bytes and content type for a URI without text extraction

func (*ContentPipeline) Matcher

func (p *ContentPipeline) Matcher() *URLPatternMatcher

Matcher returns the pipeline's URL pattern matcher. SEM@d98d9d1c0d122ade355ea522b49b132e523ebf52: fetch the pipeline's URL pattern matcher (pure)

func (*ContentPipeline) SetExtractedTextNoteDumper

func (p *ContentPipeline) SetExtractedTextNoteDumper(d *extractedTextNoteDumper)

SetExtractedTextNoteDumper enables the dev/test-only hook that persists each successful extraction's markdown as a Note on the parent threat model. The caller is responsible for verifying that the build mode permits the hook; passing a non-nil dumper in production builds is a programming error and should be prevented at config-validation time. Pass nil to disable. SEM@117032a3c5523a04e970f76a285e342169d5150c: register a dev-mode hook to persist extracted text as notes (mutates shared state)

func (*ContentPipeline) Sources

func (p *ContentPipeline) Sources() *ContentSourceRegistry

Sources returns the pipeline's source registry. SEM@d98d9d1c0d122ade355ea522b49b132e523ebf52: fetch the pipeline's content source registry (pure)

type ContentPipelineFactory

type ContentPipelineFactory func(sources *ContentSourceRegistry) *ContentPipeline

ContentPipelineFactory builds a ContentPipeline from a given ContentSourceRegistry. The factory captures the startup-wired extractor registry, concurrency limiter, and limits so they can be reused across registry rebuilds. Only the source registry changes on runtime toggle. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: factory function type that builds a ContentPipeline from a given source registry (pure)

type ContentProvider

type ContentProvider struct {
	// Icon Font Awesome class string (matches OAuth IdP convention). Empty if no default and no override.
	Icon string `json:"icon"`

	// Id Source identifier (matches ContentSource.Name())
	Id string `json:"id"`

	// Kind delegated: per-user OAuth (client must call /me/content_tokens/{id}/authorize); service: operator-credentialed (no per-user link); direct: no auth (e.g., HTTP fetch)
	Kind ContentProviderKind `json:"kind"`

	// Name Display label for the provider
	Name string `json:"name"`

	// PickerConfig Browser-safe OAuth/picker bootstrap values for in-browser file pickers. Present only when the operator has configured a public Web OAuth client for this provider. All values are intended for browser use; never include client_secret or service-account material here. Per-provider keys are documented in the provider's section.
	PickerConfig *map[string]string `json:"picker_config,omitempty"`
}

ContentProvider defines model for ContentProvider.

type ContentProviderKind

type ContentProviderKind string

ContentProviderKind delegated: per-user OAuth (client must call /me/content_tokens/{id}/authorize); service: operator-credentialed (no per-user link); direct: no auth (e.g., HTTP fetch)

const (
	ContentProviderKindDelegated ContentProviderKind = "delegated"
	ContentProviderKindDirect    ContentProviderKind = "direct"
	ContentProviderKindService   ContentProviderKind = "service"
)

Defines values for ContentProviderKind.

func (ContentProviderKind) Valid

func (e ContentProviderKind) Valid() bool

Valid indicates whether the value is a known member of the ContentProviderKind enum.

type ContentSource

type ContentSource interface {
	Name() string
	CanHandle(ctx context.Context, uri string) bool
	Fetch(ctx context.Context, uri string) (data []byte, contentType string, err error)
}

ContentSource authenticates and fetches raw bytes from a URI. SEM@789146ae6555f1667678ed835a68faac5b22ad30: interface for authenticating and fetching raw bytes from a URI

type ContentSourceBundle

type ContentSourceBundle struct {
	Sources  *ContentSourceRegistry
	Pipeline *ContentPipeline
	Poller   *AccessPoller
}

ContentSourceBundle groups the rebuildable content-source objects served to request handlers and background pollers. It is immutable once built; ContentSourceHolder swaps the whole struct on rebuild. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: immutable snapshot grouping content sources, pipeline, and access poller for a single wiring revision (pure)

type ContentSourceBundleBuilder

type ContentSourceBundleBuilder func(ctx context.Context, cfg config.Config) (*ContentSourceBundle, error)

ContentSourceBundleBuilder constructs a ContentSourceBundle from a resolved config. Injected so tests can substitute a fake builder instead of constructing real OAuth clients or filesystem sources.

Implementations MUST NOT call Start() on the returned Poller — the holder calls Start() after installing the bundle so the poller always runs against the live sources.

On misconfiguration the builder should return (bundle, nil) with only the healthy sources registered (logging a WARN for each skipped source), NOT return an error that would leave the server with no sources at all. A nil bundle is returned only when the entire subsystem cannot be set up (e.g. nil document store), in which case the holder keeps its previous bundle. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: factory contract for building a ContentSourceBundle from live config without starting the poller (pure)

func BuildContentSourceBundle

func BuildContentSourceBundle(
	tokenRepo ContentTokenRepository,
	contentOAuthValidator *URIValidator,
	timmyURIValidator *URIValidator,
	pipelineFactory ContentPipelineFactory,
) ContentSourceBundleBuilder

BuildContentSourceBundle is the production builder for ContentSourceHolder. It mirrors the logic that was in initializeTimmySubsystem but converts every os.Exit(1) content-source validation into a graceful WARN+skip so a live server is never crashed by a misconfigured content source.

pipelineFactory is called with the newly-built source registry to assemble a ContentPipeline that wraps it. Pass nil to skip pipeline construction (pipeline will be nil in the returned bundle).

The function signature matches ContentSourceBundleBuilder. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: build the production ContentSourceBundleBuilder, registering all enabled content sources with graceful skip on misconfiguration

type ContentSourceHolder

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

ContentSourceHolder owns the live ContentSourceBundle and rebuilds it lazily when the wiring configuration has changed. Safe for concurrent use.

The pattern mirrors TimmyCore: a stable hash of the config fields that affect source construction gates whether a rebuild is needed. In-flight requests hold their *ContentSourceBundle pointer for the duration of the call; a swap replaces the holder's pointer but never mutates an in-use bundle. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: thread-safe holder that lazily rebuilds the content-source bundle when wiring config changes (mutates shared state)

func NewContentSourceHolder

func NewContentSourceHolder(
	cfgReader func(ctx context.Context) config.Config,
	builder ContentSourceBundleBuilder,
) *ContentSourceHolder

NewContentSourceHolder constructs a holder over the given config reader and builder. Neither argument may be nil. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: build a ContentSourceHolder wired to the given config reader and bundle builder (pure)

func (*ContentSourceHolder) AddRebuildHook

func (h *ContentSourceHolder) AddRebuildHook(fn func(*ContentSourceBundle))

AddRebuildHook registers a callback that is invoked (while the write lock is held) after each successful rebuild. Hooks are called in registration order with the newly installed bundle. The bundle is never nil when a hook fires. Hooks MUST NOT call Get (deadlock) or block for more than a few microseconds. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: register a callback invoked after each successful content-source bundle rebuild (mutates shared state)

func (*ContentSourceHolder) Get

Get returns the live ContentSourceBundle, rebuilding it if the wiring configuration has changed since the last build. A build error is returned to the caller and does NOT poison the cache: the next Get retries. Callers hold the returned pointer for the duration of their request; a concurrent rebuild swaps the holder's pointer but never mutates an in-use bundle.

Concurrency: the fast path (hash unchanged) acquires only an RLock. A rebuild upgrades to WLock with a double-check to prevent two goroutines from both rebuilding. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: fetch the live content-source bundle, rebuilding lazily when wiring config hash changes (mutates shared state)

func (*ContentSourceHolder) StopPoller

func (h *ContentSourceHolder) StopPoller()

StopPoller stops the currently-running access poller, if any. Called during server shutdown so the goroutine is cleaned up before the process exits. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: stop the active content-source access poller for graceful shutdown (mutates shared state)

type ContentSourceRegistry

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

ContentSourceRegistry manages content sources in priority order. SEM@789146ae6555f1667678ed835a68faac5b22ad30: ordered registry of content sources for URI dispatch (pure)

func NewContentSourceRegistry

func NewContentSourceRegistry() *ContentSourceRegistry

NewContentSourceRegistry creates a new registry. SEM@789146ae6555f1667678ed835a68faac5b22ad30: build an empty content source registry (pure)

func (*ContentSourceRegistry) FindSource

func (r *ContentSourceRegistry) FindSource(ctx context.Context, uri string) (ContentSource, bool)

FindSource returns the first source that can handle the given URI. SEM@789146ae6555f1667678ed835a68faac5b22ad30: find the first registered content source that can handle a URI (pure)

func (*ContentSourceRegistry) FindSourceByName

func (r *ContentSourceRegistry) FindSourceByName(name string) (ContentSource, bool)

FindSourceByName returns the source with the given name, if registered. SEM@90539292d25d541a7e322a67f50ecb928268f215: find a registered content source by provider name (pure)

func (*ContentSourceRegistry) FindSourceForDocument

func (r *ContentSourceRegistry) FindSourceForDocument(
	ctx context.Context,
	uri string,
	picker *PickerMetadata,
	userID string,
	checker LinkedProviderChecker,
) (ContentSource, bool)

FindSourceForDocument picks a ContentSource for fetching a specific document. The delegated source wins when the document has picker metadata for a provider that is registered and the user has an active linked token for that provider. Otherwise, dispatch falls through to URL-based lookup (which picks the first CanHandle match in registration order).

Why not put this on ContentSource or Document: URL-based dispatch must still work for documents that predate the picker feature, and picker metadata is a per-row concern. Keeping the dispatch logic here centralizes the policy. SEM@faff1a18afeac13e5f8de0f7b7b2e16ba77529af: dispatch to the delegated content source when picker metadata and active token exist, else fall back to URI lookup (pure)

func (*ContentSourceRegistry) Names

func (r *ContentSourceRegistry) Names() []string

Names returns the names of all registered sources. SEM@cccf2de369faf0f0361b1d829e82b8ce594f4a99: list names of all registered content sources in priority order (pure)

func (*ContentSourceRegistry) Register

func (r *ContentSourceRegistry) Register(source ContentSource)

Register adds a source to the registry (tried in registration order). SEM@789146ae6555f1667678ed835a68faac5b22ad30: add a content source to the registry in priority order (mutates shared state)

type ContentToken

type ContentToken struct {
	ID                   string
	UserID               string
	ProviderID           string
	AccessToken          string
	RefreshToken         string
	Scopes               string
	ExpiresAt            *time.Time
	Status               string // ContentTokenStatus*
	LastRefreshAt        *time.Time
	LastError            string
	ProviderAccountID    string
	ProviderAccountLabel string
	CreatedAt            time.Time
	ModifiedAt           time.Time
}

ContentToken is the domain representation of a per-user OAuth token used by delegated content providers. Access/refresh tokens are plaintext here; the repository handles encryption at rest. SEM@400c5be318ff2723d5b2aaa9ef1c05111d4629c0: domain model for a per-user OAuth delegated-access token with plaintext credentials

type ContentTokenEncryptor

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

ContentTokenEncryptor performs AES-256-GCM encryption for per-user content OAuth tokens. The nonce is prepended to the ciphertext. SEM@67cb05be66f163c6b55ee71681e1807b49071897: AES-256-GCM encryptor for per-user content OAuth tokens (pure)

func NewContentTokenEncryptor

func NewContentTokenEncryptor(hexKey string) (*ContentTokenEncryptor, error)

NewContentTokenEncryptor constructs an encryptor from a hex-encoded 32-byte key. SEM@67cb05be66f163c6b55ee71681e1807b49071897: build a ContentTokenEncryptor from a hex-encoded 32-byte AES-256 key (pure)

func (*ContentTokenEncryptor) Decrypt

func (e *ContentTokenEncryptor) Decrypt(nonceAndCiphertext []byte) ([]byte, error)

Decrypt parses nonce || ciphertext and returns the plaintext. SEM@67cb05be66f163c6b55ee71681e1807b49071897: decode AES-256-GCM nonce+ciphertext and return the plaintext, rejecting short inputs (pure)

func (*ContentTokenEncryptor) Encrypt

func (e *ContentTokenEncryptor) Encrypt(plaintext []byte) ([]byte, error)

Encrypt returns nonce || ciphertext. SEM@67cb05be66f163c6b55ee71681e1807b49071897: encrypt plaintext under AES-256-GCM and return nonce prepended to ciphertext (pure)

type ContentTokenInfo

type ContentTokenInfo struct {
	// CreatedAt Creation timestamp for this linked token (ISO 8601).
	CreatedAt time.Time `json:"created_at"`

	// ExpiresAt Access-token expiry reported by the provider (ISO 8601).
	ExpiresAt *time.Time `json:"expires_at,omitempty"`

	// LastRefreshAt Timestamp of the most recent successful refresh (ISO 8601).
	LastRefreshAt *time.Time `json:"last_refresh_at,omitempty"`

	// ProviderAccountId External account identifier reported by the provider. May be empty if the provider has no stable id.
	ProviderAccountId *string `json:"provider_account_id,omitempty"`

	// ProviderAccountLabel Human-readable account label (email or username) for display.
	ProviderAccountLabel *string `json:"provider_account_label,omitempty"`

	// ProviderId Content OAuth provider id (e.g., 'confluence').
	ProviderId string `json:"provider_id"`

	// Scopes OAuth scopes granted to the stored token.
	Scopes []string `json:"scopes"`

	// Status Current health of the stored token. 'failed_refresh' indicates the most recent refresh attempt failed and the user must re-link.
	Status ContentTokenInfoStatus `json:"status"`
}

ContentTokenInfo Information about a linked delegated content provider token. Does not expose secret token material.

type ContentTokenInfoStatus

type ContentTokenInfoStatus string

ContentTokenInfoStatus Current health of the stored token. 'failed_refresh' indicates the most recent refresh attempt failed and the user must re-link.

const (
	ContentTokenInfoStatusActive        ContentTokenInfoStatus = "active"
	ContentTokenInfoStatusFailedRefresh ContentTokenInfoStatus = "failed_refresh"
)

Defines values for ContentTokenInfoStatus.

func (ContentTokenInfoStatus) Valid

func (e ContentTokenInfoStatus) Valid() bool

Valid indicates whether the value is a known member of the ContentTokenInfoStatus enum.

type ContentTokenLinkedChecker

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

ContentTokenLinkedChecker implements LinkedProviderChecker over a ContentTokenRepository. It returns true when the user has a token for the given provider with status == ContentTokenStatusActive.

When tokens is nil or any input is empty, returns false (closed-fail). SEM@d330121ff53e262b1d2c0ff6713294e41f615330: LinkedProviderChecker implementation backed by a ContentTokenRepository

func NewContentTokenLinkedChecker

func NewContentTokenLinkedChecker(tokens ContentTokenRepository) *ContentTokenLinkedChecker

NewContentTokenLinkedChecker constructs a LinkedProviderChecker backed by the given ContentTokenRepository. SEM@d330121ff53e262b1d2c0ff6713294e41f615330: build a ContentTokenLinkedChecker from a ContentTokenRepository (pure)

func (*ContentTokenLinkedChecker) HasActiveToken

func (c *ContentTokenLinkedChecker) HasActiveToken(ctx context.Context, userID, providerID string) bool

HasActiveToken returns true iff the user has an active linked token for the provider. See LinkedProviderChecker. SEM@d330121ff53e262b1d2c0ff6713294e41f615330: check whether a user has an active linked token for a provider (reads DB)

type ContentTokenList

type ContentTokenList struct {
	// ContentTokens Array of linked content tokens for the user.
	ContentTokens []ContentTokenInfo `json:"content_tokens"`
}

ContentTokenList List response wrapper for delegated content provider tokens.

type ContentTokenRepository

type ContentTokenRepository interface {
	// GetByUserAndProvider retrieves a token by user ID and provider ID.
	// Returns ErrContentTokenNotFound if no matching token exists.
	GetByUserAndProvider(ctx context.Context, userID, providerID string) (*ContentToken, error)

	// ListByUser returns all tokens for the given user ID.
	ListByUser(ctx context.Context, userID string) ([]ContentToken, error)

	// Upsert creates or updates a token for the (UserID, ProviderID) pair.
	// Returns ErrContentTokenDuplicate on an unexpected unique-key conflict.
	Upsert(ctx context.Context, token *ContentToken) error

	// UpdateStatus updates the status and last_error fields for the token with the given ID.
	// Returns ErrContentTokenNotFound if the token does not exist.
	UpdateStatus(ctx context.Context, id, status, lastError string) error

	// Delete removes the token with the given ID.
	// Returns ErrContentTokenNotFound if the token does not exist.
	Delete(ctx context.Context, id string) error

	// DeleteByUserAndProvider removes the token for the given user/provider pair and
	// returns the deleted token. Returns ErrContentTokenNotFound if it did not exist.
	DeleteByUserAndProvider(ctx context.Context, userID, providerID string) (*ContentToken, error)

	// RefreshWithLock opens a transaction, SELECT ... FOR UPDATE on the row,
	// invokes fn with the current decrypted token, and persists the returned
	// token. Returns the updated token or the fn error.
	RefreshWithLock(ctx context.Context, id string, fn func(current *ContentToken) (*ContentToken, error)) (*ContentToken, error)
}

ContentTokenRepository is the repository abstraction over user_content_tokens. All methods return typed errors from internal/dberrors. SEM@400c5be318ff2723d5b2aaa9ef1c05111d4629c0: repository interface for persisting and retrieving per-user OAuth content tokens

type ContextAwareExtractor

type ContextAwareExtractor = extract.ContextAwareExtractor

Type aliases re-exporting pkg/extract into the api package. The extractor logic was relocated to pkg/extract during Component Platform Plan 2 (#347) so the sandboxed worker can link it without pulling in Gin/GORM. These aliases keep the monolith's many call sites unchanged.

type ContextBuilder

type ContextBuilder struct{}

ContextBuilder constructs LLM context from structured data and vector search results SEM@eec102aedf0150afa44dc0d334e7923359c1f2aa: build structured LLM prompt context from threat-model entities and vector search results (pure)

func NewContextBuilder

func NewContextBuilder() *ContextBuilder

NewContextBuilder creates a new ContextBuilder SEM@eec102aedf0150afa44dc0d334e7923359c1f2aa: build a new ContextBuilder instance (pure)

func (*ContextBuilder) BuildFullContext

func (cb *ContextBuilder) BuildFullContext(basePrompt, tier1, tier2 string) string

BuildFullContext assembles the complete system prompt with context SEM@eec102aedf0150afa44dc0d334e7923359c1f2aa: assemble a complete LLM system prompt by appending tier-1 and tier-2 context blocks (pure)

func (*ContextBuilder) BuildTier1Context

func (cb *ContextBuilder) BuildTier1Context(entitySummaries []EntitySummary) string

BuildTier1Context creates a structured overview of the threat model. This is a placeholder that formats entity names and descriptions. The full implementation will read from stores to get all entity details. SEM@eec102aedf0150afa44dc0d334e7923359c1f2aa: format entity summaries into a structured threat-model overview for an LLM prompt (pure)

func (*ContextBuilder) BuildTier2Context

func (cb *ContextBuilder) BuildTier2Context(index *VectorIndex, queryVector []float32, topK int) string

BuildTier2Context performs vector search and formats results with source attribution SEM@bcbbb37ef77dea47d5a3d7df260c73ad52892c12: search a vector index and format top-K results as attributed source material for an LLM prompt (pure)

func (*ContextBuilder) BuildTier2ContextFromResults

func (cb *ContextBuilder) BuildTier2ContextFromResults(results []VectorSearchResult) string

BuildTier2ContextFromResults formats pre-searched (and optionally reranked) vector search results into tier 2 context for the LLM prompt.

T13 (#353): the chunk text comes from documents the user uploaded or fetched from external URLs and is therefore attacker-controlled. We wrap each chunk in a <document> XML-style fence and sanitize any closing </document> tag inside the chunk so an attacker cannot break out of the untrusted region. The fence is paired with the system-prompt guard (BuildFullContext) which instructs the model to treat <document> blocks as data, never as commands. This is the same pattern Anthropic recommends for prompt injection mitigation. SEM@bcbbb37ef77dea47d5a3d7df260c73ad52892c12: format pre-fetched vector search results as sandboxed document excerpts for an LLM prompt (pure)

type CreateAddonJSONRequestBody

type CreateAddonJSONRequestBody = CreateAddonRequest

CreateAddonJSONRequestBody defines body for CreateAddon for application/json ContentType.

type CreateAddonRequest

type CreateAddonRequest struct {
	// Description Description of what the add-on does
	Description *string `json:"description,omitempty"`

	// Icon Icon identifier (Material Symbols or FontAwesome format)
	Icon *string `json:"icon,omitempty"`

	// Name Display name for the add-on
	Name string `json:"name"`

	// Objects TMI object types this add-on can operate on
	Objects *[]CreateAddonRequestObjects `json:"objects,omitempty"`

	// Parameters Typed parameter declarations for client UI generation. Each parameter defines a name, type, and type-specific configuration that clients use to render appropriate input controls.
	Parameters *[]AddonParameter `json:"parameters,omitempty"`

	// ThreatModelId Optional: Scope add-on to specific threat model
	ThreatModelId *openapi_types.UUID `json:"threat_model_id,omitempty"`

	// WebhookId UUID of the associated webhook subscription
	WebhookId openapi_types.UUID `json:"webhook_id"`
}

CreateAddonRequest Request schema for registering a new addon

type CreateAddonRequestObjects

type CreateAddonRequestObjects string

CreateAddonRequestObjects defines model for CreateAddonRequest.Objects.

const (
	CreateAddonRequestObjectsAsset          CreateAddonRequestObjects = "asset"
	CreateAddonRequestObjectsDiagram        CreateAddonRequestObjects = "diagram"
	CreateAddonRequestObjectsDocument       CreateAddonRequestObjects = "document"
	CreateAddonRequestObjectsMetadata       CreateAddonRequestObjects = "metadata"
	CreateAddonRequestObjectsNote           CreateAddonRequestObjects = "note"
	CreateAddonRequestObjectsRepository     CreateAddonRequestObjects = "repository"
	CreateAddonRequestObjectsSurvey         CreateAddonRequestObjects = "survey"
	CreateAddonRequestObjectsSurveyResponse CreateAddonRequestObjects = "survey_response"
	CreateAddonRequestObjectsThreat         CreateAddonRequestObjects = "threat"
	CreateAddonRequestObjectsThreatModel    CreateAddonRequestObjects = "threat_model"
)

Defines values for CreateAddonRequestObjects.

func (CreateAddonRequestObjects) Valid

func (e CreateAddonRequestObjects) Valid() bool

Valid indicates whether the value is a known member of the CreateAddonRequestObjects enum.

type CreateAdminGroupJSONRequestBody

type CreateAdminGroupJSONRequestBody = CreateAdminGroupRequest

CreateAdminGroupJSONRequestBody defines body for CreateAdminGroup for application/json ContentType.

type CreateAdminGroupRequest

type CreateAdminGroupRequest struct {
	// Description Optional group description
	Description *string `json:"description,omitempty"`

	// GroupName Group identifier (alphanumeric, hyphens, underscores only)
	GroupName string `json:"group_name"`

	// Name Human-readable group name
	Name string `json:"name"`
}

CreateAdminGroupRequest Request body for creating a TMI built-in group

type CreateAdminSurveyJSONRequestBody

type CreateAdminSurveyJSONRequestBody = SurveyInput

CreateAdminSurveyJSONRequestBody defines body for CreateAdminSurvey for application/json ContentType.

type CreateAdminSurveyMetadataJSONRequestBody

type CreateAdminSurveyMetadataJSONRequestBody = Metadata

CreateAdminSurveyMetadataJSONRequestBody defines body for CreateAdminSurveyMetadata for application/json ContentType.

type CreateAdminUserClientCredentialJSONBody

type CreateAdminUserClientCredentialJSONBody struct {
	// Description Optional description of the credential's purpose
	Description *string `json:"description,omitempty"`

	// ExpiresAt Optional expiration timestamp (ISO 8601)
	ExpiresAt *time.Time `json:"expires_at,omitempty"`

	// Name Human-readable name for the credential
	Name string `json:"name"`
}

CreateAdminUserClientCredentialJSONBody defines parameters for CreateAdminUserClientCredential.

type CreateAdminUserClientCredentialJSONRequestBody

type CreateAdminUserClientCredentialJSONRequestBody CreateAdminUserClientCredentialJSONBody

CreateAdminUserClientCredentialJSONRequestBody defines body for CreateAdminUserClientCredential for application/json ContentType.

type CreateAutomationAccountJSONRequestBody

type CreateAutomationAccountJSONRequestBody = CreateAutomationAccountRequest

CreateAutomationAccountJSONRequestBody defines body for CreateAutomationAccount for application/json ContentType.

type CreateAutomationAccountRequest

type CreateAutomationAccountRequest struct {
	// Email Optional custom email address. If not provided, defaults to tmi-automation-{normalized_name}@tmi.local.
	Email *openapi_types.Email `json:"email,omitempty"`

	// Name Short identifier for the automation account (2-64 characters). Used to construct the account name, email, and provider ID. Must start with a letter and end with a letter or digit.
	Name string `json:"name"`
}

CreateAutomationAccountRequest Request body for creating an automation (service) account

type CreateAutomationAccountResponse

type CreateAutomationAccountResponse struct {
	// ClientCredential Response from creating a client credential. WARNING: The client_secret is ONLY returned once and cannot be retrieved later.
	ClientCredential ClientCredentialResponse `json:"client_credential"`

	// User User object with administrative fields and enriched data
	User AdminUser `json:"user"`
}

CreateAutomationAccountResponse Response from creating an automation account. Contains the created user and a client credential with the plaintext secret (shown only once).

type CreateClientCredentialRequest

type CreateClientCredentialRequest struct {
	Name        string     `json:"name" binding:"required,min=1,max=100"`
	Description string     `json:"description" binding:"max=500"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
}

CreateClientCredentialRequest contains parameters for creating a new client credential SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: parameters for creating a new client credential, including name and optional expiry (pure)

type CreateClientCredentialResponse

type CreateClientCredentialResponse struct {
	ID           uuid.UUID  `json:"id"`
	ClientID     string     `json:"client_id"`
	ClientSecret string     `json:"client_secret"`
	Name         string     `json:"name"`
	Description  string     `json:"description"`
	CreatedAt    time.Time  `json:"created_at"`
	ExpiresAt    *time.Time `json:"expires_at,omitempty"`
}

CreateClientCredentialResponse contains the response from creating a client credential WARNING: The client_secret is ONLY returned at creation time and cannot be retrieved later SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: response for a new client credential including the plaintext secret shown only once (pure)

type CreateContentFeedbackJSONRequestBody

type CreateContentFeedbackJSONRequestBody = ContentFeedbackInput

CreateContentFeedbackJSONRequestBody defines body for CreateContentFeedback for application/json ContentType.

type CreateCurrentUserClientCredentialJSONBody

type CreateCurrentUserClientCredentialJSONBody struct {
	// Description Optional description of the credential's purpose
	Description *string `json:"description,omitempty"`

	// ExpiresAt Optional expiration timestamp (ISO 8601)
	ExpiresAt *time.Time `json:"expires_at,omitempty"`

	// Name Human-readable name for the credential
	Name string `json:"name"`
}

CreateCurrentUserClientCredentialJSONBody defines parameters for CreateCurrentUserClientCredential.

type CreateCurrentUserClientCredentialJSONRequestBody

type CreateCurrentUserClientCredentialJSONRequestBody CreateCurrentUserClientCredentialJSONBody

CreateCurrentUserClientCredentialJSONRequestBody defines body for CreateCurrentUserClientCredential for application/json ContentType.

type CreateCurrentUserPreferencesJSONRequestBody

type CreateCurrentUserPreferencesJSONRequestBody = UserPreferences

CreateCurrentUserPreferencesJSONRequestBody defines body for CreateCurrentUserPreferences for application/json ContentType.

type CreateDiagramMetadataJSONRequestBody

type CreateDiagramMetadataJSONRequestBody = Metadata

CreateDiagramMetadataJSONRequestBody defines body for CreateDiagramMetadata for application/json ContentType.

type CreateDiagramRequest

type CreateDiagramRequest struct {
	// Name Name of the diagram
	Name string `json:"name"`

	// Type Type of diagram with version
	Type CreateDiagramRequestType `json:"type"`
}

CreateDiagramRequest Request body for creating a new diagram - only includes client-provided fields

type CreateDiagramRequestType

type CreateDiagramRequestType string

CreateDiagramRequestType Type of diagram with version

const (
	CreateDiagramRequestTypeDFD100 CreateDiagramRequestType = "DFD-1.0.0"
)

Defines values for CreateDiagramRequestType.

func (CreateDiagramRequestType) Valid

func (e CreateDiagramRequestType) Valid() bool

Valid indicates whether the value is a known member of the CreateDiagramRequestType enum.

type CreateDocumentMetadataJSONRequestBody

type CreateDocumentMetadataJSONRequestBody = Metadata

CreateDocumentMetadataJSONRequestBody defines body for CreateDocumentMetadata for application/json ContentType.

type CreateIntakeSurveyResponseJSONRequestBody

type CreateIntakeSurveyResponseJSONRequestBody = SurveyResponseCreateRequest

CreateIntakeSurveyResponseJSONRequestBody defines body for CreateIntakeSurveyResponse for application/json ContentType.

type CreateIntakeSurveyResponseMetadataJSONRequestBody

type CreateIntakeSurveyResponseMetadataJSONRequestBody = Metadata

CreateIntakeSurveyResponseMetadataJSONRequestBody defines body for CreateIntakeSurveyResponseMetadata for application/json ContentType.

type CreateNoteMetadataJSONRequestBody

type CreateNoteMetadataJSONRequestBody = Metadata

CreateNoteMetadataJSONRequestBody defines body for CreateNoteMetadata for application/json ContentType.

type CreateProjectJSONRequestBody

type CreateProjectJSONRequestBody = ProjectInput

CreateProjectJSONRequestBody defines body for CreateProject for application/json ContentType.

type CreateProjectMetadataJSONRequestBody

type CreateProjectMetadataJSONRequestBody = Metadata

CreateProjectMetadataJSONRequestBody defines body for CreateProjectMetadata for application/json ContentType.

type CreateProjectNoteJSONRequestBody

type CreateProjectNoteJSONRequestBody = ProjectNoteInput

CreateProjectNoteJSONRequestBody defines body for CreateProjectNote for application/json ContentType.

type CreateRepositoryMetadataJSONRequestBody

type CreateRepositoryMetadataJSONRequestBody = Metadata

CreateRepositoryMetadataJSONRequestBody defines body for CreateRepositoryMetadata for application/json ContentType.

type CreateTeamJSONRequestBody

type CreateTeamJSONRequestBody = TeamInput

CreateTeamJSONRequestBody defines body for CreateTeam for application/json ContentType.

type CreateTeamMetadataJSONRequestBody

type CreateTeamMetadataJSONRequestBody = Metadata

CreateTeamMetadataJSONRequestBody defines body for CreateTeamMetadata for application/json ContentType.

type CreateTeamNoteJSONRequestBody

type CreateTeamNoteJSONRequestBody = TeamNoteInput

CreateTeamNoteJSONRequestBody defines body for CreateTeamNote for application/json ContentType.

type CreateThreatMetadataJSONRequestBody

type CreateThreatMetadataJSONRequestBody = Metadata

CreateThreatMetadataJSONRequestBody defines body for CreateThreatMetadata for application/json ContentType.

type CreateThreatModelAssetJSONRequestBody

type CreateThreatModelAssetJSONRequestBody = AssetInput

CreateThreatModelAssetJSONRequestBody defines body for CreateThreatModelAsset for application/json ContentType.

type CreateThreatModelAssetMetadataJSONRequestBody

type CreateThreatModelAssetMetadataJSONRequestBody = Metadata

CreateThreatModelAssetMetadataJSONRequestBody defines body for CreateThreatModelAssetMetadata for application/json ContentType.

type CreateThreatModelDiagramJSONRequestBody

type CreateThreatModelDiagramJSONRequestBody = CreateDiagramRequest

CreateThreatModelDiagramJSONRequestBody defines body for CreateThreatModelDiagram for application/json ContentType.

type CreateThreatModelDocumentJSONRequestBody

type CreateThreatModelDocumentJSONRequestBody = DocumentInput

CreateThreatModelDocumentJSONRequestBody defines body for CreateThreatModelDocument for application/json ContentType.

type CreateThreatModelFromSurveyResponse

type CreateThreatModelFromSurveyResponse struct {
	// SurveyResponseId ID of the source survey response
	SurveyResponseId openapi_types.UUID `json:"survey_response_id"`

	// ThreatModelId ID of the newly created threat model
	ThreatModelId openapi_types.UUID `json:"threat_model_id"`
}

CreateThreatModelFromSurveyResponse Response after creating a threat model from a survey response

type CreateThreatModelJSONRequestBody

type CreateThreatModelJSONRequestBody = ThreatModelInput

CreateThreatModelJSONRequestBody defines body for CreateThreatModel for application/json ContentType.

type CreateThreatModelMetadataJSONRequestBody

type CreateThreatModelMetadataJSONRequestBody = Metadata

CreateThreatModelMetadataJSONRequestBody defines body for CreateThreatModelMetadata for application/json ContentType.

type CreateThreatModelNoteJSONRequestBody

type CreateThreatModelNoteJSONRequestBody = NoteInput

CreateThreatModelNoteJSONRequestBody defines body for CreateThreatModelNote for application/json ContentType.

type CreateThreatModelRepositoryJSONRequestBody

type CreateThreatModelRepositoryJSONRequestBody = RepositoryInput

CreateThreatModelRepositoryJSONRequestBody defines body for CreateThreatModelRepository for application/json ContentType.

type CreateThreatModelThreatJSONRequestBody

type CreateThreatModelThreatJSONRequestBody = ThreatInput

CreateThreatModelThreatJSONRequestBody defines body for CreateThreatModelThreat for application/json ContentType.

type CreateTimmyChatMessageJSONRequestBody

type CreateTimmyChatMessageJSONRequestBody = CreateTimmyMessageRequest

CreateTimmyChatMessageJSONRequestBody defines body for CreateTimmyChatMessage for application/json ContentType.

type CreateTimmyChatSessionJSONRequestBody

type CreateTimmyChatSessionJSONRequestBody = CreateTimmySessionRequest

CreateTimmyChatSessionJSONRequestBody defines body for CreateTimmyChatSession for application/json ContentType.

type CreateTimmyMessageRequest

type CreateTimmyMessageRequest struct {
	// Content Message content to send to Timmy
	Content string `json:"content"`
}

CreateTimmyMessageRequest Request body for creating a message in a Timmy chat session

type CreateTimmySessionRequest

type CreateTimmySessionRequest struct {
	// Title Optional session title
	Title *string `json:"title,omitempty"`
}

CreateTimmySessionRequest Optional request body for creating a Timmy chat session

type CreateTriageSurveyResponseTriageNoteJSONRequestBody

type CreateTriageSurveyResponseTriageNoteJSONRequestBody = TriageNoteInput

CreateTriageSurveyResponseTriageNoteJSONRequestBody defines body for CreateTriageSurveyResponseTriageNote for application/json ContentType.

type CreateUsabilityFeedbackJSONRequestBody

type CreateUsabilityFeedbackJSONRequestBody = UsabilityFeedbackInput

CreateUsabilityFeedbackJSONRequestBody defines body for CreateUsabilityFeedback for application/json ContentType.

type CreateWebhookSubscriptionJSONRequestBody

type CreateWebhookSubscriptionJSONRequestBody = WebhookSubscriptionInput

CreateWebhookSubscriptionJSONRequestBody defines body for CreateWebhookSubscription for application/json ContentType.

type CreatedAfter

type CreatedAfter = time.Time

CreatedAfter defines model for CreatedAfter.

type CreatedAfterQueryParam

type CreatedAfterQueryParam = time.Time

CreatedAfterQueryParam defines model for CreatedAfterQueryParam.

type CreatedBefore

type CreatedBefore = time.Time

CreatedBefore defines model for CreatedBefore.

type CreatedBeforeQueryParam

type CreatedBeforeQueryParam = time.Time

CreatedBeforeQueryParam defines model for CreatedBeforeQueryParam.

type CredentialIdPathParam

type CredentialIdPathParam = openapi_types.UUID

CredentialIdPathParam defines model for CredentialIdPathParam.

type CursorPosition

type CursorPosition struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

CursorPosition represents cursor coordinates SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: 2D canvas coordinates for the presenter's cursor location (pure)

type CustomDiagram

type CustomDiagram struct {
	DfdDiagram
	Owner         string
	Authorization []Authorization
}

Fixtures provides test data for unit tests CustomDiagram extends Diagram with authorization fields for testing SEM@71c76e4f3ee8185c2e04a7476bacd2537c75d2e4: test-only diagram type extending DfdDiagram with owner and authorization fields (pure)

type DBWebhookQuota

type DBWebhookQuota struct {
	OwnerId                          uuid.UUID `json:"owner_id"`
	MaxSubscriptions                 int       `json:"max_subscriptions"`
	MaxEventsPerMinute               int       `json:"max_events_per_minute"`
	MaxSubscriptionRequestsPerMinute int       `json:"max_subscription_requests_per_minute"`
	MaxSubscriptionRequestsPerDay    int       `json:"max_subscription_requests_per_day"`
	CreatedAt                        time.Time `json:"created_at"`
	ModifiedAt                       time.Time `json:"modified_at"`
}

DBWebhookQuota represents per-owner rate limits with database timestamps This is the internal database model; the API uses the generated WebhookQuota type SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: DB model for per-owner webhook rate limits with subscription and event caps

func (*DBWebhookQuota) SetCreatedAt

func (w *DBWebhookQuota) SetCreatedAt(t time.Time)

SetCreatedAt implements WithTimestamps for DBWebhookQuota SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: set the created_at timestamp on a webhook quota record (mutates shared state)

func (*DBWebhookQuota) SetModifiedAt

func (w *DBWebhookQuota) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps for DBWebhookQuota SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: set the modified_at timestamp on a webhook quota record (mutates shared state)

type DBWebhookSubscription

type DBWebhookSubscription struct {
	Id            uuid.UUID  `json:"id"`
	OwnerId       uuid.UUID  `json:"owner_id"`
	ThreatModelId *uuid.UUID `json:"threat_model_id,omitempty"` // NULL means all threat models
	Name          string     `json:"name"`
	Url           string     `json:"url"`
	Events        []string   `json:"events"`

	Secret              string     `json:"secret,omitempty"`
	Status              string     `json:"status"` // pending_verification, active, pending_delete
	Challenge           string     `json:"challenge,omitempty"`
	ChallengesSent      int        `json:"challenges_sent"`
	CreatedAt           time.Time  `json:"created_at"`
	ModifiedAt          time.Time  `json:"modified_at"`
	LastSuccessfulUse   *time.Time `json:"last_successful_use,omitempty"`
	PublicationFailures int        `json:"publication_failures"`
	TimeoutCount        int        `json:"timeout_count"` // Count of consecutive addon invocation timeouts
	OperatorPinned      bool       `json:"operator_pinned"`
}

DBWebhookSubscription represents a webhook subscription in the database SEM@a19a29138f4caaab0d2efe0d5b6f54106b447672: DB model for a webhook subscription with lifecycle and delivery-tracking fields

func EnsurePinnedAlertSubscription

EnsurePinnedAlertSubscription upserts the single operator-pinned webhook subscription for out-of-band audit alerting (T7, #395).

When cfg.Enabled is true:

  • If no pinned subscription exists yet, a new active subscription is created owned by the operator system user with the EventSystemAuditAdminWrite event type.
  • If a pinned subscription already exists, it is updated in-place with the current URL/Secret from config and its status is set to "active".

When cfg.Enabled is false:

  • If a pinned subscription exists with status != "inactive", it is deactivated (status set to "inactive").
  • The function is a no-op if no pinned subscription exists.

The denyListStore is used for URL validation when cfg.Enabled is true. A nil denyListStore skips URL validation (e.g., in unit tests).

Returns the active/updated subscription (zero value if disabled / no-op). SEM@13c4215bf8e204da342579717f97f7393bb5fe2f: upsert or deactivate the operator-pinned audit alert webhook subscription from config (reads DB)

func (*DBWebhookSubscription) SetCreatedAt

func (w *DBWebhookSubscription) SetCreatedAt(t time.Time)

SetCreatedAt implements WithTimestamps SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: set the created_at timestamp on a webhook subscription (mutates shared state)

func (*DBWebhookSubscription) SetModifiedAt

func (w *DBWebhookSubscription) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: set the modified_at timestamp on a webhook subscription (mutates shared state)

type DLQProducer

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

DLQProducer turns JetStream MAX_DELIVERIES advisories into dead-letter messages. For each advisory on a per-component job stream it recovers the original Job envelope by sequence, republishes it to jobs.dlq, and deletes the source message (reclaiming the WorkQueue slot). It is the only durable path by which a worker that crashed mid-job (and thus never published a result) reaches a clean terminal state. SEM@9f721ae6fdda8037fd155b0c74eca0cde74fe1ba: routes MAX_DELIVERIES advisories to the dead-letter queue and reclaims source slots (mutates shared state)

func NewDLQProducer

func NewDLQProducer(conn *worker.Conn) *DLQProducer

NewDLQProducer constructs a DLQProducer bound to the monolith's NATS conn. SEM@9f721ae6fdda8037fd155b0c74eca0cde74fe1ba: build a DLQProducer bound to the given NATS connection (pure)

func (*DLQProducer) Start

func (p *DLQProducer) Start(ctx context.Context) error

Start ensures the streams exist, creates a durable consumer on the advisory-capture stream, and begins processing advisories in the background. It returns after the consumer is created. Call Stop to release resources. SEM@6d0d434b964452ae1f5422ff7c9367bbc31a56e4: subscribe a durable advisory consumer and begin dead-lettering in the background (mutates shared state)

func (*DLQProducer) Stop

func (p *DLQProducer) Stop()

Stop cancels the producer's context. Safe to call when Start was never run. SEM@9f721ae6fdda8037fd155b0c74eca0cde74fe1ba: cancel the producer's background context, halting advisory processing (mutates shared state)

type DatabaseClientCredentialQuotaStore

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

DatabaseClientCredentialQuotaStore implements ClientCredentialQuotaStore using auth service and global quota store SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: database-backed implementation of ClientCredentialQuotaStore with configurable default quota (pure)

func NewDatabaseClientCredentialQuotaStore

func NewDatabaseClientCredentialQuotaStore(authService *auth.Service, defaultQuota int, globalStore UserAPIQuotaStoreInterface) *DatabaseClientCredentialQuotaStore

NewDatabaseClientCredentialQuotaStore creates a new client credential quota store SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: build a DatabaseClientCredentialQuotaStore with a default quota floor (pure)

func (*DatabaseClientCredentialQuotaStore) CheckClientCredentialQuota

func (s *DatabaseClientCredentialQuotaStore) CheckClientCredentialQuota(ctx context.Context, userUUID uuid.UUID) error

CheckClientCredentialQuota verifies if a user can create a new credential SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: validate that a user has not exceeded their client credential quota (reads DB)

func (*DatabaseClientCredentialQuotaStore) GetClientCredentialCount

func (s *DatabaseClientCredentialQuotaStore) GetClientCredentialCount(ctx context.Context, userUUID uuid.UUID) (int, error)

GetClientCredentialCount retrieves the current number of active credentials for a user SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: count the active client credentials owned by a user (reads DB)

func (*DatabaseClientCredentialQuotaStore) GetClientCredentialQuota

func (s *DatabaseClientCredentialQuotaStore) GetClientCredentialQuota(ctx context.Context, userUUID uuid.UUID) (int, error)

GetClientCredentialQuota retrieves the maximum number of credentials allowed for a user SEM@99c8cc4c042f4729b89e24981a18dba21b40be17: fetch the maximum number of client credentials allowed for a user (pure)

type DecomposedQuery

type DecomposedQuery struct {
	TextQuery string `json:"text_query"`
	CodeQuery string `json:"code_query"`
	Strategy  string `json:"strategy"`
}

DecomposedQuery holds the sub-queries produced by decomposing a user query. SEM@f06df1eae94dd2ca361cfb88f9f58fdc2bbfced6: value type holding text and code sub-queries produced by query decomposition (pure)

type DecomposerLLM

type DecomposerLLM interface {
	GenerateResponse(ctx context.Context, systemPrompt string, userMessage string) (string, error)
}

DecomposerLLM is a narrow interface for LLM single-turn generation, used by LLMQueryDecomposer to allow easy mocking in tests. SEM@f06df1eae94dd2ca361cfb88f9f58fdc2bbfced6: interface for single-turn LLM text generation used by the query decomposer (pure)

type DelegatedConfluenceSource

type DelegatedConfluenceSource struct {
	// Delegated is the shared DelegatedSource helper that handles token
	// lookup, lazy refresh, and status transitions.
	Delegated *DelegatedSource
	// contains filtered or unexported fields
}

DelegatedConfluenceSource fetches Confluence Cloud page content under the authenticated user's identity, using a per-user OAuth token managed by the shared DelegatedSource helper.

Construct via NewDelegatedConfluenceSource. A zero-value struct has no Delegated helper and will panic on Fetch. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: content source that fetches Confluence pages via delegated OAuth tokens

func NewDelegatedConfluenceSource

func NewDelegatedConfluenceSource(
	tokens ContentTokenRepository,
	registry *ContentOAuthProviderRegistry,
	validator *URIValidator,
) *DelegatedConfluenceSource

NewDelegatedConfluenceSource constructs a Confluence delegated source wired to the given token repository and OAuth provider registry. validator MUST be non-nil; in production it is built from the operator's content-source allowlist (typically containing api.atlassian.com). SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build a DelegatedConfluenceSource with a hardened HTTP client and token store (pure)

func (*DelegatedConfluenceSource) CanHandle

func (s *DelegatedConfluenceSource) CanHandle(_ context.Context, uri string) bool

CanHandle returns true for Confluence Cloud page URLs of the form https://*.atlassian.net/wiki/... SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: validate that a URI is a supported Atlassian Cloud Confluence page URL (pure)

func (*DelegatedConfluenceSource) Fetch

func (s *DelegatedConfluenceSource) Fetch(ctx context.Context, uri string) ([]byte, string, error)

Fetch returns the page's view-format HTML for the user in ctx. Requires UserIDFromContext to return a non-empty user id; delegated sources cannot run without user context. SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: fetch Confluence page content for the authenticated user via OAuth token

func (*DelegatedConfluenceSource) Name

Name returns the provider id "confluence". SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: return the canonical provider name for this source (pure)

func (*DelegatedConfluenceSource) RequestAccess

func (s *DelegatedConfluenceSource) RequestAccess(_ context.Context, uri string) error

RequestAccess logs an actionable hint. Confluence has no programmatic access-request equivalent; the user-facing remediation is surfaced via access_diagnostics at the pipeline/handler level (re-link the account or ask a Confluence space admin for view permissions). SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: notify that Confluence access is unavailable; user must re-link (pure)

func (*DelegatedConfluenceSource) ValidateAccess

func (s *DelegatedConfluenceSource) ValidateAccess(ctx context.Context, uri string) (bool, error)

ValidateAccess probes whether the user's token can read the page metadata without downloading the page body. Uses a per-call probe DelegatedSource to avoid racing against concurrent Fetch DoFetch invocations.

Error semantics mirror DelegatedGoogleWorkspaceSource:

  • (false, ErrAuthRequired): no user in context, no token, or failed_refresh.
  • (false, ErrTransient): refresh hit a 5xx/network failure.
  • (false, nil): page is not reachable for this user (4xx) or URL is malformed; treated as "not accessible" rather than systemic.
  • (true, nil): metadata probe succeeded.

SEM@6199f1bebeb0a5e637b7c38588d721ac36b525f4: validate that the user's OAuth token can access the given Confluence page URL

type DelegatedGoogleWorkspaceSource

type DelegatedGoogleWorkspaceSource struct {
	// Delegated is the shared DelegatedSource helper (Task 3.2 sets DoFetch).
	Delegated *DelegatedSource

	// PickerDeveloperKey and PickerAppID are returned to clients via the
	// picker-token endpoint (Task 5.2); they are not used by Fetch itself.
	PickerDeveloperKey string
	PickerAppID        string
}

DelegatedGoogleWorkspaceSource fetches Drive documents under the user's own identity via drive.file-scoped tokens granted through Google Picker. Documents must have been picker-registered (stored picker_file_id) for fetches to succeed; picker registration is performed by the client at attach time.

The dispatch layer (ContentSourceRegistry.FindSourceForDocument, added in Task 4.1) decides whether to route this source or fall through to the service-account GoogleDriveSource based on whether the document has picker metadata and the user has a linked token.

Construct via NewDelegatedGoogleWorkspaceSource (Task 3.2). A zero-value struct has no Delegated helper and will panic on Fetch. SEM@3d1c365886b95c6bdb2dab7691650f26dd8e27e2: content source that fetches Google Drive files using the user's delegated picker token

func NewDelegatedGoogleWorkspaceSource

func NewDelegatedGoogleWorkspaceSource(
	tokens ContentTokenRepository,
	registry *ContentOAuthProviderRegistry,
	pickerDeveloperKey, pickerAppID string,
) *DelegatedGoogleWorkspaceSource

NewDelegatedGoogleWorkspaceSource constructs a source wired to the given token repository and OAuth provider registry. The DoFetch callback creates a Drive service with the supplied access token on each call (no connection caching — lightweight at this scale). SEM@f5ad62889026b34082705666e24770ea9883b8f9: build a DelegatedGoogleWorkspaceSource wired to the given token repository and OAuth registry

func (*DelegatedGoogleWorkspaceSource) CanHandle

CanHandle returns true for Google Docs and Google Drive URIs. The dispatch layer (FindSourceForDocument) is responsible for deciding whether this source or the service-account GoogleDriveSource handles a given document; CanHandle only filters by URI host. SEM@3d1c365886b95c6bdb2dab7691650f26dd8e27e2: report whether a URI targets Google Docs or Google Drive hosts (pure)

func (*DelegatedGoogleWorkspaceSource) Fetch

Fetch returns the raw bytes of the referenced Drive file for the user in ctx. Requires UserIDFromContext to return a non-empty user id; delegated sources cannot run without user context.

The actual Drive API call lives in the DelegatedSource.DoFetch callback (Task 3.2 implementation); this skeleton delegates to the helper. SEM@3d1c365886b95c6bdb2dab7691650f26dd8e27e2: fetch raw Drive file bytes for the user in context using delegated credentials

func (*DelegatedGoogleWorkspaceSource) Name

Name returns the provider id "google_workspace". SEM@3d1c365886b95c6bdb2dab7691650f26dd8e27e2: return the provider identifier string for Google Workspace (pure)

func (*DelegatedGoogleWorkspaceSource) RequestAccess

func (s *DelegatedGoogleWorkspaceSource) RequestAccess(_ context.Context, uri string) error

RequestAccess logs an actionable hint. The actual user-facing remediation is surfaced via access_diagnostics (reason_code + remediations[]) at the pipeline/handler level. This method exists to satisfy the AccessRequester interface; no Drive API call is made. SEM@f5ad62889026b34082705666e24770ea9883b8f9: log an access hint for a Drive URI; satisfies AccessRequester interface (no Drive call)

func (*DelegatedGoogleWorkspaceSource) ValidateAccess

func (s *DelegatedGoogleWorkspaceSource) ValidateAccess(ctx context.Context, uri string) (bool, error)

ValidateAccess checks whether the user's token can see the referenced file without downloading content. Implementation uses a per-call probe DelegatedSource so concurrent ValidateAccess calls don't race on the shared source's DoFetch field.

Error semantics:

  • (false, ErrAuthRequired): no user in context, no linked token, or the stored token is in failed_refresh.
  • (false, ErrTransient): provider returned 5xx/network during refresh.
  • (false, nil): Drive returned a 4xx for the file (not accessible); this includes malformed file id extraction, since that is treated as "we can't reach this file" rather than a systemic error.
  • (true, nil): Drive accepted the metadata probe.

SEM@f5ad62889026b34082705666e24770ea9883b8f9: probe whether the user's linked token can access a Drive file without downloading it

type DelegatedMicrosoftSource

type DelegatedMicrosoftSource struct {
	// Delegated is the shared DelegatedSource helper.
	Delegated *DelegatedSource

	// GraphBaseURL overrides graphV1Base in tests.
	GraphBaseURL string
	// contains filtered or unexported fields
}

DelegatedMicrosoftSource fetches OneDrive-for-Business and SharePoint content under the user's own delegated identity. The user's token must carry Files.SelectedOperations.Selected (granted per-file by either the file owner — Experience 1, paste-URL with a copy-pasteable Graph snippet — or by TMI's picker-grant endpoint — Experience 2, after the user picks a file via the Microsoft File Picker). The provider name "microsoft" is reused for both OneDrive-for-Business and SharePoint Online. See issue #286 for the design discussion. SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: content source that fetches OneDrive and SharePoint files under the user's delegated identity

func NewDelegatedMicrosoftSource

func NewDelegatedMicrosoftSource(
	tokens ContentTokenRepository,
	registry *ContentOAuthProviderRegistry,
	validator *URIValidator,
) *DelegatedMicrosoftSource

NewDelegatedMicrosoftSource constructs a source wired to the given token repository and OAuth provider registry. The DoFetch callback uses the share-id resolution path (Experience 1). The picker-mediated path is equivalent at fetch time because the per-file grant from the picker makes /shares/{shareId}/driveItem succeed for that specific file.

validator MUST be non-nil; in production it is built from the operator's content-source allowlist (typically containing graph.microsoft.com). SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build a DelegatedMicrosoftSource wired to the given token repository and OAuth provider registry

func (*DelegatedMicrosoftSource) CanHandle

func (s *DelegatedMicrosoftSource) CanHandle(_ context.Context, uri string) bool

CanHandle returns true for hosts served by the multi-audience Microsoft delegated provider:

  • *.sharepoint.com — Entra-managed OneDrive-for-Business + SharePoint (#286)
  • onedrive.live.com — consumer OneDrive root (#297)
  • *.onedrive.live.com — consumer OneDrive regional/tenant subdomains (#297)
  • 1drv.ms — consumer OneDrive short link (#297)

All four route to the same DelegatedMicrosoftSource because Microsoft Graph /shares/{shareId}/driveItem resolves uniformly across audiences once the user has consented and per-file permission is in place. SEM@a2db6d159e7859f682bdd332f9a3bfb0b222b7af: report whether a URI targets SharePoint, OneDrive, or OneDrive short-link hosts (pure)

func (*DelegatedMicrosoftSource) Fetch

func (s *DelegatedMicrosoftSource) Fetch(ctx context.Context, uri string) ([]byte, string, error)

Fetch returns the raw bytes of the referenced SharePoint/OneDrive-for-Business file for the user in ctx. Requires UserIDFromContext to return a non-empty user id; delegated sources cannot run without user context. SEM@954ba87f4131d0a3fd27a1c4aa0e39eaf576dd4e: fetch a SharePoint or OneDrive file using the requesting user's delegated token

func (*DelegatedMicrosoftSource) Name

func (s *DelegatedMicrosoftSource) Name() string

Name returns the provider id "microsoft". SEM@954ba87f4131d0a3fd27a1c4aa0e39eaf576dd4e: return the provider identifier "microsoft" (pure)

func (*DelegatedMicrosoftSource) RequestAccess

func (s *DelegatedMicrosoftSource) RequestAccess(_ context.Context, uri string) error

RequestAccess logs an informational entry and returns nil. The user-facing remediation is surfaced via document access_diagnostics (reason_code + remediations[]) at the handler level. See api/access_diagnostics.go and the document GET handler for the user-visible "share with TMI app" snippet. SEM@a2be144a7f5811ad4833b7435ffaf713e3becd3a: log that the user must grant per-file Graph permissions to the TMI app

func (*DelegatedMicrosoftSource) ValidateAccess

func (s *DelegatedMicrosoftSource) ValidateAccess(ctx context.Context, uri string) (bool, error)

ValidateAccess checks whether the user's token can resolve the URI to a drive item without downloading the body. Per-call probe DelegatedSource avoids racing on the shared source's DoFetch field when concurrent ValidateAccess calls are in flight.

Error semantics:

  • (false, ErrAuthRequired): no user, no token, or token in failed_refresh.
  • (false, ErrTransient): provider returned 5xx during refresh OR Graph 5xx.
  • (false, nil): Graph returned 4xx (not accessible).
  • (true, nil): metadata probe succeeded.

SEM@a2be144a7f5811ad4833b7435ffaf713e3becd3a: probe whether the user's delegated token can resolve a SharePoint URI without downloading the file

type DelegatedSource

type DelegatedSource struct {
	// ProviderID is the OAuth provider identifier (e.g. "confluence").
	ProviderID string
	// Tokens is the repository used to look up and refresh tokens.
	Tokens ContentTokenRepository
	// Registry is used to look up the OAuth provider by ProviderID.
	Registry *ContentOAuthProviderRegistry
	// DoFetch is the provider-specific fetch callback. It receives the
	// plaintext access token and URI and returns raw bytes + content-type.
	DoFetch DelegatedSourceDoFetch
	// Skew is the time added to now() when comparing against ExpiresAt to
	// proactively refresh tokens about to expire. Defaults to 30s when zero.
	Skew time.Duration
}

DelegatedSource is a reusable helper that concrete delegated content sources (e.g. Confluence, Google Workspace) embed to handle token lookup, skew-aware expiry detection, lazy refresh with SELECT … FOR UPDATE serialization, status transitions, and error propagation (ErrAuthRequired, ErrTransient). SEM@df6661062f48aa17a42442510c452bf0eebc4542: reusable helper embedding token lookup, expiry detection, and lazy refresh for delegated content sources (struct)

func (*DelegatedSource) FetchForUser

func (d *DelegatedSource) FetchForUser(ctx context.Context, userID, uri string) ([]byte, string, error)

FetchForUser fetches the resource at uri on behalf of userID.

Error semantics:

  • ErrAuthRequired: no token, or token status is failed_refresh. The caller should redirect the user to re-authorize.
  • ErrTransient: refresh failed with a transient (5xx/network) error. The caller may retry.
  • Any other error: propagated from DoFetch.

SEM@df6661062f48aa17a42442510c452bf0eebc4542: fetch a URI on behalf of a user, refreshing the access token if expired; returns ErrAuthRequired or ErrTransient on failure

type DelegatedSourceDoFetch

type DelegatedSourceDoFetch func(ctx context.Context, accessToken, uri string) (data []byte, contentType string, err error)

DelegatedSourceDoFetch is the callback concrete delegated sources implement. It receives the plaintext access token and the URI to fetch, and returns the raw bytes and content-type of the fetched resource. SEM@df6661062f48aa17a42442510c452bf0eebc4542: callback type for fetching a URI with an access token, returning bytes and content type (pure)

type DelegationTokenIssuer

type DelegationTokenIssuer interface {
	// IssueForInvocation mints a delegation JWT impersonating the invoker
	// (looked up by invokerInternalUUID) for one addon-invocation
	// write-back. The token's scope is bound to addonID + deliveryID +
	// threatModelID, with a wall-clock TTL matching the addon-invocation
	// budget (60s today). On success it returns the encoded JWT.
	IssueForInvocation(
		ctx context.Context,
		invokerInternalUUID string,
		addonID, deliveryID, threatModelID uuid.UUID,
	) (string, error)
}

DelegationTokenIssuer is the seam between the api package and the auth package's IssueAddonDelegationToken. The webhook delivery worker uses it to mint a fresh, scoped delegation JWT for each addon.invoked delivery so the downstream addon can perform write-backs as the invoker (T18, #358) rather than as its own service-account.

Set from cmd/server/main.go after the auth service is initialized via SetGlobalDelegationTokenIssuer. The implementation lives in auth_service_adapter.go and wraps auth.Service.GetUserByID + auth.Service.IssueAddonDelegationToken. SEM@e6be8a8f816c564356a656ac18f3693ac7f10369: interface for minting a scoped delegation JWT impersonating an invoker for addon write-backs (pure)

var GlobalDelegationTokenIssuer DelegationTokenIssuer

GlobalDelegationTokenIssuer is the package-level hook the webhook delivery worker reads. nil during early startup and in unit tests that do not exercise the addon path; the worker degrades gracefully (no delegation token attached) when nil and logs at Warn.

type DeleteAdminSurveyParams

type DeleteAdminSurveyParams struct {
	// Force When true, delete the survey even if it has responses, cascading deletion to all of its responses and their sub-resources (triage notes, access grants, metadata, answers). Intended as an admin cleanup affordance; without it a survey that has responses cannot be deleted (409).
	Force *bool `form:"force,omitempty" json:"force,omitempty"`
}

DeleteAdminSurveyParams defines parameters for DeleteAdminSurvey.

type DeleteEmbeddingsParams

type DeleteEmbeddingsParams struct {
	// EntityType Filter by entity type
	EntityType *string `form:"entity_type,omitempty" json:"entity_type,omitempty"`

	// EntityId Filter by entity UUID
	EntityId *openapi_types.UUID `form:"entity_id,omitempty" json:"entity_id,omitempty"`

	// IndexType Filter by index type
	IndexType *DeleteEmbeddingsParamsIndexType `form:"index_type,omitempty" json:"index_type,omitempty"`
}

DeleteEmbeddingsParams defines parameters for DeleteEmbeddings.

type DeleteEmbeddingsParamsIndexType

type DeleteEmbeddingsParamsIndexType string

DeleteEmbeddingsParamsIndexType defines parameters for DeleteEmbeddings.

const (
	DeleteEmbeddingsParamsIndexTypeCode DeleteEmbeddingsParamsIndexType = "code"
	DeleteEmbeddingsParamsIndexTypeText DeleteEmbeddingsParamsIndexType = "text"
)

Defines values for DeleteEmbeddingsParamsIndexType.

func (DeleteEmbeddingsParamsIndexType) Valid

Valid indicates whether the value is a known member of the DeleteEmbeddingsParamsIndexType enum.

type DeleteUserAccountParams

type DeleteUserAccountParams struct {
	// Challenge Challenge string from first request (step 2 only). Must match exactly.
	Challenge *ChallengeQueryParam `form:"challenge,omitempty" json:"challenge,omitempty"`
}

DeleteUserAccountParams defines parameters for DeleteUserAccount.

type DeletionChallenge

type DeletionChallenge struct {
	// ChallengeText The exact challenge string that must be provided to confirm deletion
	ChallengeText string `json:"challenge_text"`

	// ExpiresAt When the challenge expires (3 minutes from issuance)
	ExpiresAt time.Time `json:"expires_at"`
}

DeletionChallenge Challenge response for user account deletion

type DeletionStats

type DeletionStats struct {
	ThreatModelsTransferred int    `json:"threat_models_transferred"`
	ThreatModelsDeleted     int    `json:"threat_models_deleted"`
	UserEmail               string `json:"user_email"`
}

DeletionStats contains statistics about user deletion SEM@fb03bf4ae62f9d2e9e38b6a31882e902b0673586: report of threat model transfers and deletions produced when a user account is removed (pure)

type DeliveryId

type DeliveryId = openapi_types.UUID

DeliveryId defines model for DeliveryId.

type DescriptionQueryParam

type DescriptionQueryParam = string

DescriptionQueryParam defines model for DescriptionQueryParam.

type DfdDiagram

type DfdDiagram struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// AutoGenerated True when the diagram was created by an automation/service-account principal. Sticky from creation.
	AutoGenerated *bool `json:"auto_generated,omitempty"`

	// Cells List of diagram cells (nodes and edges) following X6 structure
	Cells []DfdDiagram_Cells_Item `json:"cells"`

	// ColorPalette Custom color palette for diagram elements, ordered by position
	ColorPalette *[]ColorPaletteEntry `json:"color_palette,omitempty"`

	// CreatedAt Creation timestamp (ISO3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Optional description of the diagram
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the diagram (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// Image Image data with version information
	Image *struct {
		// Svg BASE64 encoded SVG representation of the diagram, used for thumbnails and reports
		Svg *[]byte `json:"svg,omitempty"`

		// UpdateVector Version of the diagram when this SVG was generated. If not provided when svg is updated, will be auto-set to BaseDiagram.update_vector
		UpdateVector *int64 `json:"update_vector,omitempty"`
	} `json:"image,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Key-value pairs for additional diagram metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (ISO3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name of the diagram
	Name string `json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type DFD diagram type with version
	Type DfdDiagramType `json:"type"`

	// UpdateVector Server-managed monotonic version counter, incremented on each diagram update
	UpdateVector *int64 `json:"update_vector,omitempty"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

DfdDiagram defines model for DfdDiagram.

func (*DfdDiagram) SetCreatedAt

func (d *DfdDiagram) SetCreatedAt(t time.Time)

SetCreatedAt implements WithTimestamps interface for DfdDiagram SEM@de36efe7c9abdb238cea29efae95937751a21874: set the created_at timestamp on a DfdDiagram to implement WithTimestamps (pure)

func (*DfdDiagram) SetModifiedAt

func (d *DfdDiagram) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps interface for DfdDiagram SEM@de36efe7c9abdb238cea29efae95937751a21874: set the modified_at timestamp on a DfdDiagram to implement WithTimestamps (pure)

type DfdDiagramInput

type DfdDiagramInput struct {
	// Cells List of diagram cells (nodes and edges) following X6 structure
	Cells []DfdDiagramInput_Cells_Item `json:"cells"`

	// ColorPalette Custom color palette for diagram elements, ordered by position
	ColorPalette *[]ColorPaletteEntry `json:"color_palette,omitempty"`

	// Description Optional description of the diagram
	Description *string `json:"description,omitempty"`

	// Image Image data with version information
	Image *struct {
		// Svg BASE64 encoded SVG representation of the diagram, used for thumbnails and reports
		Svg *[]byte `json:"svg,omitempty"`

		// UpdateVector Version of the diagram when this SVG was generated. If not provided when svg is updated, will be auto-set to BaseDiagram.update_vector
		UpdateVector *int64 `json:"update_vector,omitempty"`
	} `json:"image,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Key-value pairs for additional diagram metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// Name Name of the diagram
	Name string `json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type DFD diagram type with version
	Type DfdDiagramInputType `json:"type"`
}

DfdDiagramInput defines model for DfdDiagramInput.

type DfdDiagramInputType

type DfdDiagramInputType string

DfdDiagramInputType DFD diagram type with version

const (
	DfdDiagramInputTypeDFD100 DfdDiagramInputType = "DFD-1.0.0"
)

Defines values for DfdDiagramInputType.

func (DfdDiagramInputType) Valid

func (e DfdDiagramInputType) Valid() bool

Valid indicates whether the value is a known member of the DfdDiagramInputType enum.

type DfdDiagramInput_Cells_Item

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

DfdDiagramInput_Cells_Item defines model for DfdDiagramInput.cells.Item.

func (DfdDiagramInput_Cells_Item) AsEdge

func (t DfdDiagramInput_Cells_Item) AsEdge() (Edge, error)

AsEdge returns the union data inside the DfdDiagramInput_Cells_Item as a Edge

func (DfdDiagramInput_Cells_Item) AsNode

func (t DfdDiagramInput_Cells_Item) AsNode() (Node, error)

AsNode returns the union data inside the DfdDiagramInput_Cells_Item as a Node

func (DfdDiagramInput_Cells_Item) Discriminator

func (t DfdDiagramInput_Cells_Item) Discriminator() (string, error)

func (*DfdDiagramInput_Cells_Item) FromEdge

func (t *DfdDiagramInput_Cells_Item) FromEdge(v Edge) error

FromEdge overwrites any union data inside the DfdDiagramInput_Cells_Item as the provided Edge

func (*DfdDiagramInput_Cells_Item) FromNode

func (t *DfdDiagramInput_Cells_Item) FromNode(v Node) error

FromNode overwrites any union data inside the DfdDiagramInput_Cells_Item as the provided Node

func (DfdDiagramInput_Cells_Item) MarshalJSON

func (t DfdDiagramInput_Cells_Item) MarshalJSON() ([]byte, error)

func (*DfdDiagramInput_Cells_Item) MergeEdge

func (t *DfdDiagramInput_Cells_Item) MergeEdge(v Edge) error

MergeEdge performs a merge with any union data inside the DfdDiagramInput_Cells_Item, using the provided Edge

func (*DfdDiagramInput_Cells_Item) MergeNode

func (t *DfdDiagramInput_Cells_Item) MergeNode(v Node) error

MergeNode performs a merge with any union data inside the DfdDiagramInput_Cells_Item, using the provided Node

func (*DfdDiagramInput_Cells_Item) UnmarshalJSON

func (t *DfdDiagramInput_Cells_Item) UnmarshalJSON(b []byte) error

func (DfdDiagramInput_Cells_Item) ValueByDiscriminator

func (t DfdDiagramInput_Cells_Item) ValueByDiscriminator() (interface{}, error)

type DfdDiagramType

type DfdDiagramType string

DfdDiagramType DFD diagram type with version

const (
	DfdDiagramTypeDFD100 DfdDiagramType = "DFD-1.0.0"
)

Defines values for DfdDiagramType.

func (DfdDiagramType) Valid

func (e DfdDiagramType) Valid() bool

Valid indicates whether the value is a known member of the DfdDiagramType enum.

type DfdDiagram_Cells_Item

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

DfdDiagram_Cells_Item defines model for DfdDiagram.cells.Item.

func CreateEdge

func CreateEdge(id string, shape EdgeShape, sourceId, targetId string) (DfdDiagram_Cells_Item, error)

CreateEdge creates an Edge union item from basic parameters (test helper) SEM@e0319b46956724d532b5b4f64b9f66b006e3a0a9: build a diagram cell union item representing a directed edge between two node cells (pure)

func CreateNode

func CreateNode(id string, shape NodeShape, x, y, width, height float32) (DfdDiagram_Cells_Item, error)

CreateNode creates a Node union item from basic parameters (test helper) SEM@e0319b46956724d532b5b4f64b9f66b006e3a0a9: build a diagram cell union item representing a positioned node with given shape and dimensions (pure)

func (DfdDiagram_Cells_Item) AsEdge

func (t DfdDiagram_Cells_Item) AsEdge() (Edge, error)

AsEdge returns the union data inside the DfdDiagram_Cells_Item as a Edge

func (DfdDiagram_Cells_Item) AsNode

func (t DfdDiagram_Cells_Item) AsNode() (Node, error)

AsNode returns the union data inside the DfdDiagram_Cells_Item as a Node

func (DfdDiagram_Cells_Item) Discriminator

func (t DfdDiagram_Cells_Item) Discriminator() (string, error)

func (*DfdDiagram_Cells_Item) FromEdge

func (t *DfdDiagram_Cells_Item) FromEdge(v Edge) error

FromEdge overwrites any union data inside the DfdDiagram_Cells_Item as the provided Edge

func (*DfdDiagram_Cells_Item) FromNode

func (t *DfdDiagram_Cells_Item) FromNode(v Node) error

FromNode overwrites any union data inside the DfdDiagram_Cells_Item as the provided Node

func (DfdDiagram_Cells_Item) MarshalJSON

func (t DfdDiagram_Cells_Item) MarshalJSON() ([]byte, error)

func (*DfdDiagram_Cells_Item) MergeEdge

func (t *DfdDiagram_Cells_Item) MergeEdge(v Edge) error

MergeEdge performs a merge with any union data inside the DfdDiagram_Cells_Item, using the provided Edge

func (*DfdDiagram_Cells_Item) MergeNode

func (t *DfdDiagram_Cells_Item) MergeNode(v Node) error

MergeNode performs a merge with any union data inside the DfdDiagram_Cells_Item, using the provided Node

func (*DfdDiagram_Cells_Item) UnmarshalJSON

func (t *DfdDiagram_Cells_Item) UnmarshalJSON(b []byte) error

func (DfdDiagram_Cells_Item) ValueByDiscriminator

func (t DfdDiagram_Cells_Item) ValueByDiscriminator() (interface{}, error)

type Diagram

type Diagram struct {
	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
	// contains filtered or unexported fields
}

Diagram DEPRECATED: Empty wrapper schema for polymorphic diagram types. Use DfdDiagram directly instead. This schema is kept for backward compatibility but generates empty classes in client libraries.

func (Diagram) AsDfdDiagram

func (t Diagram) AsDfdDiagram() (DfdDiagram, error)

AsDfdDiagram returns the union data inside the Diagram as a DfdDiagram

func (Diagram) Discriminator

func (t Diagram) Discriminator() (string, error)

func (*Diagram) FromDfdDiagram

func (t *Diagram) FromDfdDiagram(v DfdDiagram) error

FromDfdDiagram overwrites any union data inside the Diagram as the provided DfdDiagram

func (Diagram) MarshalJSON

func (t Diagram) MarshalJSON() ([]byte, error)

func (*Diagram) MergeDfdDiagram

func (t *Diagram) MergeDfdDiagram(v DfdDiagram) error

MergeDfdDiagram performs a merge with any union data inside the Diagram, using the provided DfdDiagram

func (*Diagram) UnmarshalJSON

func (t *Diagram) UnmarshalJSON(b []byte) error

func (Diagram) ValueByDiscriminator

func (t Diagram) ValueByDiscriminator() (interface{}, error)

type DiagramId

type DiagramId = openapi_types.UUID

DiagramId defines model for DiagramId.

type DiagramIdPathParam

type DiagramIdPathParam = openapi_types.UUID

DiagramIdPathParam defines model for DiagramIdPathParam.

type DiagramIdQueryParam

type DiagramIdQueryParam = openapi_types.UUID

DiagramIdQueryParam defines model for DiagramIdQueryParam.

type DiagramListItem

type DiagramListItem struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// CreatedAt Creation timestamp (ISO3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Optional description of the diagram
	Description *string `json:"description,omitempty"`

	// Id Unique identifier of the diagram (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// Image Image data with version information for thumbnail rendering
	Image *struct {
		// Svg BASE64 encoded SVG representation of the diagram, used for thumbnails and reports
		Svg *[]byte `json:"svg,omitempty"`

		// UpdateVector Version of the diagram when this SVG was generated
		UpdateVector *int64 `json:"update_vector,omitempty"`
	} `json:"image,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// ModifiedAt Last modification timestamp (ISO3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name of the diagram
	Name string `json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Type of the diagram
	Type DiagramListItemType `json:"type"`
}

DiagramListItem Summary diagram object for GET /diagrams list endpoints. Excludes large fields (cells) for performance. Includes image for thumbnail rendering and description for display. Full diagram details available via GET /diagrams/{id} which returns DfdDiagram.

type DiagramListItemType

type DiagramListItemType string

DiagramListItemType Type of the diagram

const (
	DiagramListItemTypeDFD100 DiagramListItemType = "DFD-1.0.0"
)

Defines values for DiagramListItemType.

func (DiagramListItemType) Valid

func (e DiagramListItemType) Valid() bool

Valid indicates whether the value is a known member of the DiagramListItemType enum.

type DiagramOperation

type DiagramOperation struct {
	// Operation type (add, remove, update)
	Type string `json:"type"`
	// Component ID (for update/remove)
	ComponentID string `json:"component_id,omitempty"`
	// Properties to update (for update)
	Properties map[string]any `json:"properties,omitempty"`
}

DiagramOperation defines a change to a diagram SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: data type representing a single diagram cell change with operation type and properties (pure)

type DiagramOperationEvent

type DiagramOperationEvent struct {
	MessageType    MessageType        `json:"message_type"`
	InitiatingUser User               `json:"initiating_user"`
	OperationID    string             `json:"operation_id"`
	SequenceNumber *uint64            `json:"sequence_number,omitempty"`
	UpdateVector   int64              `json:"update_vector"` // Server's update vector after operation
	Operation      CellPatchOperation `json:"operation"`
}

DiagramOperationEvent is broadcast by server when a diagram operation occurs SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: server-to-client WebSocket event broadcast when a diagram cell operation is applied (pure)

func (DiagramOperationEvent) GetMessageType

func (m DiagramOperationEvent) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for DiagramOperationEvent (pure)

func (DiagramOperationEvent) Validate

func (m DiagramOperationEvent) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a DiagramOperationEvent has correct type, user identity, UUID, and valid operation (pure)

type DiagramOperationMessage

type DiagramOperationMessage struct {
	MessageType    MessageType        `json:"message_type"`
	InitiatingUser User               `json:"initiating_user"`
	OperationID    string             `json:"operation_id"`
	SequenceNumber *uint64            `json:"sequence_number,omitempty"` // Server-assigned
	Operation      CellPatchOperation `json:"operation"`
}

DiagramOperationMessage represents enhanced collaborative editing operations SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: WebSocket message carrying a collaborative cell patch operation with user identity (pure)

func (DiagramOperationMessage) GetMessageType

func (m DiagramOperationMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for DiagramOperationMessage (pure)

func (DiagramOperationMessage) Validate

func (m DiagramOperationMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a DiagramOperationMessage has correct type, UUID operation_id, and valid operation (pure)

type DiagramOperationRequest

type DiagramOperationRequest struct {
	MessageType    MessageType        `json:"message_type"`
	OperationID    string             `json:"operation_id"`
	BaseVector     *int64             `json:"base_vector,omitempty"`     // Client's state when operation was created
	SequenceNumber *uint64            `json:"sequence_number,omitempty"` // Server-assigned
	Operation      CellPatchOperation `json:"operation"`
}

DiagramOperationRequest is sent by client to perform a diagram operation SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: client-to-server WebSocket request to apply a diagram cell patch operation (pure)

func (DiagramOperationRequest) GetMessageType

func (m DiagramOperationRequest) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for DiagramOperationRequest (pure)

func (DiagramOperationRequest) Validate

func (m DiagramOperationRequest) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a DiagramOperationRequest has correct type, UUID operation_id, and valid operation (pure)

type DiagramOperationRequestHandler

type DiagramOperationRequestHandler struct{}

DiagramOperationRequestHandler handles diagram operation request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: WebSocket handler that processes diagram operation request messages

func (*DiagramOperationRequestHandler) HandleMessage

func (h *DiagramOperationRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

HandleMessage processes diagram operation request messages SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: validate, apply, and broadcast a diagram cell operation from a WebSocket client (mutates shared state)

func (*DiagramOperationRequestHandler) MessageType

func (h *DiagramOperationRequestHandler) MessageType() string

MessageType returns the message type this handler processes SEM@4c26178bb9014e2fcc62e1a29307dad2c36b6ada: return the message type string this handler is registered for (pure)

type DiagramRequest

type DiagramRequest struct {
	Name        string  `json:"name" binding:"required"`
	Description *string `json:"description,omitempty"`
	GraphData   []Cell  `json:"graphData,omitempty"`
}

DiagramRequest is used for creating and updating diagrams SEM@15f518ec5394b0508ff8c84d08d6c785286d76e2: request DTO for creating or updating a diagram (pure)

type DiagramSession

type DiagramSession struct {
	// Session ID
	ID string
	// Diagram ID
	DiagramID string
	// Threat Model ID (parent of the diagram)
	ThreatModelID string
	// Session state
	State SessionState
	// Connected clients
	Clients map[*WebSocketClient]bool
	// Inbound messages from clients
	Broadcast chan []byte
	// Register requests
	Register chan *WebSocketClient
	// Unregister requests
	Unregister chan *WebSocketClient
	// Last activity timestamp
	LastActivity time.Time
	// Session creation timestamp
	CreatedAt time.Time
	// Session termination timestamp (when host disconnected)
	TerminatedAt *time.Time

	// Reference to the hub for cleanup when session terminates
	Hub *WebSocketHub
	// Message router for handling WebSocket messages
	MessageRouter *MessageRouter

	// Enhanced collaboration state
	// Host (user who created the session)
	Host ResolvedUser
	// Current presenter (user whose cursor/selection is broadcast)
	CurrentPresenter *ResolvedUser
	// Deny list for removed participants (session-specific), keyed by InternalUUID
	DeniedUsers map[string]bool
	// Operation history for conflict resolution
	OperationHistory *OperationHistory
	// Next sequence number for operations
	NextSequenceNumber uint64
	// contains filtered or unexported fields
}

DiagramSession represents a collaborative editing session SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: collaborative editing session for one diagram, tracking clients, host, history, and deny list

func (*DiagramSession) GetHistoryEntry

func (s *DiagramSession) GetHistoryEntry(sequenceNumber uint64) (*HistoryEntry, bool)

GetHistoryEntry retrieves a specific history entry by sequence number SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: fetch a history entry by sequence number from the session's operation log (pure)

func (*DiagramSession) GetHistoryStats

func (s *DiagramSession) GetHistoryStats() map[string]any

GetHistoryStats returns statistics about the operation history SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: compute count and sequence range of a session's operation history (pure)

func (*DiagramSession) GetRecentOperations

func (s *DiagramSession) GetRecentOperations(count int) []*HistoryEntry

GetRecentOperations returns the most recent N operations SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: fetch the most recent N history entries from a session's operation log (pure)

func (*DiagramSession) ProcessMessage

func (s *DiagramSession) ProcessMessage(client *WebSocketClient, message []byte)

ProcessMessage handles enhanced message types for collaborative editing SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: route an incoming WebSocket message to the appropriate handler via the message router (mutates shared state)

func (*DiagramSession) Run

func (s *DiagramSession) Run()

Run processes messages for a diagram session SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: drive session lifecycle: register/unregister clients and broadcast messages until host departs (mutates shared state)

type DiagramStateMessage

type DiagramStateMessage struct {
	MessageType  MessageType             `json:"message_type"`
	DiagramID    string                  `json:"diagram_id"`
	UpdateVector int64                   `json:"update_vector"`
	Cells        []DfdDiagram_Cells_Item `json:"cells"`
	ColorPalette *[]ColorPaletteEntry    `json:"color_palette,omitempty"`
}

DiagramStateMessage is sent by server with full diagram state SEM@3178cfdb4d9b95cb34c34db7f16dc14e46867342: server-to-client WebSocket message delivering full diagram cell state for resync (pure)

func (DiagramStateMessage) GetMessageType

func (m DiagramStateMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for DiagramStateMessage (pure)

func (DiagramStateMessage) Validate

func (m DiagramStateMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a DiagramStateMessage has correct type, UUID diagram ID, non-negative vector, and cells (pure)

type DiagramStoreInterface

type DiagramStoreInterface interface {
	Get(id string) (DfdDiagram, error)
	GetIncludingDeleted(id string) (DfdDiagram, error)
	GetBatch(ids []string) ([]DfdDiagram, error)
	GetThreatModelID(diagramID string) (string, error)
	List(offset, limit int, filter func(DfdDiagram) bool) []DfdDiagram
	Create(item DfdDiagram, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)
	CreateWithThreatModel(item DfdDiagram, threatModelID string, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)
	// Update accepts a context.Context so the underlying retry wrapper uses
	// the caller's ctx instead of context.Background(); see #334.
	Update(ctx context.Context, id string, item DfdDiagram) error
	Delete(id string) error
	// SoftDelete accepts a context.Context for retry-wrapper cancellability; see #334.
	SoftDelete(ctx context.Context, id string) error
	Restore(id string) error
	HardDelete(id string) error
	Count() int
}

SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: interface for CRUD, batch fetch, soft-delete, and count operations on DFD diagrams

var DiagramStore DiagramStoreInterface

type DirectTextProvider

type DirectTextProvider struct{}

DirectTextProvider extracts text from DB-resident entities (notes, assets, threats, repositories) SEM@1726f5cd4954fda37fad0ef11e5205ed957ad7a2: content provider that extracts plain text from DB-resident entities (pure)

func NewDirectTextProvider

func NewDirectTextProvider() *DirectTextProvider

NewDirectTextProvider creates a new DirectTextProvider SEM@1726f5cd4954fda37fad0ef11e5205ed957ad7a2: build a DirectTextProvider (pure)

func (*DirectTextProvider) CanHandle

func (p *DirectTextProvider) CanHandle(_ context.Context, ref EntityReference) bool

CanHandle returns true for DB-resident entities that don't have an external URI SEM@d17204e0b973a10994d2e5e445738cf9103864e3: report whether the entity reference is a URI-less DB-resident entity type (pure)

func (*DirectTextProvider) Extract

Extract fetches and returns plain text content from the entity SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch plain text content from a DB-resident entity by type and ID (reads DB)

func (*DirectTextProvider) Name

func (p *DirectTextProvider) Name() string

Name returns the provider name for logging SEM@1726f5cd4954fda37fad0ef11e5205ed957ad7a2: return the canonical name of this content provider (pure)

type Document

type Document struct {
	// AccessDiagnostics Per-viewer access diagnostics; present when access_status is not 'accessible'
	AccessDiagnostics *DocumentAccessDiagnostics `json:"access_diagnostics,omitempty"`

	// AccessStatus Access validation status for external content providers
	AccessStatus *DocumentAccessStatus `json:"access_status,omitempty"`

	// AccessStatusUpdatedAt Timestamp of the last access_status transition (RFC3339)
	AccessStatusUpdatedAt *time.Time `json:"access_status_updated_at,omitempty"`

	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// ContentSource Content provider that handles this documents URI (e.g., google_drive, http)
	ContentSource *string `json:"content_source,omitempty"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of document purpose or content
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the document
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Document name
	Name string `binding:"required" json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Uri URL location of the document
	Uri string `binding:"required,url" json:"uri"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

Document defines model for Document.

func CreateTestDocumentWithMetadata

func CreateTestDocumentWithMetadata(metadata []Metadata) Document

CreateTestDocumentWithMetadata creates a document with associated metadata for testing SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: build a Document with attached metadata for use in unit tests (pure)

type DocumentAccessDiagnostics

type DocumentAccessDiagnostics struct {
	ReasonCode DocumentAccessDiagnosticsReasonCode `json:"reason_code"`

	// ReasonDetail Raw error text; populated only when reason_code is 'other'
	ReasonDetail *string             `json:"reason_detail,omitempty"`
	Remediations []AccessRemediation `json:"remediations"`
}

DocumentAccessDiagnostics Per-viewer diagnostics explaining why a document is currently not accessible and what the viewer (or the document owner) can do to restore access. Emitted on Document responses whenever `access_status` is not `accessible`.

type DocumentAccessDiagnosticsReasonCode

type DocumentAccessDiagnosticsReasonCode string

DocumentAccessDiagnosticsReasonCode defines model for DocumentAccessDiagnostics.ReasonCode.

const (
	DocumentAccessDiagnosticsReasonCodeFetchError                DocumentAccessDiagnosticsReasonCode = "fetch_error"
	DocumentAccessDiagnosticsReasonCodeMicrosoftNotShared        DocumentAccessDiagnosticsReasonCode = "microsoft_not_shared"
	DocumentAccessDiagnosticsReasonCodeNoAccessibleSource        DocumentAccessDiagnosticsReasonCode = "no_accessible_source"
	DocumentAccessDiagnosticsReasonCodeOther                     DocumentAccessDiagnosticsReasonCode = "other"
	DocumentAccessDiagnosticsReasonCodePickerRegistrationInvalid DocumentAccessDiagnosticsReasonCode = "picker_registration_invalid"
	DocumentAccessDiagnosticsReasonCodeSourceNotFound            DocumentAccessDiagnosticsReasonCode = "source_not_found"
	DocumentAccessDiagnosticsReasonCodeTokenNotLinked            DocumentAccessDiagnosticsReasonCode = "token_not_linked"
	DocumentAccessDiagnosticsReasonCodeTokenRefreshFailed        DocumentAccessDiagnosticsReasonCode = "token_refresh_failed"
	DocumentAccessDiagnosticsReasonCodeTokenTransientFailure     DocumentAccessDiagnosticsReasonCode = "token_transient_failure"
)

Defines values for DocumentAccessDiagnosticsReasonCode.

func (DocumentAccessDiagnosticsReasonCode) Valid

Valid indicates whether the value is a known member of the DocumentAccessDiagnosticsReasonCode enum.

type DocumentAccessStatus

type DocumentAccessStatus string

DocumentAccessStatus Access validation status for external content providers

const (
	DocumentAccessStatusAccessible       DocumentAccessStatus = "accessible"
	DocumentAccessStatusAuthRequired     DocumentAccessStatus = "auth_required"
	DocumentAccessStatusExtractionFailed DocumentAccessStatus = "extraction_failed"
	DocumentAccessStatusPendingAccess    DocumentAccessStatus = "pending_access"
	DocumentAccessStatusUnknown          DocumentAccessStatus = "unknown"
)

Defines values for DocumentAccessStatus.

func (DocumentAccessStatus) Valid

func (e DocumentAccessStatus) Valid() bool

Valid indicates whether the value is a known member of the DocumentAccessStatus enum.

type DocumentBase

type DocumentBase struct {
	// Description Description of document purpose or content
	Description *string `json:"description,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Name Document name
	Name string `binding:"required" json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Uri URL location of the document
	Uri string `binding:"required,url" json:"uri"`
}

DocumentBase Base fields for Document (user-writable only)

type DocumentId

type DocumentId = openapi_types.UUID

DocumentId defines model for DocumentId.

type DocumentInput

type DocumentInput struct {
	// Description Description of document purpose or content
	Description *string `json:"description,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Name Document name
	Name string `binding:"required" json:"name"`

	// PickerRegistration Optional; when present, client has performed a Picker-based attachment
	PickerRegistration *PickerRegistration `json:"picker_registration,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Uri URL location of the document
	Uri string `binding:"required,url" json:"uri"`
}

DocumentInput defines model for DocumentInput.

type DocumentRepository

type DocumentRepository interface {
	// CRUD operations
	Create(ctx context.Context, document *Document, threatModelID string) error
	Get(ctx context.Context, id string) (*Document, error)
	Update(ctx context.Context, document *Document, threatModelID string) error
	Delete(ctx context.Context, id string) error
	SoftDelete(ctx context.Context, id string) error
	Restore(ctx context.Context, id string) error
	HardDelete(ctx context.Context, id string) error
	GetIncludingDeleted(ctx context.Context, id string) (*Document, error)
	Patch(ctx context.Context, id string, operations []PatchOperation) (*Document, error)

	// List operations with pagination
	List(ctx context.Context, threatModelID string, offset, limit int) ([]Document, error)
	// ListByAccessStatus returns documents with the given access status across all threat models.
	ListByAccessStatus(ctx context.Context, status string, limit int) ([]Document, error)
	// Count returns total number of documents for a threat model
	Count(ctx context.Context, threatModelID string) (int, error)

	// Bulk operations
	BulkCreate(ctx context.Context, documents []Document, threatModelID string) error

	// UpdateAccessStatus sets the access tracking fields on a document.
	UpdateAccessStatus(ctx context.Context, id string, accessStatus string, contentSource string) error

	// UpdateAccessStatusWithDiagnostics sets the access tracking fields on a document,
	// including the diagnostic reason code and detail. reasonCode may be empty to clear
	// any existing diagnostic. reasonDetail should be empty unless reasonCode == "other".
	// access_status_updated_at is set to NOW().
	UpdateAccessStatusWithDiagnostics(
		ctx context.Context,
		id string,
		accessStatus string,
		contentSource string,
		reasonCode string,
		reasonDetail string,
	) error

	// GetAccessReason returns the diagnostic fields (reason_code, reason_detail,
	// access_status_updated_at) for a document. Returns empty strings and nil
	// time if no diagnostic has been set. Does not return an error if the
	// document has no reason (normal state); returns an error only if the
	// document doesn't exist or the DB query fails.
	GetAccessReason(ctx context.Context, id string) (reasonCode string, reasonDetail string, updatedAt *time.Time, err error)

	// GetPickerDispatch returns the picker metadata (if any) and the owner
	// internal UUID for the given document. Used by the access poller to
	// dispatch validation to the right ContentSource via FindSourceForDocument.
	//
	// picker is nil when the document has no picker metadata (i.e., was attached
	// via URL only). When non-nil, all three fields (ProviderID, FileID,
	// MimeType) are populated.
	//
	// ownerInternalUUID is the owner of the parent threat model — required by
	// LinkedProviderChecker to look up the user's content tokens.
	//
	// Returns an error if the document does not exist or the DB query fails.
	GetPickerDispatch(ctx context.Context, id string) (picker *PickerMetadata, ownerInternalUUID string, err error)

	// SetPickerMetadata persists picker_provider_id, picker_file_id, and
	// picker_mime_type for the given document. Used at attach time when the
	// caller registered the document via a Picker flow. Sets access_status to
	// 'unknown' and access_status_updated_at to NOW(); the access poller will
	// transition the row to 'accessible' when the delegated source confirms.
	//
	// This is a separate write from Create, so attach is non-atomic: if a crash
	// happens between Create and SetPickerMetadata, the row exists with no
	// picker metadata and will not be dispatched to the delegated source. The
	// caller (CreateDocument handler) treats SetPickerMetadata failures as
	// non-fatal (warn-and-continue) and the access poller will not pick up
	// such rows. This is acceptable for the current single-instance topology.
	SetPickerMetadata(ctx context.Context, id string, providerID, fileID, mimeType string) error

	// ClearPickerMetadataForOwner nulls picker metadata and resets access_status
	// to 'unknown' for every document whose picker_provider_id == providerID and
	// whose parent threat model's owner_internal_uuid == ownerInternalUUID.
	// Used by the content-token un-link cascade: when a user un-links a
	// delegated provider, all documents they picker-attached under that provider
	// revert to a non-picker state and will re-validate via URL-based dispatch
	// on next access attempt.
	// Returns the number of affected rows.
	ClearPickerMetadataForOwner(ctx context.Context, ownerInternalUUID, providerID string) (int64, error)

	// GetThreatModelID returns the parent threat model ID for the given
	// document. Returns the empty string and a non-nil error if the document
	// does not exist or the DB query fails. Lightweight lookup intended for
	// callers (e.g., the content pipeline's dev-mode dump hook) that have a
	// document ID but not the full row.
	GetThreatModelID(ctx context.Context, id string) (string, error)

	// Cache management
	InvalidateCache(ctx context.Context, id string) error
	WarmCache(ctx context.Context, threatModelID string) error
}

DocumentRepository defines the interface for document operations with caching support SEM@117032a3c5523a04e970f76a285e342169d5150c: interface for CRUD, patch, bulk, access-status, picker, and cache operations on documents (reads DB)

var GlobalDocumentRepository DocumentRepository

type DocumentSubResourceHandler

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

DocumentSubResourceHandler provides handlers for document sub-resource operations SEM@d994c2f113f9e0997f83a0815018638cc94111f7: handler struct for document sub-resource CRUD with content pipeline and async extraction support

func NewDocumentSubResourceHandler

func NewDocumentSubResourceHandler(documentStore DocumentRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *DocumentSubResourceHandler

NewDocumentSubResourceHandler creates a new document sub-resource handler SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a document sub-resource handler wired to the given store, DB, cache, and invalidator (pure)

func (*DocumentSubResourceHandler) BulkCreateDocuments

func (h *DocumentSubResourceHandler) BulkCreateDocuments(c *gin.Context)

BulkCreateDocuments creates multiple documents in a single request POST /threat_models/{threat_model_id}/documents/bulk SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: store up to 50 documents under a threat model in a single request (reads DB)

func (*DocumentSubResourceHandler) BulkUpdateDocuments

func (h *DocumentSubResourceHandler) BulkUpdateDocuments(c *gin.Context)

BulkUpdateDocuments updates or creates multiple documents (upsert operation) PUT /threat_models/{threat_model_id}/documents/bulk SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: upsert up to 50 documents for a threat model in a single request (reads DB)

func (*DocumentSubResourceHandler) CreateDocument

func (h *DocumentSubResourceHandler) CreateDocument(c *gin.Context)

CreateDocument creates a new document in a threat model POST /threat_models/{threat_model_id}/documents SEM@d994c2f113f9e0997f83a0815018638cc94111f7: store a new document under a threat model, optionally routing to async extraction (reads DB)

func (*DocumentSubResourceHandler) DeleteDocument

func (h *DocumentSubResourceHandler) DeleteDocument(c *gin.Context)

DeleteDocument deletes a document DELETE /threat_models/{threat_model_id}/documents/{document_id} SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: delete a document by ID with pre-deletion audit capture and cache invalidation (reads DB)

func (*DocumentSubResourceHandler) GetDocument

func (h *DocumentSubResourceHandler) GetDocument(c *gin.Context)

GetDocument retrieves a specific document by ID GET /threat_models/{threat_model_id}/documents/{document_id} SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a single document by ID and attach per-viewer access diagnostics when not accessible (reads DB)

func (*DocumentSubResourceHandler) GetDocuments

func (h *DocumentSubResourceHandler) GetDocuments(c *gin.Context)

GetDocuments retrieves all documents for a threat model with pagination GET /threat_models/{threat_model_id}/documents SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: list paginated documents for a threat model (reads DB)

func (*DocumentSubResourceHandler) PatchDocument

func (h *DocumentSubResourceHandler) PatchDocument(c *gin.Context)

PatchDocument applies JSON patch operations to a document PATCH /threat_models/{threat_model_id}/documents/{document_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: apply JSON patch operations to a document with role-based authorization and optimistic locking (reads DB)

func (*DocumentSubResourceHandler) SetAsyncExtraction

func (h *DocumentSubResourceHandler) SetAsyncExtraction(publisher *ExtractionPublisher, decider func(context.Context) bool)

SetAsyncExtraction injects the async extraction publisher and decider into the handler. When the decider returns true AND publisher is non-nil, CreateDocument fetches bytes and publishes an async extraction job, then returns 202 Accepted with the job_id. On any fetch/publish failure the handler falls back to the existing 201 path — extractions are never silently dropped and 500 is never returned for extraction failures.

Pass nil publisher or nil decider to keep the existing 201 path. SEM@d994c2f113f9e0997f83a0815018638cc94111f7: inject the async extraction publisher and decider; falls back to 201 path when absent (mutates shared state)

func (*DocumentSubResourceHandler) SetContentOAuthRegistry

func (h *DocumentSubResourceHandler) SetContentOAuthRegistry(r *ContentOAuthProviderRegistry)

SetContentOAuthRegistry sets the content-OAuth provider registry used to validate picker_registration payloads at document attach time. Optional: when nil, picker_registration is rejected with 422 (provider_not_registered). SEM@29c52159f07dd40fc350bf7cfe912f7a3a3def4b: register the OAuth provider registry for picker registration validation (mutates shared state)

func (*DocumentSubResourceHandler) SetContentPipeline

func (h *DocumentSubResourceHandler) SetContentPipeline(p *ContentPipeline)

SetContentPipeline sets the content pipeline for content source detection and access validation SEM@90539292d25d541a7e322a67f50ecb928268f215: register the content pipeline for provider detection and access validation (mutates shared state)

func (*DocumentSubResourceHandler) SetContentTokens

func (h *DocumentSubResourceHandler) SetContentTokens(r ContentTokenRepository)

SetContentTokens sets the content token repository used to look up the caller's linked providers when assembling per-viewer access diagnostics. Optional: when nil, diagnostics are still assembled but with empty linkedProviders. SEM@5fe247aef5f2eedfc42d4adf9058c24de12eb56e: register the content token repository for per-viewer access diagnostics (mutates shared state)

func (*DocumentSubResourceHandler) SetDocumentURIValidator

func (h *DocumentSubResourceHandler) SetDocumentURIValidator(v *URIValidator)

SetDocumentURIValidator sets the URI validator for document uri fields SEM@5eacb6f5fd0d2a1861dafb4d1fc5a18f97ee8e40: register the URI validator used for SSRF protection on document URI fields (mutates shared state)

func (*DocumentSubResourceHandler) SetMicrosoftApplicationObjectID

func (h *DocumentSubResourceHandler) SetMicrosoftApplicationObjectID(id string)

SetMicrosoftApplicationObjectID sets the TMI Entra application object id included in the share_with_application remediation for Microsoft documents. Optional: when empty, the param is an empty string. SEM@fe4cf07a3a2b954860a8df90ba211cb0919d71de: store the Entra app object ID used in Microsoft share-with-application remediations (mutates shared state)

func (*DocumentSubResourceHandler) SetServiceAccountEmail

func (h *DocumentSubResourceHandler) SetServiceAccountEmail(s string)

SetServiceAccountEmail sets the service-account email address included in the share_with_service_account remediation. Optional: when empty, the param is an empty string. SEM@5fe247aef5f2eedfc42d4adf9058c24de12eb56e: store the service account email included in share-with-service-account remediations (mutates shared state)

func (*DocumentSubResourceHandler) UpdateDocument

func (h *DocumentSubResourceHandler) UpdateDocument(c *gin.Context)

UpdateDocument updates an existing document PUT /threat_models/{threat_model_id}/documents/{document_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: replace an existing document's fields with optimistic locking and audit recording (reads DB)

type Edge

type Edge struct {
	// Attrs Visual styling attributes for the edge
	Attrs *EdgeAttrs `json:"attrs,omitempty"`

	// Connector Edge connector style configuration for visual appearance
	Connector *EdgeConnector `json:"connector,omitempty"`

	// Data Flexible data storage compatible with X6, with reserved metadata namespace
	Data *Edge_Data `json:"data,omitempty"`

	// DefaultLabel Default label configuration applied to edges without explicit labels
	DefaultLabel *EdgeLabel `json:"defaultLabel,omitempty"`

	// Id Unique identifier of the cell (UUID)
	Id openapi_types.UUID `json:"id"`

	// Labels Text labels positioned along the edge
	Labels *[]EdgeLabel `json:"labels,omitempty"`

	// Router Edge routing algorithm configuration for path calculation
	Router *EdgeRouter `json:"router,omitempty"`

	// Shape Edge type identifier
	Shape EdgeShape `json:"shape"`

	// Source Source connection point
	Source EdgeTerminal `json:"source"`

	// Target Target connection point
	Target EdgeTerminal `json:"target"`

	// Vertices Intermediate waypoints for edge routing
	Vertices *[]Point `json:"vertices,omitempty"`
}

Edge defines model for Edge.

type EdgeAttrs

type EdgeAttrs struct {
	// Line Line styling attributes
	Line *struct {
		// SourceMarker Source marker configuration
		SourceMarker *struct {
			// Name Marker type
			Name *EdgeAttrsLineSourceMarkerName `json:"name,omitempty"`

			// Size Marker size in pixels
			Size *float32 `json:"size,omitempty"`
		} `json:"sourceMarker,omitempty"`

		// Stroke Line color
		Stroke *string `json:"stroke,omitempty"`

		// StrokeDasharray Dash pattern for the line
		StrokeDasharray *string `json:"strokeDasharray,omitempty"`

		// StrokeWidth Line width in pixels
		StrokeWidth *float32 `json:"strokeWidth,omitempty"`

		// TargetMarker Arrowhead marker configuration
		TargetMarker *struct {
			// Name Marker type
			Name *EdgeAttrsLineTargetMarkerName `json:"name,omitempty"`

			// Size Marker size in pixels
			Size *float32 `json:"size,omitempty"`
		} `json:"targetMarker,omitempty"`
	} `json:"line,omitempty"`
}

EdgeAttrs Visual attributes for an edge

type EdgeAttrsLineSourceMarkerName

type EdgeAttrsLineSourceMarkerName string

EdgeAttrsLineSourceMarkerName Marker type

const (
	EdgeAttrsLineSourceMarkerNameBlock   EdgeAttrsLineSourceMarkerName = "block"
	EdgeAttrsLineSourceMarkerNameCircle  EdgeAttrsLineSourceMarkerName = "circle"
	EdgeAttrsLineSourceMarkerNameClassic EdgeAttrsLineSourceMarkerName = "classic"
	EdgeAttrsLineSourceMarkerNameDiamond EdgeAttrsLineSourceMarkerName = "diamond"
)

Defines values for EdgeAttrsLineSourceMarkerName.

func (EdgeAttrsLineSourceMarkerName) Valid

Valid indicates whether the value is a known member of the EdgeAttrsLineSourceMarkerName enum.

type EdgeAttrsLineTargetMarkerName

type EdgeAttrsLineTargetMarkerName string

EdgeAttrsLineTargetMarkerName Marker type

const (
	EdgeAttrsLineTargetMarkerNameBlock   EdgeAttrsLineTargetMarkerName = "block"
	EdgeAttrsLineTargetMarkerNameCircle  EdgeAttrsLineTargetMarkerName = "circle"
	EdgeAttrsLineTargetMarkerNameClassic EdgeAttrsLineTargetMarkerName = "classic"
	EdgeAttrsLineTargetMarkerNameDiamond EdgeAttrsLineTargetMarkerName = "diamond"
)

Defines values for EdgeAttrsLineTargetMarkerName.

func (EdgeAttrsLineTargetMarkerName) Valid

Valid indicates whether the value is a known member of the EdgeAttrsLineTargetMarkerName enum.

type EdgeConnector

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

EdgeConnector Edge connector style configuration for visual appearance

func (EdgeConnector) AsEdgeConnector0

func (t EdgeConnector) AsEdgeConnector0() (EdgeConnector0, error)

AsEdgeConnector0 returns the union data inside the EdgeConnector as a EdgeConnector0

func (EdgeConnector) AsEdgeConnector1

func (t EdgeConnector) AsEdgeConnector1() (EdgeConnector1, error)

AsEdgeConnector1 returns the union data inside the EdgeConnector as a EdgeConnector1

func (*EdgeConnector) FromEdgeConnector0

func (t *EdgeConnector) FromEdgeConnector0(v EdgeConnector0) error

FromEdgeConnector0 overwrites any union data inside the EdgeConnector as the provided EdgeConnector0

func (*EdgeConnector) FromEdgeConnector1

func (t *EdgeConnector) FromEdgeConnector1(v EdgeConnector1) error

FromEdgeConnector1 overwrites any union data inside the EdgeConnector as the provided EdgeConnector1

func (EdgeConnector) MarshalJSON

func (t EdgeConnector) MarshalJSON() ([]byte, error)

func (*EdgeConnector) MergeEdgeConnector0

func (t *EdgeConnector) MergeEdgeConnector0(v EdgeConnector0) error

MergeEdgeConnector0 performs a merge with any union data inside the EdgeConnector, using the provided EdgeConnector0

func (*EdgeConnector) MergeEdgeConnector1

func (t *EdgeConnector) MergeEdgeConnector1(v EdgeConnector1) error

MergeEdgeConnector1 performs a merge with any union data inside the EdgeConnector, using the provided EdgeConnector1

func (*EdgeConnector) UnmarshalJSON

func (t *EdgeConnector) UnmarshalJSON(b []byte) error

type EdgeConnector0

type EdgeConnector0 string

EdgeConnector0 Built-in connector name

const (
	EdgeConnector0Jumpover EdgeConnector0 = "jumpover"
	EdgeConnector0Normal   EdgeConnector0 = "normal"
	EdgeConnector0Rounded  EdgeConnector0 = "rounded"
	EdgeConnector0Smooth   EdgeConnector0 = "smooth"
)

Defines values for EdgeConnector0.

func (EdgeConnector0) Valid

func (e EdgeConnector0) Valid() bool

Valid indicates whether the value is a known member of the EdgeConnector0 enum.

type EdgeConnector1

type EdgeConnector1 struct {
	// Args Connector-specific arguments
	Args *EdgeConnector_1_Args `json:"args,omitempty"`

	// Name Connector style name
	Name EdgeConnector1Name `json:"name"`
}

EdgeConnector1 Connector with custom configuration

type EdgeConnector1ArgsJump

type EdgeConnector1ArgsJump string

EdgeConnector1ArgsJump Jump style for jumpover connectors

const (
	Arc   EdgeConnector1ArgsJump = "arc"
	Cubic EdgeConnector1ArgsJump = "cubic"
	Gap   EdgeConnector1ArgsJump = "gap"
)

Defines values for EdgeConnector1ArgsJump.

func (EdgeConnector1ArgsJump) Valid

func (e EdgeConnector1ArgsJump) Valid() bool

Valid indicates whether the value is a known member of the EdgeConnector1ArgsJump enum.

type EdgeConnector1Name

type EdgeConnector1Name string

EdgeConnector1Name Connector style name

const (
	EdgeConnector1NameJumpover EdgeConnector1Name = "jumpover"
	EdgeConnector1NameNormal   EdgeConnector1Name = "normal"
	EdgeConnector1NameRounded  EdgeConnector1Name = "rounded"
	EdgeConnector1NameSmooth   EdgeConnector1Name = "smooth"
)

Defines values for EdgeConnector1Name.

func (EdgeConnector1Name) Valid

func (e EdgeConnector1Name) Valid() bool

Valid indicates whether the value is a known member of the EdgeConnector1Name enum.

type EdgeConnector_1_Args

type EdgeConnector_1_Args struct {
	// Jump Jump style for jumpover connectors
	Jump *EdgeConnector1ArgsJump `json:"jump,omitempty"`

	// Precision Precision for smooth connectors
	Precision *float32 `json:"precision,omitempty"`

	// Radius Radius for rounded connectors
	Radius *float32 `json:"radius,omitempty"`

	// Size Jump size for jumpover connectors
	Size                 *float32               `json:"size,omitempty"`
	AdditionalProperties map[string]interface{} `json:"-"`
}

EdgeConnector_1_Args Connector-specific arguments

func (EdgeConnector_1_Args) Get

func (a EdgeConnector_1_Args) Get(fieldName string) (value interface{}, found bool)

Getter for additional properties for EdgeConnector_1_Args. Returns the specified element and whether it was found

func (EdgeConnector_1_Args) MarshalJSON

func (a EdgeConnector_1_Args) MarshalJSON() ([]byte, error)

Override default JSON handling for EdgeConnector_1_Args to handle AdditionalProperties

func (*EdgeConnector_1_Args) Set

func (a *EdgeConnector_1_Args) Set(fieldName string, value interface{})

Setter for additional properties for EdgeConnector_1_Args

func (*EdgeConnector_1_Args) UnmarshalJSON

func (a *EdgeConnector_1_Args) UnmarshalJSON(b []byte) error

Override default JSON handling for EdgeConnector_1_Args to handle AdditionalProperties

type EdgeLabel

type EdgeLabel struct {
	// Attrs Label styling attributes
	Attrs *struct {
		// Text Text styling
		Text *struct {
			// Fill Text color
			Fill *string `json:"fill,omitempty"`

			// FontFamily Font family
			FontFamily *string `json:"fontFamily,omitempty"`

			// FontSize Font size in pixels
			FontSize *float32 `json:"fontSize,omitempty"`

			// Text Label text content
			Text *string `json:"text,omitempty"`
		} `json:"text,omitempty"`
	} `json:"attrs,omitempty"`
	Position *EdgeLabel_Position `json:"position,omitempty"`
}

EdgeLabel Label positioned along an edge

type EdgeLabelPosition0

type EdgeLabelPosition0 = float32

EdgeLabelPosition0 Simple position: 0-1 for percentage, >1 for pixels from start, <0 for pixels from end

type EdgeLabelPosition1

type EdgeLabelPosition1 struct {
	// Angle Rotation angle in degrees (clockwise)
	Angle *float32 `json:"angle,omitempty"`

	// Distance Position along the edge: 0-1 for percentage, >1 for pixels from start, <0 for pixels from end
	Distance float32                      `json:"distance"`
	Offset   *EdgeLabel_Position_1_Offset `json:"offset,omitempty"`

	// Options Advanced positioning options
	Options *struct {
		// AbsoluteDistance Forces absolute coordinates for distance
		AbsoluteDistance *bool `json:"absoluteDistance,omitempty"`

		// AbsoluteOffset Forces absolute coordinates for offset
		AbsoluteOffset *bool `json:"absoluteOffset,omitempty"`

		// EnsureLegibility Rotates labels to avoid upside-down text
		EnsureLegibility *bool `json:"ensureLegibility,omitempty"`

		// KeepGradient Auto-adjusts angle to match path gradient
		KeepGradient *bool `json:"keepGradient,omitempty"`

		// ReverseDistance Forces reverse absolute coordinates
		ReverseDistance *bool `json:"reverseDistance,omitempty"`
	} `json:"options,omitempty"`
}

EdgeLabelPosition1 Advanced position with offset and angle (X6 LabelPositionObject format)

type EdgeLabelPosition1Offset0

type EdgeLabelPosition1Offset0 = float32

EdgeLabelPosition1Offset0 Perpendicular offset from edge (positive = down/right, negative = up/left)

type EdgeLabelPosition1Offset1

type EdgeLabelPosition1Offset1 struct {
	X *float32 `json:"x,omitempty"`
	Y *float32 `json:"y,omitempty"`
}

EdgeLabelPosition1Offset1 Absolute x,y offset

type EdgeLabel_Position

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

EdgeLabel_Position defines model for EdgeLabel.Position.

func (EdgeLabel_Position) AsEdgeLabelPosition0

func (t EdgeLabel_Position) AsEdgeLabelPosition0() (EdgeLabelPosition0, error)

AsEdgeLabelPosition0 returns the union data inside the EdgeLabel_Position as a EdgeLabelPosition0

func (EdgeLabel_Position) AsEdgeLabelPosition1

func (t EdgeLabel_Position) AsEdgeLabelPosition1() (EdgeLabelPosition1, error)

AsEdgeLabelPosition1 returns the union data inside the EdgeLabel_Position as a EdgeLabelPosition1

func (*EdgeLabel_Position) FromEdgeLabelPosition0

func (t *EdgeLabel_Position) FromEdgeLabelPosition0(v EdgeLabelPosition0) error

FromEdgeLabelPosition0 overwrites any union data inside the EdgeLabel_Position as the provided EdgeLabelPosition0

func (*EdgeLabel_Position) FromEdgeLabelPosition1

func (t *EdgeLabel_Position) FromEdgeLabelPosition1(v EdgeLabelPosition1) error

FromEdgeLabelPosition1 overwrites any union data inside the EdgeLabel_Position as the provided EdgeLabelPosition1

func (EdgeLabel_Position) MarshalJSON

func (t EdgeLabel_Position) MarshalJSON() ([]byte, error)

func (*EdgeLabel_Position) MergeEdgeLabelPosition0

func (t *EdgeLabel_Position) MergeEdgeLabelPosition0(v EdgeLabelPosition0) error

MergeEdgeLabelPosition0 performs a merge with any union data inside the EdgeLabel_Position, using the provided EdgeLabelPosition0

func (*EdgeLabel_Position) MergeEdgeLabelPosition1

func (t *EdgeLabel_Position) MergeEdgeLabelPosition1(v EdgeLabelPosition1) error

MergeEdgeLabelPosition1 performs a merge with any union data inside the EdgeLabel_Position, using the provided EdgeLabelPosition1

func (*EdgeLabel_Position) UnmarshalJSON

func (t *EdgeLabel_Position) UnmarshalJSON(b []byte) error

type EdgeLabel_Position_1_Offset

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

EdgeLabel_Position_1_Offset defines model for EdgeLabel.Position.1.Offset.

func (EdgeLabel_Position_1_Offset) AsEdgeLabelPosition1Offset0

func (t EdgeLabel_Position_1_Offset) AsEdgeLabelPosition1Offset0() (EdgeLabelPosition1Offset0, error)

AsEdgeLabelPosition1Offset0 returns the union data inside the EdgeLabel_Position_1_Offset as a EdgeLabelPosition1Offset0

func (EdgeLabel_Position_1_Offset) AsEdgeLabelPosition1Offset1

func (t EdgeLabel_Position_1_Offset) AsEdgeLabelPosition1Offset1() (EdgeLabelPosition1Offset1, error)

AsEdgeLabelPosition1Offset1 returns the union data inside the EdgeLabel_Position_1_Offset as a EdgeLabelPosition1Offset1

func (*EdgeLabel_Position_1_Offset) FromEdgeLabelPosition1Offset0

func (t *EdgeLabel_Position_1_Offset) FromEdgeLabelPosition1Offset0(v EdgeLabelPosition1Offset0) error

FromEdgeLabelPosition1Offset0 overwrites any union data inside the EdgeLabel_Position_1_Offset as the provided EdgeLabelPosition1Offset0

func (*EdgeLabel_Position_1_Offset) FromEdgeLabelPosition1Offset1

func (t *EdgeLabel_Position_1_Offset) FromEdgeLabelPosition1Offset1(v EdgeLabelPosition1Offset1) error

FromEdgeLabelPosition1Offset1 overwrites any union data inside the EdgeLabel_Position_1_Offset as the provided EdgeLabelPosition1Offset1

func (EdgeLabel_Position_1_Offset) MarshalJSON

func (t EdgeLabel_Position_1_Offset) MarshalJSON() ([]byte, error)

func (*EdgeLabel_Position_1_Offset) MergeEdgeLabelPosition1Offset0

func (t *EdgeLabel_Position_1_Offset) MergeEdgeLabelPosition1Offset0(v EdgeLabelPosition1Offset0) error

MergeEdgeLabelPosition1Offset0 performs a merge with any union data inside the EdgeLabel_Position_1_Offset, using the provided EdgeLabelPosition1Offset0

func (*EdgeLabel_Position_1_Offset) MergeEdgeLabelPosition1Offset1

func (t *EdgeLabel_Position_1_Offset) MergeEdgeLabelPosition1Offset1(v EdgeLabelPosition1Offset1) error

MergeEdgeLabelPosition1Offset1 performs a merge with any union data inside the EdgeLabel_Position_1_Offset, using the provided EdgeLabelPosition1Offset1

func (*EdgeLabel_Position_1_Offset) UnmarshalJSON

func (t *EdgeLabel_Position_1_Offset) UnmarshalJSON(b []byte) error

type EdgeRouter

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

EdgeRouter Edge routing algorithm configuration for pathfinding

func (EdgeRouter) AsEdgeRouter0

func (t EdgeRouter) AsEdgeRouter0() (EdgeRouter0, error)

AsEdgeRouter0 returns the union data inside the EdgeRouter as a EdgeRouter0

func (EdgeRouter) AsEdgeRouter1

func (t EdgeRouter) AsEdgeRouter1() (EdgeRouter1, error)

AsEdgeRouter1 returns the union data inside the EdgeRouter as a EdgeRouter1

func (*EdgeRouter) FromEdgeRouter0

func (t *EdgeRouter) FromEdgeRouter0(v EdgeRouter0) error

FromEdgeRouter0 overwrites any union data inside the EdgeRouter as the provided EdgeRouter0

func (*EdgeRouter) FromEdgeRouter1

func (t *EdgeRouter) FromEdgeRouter1(v EdgeRouter1) error

FromEdgeRouter1 overwrites any union data inside the EdgeRouter as the provided EdgeRouter1

func (EdgeRouter) MarshalJSON

func (t EdgeRouter) MarshalJSON() ([]byte, error)

func (*EdgeRouter) MergeEdgeRouter0

func (t *EdgeRouter) MergeEdgeRouter0(v EdgeRouter0) error

MergeEdgeRouter0 performs a merge with any union data inside the EdgeRouter, using the provided EdgeRouter0

func (*EdgeRouter) MergeEdgeRouter1

func (t *EdgeRouter) MergeEdgeRouter1(v EdgeRouter1) error

MergeEdgeRouter1 performs a merge with any union data inside the EdgeRouter, using the provided EdgeRouter1

func (*EdgeRouter) UnmarshalJSON

func (t *EdgeRouter) UnmarshalJSON(b []byte) error

type EdgeRouter0

type EdgeRouter0 string

EdgeRouter0 Built-in router name

const (
	EdgeRouter0Er        EdgeRouter0 = "er"
	EdgeRouter0Manhattan EdgeRouter0 = "manhattan"
	EdgeRouter0Metro     EdgeRouter0 = "metro"
	EdgeRouter0Normal    EdgeRouter0 = "normal"
	EdgeRouter0OneSide   EdgeRouter0 = "one_side"
	EdgeRouter0Orth      EdgeRouter0 = "orth"
)

Defines values for EdgeRouter0.

func (EdgeRouter0) Valid

func (e EdgeRouter0) Valid() bool

Valid indicates whether the value is a known member of the EdgeRouter0 enum.

type EdgeRouter1

type EdgeRouter1 struct {
	// Args Router-specific arguments
	Args *EdgeRouter_1_Args `json:"args,omitempty"`

	// Name Router algorithm name
	Name EdgeRouter1Name `json:"name"`
}

EdgeRouter1 Router with custom configuration

type EdgeRouter1ArgsDirections

type EdgeRouter1ArgsDirections string

EdgeRouter1ArgsDirections defines model for EdgeRouter.1.Args.Directions.

const (
	EdgeRouter1ArgsDirectionsBottom EdgeRouter1ArgsDirections = "bottom"
	EdgeRouter1ArgsDirectionsLeft   EdgeRouter1ArgsDirections = "left"
	EdgeRouter1ArgsDirectionsRight  EdgeRouter1ArgsDirections = "right"
	EdgeRouter1ArgsDirectionsTop    EdgeRouter1ArgsDirections = "top"
)

Defines values for EdgeRouter1ArgsDirections.

func (EdgeRouter1ArgsDirections) Valid

func (e EdgeRouter1ArgsDirections) Valid() bool

Valid indicates whether the value is a known member of the EdgeRouter1ArgsDirections enum.

type EdgeRouter1Name

type EdgeRouter1Name string

EdgeRouter1Name Router algorithm name

const (
	EdgeRouter1NameEr        EdgeRouter1Name = "er"
	EdgeRouter1NameManhattan EdgeRouter1Name = "manhattan"
	EdgeRouter1NameMetro     EdgeRouter1Name = "metro"
	EdgeRouter1NameNormal    EdgeRouter1Name = "normal"
	EdgeRouter1NameOneSide   EdgeRouter1Name = "one_side"
	EdgeRouter1NameOrth      EdgeRouter1Name = "orth"
)

Defines values for EdgeRouter1Name.

func (EdgeRouter1Name) Valid

func (e EdgeRouter1Name) Valid() bool

Valid indicates whether the value is a known member of the EdgeRouter1Name enum.

type EdgeRouter_1_Args

type EdgeRouter_1_Args struct {
	// Directions Allowed routing directions
	Directions *[]EdgeRouter1ArgsDirections `json:"directions,omitempty"`

	// Padding Padding around obstacles for routing
	Padding *float32 `json:"padding,omitempty"`

	// Step Grid step size for orthogonal routing
	Step                 *float32               `json:"step,omitempty"`
	AdditionalProperties map[string]interface{} `json:"-"`
}

EdgeRouter_1_Args Router-specific arguments

func (EdgeRouter_1_Args) Get

func (a EdgeRouter_1_Args) Get(fieldName string) (value interface{}, found bool)

Getter for additional properties for EdgeRouter_1_Args. Returns the specified element and whether it was found

func (EdgeRouter_1_Args) MarshalJSON

func (a EdgeRouter_1_Args) MarshalJSON() ([]byte, error)

Override default JSON handling for EdgeRouter_1_Args to handle AdditionalProperties

func (*EdgeRouter_1_Args) Set

func (a *EdgeRouter_1_Args) Set(fieldName string, value interface{})

Setter for additional properties for EdgeRouter_1_Args

func (*EdgeRouter_1_Args) UnmarshalJSON

func (a *EdgeRouter_1_Args) UnmarshalJSON(b []byte) error

Override default JSON handling for EdgeRouter_1_Args to handle AdditionalProperties

type EdgeShape

type EdgeShape string

EdgeShape Edge type identifier

const (
	EdgeShapeFlow EdgeShape = "flow"
)

Defines values for EdgeShape.

func (EdgeShape) Valid

func (e EdgeShape) Valid() bool

Valid indicates whether the value is a known member of the EdgeShape enum.

type EdgeTerminal

type EdgeTerminal struct {
	// Cell ID of the connected node (UUID)
	Cell openapi_types.UUID `json:"cell"`

	// Port ID of the specific port on the node (optional)
	Port *string `json:"port,omitempty"`
}

EdgeTerminal Connection point for an edge (source or target)

type Edge_Data

type Edge_Data struct {
	// UnderscoreMetadata Reserved namespace for structured business metadata
	UnderscoreMetadata *[]Metadata `json:"_metadata,omitempty"`

	// DataAssets References to Asset IDs associated with this cell. Each UUID must reference an existing Asset in the same threat model.
	DataAssets *[]openapi_types.UUID `json:"data_assets,omitempty"`

	// SecurityBoundary Indicates whether this cell represents a security boundary in the threat model
	SecurityBoundary     *bool                  `json:"security_boundary,omitempty"`
	AdditionalProperties map[string]interface{} `json:"-"`
}

Edge_Data Flexible data storage compatible with X6, with reserved metadata namespace

func (Edge_Data) Get

func (a Edge_Data) Get(fieldName string) (value interface{}, found bool)

Getter for additional properties for Edge_Data. Returns the specified element and whether it was found

func (Edge_Data) MarshalJSON

func (a Edge_Data) MarshalJSON() ([]byte, error)

Override default JSON handling for Edge_Data to handle AdditionalProperties

func (*Edge_Data) Set

func (a *Edge_Data) Set(fieldName string, value interface{})

Setter for additional properties for Edge_Data

func (*Edge_Data) UnmarshalJSON

func (a *Edge_Data) UnmarshalJSON(b []byte) error

Override default JSON handling for Edge_Data to handle AdditionalProperties

type EmailQueryParam

type EmailQueryParam = string

EmailQueryParam defines model for EmailQueryParam.

type EmbeddingCleaner

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

EmbeddingCleaner periodically deletes embeddings from idle threat models. SEM@78c94ddab0f9e346067370bad3e9d3d88bd6a99b: background service that periodically deletes embeddings from idle threat models (mutates shared state)

func NewEmbeddingCleaner

func NewEmbeddingCleaner(
	embeddingStore TimmyEmbeddingStore,
	db *gorm.DB,
	interval time.Duration,
	activeIdleDays int,
	closedIdleDays int,
) *EmbeddingCleaner

NewEmbeddingCleaner creates a new embedding cleaner. SEM@78c94ddab0f9e346067370bad3e9d3d88bd6a99b: build an EmbeddingCleaner with configurable interval and idle-day thresholds (pure)

func (*EmbeddingCleaner) CleanOnce

func (ec *EmbeddingCleaner) CleanOnce() int64

CleanOnce runs a single cleanup cycle. Returns total embeddings deleted. SEM@5981ac53dd2229e2bb211a96f0b495fe72df5f32: delete embeddings for all currently idle threat models and return the total count deleted (reads DB)

func (*EmbeddingCleaner) Start

func (ec *EmbeddingCleaner) Start()

Start begins the background cleanup loop. SEM@78c94ddab0f9e346067370bad3e9d3d88bd6a99b: start the background embedding-cleanup goroutine (mutates shared state)

func (*EmbeddingCleaner) Stop

func (ec *EmbeddingCleaner) Stop()

Stop signals the cleaner to stop. SEM@78c94ddab0f9e346067370bad3e9d3d88bd6a99b: signal the embedding-cleanup loop to stop (mutates shared state)

type EmbeddingConfig

type EmbeddingConfig struct {
	// CodeEmbedding Code embedding config. Null if not configured.
	CodeEmbedding *EmbeddingProviderConfig `json:"code_embedding,omitempty"`

	// TextEmbedding Configuration for an embedding provider, specifying the provider name, model, and optional API key or custom base URL.
	TextEmbedding EmbeddingProviderConfig `json:"text_embedding"`
}

EmbeddingConfig Aggregate embedding configuration for a threat model, holding separate provider configs for text and optionally code embeddings.

type EmbeddingDeleteResponse

type EmbeddingDeleteResponse struct {
	// Deleted Number of embeddings deleted
	Deleted int `json:"deleted"`
}

EmbeddingDeleteResponse Response returned after deleting all embeddings for a threat model, reporting the number of records removed.

type EmbeddingIngestionItem

type EmbeddingIngestionItem struct {
	// ChunkIndex Sequential chunk number
	ChunkIndex int `json:"chunk_index"`

	// ChunkText Original text of the chunk
	ChunkText string `json:"chunk_text"`

	// ContentHash SHA256 hash of the original content
	ContentHash string `json:"content_hash"`

	// EmbeddingDim Embedding vector dimension
	EmbeddingDim int `json:"embedding_dim"`

	// EmbeddingModel Model used to generate the embedding
	EmbeddingModel string `json:"embedding_model"`

	// EntityId Entity UUID
	EntityId openapi_types.UUID `json:"entity_id"`

	// EntityType Entity type (e.g., repository, asset)
	EntityType string `json:"entity_type"`

	// Vector Embedding vector
	Vector []float32 `json:"vector"`
}

EmbeddingIngestionItem A single pre-computed embedding chunk submitted for ingestion, including the source entity, chunk text, content hash, and embedding vector.

type EmbeddingIngestionRequest

type EmbeddingIngestionRequest struct {
	// Embeddings Batch of pre-computed embeddings
	Embeddings []EmbeddingIngestionItem `json:"embeddings"`

	// IndexType Target index type
	IndexType EmbeddingIngestionRequestIndexType `json:"index_type"`
}

EmbeddingIngestionRequest Request body for submitting a batch of pre-computed embeddings into a threat model index.

type EmbeddingIngestionRequestIndexType

type EmbeddingIngestionRequestIndexType string

EmbeddingIngestionRequestIndexType Target index type

const (
	EmbeddingIngestionRequestIndexTypeCode EmbeddingIngestionRequestIndexType = "code"
	EmbeddingIngestionRequestIndexTypeText EmbeddingIngestionRequestIndexType = "text"
)

Defines values for EmbeddingIngestionRequestIndexType.

func (EmbeddingIngestionRequestIndexType) Valid

Valid indicates whether the value is a known member of the EmbeddingIngestionRequestIndexType enum.

type EmbeddingIngestionResponse

type EmbeddingIngestionResponse struct {
	// Ingested Number of embeddings ingested
	Ingested int `json:"ingested"`
}

EmbeddingIngestionResponse Response returned after a successful embedding ingestion operation, reporting the number of embeddings stored.

type EmbeddingProviderConfig

type EmbeddingProviderConfig struct {
	// ApiKey Embedding provider API key
	ApiKey *string `json:"api_key,omitempty"`

	// BaseUrl Custom base URL for self-hosted endpoints
	BaseUrl *string `json:"base_url,omitempty"`

	// Model Embedding model name
	Model string `json:"model"`

	// Provider Embedding provider name
	Provider string `json:"provider"`
}

EmbeddingProviderConfig Configuration for an embedding provider, specifying the provider name, model, and optional API key or custom base URL.

type EmbeddingSource

type EmbeddingSource interface {
	// Name returns the provider name for logging
	Name() string
	// CanHandle returns true if this provider can extract content from the given entity
	CanHandle(ctx context.Context, ref EntityReference) bool
	// Extract fetches and returns plain text content
	Extract(ctx context.Context, ref EntityReference) (ExtractedContent, error)
}

EmbeddingSource extracts plain text from source entities for embedding SEM@0551ca168efde46f1a10164b714a260d65a9d52a: interface for extracting plain text from an entity reference for embedding (pure)

type EmbeddingSourceRegistry

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

EmbeddingSourceRegistry manages embedding sources in priority order SEM@80346558ce851de593c85a2d5660f92a649b1686: ordered registry of embedding sources tried in registration priority (pure)

func NewEmbeddingSourceRegistry

func NewEmbeddingSourceRegistry() *EmbeddingSourceRegistry

NewEmbeddingSourceRegistry creates a new registry SEM@80346558ce851de593c85a2d5660f92a649b1686: build an empty EmbeddingSourceRegistry (pure)

func (*EmbeddingSourceRegistry) Extract

Extract finds the first provider that can handle the entity and extracts its content SEM@80346558ce851de593c85a2d5660f92a649b1686: dispatch to the first capable provider and extract text content from an entity reference (reads DB)

func (*EmbeddingSourceRegistry) Register

func (r *EmbeddingSourceRegistry) Register(provider EmbeddingSource)

Register adds a provider to the registry (providers are tried in registration order) SEM@80346558ce851de593c85a2d5660f92a649b1686: append an embedding source provider to the registry in priority order (mutates shared state)

type EnhancedMetadataCreateRequest

type EnhancedMetadataCreateRequest struct {
	Key   string `json:"key" binding:"required" maxlength:"100"`
	Value string `json:"value" binding:"required" maxlength:"1000"`
}

Additional validation struct examples for metadata (avoiding conflicts with existing types) SEM@4fa1d37f07fd36467dea01526b97410523474271: request struct for creating a metadata key-value pair with required binding and length constraints

type EntityEmbeddingMeta

type EntityEmbeddingMeta struct {
	ContentHash    string
	EmbeddingModel string
	EmbeddingDim   int
}

EntityEmbeddingMeta is the per-entity tuple needed to decide whether existing embeddings are still usable without loading the vectors. Hash, Model, and Dim are taken from any one row of the entity's chunks (they are identical across an entity's chunks by construction in CreateBatch). SEM@c2249e83ad3c835dac1a450330c3da45b68c190c: per-entity embedding freshness metadata used to decide if stored vectors are reusable (pure)

type EntityKey

type EntityKey struct {
	EntityType string
	EntityID   string
}

EntityKey identifies a single chunked entity within a threat model. It is the natural map key for "one row per entity" lookups (e.g., the freshness metadata used by prepareVectorIndex). SEM@c2249e83ad3c835dac1a450330c3da45b68c190c: composite key identifying a chunked entity within a threat model (pure)

type EntityReference

type EntityReference = extract.EntityReference

Type aliases re-exporting pkg/extract into the api package. The extractor logic was relocated to pkg/extract during Component Platform Plan 2 (#347) so the sandboxed worker can link it without pulling in Gin/GORM. These aliases keep the monolith's many call sites unchanged.

type EntitySummary

type EntitySummary struct {
	EntityType  string
	EntityID    string
	Name        string
	Description string
	// Additional fields for specific entity types
	Extra map[string]string // e.g., "severity" for threats, "type" for assets
}

EntitySummary holds a brief summary of an entity for Tier 1 context SEM@eec102aedf0150afa44dc0d334e7923359c1f2aa: brief summary of a threat-model entity used to build tier-1 LLM context (pure)

type ErrEmbeddingModelMismatch

type ErrEmbeddingModelMismatch struct {
	ThreatModelID string
	IndexType     string
	StaleModel    string
	StaleDim      int
	ExpectedModel string
	ExpectedDim   int
	EntityType    string // first mismatched row, for diagnostics
	EntityID      string
}

ErrEmbeddingModelMismatch is returned by GetOrLoadIndex when at least one stored embedding row in the (threat_model_id, index_type) bucket disagrees with the active embedding model or dimension. The caller is expected to delete the stale rows and re-prepare the index. SEM@dfcd0fbfb9ee063edbd7fe1fcd9795399535a6c8: error indicating stored embeddings disagree with the active embedding model or dimension (pure)

func (*ErrEmbeddingModelMismatch) Error

func (e *ErrEmbeddingModelMismatch) Error() string

SEM@dfcd0fbfb9ee063edbd7fe1fcd9795399535a6c8: format the embedding model mismatch error as a descriptive string (pure)

type Error

type Error struct {
	// Details Additional context-specific error information
	Details *struct {
		// Code Machine-readable error code for programmatic handling
		Code *string `json:"code,omitempty"`

		// Context Contextual information about the error
		Context *map[string]interface{} `json:"context,omitempty"`

		// Suggestion Human-readable suggestion for resolving the error
		Suggestion *string `json:"suggestion,omitempty"`
	} `json:"details,omitempty"`

	// Error Error code
	Error string `json:"error"`

	// ErrorDescription Human-readable error description
	ErrorDescription string `json:"error_description"`

	// ErrorUri URI to documentation about the error
	ErrorUri *string `json:"error_uri,omitempty"`
}

Error Standard error response format

type ErrorDetails

type ErrorDetails struct {
	Code       *string        `json:"code,omitempty"`
	Context    map[string]any `json:"context,omitempty"`
	Suggestion *string        `json:"suggestion,omitempty"`
}

ErrorDetails provides structured context for errors SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: optional structured context attached to a request error (pure)

type ErrorMessage

type ErrorMessage struct {
	MessageType MessageType    `json:"message_type"`
	Error       string         `json:"error"`
	Message     string         `json:"message"`
	Code        *string        `json:"code,omitempty"`
	Details     map[string]any `json:"details,omitempty"`
	Timestamp   time.Time      `json:"timestamp"`
}

ErrorMessage represents an error response SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: WebSocket message struct representing a server error response with code and details (pure)

func (ErrorMessage) GetMessageType

func (m ErrorMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for an error message (pure)

func (ErrorMessage) Validate

func (m ErrorMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate an error message; reject if type, error field, or message text is missing (pure)

type ErrorResponse deprecated

type ErrorResponse = Error

ErrorResponse is deprecated. Use the OpenAPI-generated Error type instead. This type has been replaced with api.Error which uses error_description field per OpenAPI specification requirements.

Deprecated: Use Error from api.go (OpenAPI-generated)

type EventEmitter

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

EventEmitter handles event emission to Redis Streams SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: struct that emits deduplicated resource events to a Redis Stream

var GlobalEventEmitter *EventEmitter

Global event emitter instance

func NewEventEmitter

func NewEventEmitter(redisClient *redis.Client, streamKey string) *EventEmitter

NewEventEmitter creates a new event emitter SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: build an event emitter bound to a Redis client and stream key (pure)

func (*EventEmitter) EmitEvent

func (e *EventEmitter) EmitEvent(ctx context.Context, payload EventPayload) error

EmitEvent emits an event to Redis Stream with deduplication SEM@914adca66ed5ce0bcfa6a1233361a298648ccf00: publish a deduplicated resource event to the Redis Stream; skips on duplicate or unavailable Redis

type EventPayload

type EventPayload struct {
	EventType     string         `json:"event_type"`
	ThreatModelID string         `json:"threat_model_id,omitempty"`
	ObjectID      string         `json:"object_id"`
	ObjectType    string         `json:"object_type"`
	OwnerID       string         `json:"owner_id"`
	Timestamp     time.Time      `json:"timestamp"`
	Data          map[string]any `json:"data,omitempty"`
}

EventPayload represents the structure of an event emitted to Redis SEM@00add3d4f7dc1c0a9cc072d7e6ca32ace4d03641: struct carrying event type, resource references, owner, and data for a Redis Stream entry (pure)

type ExchangeOAuthCodeFormdataRequestBody

type ExchangeOAuthCodeFormdataRequestBody = TokenRequest

ExchangeOAuthCodeFormdataRequestBody defines body for ExchangeOAuthCode for application/x-www-form-urlencoded ContentType.

type ExchangeOAuthCodeJSONBody

type ExchangeOAuthCodeJSONBody struct {
	// ClientId Client identifier (required for client_credentials grant)
	ClientId *string `json:"client_id,omitempty"`

	// ClientSecret Client secret (required for client_credentials grant)
	ClientSecret *string `json:"client_secret,omitempty"`

	// Code Authorization code received from OAuth provider. Per RFC 6749, can contain any visible ASCII characters (VSCHAR: 0x20-0x7E).
	Code *string `json:"code,omitempty"`

	// CodeVerifier PKCE code verifier (RFC 7636) - High-entropy cryptographic random string used to mitigate authorization code interception attacks. Must be 43-128 characters using [A-Za-z0-9-._~] characters.
	CodeVerifier *string `json:"code_verifier,omitempty"`

	// GrantType OAuth 2.0 grant type (RFC 6749)
	GrantType ExchangeOAuthCodeJSONBodyGrantType `json:"grant_type"`

	// RedirectUri Redirect URI used in the authorization request (must match exactly)
	RedirectUri *string `json:"redirect_uri,omitempty"`

	// RefreshToken Refresh token (required for refresh_token grant)
	RefreshToken *string `json:"refresh_token,omitempty"`

	// State State parameter for CSRF protection (optional but recommended)
	State *string `json:"state,omitempty"`
}

ExchangeOAuthCodeJSONBody defines parameters for ExchangeOAuthCode.

type ExchangeOAuthCodeJSONBodyGrantType

type ExchangeOAuthCodeJSONBodyGrantType string

ExchangeOAuthCodeJSONBodyGrantType defines parameters for ExchangeOAuthCode.

const (
	AuthorizationCode ExchangeOAuthCodeJSONBodyGrantType = "authorization_code"
	ClientCredentials ExchangeOAuthCodeJSONBodyGrantType = "client_credentials"
	RefreshToken      ExchangeOAuthCodeJSONBodyGrantType = "refresh_token"
)

Defines values for ExchangeOAuthCodeJSONBodyGrantType.

func (ExchangeOAuthCodeJSONBodyGrantType) Valid

Valid indicates whether the value is a known member of the ExchangeOAuthCodeJSONBodyGrantType enum.

type ExchangeOAuthCodeJSONRequestBody

type ExchangeOAuthCodeJSONRequestBody ExchangeOAuthCodeJSONBody

ExchangeOAuthCodeJSONRequestBody defines body for ExchangeOAuthCode for application/json ContentType.

type ExchangeOAuthCodeParams

type ExchangeOAuthCodeParams struct {
	// Idp OAuth provider identifier. Defaults to 'tmi' provider in non-production builds if not specified.
	Idp *IdpQueryParam `form:"idp,omitempty" json:"idp,omitempty"`
}

ExchangeOAuthCodeParams defines parameters for ExchangeOAuthCode.

type ExtendedAsset

type ExtendedAsset struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// Classification Classification tags for the asset
	Classification *[]string `json:"classification,omitempty"`

	// CreatedAt Creation timestamp (ISO3339)
	CreatedAt time.Time `json:"created_at"`

	// Criticality Criticality level of the asset
	Criticality *string `json:"criticality,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of the asset
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the asset
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (ISO3339)
	ModifiedAt time.Time `json:"modified_at"`

	// Name Asset name
	Name string `binding:"required" json:"name"`

	// Sensitivity Sensitivity label for the asset
	Sensitivity *string `json:"sensitivity,omitempty"`

	// ThreatModelId ID of the threat model this asset belongs to
	ThreatModelId openapi_types.UUID `json:"threat_model_id"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Type of asset
	Type ExtendedAssetType `binding:"required" json:"type"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

ExtendedAsset defines model for ExtendedAsset.

type ExtendedAssetType

type ExtendedAssetType string

ExtendedAssetType Type of asset

const (
	ExtendedAssetTypeData           ExtendedAssetType = "data"
	ExtendedAssetTypeHardware       ExtendedAssetType = "hardware"
	ExtendedAssetTypeInfrastructure ExtendedAssetType = "infrastructure"
	ExtendedAssetTypePersonnel      ExtendedAssetType = "personnel"
	ExtendedAssetTypeService        ExtendedAssetType = "service"
	ExtendedAssetTypeSoftware       ExtendedAssetType = "software"
)

Defines values for ExtendedAssetType.

func (ExtendedAssetType) Valid

func (e ExtendedAssetType) Valid() bool

Valid indicates whether the value is a known member of the ExtendedAssetType enum.

type ExtractedContent

type ExtractedContent = extract.ExtractedContent

Type aliases re-exporting pkg/extract into the api package. The extractor logic was relocated to pkg/extract during Component Platform Plan 2 (#347) so the sandboxed worker can link it without pulling in Gin/GORM. These aliases keep the monolith's many call sites unchanged.

type ExtractionClassification

type ExtractionClassification struct {
	Status       string
	ReasonCode   string
	ReasonDetail string
}

ExtractionClassification describes how a typed extractor error maps to access_status + access_reason_code. The reason code comes from extract.ClassifyError; access_status is the monolith-owned overlay. SEM@3de5c96824ab56d75179c1213960ce962da87ec7: structured result describing the outcome or failure reason of a content extraction (pure)

func ClassifyExtractionError

func ClassifyExtractionError(err error) ExtractionClassification

ClassifyExtractionError classifies a typed extractor error and attaches the monolith-owned access_status. The reason-code classification is delegated to extract.ClassifyError (the relocated library logic); a non-empty reason code maps to AccessStatusExtractionFailed. SEM@d1fd850907490887fd11a6ccd4a691326ede6e4e: convert an extraction error into a structured ExtractionClassification (pure)

type ExtractionJobStore

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

ExtractionJobStore persists ExtractionJob rows. The result-consumer is the sole writer of terminal states; the publish-side callers only InsertQueued. SEM@36aa9fcae21c995e1ea57da44ded6bc1126d1af7: persistent store for extraction job lifecycle records (reads DB)

func NewExtractionJobStore

func NewExtractionJobStore(db *gorm.DB) *ExtractionJobStore

NewExtractionJobStore constructs the store. SEM@36aa9fcae21c995e1ea57da44ded6bc1126d1af7: build an ExtractionJobStore backed by the given GORM database (pure)

func (*ExtractionJobStore) GetDocumentRef

func (s *ExtractionJobStore) GetDocumentRef(ctx context.Context, jobID string) (string, error)

GetDocumentRef returns the document_ref stored for the given jobID. Returns ("", nil) when the job row does not exist (e.g. the row was never inserted, or the document was hard-deleted before the result arrived). SEM@28a744a1501431680450f9ab9c4d57cdf9bebd2d: fetch the document reference stored for a given job ID, returning empty string if absent (reads DB)

func (*ExtractionJobStore) InsertQueued

func (s *ExtractionJobStore) InsertQueued(ctx context.Context, jobID, documentRef string) error

InsertQueued inserts a queued row for job_id. Idempotent: an existing row is left unchanged (OnConflict DoNothing). Portable across PG and Oracle. Uses Col()/ColumnName() so the Oracle GORM driver receives uppercase column identifiers when emitting MERGE INTO.

Oracle note: with OnConflict the gorm-oracle driver emits MERGE INTO, not INSERT ... RETURNING. RETURNING-from-MERGE is fragile, so the store methods must not rely on struct fields populated by Create after the call — re-read via GetDocumentRef instead. SEM@36aa9fcae21c995e1ea57da44ded6bc1126d1af7: store a queued extraction job row idempotently, skipping on duplicate job ID (reads DB)

func (*ExtractionJobStore) MarkTerminal

func (s *ExtractionJobStore) MarkTerminal(ctx context.Context, jobID, status, reasonCode string) (bool, error)

MarkTerminal records the terminal state for job_id and reports whether this call performed the *first* terminal transition (true) or hit a row that was already terminal (false). The boolean is the durable, restart-safe emit-once signal the result-consumer uses to fire the document.extraction_* webhook exactly once under JetStream at-least-once redelivery (#438).

It is implemented as a guarded UPDATE followed, only when that matches no row, by an OnConflict-DoNothing insert:

  1. UPDATE ... WHERE job_id = ? AND status NOT IN ('completed','failed'). A plain UPDATE reports reliable RowsAffected on PG, Oracle, and SQLite (unlike MERGE/RETURNING). RowsAffected == 1 means we moved an existing non-terminal row to terminal — the first transition → return true. Under READ COMMITTED on both PG and Oracle the WHERE is re-evaluated after the row lock is taken, so two concurrent deliveries cannot both match: the second sees the now-terminal status and matches 0 rows.
  2. RowsAffected == 0 means the row is absent (a terminal result arrived with no prior queued row — possible under at-least-once delivery) OR it is already terminal (a redelivery). Attempt a bare insert with the unknownDocumentRef sentinel; OnConflict DoNothing makes a concurrent insert or an existing terminal row a no-op. Insert RowsAffected == 1 means we created the terminal row → first transition (true); == 0 means a row already existed and, per step 1, is already terminal → false.

document_ref is only ever written on the bare-insert path and is set to the unknownDocumentRef sentinel (NOT empty string; see the constant doc for the Oracle ORA-01400 rationale). The guarded UPDATE never touches document_ref, so an existing queued row keeps its real document_ref. An empty reasonCode string is stored as SQL NULL (NullableDBVarchar{Valid: false}).

Portable across PG, Oracle, and SQLite. Uses Col()/ColumnName()/AssignmentMap so the Oracle GORM driver receives uppercase column identifiers. SEM@b191ea0be150feb4f3aef14c234451872330fcf7: atomically transition an extraction job to a terminal state and report whether this was the first transition (reads DB)

type ExtractionPublisher

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

ExtractionPublisher submits extraction jobs to the worker pipeline. SEM@cabdea1518df8719a976053b8e28d2b37714a876: publisher that uploads document bytes and dispatches extraction jobs to the worker pipeline

func NewExtractionPublisher

func NewExtractionPublisher(conn *worker.Conn, store *ExtractionJobStore) *ExtractionPublisher

NewExtractionPublisher wraps a worker.Conn and the job store. SEM@cabdea1518df8719a976053b8e28d2b37714a876: build an ExtractionPublisher wired to a worker connection and job store (pure)

func (*ExtractionPublisher) Publish

Publish writes the document bytes to the Object Store, publishes an extract job, and records a queued row. Returns the job_id for caller correlation. SEM@cabdea1518df8719a976053b8e28d2b37714a876: store document bytes, publish an extraction job, and record a queued row; return the job ID (mutates shared state)

type ExtractionRequest

type ExtractionRequest struct {
	DocumentID  string
	ContentType string
	Bytes       []byte
}

ExtractionRequest is one document's extraction submission. SEM@cabdea1518df8719a976053b8e28d2b37714a876: document bytes and content type for one extraction job submission (pure)

type FieldErrorRegistry

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

FieldErrorRegistry provides contextual error messages for prohibited fields SEM@63189587a90229342bc1d25023ec7a515412fb4f: registry mapping prohibited field names to contextual error messages (pure)

func (*FieldErrorRegistry) GetMessage

func (r *FieldErrorRegistry) GetMessage(field, operation string) string

GetFieldErrorMessage returns a contextual error message for a prohibited field SEM@63189587a90229342bc1d25023ec7a515412fb4f: fetch the most-specific error message for a prohibited field and HTTP operation (pure)

type FilterOperator

type FilterOperator int

FilterOperator represents the type of filter operation to apply. SEM@40d9903ef472b183a4ed2bcf0478562c757f255d: enum of filter operators supported in query parameter values (pure)

const (
	// FilterOpNone indicates a plain value with no operator prefix.
	FilterOpNone FilterOperator = iota
	// FilterOpIsNull indicates the field should be NULL.
	FilterOpIsNull
	// FilterOpIsNotNull indicates the field should be NOT NULL.
	FilterOpIsNotNull
)

type Forbidden

type Forbidden = Error

Forbidden Standard error response format

type GenericId

type GenericId = openapi_types.UUID

GenericId defines model for GenericId.

type GenericMetadataHandler

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

GenericMetadataHandler provides handlers for metadata operations on any entity type. It replaces entity-specific metadata handlers with a single implementation. SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: reusable handler struct for metadata CRUD operations on any entity type

func NewGenericMetadataHandler

func NewGenericMetadataHandler(metadataStore MetadataRepository, entityType, parentParamName string, verifyParent ParentVerifier) *GenericMetadataHandler

NewGenericMetadataHandler creates a new generic metadata handler.

Parameters:

  • metadataStore: the metadata repository to use
  • entityType: the entity type string (e.g., "survey", "threat_model")
  • parentParamName: the gin parameter name for the parent entity ID (e.g., "survey_id")
  • verifyParent: optional function to verify parent entity exists (nil to skip)

SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: build a generic metadata handler for the given store, entity type, and optional parent verifier (pure)

func (*GenericMetadataHandler) BulkCreate

func (h *GenericMetadataHandler) BulkCreate(c *gin.Context)

BulkCreate creates multiple metadata entries in a single request. SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: store multiple new metadata entries for an entity, rejecting duplicates or conflicts (reads DB)

func (*GenericMetadataHandler) BulkReplace

func (h *GenericMetadataHandler) BulkReplace(c *gin.Context)

BulkReplace replaces all metadata for an entity with the provided set. All existing metadata is deleted and replaced with the provided entries. An empty array clears all metadata for the entity. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: replace all metadata entries for an entity with the provided set, deleting previous entries (mutates shared state)

func (*GenericMetadataHandler) BulkUpsert

func (h *GenericMetadataHandler) BulkUpsert(c *gin.Context)

BulkUpsert updates or creates multiple metadata entries in a single request. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: update or create multiple metadata entries for an entity in one request (reads DB)

func (*GenericMetadataHandler) Create

func (h *GenericMetadataHandler) Create(c *gin.Context)

Create creates a new metadata entry. SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: store a new metadata key-value pair under a parent entity, rejecting duplicates (reads DB)

func (*GenericMetadataHandler) Delete

func (h *GenericMetadataHandler) Delete(c *gin.Context)

Delete deletes a metadata entry. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: delete a metadata entry by key from a parent entity (reads DB)

func (*GenericMetadataHandler) GetByKey

func (h *GenericMetadataHandler) GetByKey(c *gin.Context)

GetByKey retrieves a specific metadata entry by key. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: fetch a single metadata entry by key for a parent entity (reads DB)

func (*GenericMetadataHandler) List

func (h *GenericMetadataHandler) List(c *gin.Context)

List retrieves all metadata for an entity. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: list all metadata entries for a parent entity (reads DB)

func (*GenericMetadataHandler) Update

func (h *GenericMetadataHandler) Update(c *gin.Context)

Update updates an existing metadata entry. SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: replace the value of an existing metadata entry identified by key (reads DB)

type GetAssetAuditTrailParams

type GetAssetAuditTrailParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

GetAssetAuditTrailParams defines parameters for GetAssetAuditTrail.

type GetDiagramAuditTrailParams

type GetDiagramAuditTrailParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

GetDiagramAuditTrailParams defines parameters for GetDiagramAuditTrail.

type GetDocumentAuditTrailParams

type GetDocumentAuditTrailParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

GetDocumentAuditTrailParams defines parameters for GetDocumentAuditTrail.

type GetNoteAuditTrailParams

type GetNoteAuditTrailParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

GetNoteAuditTrailParams defines parameters for GetNoteAuditTrail.

type GetRepositoryAuditTrailParams

type GetRepositoryAuditTrailParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

GetRepositoryAuditTrailParams defines parameters for GetRepositoryAuditTrail.

type GetThreatAuditTrailParams

type GetThreatAuditTrailParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

GetThreatAuditTrailParams defines parameters for GetThreatAuditTrail.

type GetThreatModelAssetsParams

type GetThreatModelAssetsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// IncludeDeleted Include soft-deleted (tombstoned) entities in the response. Requires owner or admin role.
	IncludeDeleted *IncludeDeletedQueryParam `form:"include_deleted,omitempty" json:"include_deleted,omitempty"`
}

GetThreatModelAssetsParams defines parameters for GetThreatModelAssets.

type GetThreatModelAuditTrailParams

type GetThreatModelAuditTrailParams struct {
	// Limit Maximum number of entries to return per page.
	Limit *AuditPageLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Cursor Opaque pagination cursor from the previous page next_cursor. Omit for the first page.
	Cursor *AuditCursor `form:"cursor,omitempty" json:"cursor,omitempty"`

	// ObjectType Filter by object type
	ObjectType *GetThreatModelAuditTrailParamsObjectType `form:"object_type,omitempty" json:"object_type,omitempty"`

	// ChangeType Filter by change type
	ChangeType *GetThreatModelAuditTrailParamsChangeType `form:"change_type,omitempty" json:"change_type,omitempty"`

	// ActorEmail Filter by actor email
	ActorEmail *AuditActorEmail `form:"actor_email,omitempty" json:"actor_email,omitempty"`

	// CreatedAfter Return only records created after this RFC 3339 timestamp.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp.
	CreatedBefore *CreatedBeforeQueryParam `form:"created_before,omitempty" json:"created_before,omitempty"`
}

GetThreatModelAuditTrailParams defines parameters for GetThreatModelAuditTrail.

type GetThreatModelAuditTrailParamsChangeType

type GetThreatModelAuditTrailParamsChangeType string

GetThreatModelAuditTrailParamsChangeType defines parameters for GetThreatModelAuditTrail.

const (
	GetThreatModelAuditTrailParamsChangeTypeCreated    GetThreatModelAuditTrailParamsChangeType = "created"
	GetThreatModelAuditTrailParamsChangeTypeDeleted    GetThreatModelAuditTrailParamsChangeType = "deleted"
	GetThreatModelAuditTrailParamsChangeTypePatched    GetThreatModelAuditTrailParamsChangeType = "patched"
	GetThreatModelAuditTrailParamsChangeTypeRestored   GetThreatModelAuditTrailParamsChangeType = "restored"
	GetThreatModelAuditTrailParamsChangeTypeRolledBack GetThreatModelAuditTrailParamsChangeType = "rolled_back"
	GetThreatModelAuditTrailParamsChangeTypeUpdated    GetThreatModelAuditTrailParamsChangeType = "updated"
)

Defines values for GetThreatModelAuditTrailParamsChangeType.

func (GetThreatModelAuditTrailParamsChangeType) Valid

Valid indicates whether the value is a known member of the GetThreatModelAuditTrailParamsChangeType enum.

type GetThreatModelAuditTrailParamsObjectType

type GetThreatModelAuditTrailParamsObjectType string

GetThreatModelAuditTrailParamsObjectType defines parameters for GetThreatModelAuditTrail.

const (
	GetThreatModelAuditTrailParamsObjectTypeAsset       GetThreatModelAuditTrailParamsObjectType = "asset"
	GetThreatModelAuditTrailParamsObjectTypeDiagram     GetThreatModelAuditTrailParamsObjectType = "diagram"
	GetThreatModelAuditTrailParamsObjectTypeDocument    GetThreatModelAuditTrailParamsObjectType = "document"
	GetThreatModelAuditTrailParamsObjectTypeNote        GetThreatModelAuditTrailParamsObjectType = "note"
	GetThreatModelAuditTrailParamsObjectTypeRepository  GetThreatModelAuditTrailParamsObjectType = "repository"
	GetThreatModelAuditTrailParamsObjectTypeThreat      GetThreatModelAuditTrailParamsObjectType = "threat"
	GetThreatModelAuditTrailParamsObjectTypeThreatModel GetThreatModelAuditTrailParamsObjectType = "threat_model"
)

Defines values for GetThreatModelAuditTrailParamsObjectType.

func (GetThreatModelAuditTrailParamsObjectType) Valid

Valid indicates whether the value is a known member of the GetThreatModelAuditTrailParamsObjectType enum.

type GetThreatModelDiagramsParams

type GetThreatModelDiagramsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// IncludeDeleted Include soft-deleted (tombstoned) entities in the response. Requires owner or admin role.
	IncludeDeleted *IncludeDeletedQueryParam `form:"include_deleted,omitempty" json:"include_deleted,omitempty"`
}

GetThreatModelDiagramsParams defines parameters for GetThreatModelDiagrams.

type GetThreatModelDocumentsParams

type GetThreatModelDocumentsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// IncludeDeleted Include soft-deleted (tombstoned) entities in the response. Requires owner or admin role.
	IncludeDeleted *IncludeDeletedQueryParam `form:"include_deleted,omitempty" json:"include_deleted,omitempty"`
}

GetThreatModelDocumentsParams defines parameters for GetThreatModelDocuments.

type GetThreatModelNotesParams

type GetThreatModelNotesParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// IncludeDeleted Include soft-deleted (tombstoned) entities in the response. Requires owner or admin role.
	IncludeDeleted *IncludeDeletedQueryParam `form:"include_deleted,omitempty" json:"include_deleted,omitempty"`
}

GetThreatModelNotesParams defines parameters for GetThreatModelNotes.

type GetThreatModelRepositoriesParams

type GetThreatModelRepositoriesParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// IncludeDeleted Include soft-deleted (tombstoned) entities in the response. Requires owner or admin role.
	IncludeDeleted *IncludeDeletedQueryParam `form:"include_deleted,omitempty" json:"include_deleted,omitempty"`
}

GetThreatModelRepositoriesParams defines parameters for GetThreatModelRepositories.

type GetThreatModelThreatsParams

type GetThreatModelThreatsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// Sort Sort order (e.g., created_at:desc, name:asc, severity:desc, score:desc)
	Sort *SortQueryParam `form:"sort,omitempty" json:"sort,omitempty"`

	// Name Filter by name (case-insensitive substring match)
	Name *NameQueryParam `form:"name,omitempty" json:"name,omitempty"`

	// Description Filter by threat model description (partial match)
	Description *DescriptionQueryParam `form:"description,omitempty" json:"description,omitempty"`

	// ThreatType Filter by threat types (OR logic). Returns threats matching ANY of the specified types. Example: ?threat_type=Tampering&threat_type=Spoofing
	ThreatType *ThreatTypeQueryParam `form:"threat_type,omitempty" json:"threat_type,omitempty"`

	// Severity Filter by severity level (OR logic). Returns threats matching ANY of the specified severities. Example: ?severity=high&severity=critical
	Severity *SeverityQueryParam `form:"severity,omitempty" json:"severity,omitempty"`

	// Priority Filter by priority (OR logic). Returns threats matching ANY of the specified priorities. Example: ?priority=high&priority=critical
	Priority *PriorityQueryParam `form:"priority,omitempty" json:"priority,omitempty"`

	// Status Filter by status (OR logic). Returns threats matching ANY of the specified statuses. Example: ?status=identified&status=mitigated
	Status *StatusQueryParam `form:"status,omitempty" json:"status,omitempty"`

	// Mitigated Filter by mitigated status (exact match)
	Mitigated *MitigatedQueryParam `form:"mitigated,omitempty" json:"mitigated,omitempty"`

	// DiagramId Filter by diagram ID (exact match)
	DiagramId *DiagramIdQueryParam `form:"diagram_id,omitempty" json:"diagram_id,omitempty"`

	// CellId Filter by cell ID (exact match)
	CellId *CellIdQueryParam `form:"cell_id,omitempty" json:"cell_id,omitempty"`

	// ScoreGt Filter threats with score greater than this value
	ScoreGt *ScoreGtQueryParam `form:"score_gt,omitempty" json:"score_gt,omitempty"`

	// ScoreLt Filter threats with score less than this value
	ScoreLt *ScoreLtQueryParam `form:"score_lt,omitempty" json:"score_lt,omitempty"`

	// ScoreEq Filter threats with score equal to this value
	ScoreEq *ScoreEqQueryParam `form:"score_eq,omitempty" json:"score_eq,omitempty"`

	// ScoreGe Filter threats with score greater than or equal to this value
	ScoreGe *ScoreGeQueryParam `form:"score_ge,omitempty" json:"score_ge,omitempty"`

	// ScoreLe Filter threats with score less than or equal to this value
	ScoreLe *ScoreLeQueryParam `form:"score_le,omitempty" json:"score_le,omitempty"`

	// CreatedAfter Filter results created after this timestamp (ISO 8601)
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601)
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601)
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601)
	ModifiedBefore *ModifiedBefore `form:"modified_before,omitempty" json:"modified_before,omitempty"`

	// IncludeDeleted Include soft-deleted (tombstoned) entities in the response. Requires owner or admin role.
	IncludeDeleted *IncludeDeletedQueryParam `form:"include_deleted,omitempty" json:"include_deleted,omitempty"`
}

GetThreatModelThreatsParams defines parameters for GetThreatModelThreats.

type GetThreatModelThreatsParamsSeverity

type GetThreatModelThreatsParamsSeverity string

GetThreatModelThreatsParamsSeverity defines parameters for GetThreatModelThreats.

Defines values for GetThreatModelThreatsParamsSeverity.

func (GetThreatModelThreatsParamsSeverity) Valid

Valid indicates whether the value is a known member of the GetThreatModelThreatsParamsSeverity enum.

type GetTimmyUsageParams

type GetTimmyUsageParams struct {
	// UserId Filter usage by user identifier
	UserId *openapi_types.UUID `form:"user_id,omitempty" json:"user_id,omitempty"`

	// ThreatModelId Filter usage by threat model identifier
	ThreatModelId *openapi_types.UUID `form:"threat_model_id,omitempty" json:"threat_model_id,omitempty"`

	// StartDate Filter usage records starting from this date (RFC3339)
	StartDate *time.Time `form:"start_date,omitempty" json:"start_date,omitempty"`

	// EndDate Filter usage records up to this date (RFC3339)
	EndDate *time.Time `form:"end_date,omitempty" json:"end_date,omitempty"`
}

GetTimmyUsageParams defines parameters for GetTimmyUsage.

type GetWebhookDeliveryStatusParams

type GetWebhookDeliveryStatusParams struct {
	// XWebhookSignature HMAC-SHA256 signature (format: sha256={hex_signature}). Required for HMAC authentication, optional when using JWT.
	XWebhookSignature *string `json:"X-Webhook-Signature,omitempty"`
}

GetWebhookDeliveryStatusParams defines parameters for GetWebhookDeliveryStatus.

type GetWsTicketParams

type GetWsTicketParams struct {
	// SessionId The collaboration session ID the ticket is scoped to
	SessionId openapi_types.UUID `form:"session_id" json:"session_id"`
}

GetWsTicketParams defines parameters for GetWsTicket.

type GinServerOptions

type GinServerOptions struct {
	BaseURL      string
	Middlewares  []MiddlewareFunc
	ErrorHandler func(*gin.Context, error, int)
}

GinServerOptions provides options for the Gin server.

type GoogleDriveSource

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

GoogleDriveSource fetches content from Google Drive using a service account. SEM@1b4dd947b81f4574ca97fa5898daa7620731ab60: content source that fetches files from Google Drive via service account

func NewGoogleDriveSource

func NewGoogleDriveSource(credentialsFile string, serviceAccountEmail string) (*GoogleDriveSource, error)

NewGoogleDriveSource creates a new GoogleDriveSource from a credentials JSON file. SEM@1b4dd947b81f4574ca97fa5898daa7620731ab60: build a GoogleDriveSource authenticated from a service account credentials file

func (*GoogleDriveSource) CanHandle

func (s *GoogleDriveSource) CanHandle(_ context.Context, uri string) bool

CanHandle returns true for docs.google.com and drive.google.com URIs. SEM@3d1c365886b95c6bdb2dab7691650f26dd8e27e2: report whether a URI belongs to docs.google.com or drive.google.com (pure)

func (*GoogleDriveSource) Fetch

func (s *GoogleDriveSource) Fetch(ctx context.Context, uri string) ([]byte, string, error)

Fetch fetches the content of the Google Drive file identified by uri. Google Workspace documents (Docs, Sheets, Slides) are exported as OOXML (DOCX, XLSX, PPTX) so the higher-fidelity OOXML extractors can parse structured content (tables, headings, formatting) rather than the lossy text/plain or text/csv export formats. Binary files are downloaded directly. SEM@7231febccdb44b858ff3622e6e6bc81ac0ebb575: fetch a Google Drive file, exporting Workspace documents as OOXML

func (*GoogleDriveSource) Name

func (s *GoogleDriveSource) Name() string

Name returns the source name. SEM@f2e01937e40c91e87ac47a34d11870fde716d093: return the provider name "google-drive" (pure)

func (*GoogleDriveSource) RequestAccess

func (s *GoogleDriveSource) RequestAccess(ctx context.Context, uri string) error

RequestAccess logs that the document owner should share the file with the service account. SEM@1b4dd947b81f4574ca97fa5898daa7620731ab60: log that the document owner must share the Drive file with the service account

func (*GoogleDriveSource) ValidateAccess

func (s *GoogleDriveSource) ValidateAccess(ctx context.Context, uri string) (bool, error)

ValidateAccess checks whether the service account can access the file without downloading it. A Drive API error (e.g., 403 Forbidden, 404 Not Found) is treated as "not accessible" rather than an application error — the caller should check the bool result. SEM@1b4dd947b81f4574ca97fa5898daa7620731ab60: check whether the service account can access a Google Drive file without downloading it

type GormAddonInvocationQuotaStore

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

GormAddonInvocationQuotaStore implements AddonInvocationQuotaStore using GORM SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: GORM-backed store for per-user addon invocation quota records (reads DB)

func NewGormAddonInvocationQuotaStore

func NewGormAddonInvocationQuotaStore(db *gorm.DB) *GormAddonInvocationQuotaStore

NewGormAddonInvocationQuotaStore creates a new GORM-backed quota store SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a GormAddonInvocationQuotaStore backed by the given database connection (pure)

func (*GormAddonInvocationQuotaStore) Count

Count returns the total number of addon invocation quotas SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: count total addon invocation quota records in the store (reads DB)

func (*GormAddonInvocationQuotaStore) Delete

func (s *GormAddonInvocationQuotaStore) Delete(ctx context.Context, ownerID uuid.UUID) error

Delete removes quota for a user (reverts to defaults) SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: delete the addon invocation quota for an owner, reverting to system defaults (reads DB)

func (*GormAddonInvocationQuotaStore) Get

Get retrieves quota for a user, returns error if not found SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: fetch the addon invocation quota record for an owner, returning not-found when absent (reads DB)

func (*GormAddonInvocationQuotaStore) GetOrDefault

GetOrDefault retrieves quota for a user, or returns defaults if not set SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: fetch the addon invocation quota for an owner, falling back to system defaults when absent (reads DB)

func (*GormAddonInvocationQuotaStore) List

func (s *GormAddonInvocationQuotaStore) List(ctx context.Context, offset, limit int) ([]*AddonInvocationQuota, error)

List retrieves all addon invocation quotas with pagination SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: list all addon invocation quota records with offset/limit pagination (reads DB)

func (*GormAddonInvocationQuotaStore) Set

Set creates or updates quota for a user using GORM's OnConflict clause SEM@aa6d284f5df5c13ccb0001366a1f228490aba957: upsert an addon invocation quota record for an owner using conflict resolution (reads DB)

type GormAddonStore

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

GormAddonStore implements AddonStore using GORM SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: GORM-backed persistent store for add-on records (reads DB)

func NewGormAddonStore

func NewGormAddonStore(db *gorm.DB) *GormAddonStore

NewGormAddonStore creates a new GORM-backed add-on store SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a GormAddonStore wrapping the given GORM database (pure)

func (*GormAddonStore) CountActiveInvocations

func (s *GormAddonStore) CountActiveInvocations(ctx context.Context, addonID uuid.UUID) (int, error)

CountActiveInvocations counts pending/in_progress invocations for an add-on SEM@1f7fa52ef92fb87a8cf91a548761c53324b4c630: count pending and in-progress invocations for an add-on via the Redis delivery store (reads DB)

func (*GormAddonStore) Create

func (s *GormAddonStore) Create(ctx context.Context, addon *Addon) error

Create creates a new add-on SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: store a new add-on record in the database, assigning ID and timestamp if absent (writes DB)

func (*GormAddonStore) Delete

func (s *GormAddonStore) Delete(ctx context.Context, id uuid.UUID) error

Delete removes an add-on by ID SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: delete an add-on by UUID, returning ErrAddonNotFound if not present (writes DB)

func (*GormAddonStore) DeleteByWebhookID

func (s *GormAddonStore) DeleteByWebhookID(ctx context.Context, webhookID uuid.UUID) (int, error)

DeleteByWebhookID deletes all add-ons associated with a webhook SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: delete all addon records associated with a webhook ID (reads DB)

func (*GormAddonStore) Get

func (s *GormAddonStore) Get(ctx context.Context, id uuid.UUID) (*Addon, error)

Get retrieves an add-on by ID SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: fetch a single add-on by UUID, returning ErrAddonNotFound if absent (reads DB)

func (*GormAddonStore) GetByWebhookID

func (s *GormAddonStore) GetByWebhookID(ctx context.Context, webhookID uuid.UUID) ([]Addon, error)

GetByWebhookID retrieves all add-ons associated with a webhook SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: fetch all add-ons associated with a given webhook UUID (reads DB)

func (*GormAddonStore) List

func (s *GormAddonStore) List(ctx context.Context, limit, offset int, threatModelID *uuid.UUID) ([]Addon, int, error)

List retrieves add-ons with pagination, optionally filtered by threat model SEM@263482d75164f5d9cc6ecfbf63ecc20515b79b0d: list add-ons with pagination and optional threat-model filter, returning total count (reads DB)

type GormAssetRepository

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

GormAssetRepository implements AssetRepository with GORM for database persistence and Redis caching SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: GORM-backed asset repository struct with Redis cache and cache invalidator (reads DB)

func NewGormAssetRepository

func NewGormAssetRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormAssetRepository

NewGormAssetRepository creates a new GORM-backed asset repository with caching SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a GormAssetRepository wired to a DB, cache service, and invalidator (pure)

func (*GormAssetRepository) BulkCreate

func (s *GormAssetRepository) BulkCreate(ctx context.Context, assets []Asset, threatModelID string) error

BulkCreate creates multiple assets in a single transaction using GORM SEM@2a92752bd40820690b955370428f08e99f122b5e: store multiple assets in a single transaction with alias allocation and cache warming (mutates shared state)

func (*GormAssetRepository) CheckAndBumpVersion

func (s *GormAssetRepository) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the asset row's version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the asset row's optimistic-lock version (reads DB)

func (*GormAssetRepository) Count

func (s *GormAssetRepository) Count(ctx context.Context, threatModelID string) (int, error)

Count returns the total number of assets for a threat model SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: count non-deleted assets belonging to a threat model (reads DB)

func (*GormAssetRepository) Create

func (s *GormAssetRepository) Create(ctx context.Context, asset *Asset, threatModelID string) error

Create creates a new asset with write-through caching using GORM SEM@76be6ab76e896b646e29868be2ffc9503d184cad: store a new asset under a threat model, allocate its alias, and warm the cache (mutates shared state)

func (*GormAssetRepository) Delete

func (s *GormAssetRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes an asset by setting deleted_at SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: soft-delete an asset by delegating to SoftDelete (mutates shared state)

func (*GormAssetRepository) Get

func (s *GormAssetRepository) Get(ctx context.Context, id string) (*Asset, error)

Get retrieves an asset by ID with cache-first strategy using GORM SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch an asset by ID, using cache-first then DB fallback (reads DB)

func (*GormAssetRepository) GetIncludingDeleted

func (s *GormAssetRepository) GetIncludingDeleted(ctx context.Context, id string) (*Asset, error)

SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch an asset by ID regardless of its deleted_at status, including metadata (reads DB)

func (*GormAssetRepository) HardDelete

func (s *GormAssetRepository) HardDelete(ctx context.Context, id string) error

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently delete an asset (mutates DB)

func (*GormAssetRepository) InvalidateCache

func (s *GormAssetRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache invalidates the cache for a specific asset SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: evict a single asset's cache entry by ID (mutates shared state)

func (*GormAssetRepository) List

func (s *GormAssetRepository) List(ctx context.Context, threatModelID string, offset, limit int) ([]Asset, error)

List retrieves assets for a threat model with pagination and caching using GORM SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: list paginated assets for a threat model with cache-first strategy (reads DB)

func (*GormAssetRepository) Patch

func (s *GormAssetRepository) Patch(ctx context.Context, id string, operations []PatchOperation) (*Asset, error)

Patch applies JSON patch operations to an asset using GORM SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: apply JSON patch operations to an asset and persist the result (mutates shared state)

func (*GormAssetRepository) Restore

func (s *GormAssetRepository) Restore(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: restore a soft-deleted asset by clearing its deleted_at timestamp (mutates DB)

func (*GormAssetRepository) SoftDelete

func (s *GormAssetRepository) SoftDelete(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete an asset and invalidate its cache entry (mutates DB)

func (*GormAssetRepository) Update

func (s *GormAssetRepository) Update(ctx context.Context, asset *Asset, threatModelID string) error

Update updates an existing asset with write-through caching using GORM SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: update all asset fields in the DB and refresh the cache entry (mutates shared state)

func (*GormAssetRepository) WarmCache

func (s *GormAssetRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache pre-loads assets for a threat model into the cache SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: pre-load the first page of assets for a threat model into the cache (mutates shared state)

type GormAuditService

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

GormAuditService implements AuditServiceInterface using GORM. SEM@f01a64c2e8171748ed345be12c73a8e143fd32e3: GORM-backed audit service holding retention configuration and a database handle (reads DB)

func NewGormAuditService

func NewGormAuditService(db *gorm.DB) *GormAuditService

NewGormAuditService creates a new GormAuditService with configuration from environment. SEM@f01a64c2e8171748ed345be12c73a8e143fd32e3: build a GormAuditService with retention settings resolved from environment variables (reads DB)

func (*GormAuditService) AroundAuditEntriesAdmin

func (s *GormAuditService) AroundAuditEntriesAdmin(ctx context.Context, limit int, anchorID string, filters *AuditFilters) ([]AuditEntryResponse, int, *string, *string, error)

AroundAuditEntriesAdmin returns a page centered on anchorID. SEM@308a4c3ecc46e5d5c087e9d885766ea10322b1ba: fetch a page of audit entries centered on an anchor entry ID with filters (reads DB)

func (*GormAuditService) GetAuditEntry

func (s *GormAuditService) GetAuditEntry(ctx context.Context, entryID string) (*AuditEntryResponse, error)

GetAuditEntry retrieves a single audit entry by ID. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: fetch a single audit entry by ID, returning nil if not found (reads DB)

func (*GormAuditService) GetObjectAuditTrail

func (s *GormAuditService) GetObjectAuditTrail(ctx context.Context, objectType, objectID string, offset, limit int) ([]AuditEntryResponse, int, error)

GetObjectAuditTrail retrieves audit entries for a specific object. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: fetch a paginated audit trail for a specific object by type and ID (reads DB)

func (*GormAuditService) GetSnapshot

func (s *GormAuditService) GetSnapshot(ctx context.Context, entryID string) ([]byte, error)

GetSnapshot reconstructs the full entity state at a given audit entry's version. It finds the nearest checkpoint and applies reverse diffs to reconstruct the state. SEM@ebf201816c3638ec74fc8483a2a649af3ccddfc9: reconstruct the full entity state at an audit entry's version from checkpoint and diffs (reads DB)

func (*GormAuditService) GetThreatModelAuditTrailKeyset

func (s *GormAuditService) GetThreatModelAuditTrailKeyset(ctx context.Context, threatModelID string, limit int, cursor *auditCursor, filters *AuditFilters) ([]AuditEntryResponse, int, *string, *string, error)

GetThreatModelAuditTrailKeyset retrieves audit entries for a threat model and its sub-objects using bidirectional keyset pagination ordered (created_at DESC, id DESC). The total is the filtered count ignoring the cursor, mirroring the admin path. The composite index idx_audit_tm_created (threat_model_id, created_at) backs the threat_model_id equality scope and the leading created_at ordering; the id tiebreaker is resolved by a bounded micro-sort over rows sharing an identical created_at (typically 0-1 within a page), so no full sort is needed (#457). SEM@24454e2885191ae61007ef13d2194c563ebe6d37: fetch a keyset-paginated audit trail for a threat model and its sub-objects (reads DB)

func (*GormAuditService) ListAuditEntriesAdmin

func (s *GormAuditService) ListAuditEntriesAdmin(ctx context.Context, limit int, cursor *auditCursor, filters *AuditFilters) ([]AuditEntryResponse, int, *string, *string, error)

ListAuditEntriesAdmin lists audit entries across all threat models with bidirectional keyset pagination ordered (created_at DESC, id DESC). SEM@308a4c3ecc46e5d5c087e9d885766ea10322b1ba: list audit entries across all threat models with bidirectional keyset pagination and filters (reads DB)

func (*GormAuditService) PruneAuditEntries

func (s *GormAuditService) PruneAuditEntries(ctx context.Context) (int, error)

PruneAuditEntries removes audit entries older than the configured retention period. SEM@a1f271c8c84084548552b08828e5325d3255eb2a: delete audit entries and their version snapshots older than the retention cutoff (mutates DB)

func (*GormAuditService) PruneOrphanedVersionSnapshots

func (s *GormAuditService) PruneOrphanedVersionSnapshots(ctx context.Context) (int, error)

PruneOrphanedVersionSnapshots removes version snapshots whose referenced entity no longer exists in its table.

The delete is filtered to snapshots older than versionRetentionDays, which drives the installed append-only delete floor (floor = retention-1, hard-min 7 days), so every targeted row is guaranteed to clear the floor — identical safety margin to PruneVersionSnapshots. Orphans younger than the cutoff are left for a later cycle once they age past the floor; this keeps the delete from ever tripping the trigger and aborting, and is why orphan cleanup lives here rather than inside the hard-delete transaction.

NOT EXISTS against the raw table (not GORM's soft-delete-scoped query) means a soft-deleted-but-present row counts as existing, so only truly hard-deleted entities are swept. The correlated subquery is portable across PostgreSQL and Oracle, and the age predicate keeps each statement set small, avoiding the ORA-01795 IN-list cap entirely. SEM@225dee65a650d4cb8241fb5be7bf3c49c84642b5: delete version snapshots whose referenced entity no longer exists in its table (mutates DB)

func (*GormAuditService) PruneSystemAuditEntries

func (s *GormAuditService) PruneSystemAuditEntries(ctx context.Context) (int, error)

PruneSystemAuditEntries removes system audit entries older than the configured retention period, in bounded per-transaction batches. Unlike threat-model audit, there are no tombstone rows to preserve — every row past retention is deleted. SEM@6f92be9d792efd59c9cb4f7fd595d4e053a3120b: delete system audit entries older than the retention period in bounded batches (reads DB)

func (*GormAuditService) PruneVersionSnapshots

func (s *GormAuditService) PruneVersionSnapshots(ctx context.Context) (int, error)

PruneVersionSnapshots removes version snapshots outside the retention window. Always stops at a checkpoint boundary so remaining diffs can be reconstructed. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: delete version snapshots outside the retention window, always stopping at a checkpoint boundary (mutates DB)

func (*GormAuditService) PurgeTombstones

func (s *GormAuditService) PurgeTombstones(ctx context.Context) (int, error)

PurgeTombstones hard-deletes entities that have been soft-deleted longer than the retention period. SEM@df8dc0b3bc019d77933b5b20925f456071947e2e: hard-delete soft-deleted threat models and sub-resources past the tombstone retention period (reads DB)

func (*GormAuditService) RecordMutation

func (s *GormAuditService) RecordMutation(ctx context.Context, params AuditParams) error

RecordMutation records a mutation in the audit trail and creates a version snapshot. SEM@d0742bff5d3b93b3ab7b22df0377398a720a8d9c: store an audit entry and version snapshot for a mutation within a retryable transaction (mutates DB)

type GormContentFeedbackRepository

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

GormContentFeedbackRepository implements ContentFeedbackRepository with GORM. SEM@7189df9e563ddcdb55d93d17322355f4ee6c57d0: GORM-backed repository for content feedback records (reads DB)

func NewGormContentFeedbackRepository

func NewGormContentFeedbackRepository(db *gorm.DB) *GormContentFeedbackRepository

NewGormContentFeedbackRepository constructs a repository. SEM@7189df9e563ddcdb55d93d17322355f4ee6c57d0: build a content feedback repository backed by the provided GORM database (pure)

func (*GormContentFeedbackRepository) Count

Count returns the row count for a threat model and filter. SEM@7189df9e563ddcdb55d93d17322355f4ee6c57d0: count content feedback rows for a threat model matching a filter (reads DB)

func (*GormContentFeedbackRepository) Create

Create inserts a feedback row. CreatedAt is set explicitly here (not via GORM's autoCreateTime) for Oracle compatibility — matches the Threat-model pattern (see #380). SEM@f0dc4a18f547f807534300d1d5683b959965e3ab: insert a content feedback row with an explicit timestamp for Oracle compatibility (reads DB)

func (*GormContentFeedbackRepository) CreateWithTargetCheck

CreateWithTargetCheck verifies the target row exists in the named threat model and inserts the feedback row inside a single transaction. The target row is acquired with SELECT ... FOR UPDATE so a concurrent DELETE of the target either waits for this transaction to commit or finds the row gone.

On Oracle and PostgreSQL this is a real row lock; on SQLite (used in unit tests) GORM's clause.Locking is silently ignored and the check still serializes via the surrounding transaction's default isolation. SEM@d0742bff5d3b93b3ab7b22df0377398a720a8d9c: insert content feedback only if its target row exists in the threat model, using a row lock (reads DB)

func (*GormContentFeedbackRepository) Get

Get returns a feedback row by ID, or NotFound if absent. SEM@7189df9e563ddcdb55d93d17322355f4ee6c57d0: fetch a content feedback row by ID, returning not-found if absent (reads DB)

func (*GormContentFeedbackRepository) List

func (r *GormContentFeedbackRepository) List(ctx context.Context, threatModelID string, filter ContentFeedbackListFilter, offset, limit int) ([]models.ContentFeedback, error)

List returns feedback for a threat model matching the filter. SEM@7189df9e563ddcdb55d93d17322355f4ee6c57d0: list content feedback rows for a threat model matching a filter with pagination (reads DB)

type GormContentTokenRepository

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

GormContentTokenRepository persists ContentToken records via GORM. AccessToken and RefreshToken are AES-256-GCM encrypted at rest. SEM@4db312947ac9ae7ecc1e04865be072705812c8a8: GORM-backed content token repository with AES-256-GCM encryption at rest

func NewGormContentTokenRepository

func NewGormContentTokenRepository(db *gorm.DB, enc *ContentTokenEncryptor) *GormContentTokenRepository

NewGormContentTokenRepository creates a new GORM-backed content-token repository. SEM@4db312947ac9ae7ecc1e04865be072705812c8a8: build a GORM content token repository with the given DB and encryptor (pure)

func (*GormContentTokenRepository) Delete

Delete removes the token with the given ID. SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: delete a content token by ID (reads DB)

func (*GormContentTokenRepository) DeleteByUserAndProvider

func (r *GormContentTokenRepository) DeleteByUserAndProvider(ctx context.Context, userID, providerID string) (*ContentToken, error)

DeleteByUserAndProvider removes the token for the given user/provider pair and returns the deleted token. SEM@d0742bff5d3b93b3ab7b22df0377398a720a8d9c: delete and return the content token for a user/provider pair within a retryable transaction (reads DB)

func (*GormContentTokenRepository) GetByUserAndProvider

func (r *GormContentTokenRepository) GetByUserAndProvider(ctx context.Context, userID, providerID string) (*ContentToken, error)

GetByUserAndProvider retrieves a token by user ID and provider ID. SEM@4db312947ac9ae7ecc1e04865be072705812c8a8: fetch a content token by user and provider, decrypting credentials (reads DB)

func (*GormContentTokenRepository) ListByUser

func (r *GormContentTokenRepository) ListByUser(ctx context.Context, userID string) ([]ContentToken, error)

ListByUser returns all tokens for the given user ID. SEM@4db312947ac9ae7ecc1e04865be072705812c8a8: list all decrypted content tokens for a user (reads DB)

func (*GormContentTokenRepository) RefreshWithLock

func (r *GormContentTokenRepository) RefreshWithLock(ctx context.Context, id string, fn func(current *ContentToken) (*ContentToken, error)) (*ContentToken, error)

RefreshWithLock opens a transaction, locks the row with SELECT … FOR UPDATE, invokes fn with the decrypted token, and persists the token returned by fn. On SQLite (unit tests) the locking clause is a no-op; real serialization is verified against PostgreSQL in integration tests.

The transaction runs SERIALIZABLE with serialization-failure retries, so the closure can re-run. The FOR UPDATE lock is taken as the FIRST statement, so any serialization conflict (ORA-08177 / 40001) surfaces on the locking read, before fn is ever invoked — fn therefore runs at most once per successful call and a non-idempotent fn (e.g. a one-time OAuth refresh) is not double-fired on retry. Do not reorder fn ahead of the locking read. SEM@d0742bff5d3b93b3ab7b22df0377398a720a8d9c: lock a content token row, invoke a refresh callback, and persist the updated token atomically (reads DB)

func (*GormContentTokenRepository) UpdateStatus

func (r *GormContentTokenRepository) UpdateStatus(ctx context.Context, id, status, lastError string) error

UpdateStatus updates the status and last_error fields for the given token ID. SEM@4db312947ac9ae7ecc1e04865be072705812c8a8: update the status and last error fields of a content token (reads DB)

func (*GormContentTokenRepository) Upsert

Upsert creates or updates the token for the (UserID, ProviderID) pair using ON CONFLICT DO UPDATE so the operation is idempotent. SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: create or update a content token for the user/provider pair with encrypted credentials (reads DB)

type GormDiagramStore

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

GormDiagramStore handles diagram database operations using GORM SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: GORM-backed store for diagram persistence with read-write mutex (reads DB)

func NewGormDiagramStore

func NewGormDiagramStore(database *gorm.DB) *GormDiagramStore

NewGormDiagramStore creates a new diagram GORM store SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a GORM diagram store wrapping the provided database connection (pure)

func (*GormDiagramStore) CheckAndBumpVersion

func (s *GormDiagramStore) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the diagram row's version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the diagram row's optimistic-lock version (reads DB)

func (*GormDiagramStore) Count

func (s *GormDiagramStore) Count() int

Count returns the total number of diagrams using GORM SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: fetch the total count of diagrams (reads DB)

func (*GormDiagramStore) Create

func (s *GormDiagramStore) Create(item DfdDiagram, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)

Create adds a new diagram using GORM (maintains backward compatibility) SEM@178dbd0418cfb7e057d4297c7a88c5879cb64c7f: persist a new diagram with a nil threat model ID for backward compatibility (reads DB)

func (*GormDiagramStore) CreateWithThreatModel

func (s *GormDiagramStore) CreateWithThreatModel(item DfdDiagram, threatModelID string, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)

CreateWithThreatModel adds a new diagram with a specific threat model ID using GORM SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: persist a new diagram linked to a threat model, allocating an alias in a transaction (reads DB)

func (*GormDiagramStore) Delete

func (s *GormDiagramStore) Delete(id string) error

Delete removes a diagram using GORM. Uses a transaction to nullify diagram references on related threats before deleting, avoiding foreign key constraint violations from fk_threats_diagram. Delete soft-deletes a diagram. Use HardDelete for permanent removal (e.g., tombstone cleanup). Delete is on the legacy non-ctx path; SoftDelete now requires a context, so we pass context.Background() to preserve the existing Delete signature. Callers that have a request ctx should call SoftDelete directly. SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: soft-delete a diagram by delegating to SoftDelete (reads DB)

func (*GormDiagramStore) Get

func (s *GormDiagramStore) Get(id string) (DfdDiagram, error)

Get retrieves a diagram by ID using GORM SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: fetch a diagram by ID from the database (reads DB)

func (*GormDiagramStore) GetBatch

func (s *GormDiagramStore) GetBatch(ids []string) ([]DfdDiagram, error)

GetBatch retrieves multiple diagrams by ID in a single query. SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: fetch multiple diagrams by ID in a single batch query (reads DB)

func (*GormDiagramStore) GetIncludingDeleted

func (s *GormDiagramStore) GetIncludingDeleted(id string) (DfdDiagram, error)

GetIncludingDeleted retrieves a diagram by ID without filtering on deleted_at SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch a diagram by ID regardless of its deleted_at status (reads DB)

func (*GormDiagramStore) GetThreatModelID

func (s *GormDiagramStore) GetThreatModelID(diagramID string) (string, error)

GetThreatModelID returns the threat model ID for a given diagram SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: return the parent threat model ID for a given diagram ID (reads DB)

func (*GormDiagramStore) HardDelete

func (s *GormDiagramStore) HardDelete(id string) error

HardDelete permanently removes a diagram (original Delete behavior with FK cleanup) SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently delete a diagram with FK cleanup (mutates DB)

func (*GormDiagramStore) List

func (s *GormDiagramStore) List(offset, limit int, filter func(DfdDiagram) bool) []DfdDiagram

List returns all diagrams (not used in current implementation) SEM@8992eaca709573d0f6834edf30a3ef57370db6fa: return an empty diagram list (stub; diagrams are loaded via threat model) (pure)

func (*GormDiagramStore) Restore

func (s *GormDiagramStore) Restore(id string) error

Restore clears deleted_at on a diagram SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: restore a soft-deleted diagram by clearing its deleted_at timestamp (mutates DB)

func (*GormDiagramStore) SoftDelete

func (s *GormDiagramStore) SoftDelete(ctx context.Context, id string) error

SoftDelete sets deleted_at on a diagram and nullifies diagram_id/cell_id on related threats SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete a diagram and nullify diagram/cell references on related threats (mutates DB)

func (*GormDiagramStore) Update

func (s *GormDiagramStore) Update(ctx context.Context, id string, item DfdDiagram) error

Update modifies an existing diagram using GORM SEM@ebf201816c3638ec74fc8483a2a649af3ccddfc9: update diagram fields and metadata in a retryable transaction (reads DB)

type GormDocumentRepository

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

GormDocumentRepository implements DocumentStore using GORM SEM@295362baebc5fe956353b6eb0f33773e00895092: GORM-backed document store with optional Redis cache and cache invalidator (mutates shared state)

func NewGormDocumentRepository

func NewGormDocumentRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormDocumentRepository

NewGormDocumentRepository creates a new GORM-backed document store with optional caching SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a GormDocumentRepository wiring DB, cache, and cache invalidator (pure)

func (*GormDocumentRepository) BulkCreate

func (s *GormDocumentRepository) BulkCreate(ctx context.Context, documents []Document, threatModelID string) error

BulkCreate creates multiple documents in a single transaction SEM@87d6f75bc3aecf3edd6c4103567546955c1afadf: store multiple documents for a threat model in a single transaction, allocating aliases (reads DB)

func (*GormDocumentRepository) CheckAndBumpVersion

func (s *GormDocumentRepository) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the document row's version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the document row's optimistic-lock version (reads DB)

func (*GormDocumentRepository) ClearPickerMetadataForOwner

func (s *GormDocumentRepository) ClearPickerMetadataForOwner(
	ctx context.Context, ownerInternalUUID, providerID string,
) (int64, error)

ClearPickerMetadataForOwner nulls picker metadata and access-diagnostic fields on all documents owned by the given user (via threat-model owner) that were picker-registered under the given provider. See DocumentStore.ClearPickerMetadataForOwner. SEM@f8417a5cf7ccccd973f67a4a09364e8065dddf5f: null picker metadata and access diagnostics for all documents owned by a user under a given provider (reads DB)

func (*GormDocumentRepository) Count

func (s *GormDocumentRepository) Count(ctx context.Context, threatModelID string) (int, error)

Count returns the total number of documents for a threat model SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: count non-deleted documents for a threat model (reads DB)

func (*GormDocumentRepository) Create

func (s *GormDocumentRepository) Create(ctx context.Context, document *Document, threatModelID string) error

Create creates a new document SEM@87d6f75bc3aecf3edd6c4103567546955c1afadf: store a new document under a threat model, allocate its alias, and warm cache (reads DB)

func (*GormDocumentRepository) Delete

func (s *GormDocumentRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes a document by setting deleted_at SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: soft-delete a document by setting deleted_at (reads DB)

func (*GormDocumentRepository) Get

Get retrieves a document by ID SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a document by ID from cache or DB, loading metadata (reads DB)

func (*GormDocumentRepository) GetAccessReason

func (s *GormDocumentRepository) GetAccessReason(
	ctx context.Context, id string,
) (reasonCode string, reasonDetail string, updatedAt *time.Time, err error)

GetAccessReason returns the diagnostic fields for a document. See DocumentStore.GetAccessReason. SEM@df8dc0b3bc019d77933b5b20925f456071947e2e: fetch access reason code, detail, and status timestamp for a document (reads DB)

func (*GormDocumentRepository) GetIncludingDeleted

func (s *GormDocumentRepository) GetIncludingDeleted(ctx context.Context, id string) (*Document, error)

SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch a document by ID regardless of its deleted_at status, including metadata (reads DB)

func (*GormDocumentRepository) GetPickerDispatch

func (s *GormDocumentRepository) GetPickerDispatch(
	ctx context.Context, id string,
) (*PickerMetadata, string, error)

GetPickerDispatch returns picker metadata + owner UUID for poller dispatch. See DocumentStore.GetPickerDispatch. SEM@df8dc0b3bc019d77933b5b20925f456071947e2e: fetch picker metadata and threat model owner UUID for poller dispatch (reads DB)

func (*GormDocumentRepository) GetThreatModelID

func (s *GormDocumentRepository) GetThreatModelID(ctx context.Context, id string) (string, error)

GetThreatModelID returns the parent threat model ID for the given document. See DocumentRepository.GetThreatModelID. SEM@117032a3c5523a04e970f76a285e342169d5150c: fetch the parent threat model ID for a document (reads DB)

func (*GormDocumentRepository) HardDelete

func (s *GormDocumentRepository) HardDelete(ctx context.Context, id string) error

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently delete a document (mutates DB)

func (*GormDocumentRepository) InvalidateCache

func (s *GormDocumentRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes document-related cache entries SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: evict a document's cache entry by ID (mutates shared state)

func (*GormDocumentRepository) List

func (s *GormDocumentRepository) List(ctx context.Context, threatModelID string, offset, limit int) ([]Document, error)

List retrieves documents for a threat model with pagination SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: list paginated documents for a threat model from cache or DB with metadata (reads DB)

func (*GormDocumentRepository) ListByAccessStatus

func (s *GormDocumentRepository) ListByAccessStatus(ctx context.Context, status string, limit int) ([]Document, error)

ListByAccessStatus returns documents matching the given access status across all threat models. SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: list documents across all threat models matching a given access status (reads DB)

func (*GormDocumentRepository) Patch

func (s *GormDocumentRepository) Patch(ctx context.Context, id string, operations []PatchOperation) (*Document, error)

Patch applies JSON patch operations to a document SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: apply JSON patch operations to a document and persist the result (reads DB)

func (*GormDocumentRepository) Restore

func (s *GormDocumentRepository) Restore(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: restore a soft-deleted document by clearing its deleted_at timestamp (mutates DB)

func (*GormDocumentRepository) SetPickerMetadata

func (s *GormDocumentRepository) SetPickerMetadata(
	ctx context.Context, id string, providerID, fileID, mimeType string,
) error

SetPickerMetadata persists picker_provider_id, picker_file_id, and picker_mime_type on the document. Resets access_status to 'unknown' so the poller will validate.

Non-atomic with Create — see DocumentStore.SetPickerMetadata for the failure-handling contract.

See DocumentStore.SetPickerMetadata. SEM@f8417a5cf7ccccd973f67a4a09364e8065dddf5f: persist picker provider/file/mime fields on a document and reset access status to unknown (reads DB)

func (*GormDocumentRepository) SoftDelete

func (s *GormDocumentRepository) SoftDelete(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete a document and invalidate its cache entry (mutates DB)

func (*GormDocumentRepository) Update

func (s *GormDocumentRepository) Update(ctx context.Context, document *Document, threatModelID string) error

Update updates an existing document SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: update a document's fields and metadata in DB and cache (reads DB)

func (*GormDocumentRepository) UpdateAccessStatus

func (s *GormDocumentRepository) UpdateAccessStatus(ctx context.Context, id string, accessStatus string, contentSource string) error

UpdateAccessStatus sets the access tracking fields on a document. SEM@f8417a5cf7ccccd973f67a4a09364e8065dddf5f: update access_status and content_source on a document and invalidate its cache entry (reads DB)

func (*GormDocumentRepository) UpdateAccessStatusWithDiagnostics

func (s *GormDocumentRepository) UpdateAccessStatusWithDiagnostics(
	ctx context.Context,
	id string,
	accessStatus string,
	contentSource string,
	reasonCode string,
	reasonDetail string,
) error

UpdateAccessStatusWithDiagnostics sets access tracking fields on a document. See DocumentStore.UpdateAccessStatusWithDiagnostics.

Uses Table("documents") (not Model(&models.Document{})) to avoid triggering the Document.BeforeSave hook, which validates Name/URI on the empty struct and would produce false "cannot be empty" errors for map-based updates — same pattern as UpdateAccessStatus. SEM@f8417a5cf7ccccd973f67a4a09364e8065dddf5f: update access status and diagnostic reason fields on a document and invalidate its cache entry (reads DB)

func (*GormDocumentRepository) WarmCache

func (s *GormDocumentRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads documents for a threat model into cache SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: preload the first page of documents for a threat model into cache (reads DB)

type GormGroupMemberRepository

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

GormGroupMemberRepository implements GroupMemberRepository using GORM SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: GORM-backed repository for group membership operations (reads DB)

func NewGormGroupMemberRepository

func NewGormGroupMemberRepository(db *gorm.DB) *GormGroupMemberRepository

NewGormGroupMemberRepository creates a new GORM-backed group member repository SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: build a GormGroupMemberRepository from a GORM database connection (pure)

func (*GormGroupMemberRepository) AddGroupMember

func (r *GormGroupMemberRepository) AddGroupMember(ctx context.Context, groupInternalUUID, memberGroupInternalUUID uuid.UUID, addedByInternalUUID *uuid.UUID, notes *string) (*GroupMember, error)

AddGroupMember adds a group as a member of another group (one level of nesting) SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: store a group as a nested member of another group and return the created membership (reads DB)

func (*GormGroupMemberRepository) AddMember

func (r *GormGroupMemberRepository) AddMember(ctx context.Context, groupInternalUUID, userInternalUUID uuid.UUID, addedByInternalUUID *uuid.UUID, notes *string) (*GroupMember, error)

AddMember adds a user to a group SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: store a user as a direct member of a group and return the created membership (reads DB)

func (*GormGroupMemberRepository) CountMembers

func (r *GormGroupMemberRepository) CountMembers(ctx context.Context, groupInternalUUID uuid.UUID) (int, error)

CountMembers returns the total number of members in a group SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: count total group members for a group (reads DB)

func (*GormGroupMemberRepository) GetGroupsForUser

func (r *GormGroupMemberRepository) GetGroupsForUser(ctx context.Context, userInternalUUID uuid.UUID) ([]Group, error)

GetGroupsForUser returns all TMI-managed groups that a user has direct membership in. This queries the group_members table for user-type memberships and joins the groups table to return group metadata. The "everyone" pseudo-group is excluded since it has no membership records (all authenticated users are implicitly members). SEM@df8dc0b3bc019d77933b5b20925f456071947e2e: list all TMI-managed groups a user has direct membership in (reads DB)

func (*GormGroupMemberRepository) HasAnyMembers

func (r *GormGroupMemberRepository) HasAnyMembers(ctx context.Context, groupInternalUUID uuid.UUID) (bool, error)

HasAnyMembers checks if a group has any members (user or group) SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: check whether a group has any user or group members (reads DB)

func (*GormGroupMemberRepository) IsEffectiveMember

func (r *GormGroupMemberRepository) IsEffectiveMember(ctx context.Context, groupInternalUUID uuid.UUID, userInternalUUID uuid.UUID, userGroupUUIDs []uuid.UUID) (bool, error)

IsEffectiveMember checks if a user is an effective member of a group, either through direct user membership or because one of the user's IdP groups is a group member (one level of nesting). SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: check whether a user is a direct or IdP-group-transitive member of a group (reads DB)

func (*GormGroupMemberRepository) IsMember

func (r *GormGroupMemberRepository) IsMember(ctx context.Context, groupInternalUUID, userInternalUUID uuid.UUID) (bool, error)

IsMember checks if a user is a direct member of a group SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: check whether a user is a direct member of a group (reads DB)

func (*GormGroupMemberRepository) ListMembers

ListMembers returns all members of a group with pagination SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: list paginated group members with user and group metadata via joined query (reads DB)

func (*GormGroupMemberRepository) RemoveGroupMember

func (r *GormGroupMemberRepository) RemoveGroupMember(ctx context.Context, groupInternalUUID, memberGroupInternalUUID uuid.UUID) error

RemoveGroupMember removes a group from membership in another group SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: delete a group's nested membership from another group (mutates shared state)

func (*GormGroupMemberRepository) RemoveMember

func (r *GormGroupMemberRepository) RemoveMember(ctx context.Context, groupInternalUUID, userInternalUUID uuid.UUID) error

RemoveMember removes a user from a group SEM@f9ee21801aeaafee608b61a6e35aa8c146928a03: delete a user's direct membership from a group (mutates shared state)

type GormGroupRepository

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

GormGroupRepository implements GroupRepository using GORM for cross-database support SEM@c82b74e37eeb6c562c203628ab2aacb25bccdb04: GORM-backed group repository providing cross-database CRUD for identity provider groups (reads DB)

func NewGormGroupRepository

func NewGormGroupRepository(db *gorm.DB) *GormGroupRepository

NewGormGroupRepository creates a new GORM-backed group repository SEM@c82b74e37eeb6c562c203628ab2aacb25bccdb04: build a GormGroupRepository wiring a GORM DB connection (pure)

func (*GormGroupRepository) Count

func (r *GormGroupRepository) Count(ctx context.Context, filter GroupFilter) (int, error)

Count returns total count of groups matching the filter SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: count groups matching provider, name, and authorization-usage filters (reads DB)

func (*GormGroupRepository) Create

func (r *GormGroupRepository) Create(ctx context.Context, group Group) error

Create creates a new group (primarily for provider-independent groups) SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: store a new group with default usage tracking fields (reads DB)

func (*GormGroupRepository) EnrichGroups

func (r *GormGroupRepository) EnrichGroups(ctx context.Context, groups []Group) ([]Group, error)

EnrichGroups adds related data to groups (usage in authorizations/admin grants) SEM@402df88179fdf587dd628ea930a569f4f72e7ac8: augment groups with authorization and admin-grant membership flags (reads DB)

func (*GormGroupRepository) Get

func (r *GormGroupRepository) Get(ctx context.Context, internalUUID uuid.UUID) (*Group, error)

Get retrieves a group by internal UUID SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: fetch a group by its internal UUID (reads DB)

func (*GormGroupRepository) GetByProviderAndName

func (r *GormGroupRepository) GetByProviderAndName(ctx context.Context, provider string, groupName string) (*Group, error)

GetByProviderAndName retrieves a group by provider and group_name SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: fetch a group by identity provider and group name (reads DB)

func (*GormGroupRepository) GetGroupsForProvider

func (r *GormGroupRepository) GetGroupsForProvider(ctx context.Context, provider string) ([]Group, error)

GetGroupsForProvider returns all groups for a specific provider (for UI autocomplete) SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: list up to 500 groups for a provider sorted by last used, for autocomplete (reads DB)

func (*GormGroupRepository) List

func (r *GormGroupRepository) List(ctx context.Context, filter GroupFilter) ([]Group, error)

List returns groups with optional filtering and pagination SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: list groups with optional provider, name, authorization-usage filters, sorting, and pagination (reads DB)

func (*GormGroupRepository) Update

func (r *GormGroupRepository) Update(ctx context.Context, group Group) error

Update updates group metadata (name, description) SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: update group display name and description, refreshing last_used timestamp (reads DB)

func (*GormGroupRepository) UpsertGroup

func (r *GormGroupRepository) UpsertGroup(ctx context.Context, group Group) error

UpsertGroup creates or updates a group (used during JWT group sync) This is a concrete method not on the GroupRepository interface — kept for future JWT group sync use. SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: create or update a group by provider+name conflict key, refreshing usage fields (reads DB)

type GormMetadataRepository

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

GormMetadataRepository implements MetadataRepository using GORM SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: GORM-backed repository for entity metadata key-value pairs with cache and invalidation support

func NewGormMetadataRepository

func NewGormMetadataRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormMetadataRepository

NewGormMetadataRepository creates a new GORM-backed metadata repository SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: build a GormMetadataRepository with the given DB, cache, and invalidator (pure)

func (*GormMetadataRepository) BulkCreate

func (r *GormMetadataRepository) BulkCreate(ctx context.Context, entityType, entityID string, metadata []Metadata) error

BulkCreate creates multiple metadata entries in a single transaction SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: store multiple metadata entries in one transaction, rejecting any duplicate keys (mutates shared state)

func (*GormMetadataRepository) BulkDelete

func (r *GormMetadataRepository) BulkDelete(ctx context.Context, entityType, entityID string, keys []string) error

BulkDelete deletes multiple metadata entries by key in a single transaction SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: delete multiple metadata entries by key in one transaction and invalidate caches (mutates shared state)

func (*GormMetadataRepository) BulkReplace

func (r *GormMetadataRepository) BulkReplace(ctx context.Context, entityType, entityID string, metadata []Metadata) error

BulkReplace replaces all metadata for an entity atomically. All existing metadata is deleted, then the provided entries are inserted. An empty metadata slice clears all metadata for the entity. This implements PUT (full replace) semantics. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: atomically replace all metadata for an entity with a new set using PUT semantics (mutates shared state)

func (*GormMetadataRepository) BulkUpdate

func (r *GormMetadataRepository) BulkUpdate(ctx context.Context, entityType, entityID string, metadata []Metadata) error

BulkUpdate upserts multiple metadata entries in a single transaction. Keys present in the request are created or updated; keys not present are left untouched. This implements PATCH (merge/upsert) semantics. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: upsert multiple metadata entries in one transaction using PATCH merge semantics (mutates shared state)

func (*GormMetadataRepository) Create

func (r *GormMetadataRepository) Create(ctx context.Context, entityType, entityID string, metadata *Metadata) error

Create creates a new metadata entry SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: store a single metadata entry for an entity, rejecting duplicate keys (mutates shared state)

func (*GormMetadataRepository) Delete

func (r *GormMetadataRepository) Delete(ctx context.Context, entityType, entityID, key string) error

Delete removes a metadata entry SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: delete a metadata entry by key and invalidate related caches (mutates shared state)

func (*GormMetadataRepository) Get

func (r *GormMetadataRepository) Get(ctx context.Context, entityType, entityID, key string) (*Metadata, error)

Get retrieves a specific metadata entry by key SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: fetch a metadata entry by key, using the cache when available (reads DB)

func (*GormMetadataRepository) GetByKey

func (r *GormMetadataRepository) GetByKey(ctx context.Context, key string) ([]Metadata, error)

GetByKey retrieves all metadata entries with a specific key across all entities SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: fetch all metadata entries with a given key across all entities (reads DB)

func (*GormMetadataRepository) InvalidateCache

func (r *GormMetadataRepository) InvalidateCache(ctx context.Context, entityType, entityID string) error

InvalidateCache removes metadata-related cache entries SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: remove cached metadata for an entity from the cache store (mutates shared state)

func (*GormMetadataRepository) List

func (r *GormMetadataRepository) List(ctx context.Context, entityType, entityID string) ([]Metadata, error)

List retrieves all metadata for an entity SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: list all metadata entries for an entity, using the cache when available (reads DB)

func (*GormMetadataRepository) ListKeys

func (r *GormMetadataRepository) ListKeys(ctx context.Context, entityType, entityID string) ([]string, error)

ListKeys retrieves all metadata keys for an entity SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: list all distinct metadata keys for an entity (reads DB)

func (*GormMetadataRepository) Post

func (r *GormMetadataRepository) Post(ctx context.Context, entityType, entityID string, metadata *Metadata) error

Post creates a new metadata entry using POST semantics SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: create a metadata entry using POST semantics, delegating to Create (mutates shared state)

func (*GormMetadataRepository) Update

func (r *GormMetadataRepository) Update(ctx context.Context, entityType, entityID string, metadata *Metadata) error

Update updates an existing metadata entry SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: update the value of an existing metadata entry by key (mutates shared state)

func (*GormMetadataRepository) WarmCache

func (r *GormMetadataRepository) WarmCache(ctx context.Context, entityType, entityID string) error

WarmCache preloads metadata for an entity into cache SEM@4b5601a9cbb59c0d9d34db8808624707ebd7501e: preload an entity's metadata into the cache by listing it (reads DB)

type GormNoteRepository

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

GormNoteRepository implements NoteStore using GORM SEM@295362baebc5fe956353b6eb0f33773e00895092: GORM-backed note repository with integrated cache and invalidation support

func NewGormNoteRepository

func NewGormNoteRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormNoteRepository

NewGormNoteRepository creates a new GORM-backed note store with optional caching SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a GormNoteRepository wired to the given DB, cache service, and invalidator

func (*GormNoteRepository) Count

func (s *GormNoteRepository) Count(ctx context.Context, threatModelID string) (int, error)

Count returns the total number of notes for a threat model SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: count non-deleted notes belonging to a threat model (reads DB)

func (*GormNoteRepository) Create

func (s *GormNoteRepository) Create(ctx context.Context, note *Note, threatModelID string) error

Create creates a new note SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: store a new note under a threat model and populate its cache entry (reads DB)

func (*GormNoteRepository) Delete

func (s *GormNoteRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes a note by setting deleted_at SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: soft-delete a note by delegating to SoftDelete (reads DB)

func (*GormNoteRepository) Get

func (s *GormNoteRepository) Get(ctx context.Context, id string) (*Note, error)

Get retrieves a note by ID SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a note by ID from cache or DB, including its metadata (reads DB)

func (*GormNoteRepository) GetIncludingDeleted

func (s *GormNoteRepository) GetIncludingDeleted(ctx context.Context, id string) (*Note, error)

SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch a note by ID regardless of its deleted_at status, including metadata (reads DB)

func (*GormNoteRepository) HardDelete

func (s *GormNoteRepository) HardDelete(ctx context.Context, id string) error

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently delete a note (mutates DB)

func (*GormNoteRepository) InvalidateCache

func (s *GormNoteRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes note-related cache entries SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: evict a note's cache entry by entity ID (mutates shared state)

func (*GormNoteRepository) List

func (s *GormNoteRepository) List(ctx context.Context, threatModelID string, offset, limit int) ([]Note, error)

List retrieves notes for a threat model with pagination SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: list paginated notes for a threat model from cache or DB (reads DB)

func (*GormNoteRepository) Patch

func (s *GormNoteRepository) Patch(ctx context.Context, id string, operations []PatchOperation) (*Note, error)

Patch applies JSON patch operations to a note SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: apply JSON patch operations to a note and persist the result (reads DB)

func (*GormNoteRepository) Restore

func (s *GormNoteRepository) Restore(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: restore a soft-deleted note by clearing its deleted_at timestamp (mutates DB)

func (*GormNoteRepository) SoftDelete

func (s *GormNoteRepository) SoftDelete(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete a note and invalidate its cache entry (mutates DB)

func (*GormNoteRepository) Update

func (s *GormNoteRepository) Update(ctx context.Context, note *Note, threatModelID string) error

Update updates an existing note SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: update a note's fields in the DB and refresh its cache entry (reads DB)

func (*GormNoteRepository) WarmCache

func (s *GormNoteRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads notes for a threat model into cache SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: preload the first page of a threat model's notes into cache (mutates shared state)

type GormProjectNoteStore

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

GormProjectNoteStore implements ProjectNoteStoreInterface using GORM SEM@f860641a78901543e88ebd0a603a69bd4db1d696: GORM-backed implementation of ProjectNoteStoreInterface (reads DB)

func NewGormProjectNoteStore

func NewGormProjectNoteStore(db *gorm.DB) *GormProjectNoteStore

NewGormProjectNoteStore creates a new GORM-backed project note store SEM@f860641a78901543e88ebd0a603a69bd4db1d696: build a GORM-backed project note store from a database connection (pure)

func (*GormProjectNoteStore) Count

func (s *GormProjectNoteStore) Count(ctx context.Context, projectID string, includeNonSharable bool) (int, error)

Count returns the number of project notes for a project SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: count project notes for a project, optionally filtering by sharability (reads DB)

func (*GormProjectNoteStore) Create

func (s *GormProjectNoteStore) Create(ctx context.Context, note *ProjectNote, projectID string) (*ProjectNote, error)

Create creates a new project note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: store a new project note under a verified parent project (reads DB)

func (*GormProjectNoteStore) Delete

func (s *GormProjectNoteStore) Delete(ctx context.Context, id string) error

Delete deletes a project note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: delete a project note by ID, returning not-found if absent (reads DB)

func (*GormProjectNoteStore) Get

Get retrieves a project note by ID SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch a single project note by ID (reads DB)

func (*GormProjectNoteStore) List

func (s *GormProjectNoteStore) List(ctx context.Context, projectID string, offset, limit int, includeNonSharable bool) ([]ProjectNoteListItem, int, error)

List returns a paginated list of project notes for a project SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch a paginated list of project notes for a project, optionally filtering by sharability (reads DB)

func (*GormProjectNoteStore) Patch

func (s *GormProjectNoteStore) Patch(ctx context.Context, id string, operations []PatchOperation) (*ProjectNote, error)

Patch applies JSON Patch operations to a project note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: apply JSON Patch operations to a project note and persist the result (reads DB)

func (*GormProjectNoteStore) Update

func (s *GormProjectNoteStore) Update(ctx context.Context, id string, note *ProjectNote, projectID string) (*ProjectNote, error)

Update replaces a project note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: replace all fields of a project note within its parent project (reads DB)

type GormProjectStore

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

GormProjectStore implements ProjectStoreInterface using GORM SEM@8c7929da791c778ff88713684c47aa2a10911bba: GORM-backed implementation of the project store interface

func NewGormProjectStore

func NewGormProjectStore(db *gorm.DB) *GormProjectStore

NewGormProjectStore creates a new GORM-backed project store SEM@8c7929da791c778ff88713684c47aa2a10911bba: build a new GORM-backed project store with the given DB handle (pure)

func (*GormProjectStore) CheckAndBumpVersion

func (s *GormProjectStore) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the project row's version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the project row's optimistic-lock version (reads DB)

func (*GormProjectStore) Create

func (s *GormProjectStore) Create(ctx context.Context, project *Project, userInternalUUID string) (*Project, error)

Create creates a new project SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: store a new project with responsible parties and relationships in a retryable transaction (reads DB)

func (*GormProjectStore) Delete

func (s *GormProjectStore) Delete(ctx context.Context, id string) error

Delete removes a project by ID SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: delete a project and its dependent records, blocking if threat models exist (reads DB)

func (*GormProjectStore) Get

func (s *GormProjectStore) Get(ctx context.Context, id string) (*Project, error)

Get retrieves a project by ID SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch a project by ID with its team, responsible parties, relationships, and metadata (reads DB)

func (*GormProjectStore) GetTeamID

func (s *GormProjectStore) GetTeamID(ctx context.Context, projectID string) (string, error)

GetTeamID returns the team_id for a given project SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch the team ID for a given project (reads DB)

func (*GormProjectStore) HasThreatModels

func (s *GormProjectStore) HasThreatModels(ctx context.Context, projectID string) (bool, error)

HasThreatModels checks if a project has any associated threat models SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: check whether a project has any associated threat models (reads DB)

func (*GormProjectStore) List

func (s *GormProjectStore) List(ctx context.Context, limit, offset int, filters *ProjectFilters, userInternalUUID string, isAdmin bool) ([]ProjectListItem, int, error)

List retrieves projects with pagination and optional filters SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: list projects with pagination, access control, and optional filters (reads DB)

func (*GormProjectStore) Update

func (s *GormProjectStore) Update(ctx context.Context, id string, project *Project, userInternalUUID string) (*Project, error)

Update updates an existing project SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: replace a project's fields, responsible parties, and relationships in a retryable transaction (reads DB)

type GormRepositoryRepository

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

GormRepositoryRepository implements RepositoryStore using GORM SEM@295362baebc5fe956353b6eb0f33773e00895092: GORM-backed repository store with optional Redis cache and cache invalidation (mutates shared state)

func NewGormRepositoryRepository

func NewGormRepositoryRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormRepositoryRepository

NewGormRepositoryRepository creates a new GORM-backed repository store with optional caching SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a GormRepositoryRepository with optional cache and invalidator (pure)

func (*GormRepositoryRepository) BulkCreate

func (s *GormRepositoryRepository) BulkCreate(ctx context.Context, repositories []Repository, threatModelID string) error

BulkCreate creates multiple repositories in a single transaction SEM@87d6f75bc3aecf3edd6c4103567546955c1afadf: insert multiple repositories under a threat model in a single retryable transaction (reads DB)

func (*GormRepositoryRepository) Count

func (s *GormRepositoryRepository) Count(ctx context.Context, threatModelID string) (int, error)

Count returns the total number of repositories for a threat model SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: count repositories belonging to a threat model (reads DB)

func (*GormRepositoryRepository) Create

func (s *GormRepositoryRepository) Create(ctx context.Context, repository *Repository, threatModelID string) error

Create creates a new repository SEM@87d6f75bc3aecf3edd6c4103567546955c1afadf: store a new repository under a threat model, allocating an alias and updating the cache (reads DB)

func (*GormRepositoryRepository) Delete

Delete soft-deletes a repository by setting deleted_at SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: soft-delete a repository by setting its deleted_at timestamp (reads DB)

func (*GormRepositoryRepository) Get

Get retrieves a repository by ID SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a repository by ID from cache or DB, including its metadata (reads DB)

func (*GormRepositoryRepository) GetIncludingDeleted

func (s *GormRepositoryRepository) GetIncludingDeleted(ctx context.Context, id string) (*Repository, error)

SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch a repository by ID regardless of its deleted_at status, including metadata (reads DB)

func (*GormRepositoryRepository) HardDelete

func (s *GormRepositoryRepository) HardDelete(ctx context.Context, id string) error

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently delete a repository (mutates DB)

func (*GormRepositoryRepository) InvalidateCache

func (s *GormRepositoryRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes repository-related cache entries SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: delete cache entries for a repository by ID (mutates shared state)

func (*GormRepositoryRepository) List

func (s *GormRepositoryRepository) List(ctx context.Context, threatModelID string, offset, limit int) ([]Repository, error)

List retrieves repositories for a threat model with pagination SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: list repositories for a threat model with pagination from cache or DB (reads DB)

func (*GormRepositoryRepository) Patch

func (s *GormRepositoryRepository) Patch(ctx context.Context, id string, operations []PatchOperation) (*Repository, error)

Patch applies JSON patch operations to a repository SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: apply JSON Patch operations to a repository and persist the result (reads DB)

func (*GormRepositoryRepository) Restore

func (s *GormRepositoryRepository) Restore(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: restore a soft-deleted repository by clearing its deleted_at timestamp (mutates DB)

func (*GormRepositoryRepository) SoftDelete

func (s *GormRepositoryRepository) SoftDelete(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete a repository and invalidate its cache entry (mutates DB)

func (*GormRepositoryRepository) Update

func (s *GormRepositoryRepository) Update(ctx context.Context, repository *Repository, threatModelID string) error

Update updates an existing repository SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: update an existing repository's fields and metadata, refreshing the cache (reads DB)

func (*GormRepositoryRepository) WarmCache

func (s *GormRepositoryRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads repositories for a threat model into cache SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: preload the first page of repositories for a threat model into cache (mutates shared state)

type GormSurveyAnswerStore

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

GormSurveyAnswerStore implements SurveyAnswerStore backed by a GORM database. SEM@851a41a40d0b86e1ef600270d09c44cd95ac25d7: GORM-backed implementation of SurveyAnswerStore (reads/writes DB)

func NewGormSurveyAnswerStore

func NewGormSurveyAnswerStore(db *gorm.DB) *GormSurveyAnswerStore

NewGormSurveyAnswerStore creates a new GORM-backed SurveyAnswerStore. SEM@851a41a40d0b86e1ef600270d09c44cd95ac25d7: build a GORM-backed SurveyAnswerStore from a database connection (pure)

func (*GormSurveyAnswerStore) DeleteByResponseID

func (s *GormSurveyAnswerStore) DeleteByResponseID(ctx context.Context, responseID string) error

DeleteByResponseID implements SurveyAnswerStore. SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: delete all stored answers for a survey response (writes DB)

func (*GormSurveyAnswerStore) ExtractAndSave

func (s *GormSurveyAnswerStore) ExtractAndSave(ctx context.Context, responseID string, surveyJSON map[string]any, answers map[string]any, responseStatus string) error

ExtractAndSave implements SurveyAnswerStore. SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: atomically replace all stored answers for a survey response by extracting questions and pairing answers (writes DB)

func (*GormSurveyAnswerStore) GetAnswers

func (s *GormSurveyAnswerStore) GetAnswers(ctx context.Context, responseID string) ([]SurveyAnswerRow, error)

GetAnswers implements SurveyAnswerStore. SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: fetch all answer rows for a survey response in insertion order (reads DB)

func (*GormSurveyAnswerStore) GetFieldMappings

func (s *GormSurveyAnswerStore) GetFieldMappings(ctx context.Context, responseID string) (map[string]SurveyAnswerRow, error)

GetFieldMappings implements SurveyAnswerStore. SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: fetch a map of threat-model field name to answer row for a survey response (reads DB)

type GormSurveyResponseStore

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

GormSurveyResponseStore implements SurveyResponseStore using GORM SEM@5998227fb120ee0575a994ea2c0ecb24f0e67109: GORM-backed implementation of SurveyResponseStore (reads DB)

func NewGormSurveyResponseStore

func NewGormSurveyResponseStore(db *gorm.DB) *GormSurveyResponseStore

NewGormSurveyResponseStore creates a new GORM-backed survey response store SEM@5998227fb120ee0575a994ea2c0ecb24f0e67109: build a GormSurveyResponseStore wrapping the given database connection (pure)

func (*GormSurveyResponseStore) CheckAndBumpVersion

func (s *GormSurveyResponseStore) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the survey response row's version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the survey response row's optimistic-lock version (reads DB)

func (*GormSurveyResponseStore) Create

func (s *GormSurveyResponseStore) Create(ctx context.Context, response *SurveyResponse, userInternalUUID string) error

Create creates a new survey response SEM@ebf201816c3638ec74fc8483a2a649af3ccddfc9: store a new survey response with owner ACL, reviewer group, and automation group in a transaction (reads DB)

func (*GormSurveyResponseStore) Delete

Delete removes a survey response by ID SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: delete a survey response and all dependent rows in a single transaction (mutates DB)

func (*GormSurveyResponseStore) Get

Get retrieves a survey response by ID SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: fetch a survey response by ID with authorization and metadata (reads DB)

func (*GormSurveyResponseStore) GetAuthorization

func (s *GormSurveyResponseStore) GetAuthorization(ctx context.Context, id uuid.UUID) ([]Authorization, error)

GetAuthorization retrieves authorization entries for a response SEM@5998227fb120ee0575a994ea2c0ecb24f0e67109: fetch all authorization entries for a survey response (reads DB)

func (*GormSurveyResponseStore) HasAccess

func (s *GormSurveyResponseStore) HasAccess(ctx context.Context, id uuid.UUID, userInternalUUID string, requiredRole AuthorizationRole) (bool, error)

HasAccess checks if a user has the required access to a response SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: check whether a user holds the required role on a survey response via direct or group membership (reads DB)

func (*GormSurveyResponseStore) List

List retrieves survey responses with pagination and optional filters SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: list paginated survey responses with optional status/survey/owner filters (reads DB)

func (*GormSurveyResponseStore) ListByOwner

func (s *GormSurveyResponseStore) ListByOwner(ctx context.Context, ownerInternalUUID string, limit, offset int, status *string) ([]SurveyResponseListItem, int, error)

ListByOwner retrieves survey responses for a specific owner SEM@0bd9c0e0e0c0649294d164b9dc945b801cfd507c: list paginated survey responses for a specific owner with optional status filter (reads DB)

func (*GormSurveyResponseStore) SetCreatedThreatModel

func (s *GormSurveyResponseStore) SetCreatedThreatModel(ctx context.Context, id uuid.UUID, threatModelID string) error

SetCreatedThreatModel atomically sets created_threat_model_id and transitions status to review_created with an optimistic concurrency guard.

Idempotent on retry: if the optimistic-concurrency UPDATE matches zero rows, re-read the row and treat it as success when the row already shows (status=review_created, created_threat_model_id=requested). This handles the commit-ack-loss case where a transient ADB error fires after the server-side commit but before the client receives the ack — the original update is already persisted; the retry's WHERE predicate fails because status has moved past ready_for_review. Without this check, the retry surfaced a misleading "not in ready_for_review status" error even though the operation succeeded. SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: atomically link a threat model and transition survey response to review_created; idempotent on retry (mutates DB)

func (*GormSurveyResponseStore) Update

func (s *GormSurveyResponseStore) Update(ctx context.Context, response *SurveyResponse) error

Update updates an existing survey response SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: store mutable fields of an existing survey response; preserves immutable fields (mutates DB)

func (*GormSurveyResponseStore) UpdateAuthorization

func (s *GormSurveyResponseStore) UpdateAuthorization(ctx context.Context, id uuid.UUID, authorization []Authorization) error

UpdateAuthorization updates authorization entries for a response SEM@fcd7743e746718c31b33ef56fb3ba2f8ccf669c7: replace all survey response authorization entries within a locked transaction (reads DB)

func (*GormSurveyResponseStore) UpdateStatus

func (s *GormSurveyResponseStore) UpdateStatus(ctx context.Context, id uuid.UUID, newStatus string, reviewerInternalUUID *string, revisionNotes *string) error

UpdateStatus transitions a response to a new status with validation SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: validate and apply a status transition to a survey response, recording reviewer and notes (mutates DB)

type GormSurveyStore

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

GormSurveyStore implements SurveyStore using GORM SEM@bd26290d65c881980433c4a4b599847bb68193d1: GORM-backed implementation of SurveyStore (reads/writes DB)

func NewGormSurveyStore

func NewGormSurveyStore(db *gorm.DB) *GormSurveyStore

NewGormSurveyStore creates a new GORM-backed survey store SEM@bd26290d65c881980433c4a4b599847bb68193d1: build a GORM-backed SurveyStore from a database connection (pure)

func (*GormSurveyStore) Create

func (s *GormSurveyStore) Create(ctx context.Context, survey *Survey, userInternalUUID string) error

Create creates a new survey SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: store a new survey template and return server-assigned timestamps (writes DB)

func (*GormSurveyStore) Delete

func (s *GormSurveyStore) Delete(ctx context.Context, id uuid.UUID) error

Delete removes a survey by ID SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: delete a survey template by ID (writes DB)

func (*GormSurveyStore) ForceDelete

func (s *GormSurveyStore) ForceDelete(ctx context.Context, id uuid.UUID) error

ForceDelete removes a survey template together with all of its responses and each response's dependent rows (triage notes, access grants, metadata, answers), in a single transaction. This backs the admin force-delete path so a survey that still has responses can be removed (the default Delete refuses via 409). Deletion is child-first: every dependent row is removed before the responses, and the responses before the survey template itself.

func (*GormSurveyStore) Get

func (s *GormSurveyStore) Get(ctx context.Context, id uuid.UUID) (*Survey, error)

Get retrieves a survey by ID SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: fetch a survey template by ID including its metadata (reads DB)

func (*GormSurveyStore) HasResponses

func (s *GormSurveyStore) HasResponses(ctx context.Context, id uuid.UUID) (bool, error)

HasResponses checks if a survey has any associated responses SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: check whether a survey template has any associated responses (reads DB)

func (*GormSurveyStore) List

func (s *GormSurveyStore) List(ctx context.Context, limit, offset int, status *string) ([]SurveyListItem, int, error)

List retrieves surveys with pagination and optional status filter SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: list survey templates with optional status filter and pagination (reads DB)

func (*GormSurveyStore) ListActive

func (s *GormSurveyStore) ListActive(ctx context.Context, limit, offset int) ([]SurveyListItem, int, error)

ListActive retrieves only active surveys (for intake endpoints) SEM@bd26290d65c881980433c4a4b599847bb68193d1: list only active survey templates with pagination (reads DB)

func (*GormSurveyStore) Update

func (s *GormSurveyStore) Update(ctx context.Context, survey *Survey) error

Update updates an existing survey SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: update an existing survey template's fields and metadata (writes DB)

type GormTeamNoteStore

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

GormTeamNoteStore implements TeamNoteStoreInterface using GORM SEM@f860641a78901543e88ebd0a603a69bd4db1d696: GORM-backed implementation of TeamNoteStoreInterface (pure)

func NewGormTeamNoteStore

func NewGormTeamNoteStore(db *gorm.DB) *GormTeamNoteStore

NewGormTeamNoteStore creates a new GORM-backed team note store SEM@f860641a78901543e88ebd0a603a69bd4db1d696: build a GormTeamNoteStore wrapping the provided DB connection (pure)

func (*GormTeamNoteStore) Count

func (s *GormTeamNoteStore) Count(ctx context.Context, teamID string, includeNonSharable bool) (int, error)

Count returns the number of team notes for a team SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: count team notes for a team with optional non-sharable inclusion (reads DB)

func (*GormTeamNoteStore) Create

func (s *GormTeamNoteStore) Create(ctx context.Context, note *TeamNote, teamID string) (*TeamNote, error)

Create creates a new team note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: persist a new team note under a verified parent team (reads DB)

func (*GormTeamNoteStore) Delete

func (s *GormTeamNoteStore) Delete(ctx context.Context, id string) error

Delete deletes a team note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: delete a team note by ID (reads DB)

func (*GormTeamNoteStore) Get

func (s *GormTeamNoteStore) Get(ctx context.Context, id string) (*TeamNote, error)

Get retrieves a team note by ID SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch a team note by ID (reads DB)

func (*GormTeamNoteStore) List

func (s *GormTeamNoteStore) List(ctx context.Context, teamID string, offset, limit int, includeNonSharable bool) ([]TeamNoteListItem, int, error)

List returns a paginated list of team notes for a team SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: list paginated team notes for a team with optional non-sharable inclusion (reads DB)

func (*GormTeamNoteStore) Patch

func (s *GormTeamNoteStore) Patch(ctx context.Context, id string, operations []PatchOperation) (*TeamNote, error)

Patch applies JSON Patch operations to a team note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: apply JSON Patch operations to a team note and persist the result (reads DB)

func (*GormTeamNoteStore) Update

func (s *GormTeamNoteStore) Update(ctx context.Context, id string, note *TeamNote, teamID string) (*TeamNote, error)

Update replaces a team note SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: replace all mutable fields of an existing team note (reads DB)

type GormTeamStore

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

GormTeamStore implements TeamStoreInterface using GORM for database persistence SEM@8c7929da791c778ff88713684c47aa2a10911bba: GORM-backed implementation of TeamStoreInterface (pure)

func NewGormTeamStore

func NewGormTeamStore(db *gorm.DB) *GormTeamStore

NewGormTeamStore creates a new GORM-backed team store SEM@8c7929da791c778ff88713684c47aa2a10911bba: build a GormTeamStore from a GORM database connection (pure)

func (*GormTeamStore) CheckAndBumpVersion

func (s *GormTeamStore) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the team row's version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the team row's optimistic-lock version (reads DB)

func (*GormTeamStore) Create

func (s *GormTeamStore) Create(ctx context.Context, team *Team, userInternalUUID string) (*Team, error)

Create creates a new team, auto-adding the creator as a member with engineering_lead role SEM@87d6f75bc3aecf3edd6c4103567546955c1afadf: store a new team and auto-enroll the creator as engineering lead (writes DB)

func (*GormTeamStore) Delete

func (s *GormTeamStore) Delete(ctx context.Context, id string) error

Delete removes a team and all associated data SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: delete a team and all associated records, blocking if projects exist (writes DB)

func (*GormTeamStore) Get

func (s *GormTeamStore) Get(ctx context.Context, id string) (*Team, error)

Get retrieves a team by ID with all associated data SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch a team with its members, responsible parties, relationships and metadata (reads DB)

func (*GormTeamStore) HasProjects

func (s *GormTeamStore) HasProjects(ctx context.Context, teamID string) (bool, error)

HasProjects checks if a team has any associated projects SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: check whether a team has any associated projects (reads DB)

func (*GormTeamStore) IsMember

func (s *GormTeamStore) IsMember(ctx context.Context, teamID string, userInternalUUID string) (bool, error)

IsMember checks if a user is a member of a team SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: check whether a user is a member of a team (reads DB)

func (*GormTeamStore) List

func (s *GormTeamStore) List(ctx context.Context, limit, offset int, filters *TeamFilters, userInternalUUID string, isAdmin bool) ([]TeamListItem, int, error)

List retrieves teams with filtering, pagination, and access control SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: list teams with filters, access control, and pagination, including counts (reads DB)

func (*GormTeamStore) Update

func (s *GormTeamStore) Update(ctx context.Context, id string, team *Team, userInternalUUID string) (*Team, error)

Update updates an existing team, replacing members, responsible parties, and relationships SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: replace a team's fields, members, responsible parties, relationships, and metadata (writes DB)

type GormThreatModelStore

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

GormThreatModelStore handles threat model database operations using GORM SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: GORM-backed store for threat model persistence with read-write mutex (reads DB)

func NewGormThreatModelStore

func NewGormThreatModelStore(database *gorm.DB) *GormThreatModelStore

NewGormThreatModelStore creates a new threat model GORM store SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a GORM threat model store wrapping the provided database connection (pure)

func (*GormThreatModelStore) CheckAndBumpVersion

func (s *GormThreatModelStore) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the threat model row's version. See optimistic_locking.go::CheckAndBumpVersion for semantics. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the threat model row's optimistic-lock version (reads DB)

func (*GormThreatModelStore) Count

func (s *GormThreatModelStore) Count() int

Count returns the total number of threat models using GORM SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: return the total number of non-deleted threat models (reads DB)

func (*GormThreatModelStore) Create

func (s *GormThreatModelStore) Create(item ThreatModel, idSetter func(ThreatModel, string) ThreatModel) (ThreatModel, error)

Create adds a new threat model using GORM SEM@178dbd0418cfb7e057d4297c7a88c5879cb64c7f: persist a new threat model with authorization and metadata in a serializable retryable transaction (reads DB)

func (*GormThreatModelStore) Delete

func (s *GormThreatModelStore) Delete(id string) error

Delete soft-deletes a threat model and all its children. Use HardDelete for permanent removal (e.g., tombstone cleanup). Delete is on the legacy non-ctx path; SoftDelete now requires a context, so we pass context.Background() to preserve the existing Delete signature. Callers that have a request ctx should call SoftDelete directly. SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: soft-delete a threat model and its children (reads DB)

func (*GormThreatModelStore) Get

Get retrieves a threat model by ID using GORM SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: fetch a threat model by ID from cache or DB with all sub-resources (reads DB)

func (*GormThreatModelStore) GetAuthorization

func (s *GormThreatModelStore) GetAuthorization(id string) ([]Authorization, User, error)

GetAuthorization loads only authorization entries and owner for a threat model. Used by middleware to check access without loading the full model. SEM@0188701ac58d301e630fd335e1001e17602c8186: load authorization entries and owner for a threat model for middleware access checks (reads DB)

func (*GormThreatModelStore) GetAuthorizationIncludingDeleted

func (s *GormThreatModelStore) GetAuthorizationIncludingDeleted(id string) ([]Authorization, User, error)

GetAuthorizationIncludingDeleted loads authorization for a potentially soft-deleted threat model. SEM@0188701ac58d301e630fd335e1001e17602c8186: load authorization entries and owner for a threat model including soft-deleted records (reads DB)

func (*GormThreatModelStore) GetDB

func (s *GormThreatModelStore) GetDB() *gorm.DB

GetDB returns the underlying GORM database connection SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: return the underlying GORM database handle (pure)

func (*GormThreatModelStore) GetIncludingDeleted

func (s *GormThreatModelStore) GetIncludingDeleted(id string) (ThreatModel, error)

GetIncludingDeleted retrieves a threat model by ID without filtering on deleted_at SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch a threat model by ID regardless of its deleted_at status (reads DB)

func (*GormThreatModelStore) HardDelete

func (s *GormThreatModelStore) HardDelete(id string) error

HardDelete permanently removes a threat model and all its children (the original Delete behavior) SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently delete a threat model and all its children from the DB (mutates DB)

func (*GormThreatModelStore) List

func (s *GormThreatModelStore) List(offset, limit int, filter func(ThreatModel) bool) []ThreatModel

List returns filtered and paginated threat models using GORM SEM@8992eaca709573d0f6834edf30a3ef57370db6fa: list filtered and paginated threat models with full sub-resource hydration (reads DB)

func (*GormThreatModelStore) ListWithCounts

func (s *GormThreatModelStore) ListWithCounts(offset, limit int, filter func(ThreatModel) bool, filters *ThreatModelFilters) ([]TMListItem, int)

SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: list paginated threat model summaries with per-model sub-resource counts and auth filtering (reads DB)

func (*GormThreatModelStore) Restore

func (s *GormThreatModelStore) Restore(id string) error

Restore clears deleted_at on a threat model and all its children SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: restore a soft-deleted threat model and all its child entities (mutates DB)

func (*GormThreatModelStore) SoftDelete

func (s *GormThreatModelStore) SoftDelete(ctx context.Context, id string) error

SoftDelete sets deleted_at on a threat model and all its children SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete a threat model and cascade deleted_at to all child entities (mutates DB)

func (*GormThreatModelStore) Update

func (s *GormThreatModelStore) Update(ctx context.Context, id string, item ThreatModel) error

Update modifies an existing threat model using GORM SEM@ebf201816c3638ec74fc8483a2a649af3ccddfc9: update threat model fields, authorization, and metadata in a retryable transaction (reads DB)

type GormThreatRepository

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

GormThreatRepository implements ThreatStore with GORM for database persistence and Redis caching SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: GORM-backed threat repository with cache and invalidator dependencies

func NewGormThreatRepository

func NewGormThreatRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormThreatRepository

NewGormThreatRepository creates a new GORM-backed threat repository with caching SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a GormThreatRepository wired to a database, cache, and invalidator (pure)

func (*GormThreatRepository) BulkCreate

func (s *GormThreatRepository) BulkCreate(ctx context.Context, threats []Threat) error

BulkCreate creates multiple threats in a single transaction using GORM SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: store multiple threats in a single transaction with alias allocation and cache invalidation (reads DB)

func (*GormThreatRepository) BulkUpdate

func (s *GormThreatRepository) BulkUpdate(ctx context.Context, threats []Threat) error

BulkUpdate updates multiple threats in a single transaction using GORM SEM@fcd7743e746718c31b33ef56fb3ba2f8ccf669c7: atomically update multiple threats and their metadata in one transaction (reads DB)

func (*GormThreatRepository) CheckAndBumpVersion

func (s *GormThreatRepository) CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)

CheckAndBumpVersion atomically validates and increments the threat row's version. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: atomically validate and increment the threat row's optimistic-lock version (reads DB)

func (*GormThreatRepository) Create

func (s *GormThreatRepository) Create(ctx context.Context, threat *Threat) error

Create creates a new threat with write-through caching using GORM SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: store a new threat with alias allocation and write-through cache update (reads DB)

func (*GormThreatRepository) Delete

func (s *GormThreatRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes a threat by setting deleted_at SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: soft-delete a threat by delegating to SoftDelete (reads DB)

func (*GormThreatRepository) Get

func (s *GormThreatRepository) Get(ctx context.Context, id string) (*Threat, error)

Get retrieves a threat by ID with cache-first strategy using GORM SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a threat by ID using cache-first strategy, falling back to DB (reads DB)

func (*GormThreatRepository) GetIncludingDeleted

func (s *GormThreatRepository) GetIncludingDeleted(ctx context.Context, id string) (*Threat, error)

SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch a threat by ID regardless of its deleted_at status (reads DB)

func (*GormThreatRepository) HardDelete

func (s *GormThreatRepository) HardDelete(ctx context.Context, id string) error

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently delete a threat (mutates DB)

func (*GormThreatRepository) InvalidateCache

func (s *GormThreatRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes threat-related cache entries SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: remove a threat's cache entry by ID (mutates shared state)

func (*GormThreatRepository) List

func (s *GormThreatRepository) List(ctx context.Context, threatModelID string, filter ThreatFilter) ([]Threat, int, error)

List retrieves threats for a threat model with advanced filtering, sorting and pagination using GORM Returns: items, total count (before pagination), error SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: list threats for a threat model with filtering, sorting, pagination, and cache (reads DB)

func (*GormThreatRepository) Patch

func (s *GormThreatRepository) Patch(ctx context.Context, id string, operations []PatchOperation) (*Threat, error)

Patch applies JSON patch operations to a threat using GORM SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: apply JSON Patch operations to a threat and persist the result (reads DB)

func (*GormThreatRepository) Restore

func (s *GormThreatRepository) Restore(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: restore a soft-deleted threat by clearing its deleted_at timestamp (mutates DB)

func (*GormThreatRepository) SoftDelete

func (s *GormThreatRepository) SoftDelete(ctx context.Context, id string) error

SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete a threat and invalidate its cache entry (mutates DB)

func (*GormThreatRepository) Update

func (s *GormThreatRepository) Update(ctx context.Context, threat *Threat) error

Update updates an existing threat with write-through caching using GORM SEM@fcd7743e746718c31b33ef56fb3ba2f8ccf669c7: store updated threat fields and metadata, then refresh the cache (reads DB)

func (*GormThreatRepository) WarmCache

func (s *GormThreatRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads threats for a threat model into cache SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: preload the first page of threats for a threat model into cache (reads DB)

type GormTimmyEmbeddingStore

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

GormTimmyEmbeddingStore implements TimmyEmbeddingStore using GORM SEM@38c9cd78ea6f81a7cfa5891e34a980915566378b: GORM-backed store for Timmy vector embedding records with a read-write mutex

func NewGormTimmyEmbeddingStore

func NewGormTimmyEmbeddingStore(db *gorm.DB) *GormTimmyEmbeddingStore

NewGormTimmyEmbeddingStore creates a new GORM-backed embedding store SEM@38c9cd78ea6f81a7cfa5891e34a980915566378b: build a new GORM-backed Timmy embedding store (pure)

func (*GormTimmyEmbeddingStore) CreateBatch

func (s *GormTimmyEmbeddingStore) CreateBatch(ctx context.Context, embeddings []models.TimmyEmbedding) error

CreateBatch creates a batch of embeddings SEM@fb2f7a7145abd513579b00a314e93717693bf60d: store a batch of embedding records in a single retryable transaction (reads DB)

func (*GormTimmyEmbeddingStore) DeleteByEntity

func (s *GormTimmyEmbeddingStore) DeleteByEntity(ctx context.Context, threatModelID, entityType, entityID string) (int64, error)

DeleteByEntity deletes all embeddings for a specific entity within a threat model SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: delete all embeddings for a specific entity within a threat model and return count removed (reads DB)

func (*GormTimmyEmbeddingStore) DeleteByThreatModel

func (s *GormTimmyEmbeddingStore) DeleteByThreatModel(ctx context.Context, threatModelID string) (int64, error)

DeleteByThreatModel deletes all embeddings for a threat model SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: delete all embeddings for a threat model and return count removed (reads DB)

func (*GormTimmyEmbeddingStore) DeleteByThreatModelAndIndexType

func (s *GormTimmyEmbeddingStore) DeleteByThreatModelAndIndexType(ctx context.Context, threatModelID, indexType string) (int64, error)

DeleteByThreatModelAndIndexType deletes all embeddings for a threat model and index type SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: delete all embeddings for a threat model and index type and return count removed (reads DB)

func (*GormTimmyEmbeddingStore) DeleteEntitiesWithStaleEmbeddingMetadata

func (s *GormTimmyEmbeddingStore) DeleteEntitiesWithStaleEmbeddingMetadata(
	ctx context.Context, threatModelID, indexType, currentModel string, currentDim int,
) (int64, error)

DeleteEntitiesWithStaleEmbeddingMetadata deletes rows where the stored embedding_model or embedding_dim disagrees with (currentModel, currentDim). See TimmyEmbeddingStore.DeleteEntitiesWithStaleEmbeddingMetadata. SEM@6081f52fc388ecc8072369db4a8490b7b7f499c6: delete embeddings whose model or dimension disagrees with the current configuration (reads DB)

func (*GormTimmyEmbeddingStore) ListByThreatModelAndIndexType

func (s *GormTimmyEmbeddingStore) ListByThreatModelAndIndexType(ctx context.Context, threatModelID, indexType string) ([]models.TimmyEmbedding, error)

ListByThreatModelAndIndexType returns all embeddings for a threat model and index type ordered by entity_type, entity_id, chunk_index SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch all embeddings for a threat model and index type ordered by entity and chunk (reads DB)

func (*GormTimmyEmbeddingStore) ListEntityMetadataByThreatModelAndIndexType

func (s *GormTimmyEmbeddingStore) ListEntityMetadataByThreatModelAndIndexType(
	ctx context.Context, threatModelID, indexType string,
) (map[EntityKey]EntityEmbeddingMeta, error)

ListEntityMetadataByThreatModelAndIndexType returns one EntityEmbeddingMeta per entity. See TimmyEmbeddingStore.ListEntityMetadataByThreatModelAndIndexType. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch a map of entity keys to embedding metadata for a threat model and index type (reads DB)

type GormTimmyMessageStore

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

GormTimmyMessageStore implements TimmyMessageStore using GORM SEM@3f30cf32cf8bc373eef534adfb1126a7b2018f76: GORM-backed store for Timmy session messages

func NewGormTimmyMessageStore

func NewGormTimmyMessageStore(db *gorm.DB) *GormTimmyMessageStore

NewGormTimmyMessageStore creates a new GORM-backed message store SEM@3f30cf32cf8bc373eef534adfb1126a7b2018f76: build a GORM-backed Timmy message store

func (*GormTimmyMessageStore) Create

func (s *GormTimmyMessageStore) Create(ctx context.Context, message *models.TimmyMessage) error

Create persists a new message SEM@fb2f7a7145abd513579b00a314e93717693bf60d: persist a new Timmy message to the database (writes DB)

func (*GormTimmyMessageStore) GetNextSequence

func (s *GormTimmyMessageStore) GetNextSequence(ctx context.Context, sessionID string) (int, error)

GetNextSequence returns the next sequence number for a session (MAX(sequence) + 1, starting at 1) SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: compute the next message sequence number for a session (reads DB)

func (*GormTimmyMessageStore) ListBySession

func (s *GormTimmyMessageStore) ListBySession(ctx context.Context, sessionID string, offset, limit int) ([]models.TimmyMessage, int, error)

ListBySession returns paginated messages for a session ordered by sequence ascending Returns the messages, the total count, and any error SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch paginated Timmy messages for a session ordered by sequence (reads DB)

type GormTimmySessionStore

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

GormTimmySessionStore implements TimmySessionStore using GORM SEM@3f30cf32cf8bc373eef534adfb1126a7b2018f76: GORM-backed store for Timmy chat sessions with a read-write mutex

func NewGormTimmySessionStore

func NewGormTimmySessionStore(db *gorm.DB) *GormTimmySessionStore

NewGormTimmySessionStore creates a new GORM-backed session store SEM@3f30cf32cf8bc373eef534adfb1126a7b2018f76: build a new GORM-backed Timmy session store (pure)

func (*GormTimmySessionStore) CountActiveByThreatModel

func (s *GormTimmySessionStore) CountActiveByThreatModel(ctx context.Context, threatModelID string) (int, error)

CountActiveByThreatModel returns the number of active sessions for a threat model SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: count non-deleted active Timmy sessions for a threat model (reads DB)

func (*GormTimmySessionStore) Create

func (s *GormTimmySessionStore) Create(ctx context.Context, session *models.TimmySession) error

Create persists a new session SEM@fb2f7a7145abd513579b00a314e93717693bf60d: persist a new Timmy chat session in a retryable transaction (reads DB)

func (*GormTimmySessionStore) Get

Get retrieves a session by ID, excluding soft-deleted sessions SEM@fb2f7a7145abd513579b00a314e93717693bf60d: fetch a non-deleted Timmy session by ID, returning ErrTimmySessionNotFound if absent (reads DB)

func (*GormTimmySessionStore) ListByUserAndThreatModel

func (s *GormTimmySessionStore) ListByUserAndThreatModel(ctx context.Context, userID, threatModelID string, offset, limit int) ([]models.TimmySession, int, error)

ListByUserAndThreatModel returns paginated sessions for a user and threat model Returns the sessions, the total count, and any error SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: list paginated non-deleted Timmy sessions for a user and threat model, returning total count (reads DB)

func (*GormTimmySessionStore) SoftDelete

func (s *GormTimmySessionStore) SoftDelete(ctx context.Context, id string) error

SoftDelete marks a session as deleted by setting its deleted_at timestamp SEM@fb2f7a7145abd513579b00a314e93717693bf60d: mark a Timmy session deleted by setting its deleted_at timestamp (writes DB)

func (*GormTimmySessionStore) UpdateSnapshot

func (s *GormTimmySessionStore) UpdateSnapshot(ctx context.Context, id string, snapshot models.JSONRaw) error

UpdateSnapshot updates the source_snapshot JSON column for a session. SEM@fb2f7a7145abd513579b00a314e93717693bf60d: update the source snapshot JSON for an active Timmy session (writes DB)

func (*GormTimmySessionStore) UpdateTitle

func (s *GormTimmySessionStore) UpdateTitle(ctx context.Context, id, title string) error

UpdateTitle updates the title column for a session. SEM@31f1e9f6c50875c19da05aa43964a24bc7d7d156: update the title of an active Timmy session (writes DB)

type GormTimmyUsageStore

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

GormTimmyUsageStore implements TimmyUsageStore using GORM SEM@e5e141caabe74e3ce853b6d7b45827bb1864fb32: GORM-backed store for Timmy AI usage records with a reader-writer mutex

func NewGormTimmyUsageStore

func NewGormTimmyUsageStore(db *gorm.DB) *GormTimmyUsageStore

NewGormTimmyUsageStore creates a new GORM-backed usage store SEM@e5e141caabe74e3ce853b6d7b45827bb1864fb32: build a GormTimmyUsageStore backed by the given GORM DB (pure)

func (*GormTimmyUsageStore) GetAggregated

func (s *GormTimmyUsageStore) GetAggregated(ctx context.Context, userID, threatModelID string, start, end time.Time) (*UsageAggregation, error)

GetAggregated returns summed usage metrics with optional user and threat model filters SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: aggregate Timmy token and session counts filtered by user and threat model over a time range (reads DB)

func (*GormTimmyUsageStore) GetByThreatModel

func (s *GormTimmyUsageStore) GetByThreatModel(ctx context.Context, threatModelID string, start, end time.Time) ([]models.TimmyUsage, error)

GetByThreatModel returns all usage records for a threat model within the given time range SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch all Timmy usage records for a threat model within a time range (reads DB)

func (*GormTimmyUsageStore) GetByUser

func (s *GormTimmyUsageStore) GetByUser(ctx context.Context, userID string, start, end time.Time) ([]models.TimmyUsage, error)

GetByUser returns all usage records for a user within the given time range SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch all Timmy usage records for a user within a time range (reads DB)

func (*GormTimmyUsageStore) Record

func (s *GormTimmyUsageStore) Record(ctx context.Context, usage *models.TimmyUsage) error

Record persists a new usage record SEM@fb2f7a7145abd513579b00a314e93717693bf60d: persist a new Timmy usage record in a retryable transaction (reads DB)

type GormTriageNoteStore

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

GormTriageNoteStore implements TriageNoteStore using GORM SEM@869fcafe6842b187f8cfe8e7cf65ca47021b8418: GORM-backed store for triage notes

func NewGormTriageNoteStore

func NewGormTriageNoteStore(db *gorm.DB) *GormTriageNoteStore

NewGormTriageNoteStore creates a new GORM-backed triage note store SEM@869fcafe6842b187f8cfe8e7cf65ca47021b8418: build a GORM-backed triage note store

func (*GormTriageNoteStore) Count

func (s *GormTriageNoteStore) Count(ctx context.Context, surveyResponseID string) (int, error)

Count returns the total number of triage notes for a survey response SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: count triage notes belonging to a survey response (reads DB)

func (*GormTriageNoteStore) Create

func (s *GormTriageNoteStore) Create(ctx context.Context, note *TriageNote, surveyResponseID string, creatorInternalUUID string) error

Create creates a new triage note with an auto-assigned sequential ID SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: store a new triage note with sequential ID and populate creator fields (writes DB)

func (*GormTriageNoteStore) Get

func (s *GormTriageNoteStore) Get(ctx context.Context, surveyResponseID string, noteID int) (*TriageNote, error)

Get retrieves a specific triage note by survey response ID and note ID SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: fetch a single triage note by survey response and note ID (reads DB)

func (*GormTriageNoteStore) List

func (s *GormTriageNoteStore) List(ctx context.Context, surveyResponseID string, offset, limit int) ([]TriageNote, error)

List returns triage notes for a survey response with pagination, ordered by ID ascending SEM@579b4f4aa29012b989445d1a6ef052ac48216b93: list paginated triage notes for a survey response ordered by ID (reads DB)

type GormUsabilityFeedbackRepository

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

GormUsabilityFeedbackRepository implements UsabilityFeedbackRepository with GORM. SEM@e6358cd2f50a1221d6e8c0f0fe40c31b27feb5d2: GORM-backed repository for persisting and querying usability feedback records

func NewGormUsabilityFeedbackRepository

func NewGormUsabilityFeedbackRepository(db *gorm.DB) *GormUsabilityFeedbackRepository

NewGormUsabilityFeedbackRepository constructs a repository. SEM@e6358cd2f50a1221d6e8c0f0fe40c31b27feb5d2: build a GormUsabilityFeedbackRepository backed by the given DB connection (pure)

func (*GormUsabilityFeedbackRepository) Count

Count returns the row count for the filter. SEM@e6358cd2f50a1221d6e8c0f0fe40c31b27feb5d2: count usability feedback records matching a filter (reads DB)

func (*GormUsabilityFeedbackRepository) Create

Create inserts a new feedback row. The model's BeforeCreate hook generates the UUID if none is supplied. CreatedAt is set explicitly here (not via GORM's autoCreateTime) for Oracle compatibility — the Threat model uses the same pattern to avoid gorm-oracle's RETURNING INTO interaction on high-volume inserts (see #380). SEM@f0dc4a18f547f807534300d1d5683b959965e3ab: store a new usability feedback row, setting created_at explicitly for Oracle compatibility (reads DB)

func (*GormUsabilityFeedbackRepository) Get

Get returns a feedback row by ID, or NotFound if absent. SEM@e6358cd2f50a1221d6e8c0f0fe40c31b27feb5d2: fetch a usability feedback record by ID, returning NotFound if absent (reads DB)

func (*GormUsabilityFeedbackRepository) List

List returns feedback rows matching the filter, paginated. SEM@e6358cd2f50a1221d6e8c0f0fe40c31b27feb5d2: list usability feedback records matching a filter with pagination, ordered by created_at desc (reads DB)

type GormUserAPIQuotaStore

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

GormUserAPIQuotaStore implements UserAPIQuotaStoreInterface using GORM SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: GORM-backed persistent store for per-user API rate quotas

func NewGormUserAPIQuotaStore

func NewGormUserAPIQuotaStore(db *gorm.DB) *GormUserAPIQuotaStore

NewGormUserAPIQuotaStore creates a new GORM-backed user API quota store SEM@b7b932142ab960e30c578c15382ac17d2ac13d79: build a GormUserAPIQuotaStore backed by the given database connection (pure)

func (*GormUserAPIQuotaStore) Count

func (s *GormUserAPIQuotaStore) Count(ctx context.Context) (int, error)

Count returns the total number of user API quotas SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: return the total number of stored user API quota records (reads DB)

func (*GormUserAPIQuotaStore) Create

Create creates a new user API quota SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: store a new user API quota record in the database (mutates shared state)

func (*GormUserAPIQuotaStore) Delete

func (s *GormUserAPIQuotaStore) Delete(ctx context.Context, userID string) error

Delete deletes a user API quota SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: delete the API quota record for a user by internal UUID (mutates shared state)

func (*GormUserAPIQuotaStore) Get

Get retrieves a user API quota by user ID SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: fetch the API quota record for a user by internal UUID (reads DB)

func (*GormUserAPIQuotaStore) GetOrDefault

func (s *GormUserAPIQuotaStore) GetOrDefault(ctx context.Context, userID string) UserAPIQuota

GetOrDefault retrieves a quota or returns default values SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: fetch the user's API quota or return platform defaults when none is stored (reads DB)

func (*GormUserAPIQuotaStore) List

func (s *GormUserAPIQuotaStore) List(ctx context.Context, offset, limit int) ([]UserAPIQuota, error)

List retrieves all user API quotas with pagination SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: list all user API quota records with pagination (reads DB)

func (*GormUserAPIQuotaStore) Update

func (s *GormUserAPIQuotaStore) Update(ctx context.Context, userID string, item UserAPIQuota) error

Update updates an existing user API quota SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: update rate limit fields of an existing user API quota (mutates shared state)

func (*GormUserAPIQuotaStore) Upsert

Upsert creates or updates a user API quota using GORM's OnConflict clause This is cross-database compatible via GORM's dialect abstraction SEM@aa6d284f5df5c13ccb0001366a1f228490aba957: create or update a user API quota using a cross-DB conflict clause (mutates shared state)

type GormUserGroupsFetcher

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

GormUserGroupsFetcher implements auth.UserGroupsFetcher by querying the group membership repository for TMI-managed groups a user belongs to. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: adapter that fetches TMI-managed group memberships for a user via the group member repository

func NewGormUserGroupsFetcher

func NewGormUserGroupsFetcher(memberStore GroupMemberRepository) *GormUserGroupsFetcher

NewGormUserGroupsFetcher creates a new user groups fetcher. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: build a GormUserGroupsFetcher over the given group member repository (pure)

func (*GormUserGroupsFetcher) GetUserGroups

func (f *GormUserGroupsFetcher) GetUserGroups(ctx context.Context, userInternalUUID string) ([]auth.UserGroupInfo, error)

GetUserGroups returns the TMI-managed groups that a user is a direct member of. SEM@a0040890dd7b1940f542d4211d4338cd0e713cbc: fetch the TMI-managed groups a user directly belongs to and convert them to UserGroupInfo (reads DB)

type GormUserStore

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

GormUserStore implements UserStore using GORM for cross-database support SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: GORM-backed store for user records with auth service integration

func NewGormUserStore

func NewGormUserStore(db *gorm.DB, authService *auth.Service) *GormUserStore

NewGormUserStore creates a new GORM-backed user store SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: build a GORM-backed user store wired to the auth service

func (*GormUserStore) Count

func (s *GormUserStore) Count(ctx context.Context, filter UserFilter) (int, error)

Count returns total count of users matching the filter SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: count users matching the given filter criteria (reads DB)

func (*GormUserStore) Delete

func (s *GormUserStore) Delete(ctx context.Context, internalUUID uuid.UUID) (*DeletionStats, error)

Delete deletes a user by internal UUID, using the auth service's direct UUID-based deletion to avoid multi-hop identity resolution bugs. SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: delete a user by internal UUID and transfer or remove owned threat models (writes DB)

func (*GormUserStore) EnrichUsers

func (s *GormUserStore) EnrichUsers(ctx context.Context, users []AdminUser) ([]AdminUser, error)

EnrichUsers adds related data to users (admin status, groups, threat model counts) SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: attach admin status and threat model counts to a list of users (reads DB)

func (*GormUserStore) Get

func (s *GormUserStore) Get(ctx context.Context, internalUUID openapi_types.UUID) (*AdminUser, error)

Get retrieves a user by internal UUID SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: fetch a user by internal UUID (reads DB)

func (*GormUserStore) GetByProviderAndID

func (s *GormUserStore) GetByProviderAndID(ctx context.Context, provider string, providerUserID string) (*AdminUser, error)

GetByProviderAndID retrieves a user by provider and provider_user_id SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch a user by identity provider and provider user ID (reads DB)

func (*GormUserStore) List

func (s *GormUserStore) List(ctx context.Context, filter UserFilter) ([]AdminUser, error)

List returns users with optional filtering and pagination SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: list users with optional filter, sort, and pagination applied (reads DB)

func (*GormUserStore) Update

func (s *GormUserStore) Update(ctx context.Context, user AdminUser) error

Update updates user metadata (email, name, email_verified) SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: update a user's email, name, and email verification status (writes DB)

type GormWebhookQuotaStore

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

GormWebhookQuotaStore implements WebhookQuotaStoreInterface using GORM SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: GORM-backed store holding per-owner webhook quota records

func NewGormWebhookQuotaStore

func NewGormWebhookQuotaStore(db *gorm.DB) *GormWebhookQuotaStore

NewGormWebhookQuotaStore creates a new GORM-backed webhook quota store SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: build a GORM-backed webhook quota store wrapping the given DB connection (pure)

func (*GormWebhookQuotaStore) Count

func (s *GormWebhookQuotaStore) Count(ctx context.Context) (int, error)

Count returns the total number of webhook quotas using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: return total count of webhook quota records (reads DB)

func (*GormWebhookQuotaStore) Create

Create creates a new webhook quota using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: store a new webhook quota record with timestamps (mutates DB)

func (*GormWebhookQuotaStore) Delete

func (s *GormWebhookQuotaStore) Delete(ctx context.Context, ownerID string) error

Delete deletes a webhook quota using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: delete a webhook quota record by owner ID; error if not found (mutates DB)

func (*GormWebhookQuotaStore) Get

Get retrieves a webhook quota by owner ID using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: fetch a webhook quota record by owner ID; error if not found (reads DB)

func (*GormWebhookQuotaStore) GetOrDefault

func (s *GormWebhookQuotaStore) GetOrDefault(ctx context.Context, ownerID string) DBWebhookQuota

GetOrDefault retrieves a quota or returns default values using GORM.

Semantics: fail-open. Any error from Get falls back to the per-tenant defaults so request-handling never panics for missing quota rows. Non-NotFound errors (i.e., transient ADB outages such as ORA-03113 / ORA-08177) emit a WARN log so an outage is visible in observability even though the response succeeds with default limits. The historical behavior was to silently swallow all errors; the WARN is the only behavior change. SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: fetch a webhook quota by owner ID or return defaults on any error (reads DB)

func (*GormWebhookQuotaStore) List

func (s *GormWebhookQuotaStore) List(ctx context.Context, offset, limit int) ([]DBWebhookQuota, error)

List retrieves all webhook quotas with pagination using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list webhook quota records with pagination (reads DB)

func (*GormWebhookQuotaStore) Update

func (s *GormWebhookQuotaStore) Update(ctx context.Context, ownerID string, item DBWebhookQuota) error

Update updates an existing webhook quota using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: update rate-limit fields of a webhook quota record by owner ID (mutates DB)

type GormWebhookSubscriptionStore

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

GormWebhookSubscriptionStore implements WebhookSubscriptionStoreInterface using GORM SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: GORM-backed store for webhook subscription persistence with concurrency control

func NewGormWebhookSubscriptionStore

func NewGormWebhookSubscriptionStore(db *gorm.DB) *GormWebhookSubscriptionStore

NewGormWebhookSubscriptionStore creates a new GORM-backed webhook subscription store SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: build a GORM-backed webhook subscription store from a DB handle (pure)

func (*GormWebhookSubscriptionStore) Count

Count returns the total number of webhook subscriptions using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: return total count of webhook subscriptions (reads DB)

func (*GormWebhookSubscriptionStore) CountByOwner

func (s *GormWebhookSubscriptionStore) CountByOwner(ctx context.Context, ownerID string) (int, error)

CountByOwner returns the number of subscriptions for a specific owner using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: return count of webhook subscriptions belonging to a specific owner (reads DB)

func (*GormWebhookSubscriptionStore) Create

Create creates a new webhook subscription using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: store a new webhook subscription with generated ID and timestamps (mutates DB)

func (*GormWebhookSubscriptionStore) Delete

Delete deletes a webhook subscription using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: delete a webhook subscription by ID; error if not found (mutates DB)

func (*GormWebhookSubscriptionStore) Get

Get retrieves a webhook subscription by ID using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: fetch a webhook subscription by ID from the DB (reads DB)

func (*GormWebhookSubscriptionStore) IncrementTimeouts

func (s *GormWebhookSubscriptionStore) IncrementTimeouts(ctx context.Context, id string) error

IncrementTimeouts increments the timeout count using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: increment the timeout counter for a webhook subscription by ID (mutates DB)

func (*GormWebhookSubscriptionStore) List

List retrieves webhook subscriptions with pagination and filtering using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list webhook subscriptions with pagination and optional in-memory filter (reads DB)

func (*GormWebhookSubscriptionStore) ListActiveByEventType

func (s *GormWebhookSubscriptionStore) ListActiveByEventType(ctx context.Context, eventType string) ([]DBWebhookSubscription, error)

ListActiveByEventType retrieves all active subscriptions that declare the given event type (used to fan-out ownerless events such as system_audit.*). Event matching is performed in Go after fetching active rows because the Events column is stored as a serialised string array; this mirrors the approach used by the consumer's filterSubscriptions helper. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch active webhook subscriptions matching a given event type (reads DB)

func (*GormWebhookSubscriptionStore) ListActiveByOwner

func (s *GormWebhookSubscriptionStore) ListActiveByOwner(ctx context.Context, ownerID string) ([]DBWebhookSubscription, error)

ListActiveByOwner retrieves active subscriptions for an owner using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list active webhook subscriptions for a specific owner (reads DB)

func (*GormWebhookSubscriptionStore) ListBroken

func (s *GormWebhookSubscriptionStore) ListBroken(ctx context.Context, minFailures int, daysSinceSuccess int) ([]DBWebhookSubscription, error)

ListBroken retrieves subscriptions with too many failures using GORM SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch active non-pinned subscriptions exceeding failure threshold without recent success (reads DB)

func (*GormWebhookSubscriptionStore) ListByOwner

func (s *GormWebhookSubscriptionStore) ListByOwner(ctx context.Context, ownerID string, offset, limit int) ([]DBWebhookSubscription, error)

ListByOwner retrieves subscriptions for a specific owner using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list webhook subscriptions for a specific owner with pagination (reads DB)

func (*GormWebhookSubscriptionStore) ListByThreatModel

func (s *GormWebhookSubscriptionStore) ListByThreatModel(ctx context.Context, threatModelID string, offset, limit int) ([]DBWebhookSubscription, error)

ListByThreatModel retrieves subscriptions for a specific threat model using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list webhook subscriptions scoped to a specific threat model with pagination (reads DB)

func (*GormWebhookSubscriptionStore) ListIdle

ListIdle retrieves subscriptions that have been idle for a certain number of days using GORM SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch active non-pinned webhook subscriptions unused for at least N days (reads DB)

func (*GormWebhookSubscriptionStore) ListPendingDelete

ListPendingDelete retrieves subscriptions pending deletion using GORM SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch webhook subscriptions queued for deletion (reads DB)

func (*GormWebhookSubscriptionStore) ListPendingVerification

func (s *GormWebhookSubscriptionStore) ListPendingVerification(ctx context.Context) ([]DBWebhookSubscription, error)

ListPendingVerification retrieves subscriptions pending verification using GORM SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: fetch webhook subscriptions awaiting verification challenge (reads DB)

func (*GormWebhookSubscriptionStore) ResetTimeouts

func (s *GormWebhookSubscriptionStore) ResetTimeouts(ctx context.Context, id string) error

ResetTimeouts resets the timeout count using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: reset the timeout counter to zero for a webhook subscription by ID (mutates DB)

func (*GormWebhookSubscriptionStore) Update

Update updates an existing webhook subscription using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: update all fields of an existing webhook subscription by ID (mutates DB)

func (*GormWebhookSubscriptionStore) UpdateChallenge

func (s *GormWebhookSubscriptionStore) UpdateChallenge(ctx context.Context, id string, challenge string, challengesSent int) error

UpdateChallenge updates challenge-related fields using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: update verification challenge and challenge-sent count for a webhook subscription (mutates DB)

func (*GormWebhookSubscriptionStore) UpdatePublicationStats

func (s *GormWebhookSubscriptionStore) UpdatePublicationStats(ctx context.Context, id string, success bool) error

UpdatePublicationStats updates publication statistics using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: update delivery success timestamp or increment failure count for a webhook subscription (mutates DB)

func (*GormWebhookSubscriptionStore) UpdateStatus

func (s *GormWebhookSubscriptionStore) UpdateStatus(ctx context.Context, id string, status string) error

UpdateStatus updates only the status field using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: update only the status field of a webhook subscription by ID (mutates DB)

type GormWebhookUrlDenyListStore

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

GormWebhookUrlDenyListStore implements WebhookUrlDenyListStoreInterface using GORM SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: GORM-backed store holding webhook URL deny-list pattern entries

func NewGormWebhookUrlDenyListStore

func NewGormWebhookUrlDenyListStore(db *gorm.DB) *GormWebhookUrlDenyListStore

NewGormWebhookUrlDenyListStore creates a new GORM-backed store SEM@75d52ab3d1f4f71b22b1cef7144254cfdb837491: build a GORM-backed webhook URL deny-list store wrapping the given DB connection (pure)

func (*GormWebhookUrlDenyListStore) Create

Create creates a new deny list entry using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: store a new webhook URL deny-list pattern entry with generated ID (mutates DB)

func (*GormWebhookUrlDenyListStore) Delete

Delete deletes a deny list entry using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: delete a webhook URL deny-list entry by ID; error if not found (mutates DB)

func (*GormWebhookUrlDenyListStore) List

List retrieves all deny list entries using GORM SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list all webhook URL deny-list entries ordered by pattern (reads DB)

type GrantMicrosoftFilePermissionJSONRequestBody

type GrantMicrosoftFilePermissionJSONRequestBody = MicrosoftPickerGrantRequest

GrantMicrosoftFilePermissionJSONRequestBody defines body for GrantMicrosoftFilePermission for application/json ContentType.

type GraphData

type GraphData struct {
	Key   string `xml:"key,attr"`
	Value string `xml:",chardata"`
}

SEM@6e3a086017c90a6a018fd799308443eb877dd8a5: GraphML data element holding a keyed string value for a graph, node, or edge (pure)

type GraphKey

type GraphKey struct {
	ID       string `xml:"id,attr"`
	For      string `xml:"for,attr"`
	AttrName string `xml:"attr.name,attr"`
	AttrType string `xml:"attr.type,attr"`
}

SEM@6e3a086017c90a6a018fd799308443eb877dd8a5: GraphML key declaration describing an attribute schema for nodes, edges, or graphs (pure)

type GraphML

type GraphML struct {
	XMLName        xml.Name     `xml:"graphml"`
	XMLNS          string       `xml:"xmlns,attr"`
	XMLNSXSI       string       `xml:"xmlns:xsi,attr"`
	SchemaLocation string       `xml:"xsi:schemaLocation,attr"`
	Keys           []GraphKey   `xml:"key"`
	Graph          GraphMLGraph `xml:"graph"`
}

SEM@6e3a086017c90a6a018fd799308443eb877dd8a5: XML root element struct for a GraphML document (pure)

type GraphMLEdge

type GraphMLEdge struct {
	ID     string      `xml:"id,attr"`
	Source string      `xml:"source,attr"`
	Target string      `xml:"target,attr"`
	Data   []GraphData `xml:"data"`
}

SEM@6e3a086017c90a6a018fd799308443eb877dd8a5: GraphML edge element with source, target, and associated data attributes (pure)

type GraphMLGraph

type GraphMLGraph struct {
	ID          string        `xml:"id,attr"`
	EdgeDefault string        `xml:"edgedefault,attr"`
	Data        []GraphData   `xml:"data"`
	Nodes       []GraphMLNode `xml:"node"`
	Edges       []GraphMLEdge `xml:"edge"`
}

SEM@6e3a086017c90a6a018fd799308443eb877dd8a5: GraphML graph element containing nodes, edges, and graph-level data attributes (pure)

type GraphMLNode

type GraphMLNode struct {
	ID   string      `xml:"id,attr"`
	Data []GraphData `xml:"data"`
}

SEM@6e3a086017c90a6a018fd799308443eb877dd8a5: GraphML node element with id and associated data attributes (pure)

type Group

type Group struct {
	InternalUUID uuid.UUID `json:"internal_uuid"`
	Provider     string    `json:"provider"`
	GroupName    string    `json:"group_name"`
	Name         string    `json:"name,omitempty"`
	Description  string    `json:"description,omitempty"`
	FirstUsed    time.Time `json:"first_used"`
	LastUsed     time.Time `json:"last_used"`
	UsageCount   int       `json:"usage_count"`

	// Enriched fields (not in database)
	UsedInAuthorizations bool `json:"used_in_authorizations,omitempty"`
	UsedInAdminGrants    bool `json:"used_in_admin_grants,omitempty"`
	MemberCount          int  `json:"member_count,omitempty"` // If available from IdP
}

Group represents a group in the system SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: domain model for an identity provider group with usage and enrichment fields (pure)

type GroupBasedAdminChecker

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

GroupBasedAdminChecker implements auth.AdminChecker using the Administrators group. This replaces GormAdminCheckerAdapter by checking Administrators group membership instead of querying the administrators table. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: admin checker that resolves admin and security-reviewer status via group membership (pure)

func NewGroupBasedAdminChecker

func NewGroupBasedAdminChecker(db *gorm.DB, memberStore GroupMemberRepository) *GroupBasedAdminChecker

NewGroupBasedAdminChecker creates a new admin checker backed by the Administrators group. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: build a GroupBasedAdminChecker backed by the Administrators group store (pure)

func (*GroupBasedAdminChecker) GetGroupUUIDsByNames

func (a *GroupBasedAdminChecker) GetGroupUUIDsByNames(ctx context.Context, provider string, groupNames []string) ([]string, error)

GetGroupUUIDsByNames converts group names to UUIDs. Implements auth.AdminChecker. SEM@c99517d0f78396ed3e7b16e756e0318aefc525db: convert group names to UUID strings for a given provider via the admin checker (reads DB)

func (*GroupBasedAdminChecker) IsAdmin

func (a *GroupBasedAdminChecker) IsAdmin(ctx context.Context, userInternalUUID *string, provider string, groupUUIDs []string) (bool, error)

IsAdmin checks if a user is an administrator by checking Administrators group membership. Implements auth.AdminChecker. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: check whether the user is a member of the Administrators group (reads DB)

func (*GroupBasedAdminChecker) IsSecurityReviewer

func (a *GroupBasedAdminChecker) IsSecurityReviewer(ctx context.Context, userInternalUUID *string, provider string, groupUUIDs []string) (bool, error)

IsSecurityReviewer checks if a user is a security reviewer by checking Security Reviewers group membership. Implements auth.AdminChecker. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: check whether the user is a member of the Security Reviewers group (reads DB)

type GroupDeletionStats

type GroupDeletionStats struct {
	ThreatModelsDeleted  int    `json:"threat_models_deleted"`
	ThreatModelsRetained int    `json:"threat_models_retained"`
	GroupName            string `json:"group_name"`
}

GroupDeletionStats contains statistics about group deletion SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: counts of threat models deleted or retained when a group is deleted (pure)

type GroupFilter

type GroupFilter struct {
	Provider             string
	GroupName            string // Case-insensitive ILIKE %name%
	UsedInAuthorizations *bool
	Limit                int
	Offset               int
	SortBy               string // group_name, first_used, last_used, usage_count
	SortOrder            string // asc, desc
}

GroupFilter defines filtering options for group queries SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: filtering, sorting, and pagination parameters for group list queries (pure)

type GroupMember

type GroupMember struct {
	// AddedAt Timestamp when the user was added to the group (RFC3339)
	AddedAt time.Time `json:"added_at"`

	// AddedByEmail Email of the administrator who added this member
	AddedByEmail *openapi_types.Email `json:"added_by_email,omitempty"`

	// AddedByInternalUuid Internal UUID of the administrator who added this member
	AddedByInternalUuid *openapi_types.UUID `json:"added_by_internal_uuid,omitempty"`

	// GroupInternalUuid Internal UUID of the group
	GroupInternalUuid openapi_types.UUID `json:"group_internal_uuid"`

	// Id Unique identifier for the membership record
	Id openapi_types.UUID `json:"id"`

	// MemberGroupInternalUuid Internal UUID of the member group (when subject_type is group)
	MemberGroupInternalUuid *openapi_types.UUID `json:"member_group_internal_uuid,omitempty"`

	// MemberGroupName Display name of the member group (when subject_type is group)
	MemberGroupName *string `json:"member_group_name,omitempty"`

	// Notes Optional notes about this membership
	Notes *string `json:"notes,omitempty"`

	// SubjectType Type of member: user (direct user membership) or group (group-in-group membership)
	SubjectType GroupMemberSubjectType `json:"subject_type"`

	// UserEmail Email address of the user
	UserEmail *openapi_types.Email `json:"user_email,omitempty"`

	// UserInternalUuid Internal UUID of the user
	UserInternalUuid *openapi_types.UUID `json:"user_internal_uuid,omitempty"`

	// UserName Display name of the user
	UserName *string `json:"user_name,omitempty"`

	// UserProvider OAuth/SAML provider for the user
	UserProvider *string `json:"user_provider,omitempty"`

	// UserProviderUserId Provider-specific user identifier
	UserProviderUserId *string `json:"user_provider_user_id,omitempty"`
}

GroupMember Member of a group with role information

type GroupMemberFilter

type GroupMemberFilter struct {
	GroupInternalUUID uuid.UUID
	Limit             int
	Offset            int
}

GroupMemberFilter defines filtering and pagination for group membership queries SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: pagination parameters for group membership list queries scoped to a group UUID (pure)

type GroupMemberListResponse

type GroupMemberListResponse struct {
	// Limit Maximum number of results per page
	Limit   int           `json:"limit"`
	Members []GroupMember `json:"members"`

	// Offset Number of results skipped
	Offset int `json:"offset"`

	// Total Total number of members in the group
	Total int `json:"total"`
}

GroupMemberListResponse List of members in a group

type GroupMemberRepository

type GroupMemberRepository interface {
	// User membership operations
	ListMembers(ctx context.Context, filter GroupMemberFilter) ([]GroupMember, error)
	CountMembers(ctx context.Context, groupInternalUUID uuid.UUID) (int, error)
	AddMember(ctx context.Context, groupInternalUUID, userInternalUUID uuid.UUID, addedByInternalUUID *uuid.UUID, notes *string) (*GroupMember, error)
	RemoveMember(ctx context.Context, groupInternalUUID, userInternalUUID uuid.UUID) error
	IsMember(ctx context.Context, groupInternalUUID, userInternalUUID uuid.UUID) (bool, error)

	// Group-as-member operations (one level of nesting)
	AddGroupMember(ctx context.Context, groupInternalUUID, memberGroupInternalUUID uuid.UUID, addedByInternalUUID *uuid.UUID, notes *string) (*GroupMember, error)
	RemoveGroupMember(ctx context.Context, groupInternalUUID, memberGroupInternalUUID uuid.UUID) error

	// Effective membership checks (direct user membership OR via group nesting)
	IsEffectiveMember(ctx context.Context, groupInternalUUID uuid.UUID, userInternalUUID uuid.UUID, userGroupUUIDs []uuid.UUID) (bool, error)
	HasAnyMembers(ctx context.Context, groupInternalUUID uuid.UUID) (bool, error)

	// User-centric queries
	GetGroupsForUser(ctx context.Context, userInternalUUID uuid.UUID) ([]Group, error)
}

GroupMemberRepository defines the interface for group membership storage operations. Method signatures match GroupMemberStore exactly. Supports both user and group members (one level of group-in-group nesting). SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: interface for managing direct and nested group membership with effective-membership checks (reads DB)

var GlobalGroupMemberRepository GroupMemberRepository

type GroupMemberSubjectType

type GroupMemberSubjectType string

GroupMemberSubjectType Type of member: user (direct user membership) or group (group-in-group membership)

const (
	GroupMemberSubjectTypeGroup GroupMemberSubjectType = "group"
	GroupMemberSubjectTypeUser  GroupMemberSubjectType = "user"
)

Defines values for GroupMemberSubjectType.

func (GroupMemberSubjectType) Valid

func (e GroupMemberSubjectType) Valid() bool

Valid indicates whether the value is a known member of the GroupMemberSubjectType enum.

type GroupMembershipEnricher

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

GroupMembershipEnricher implements auth.ClaimsEnricher by checking effective membership in built-in groups (Administrators, Security Reviewers) and resolving the user's TMI-managed group names for inclusion in the JWT groups claim. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: JWT claims enricher that resolves a user's built-in group memberships from the DB

func NewGroupMembershipEnricher

func NewGroupMembershipEnricher(memberStore GroupMemberRepository, db *gorm.DB) *GroupMembershipEnricher

NewGroupMembershipEnricher creates a new enricher for JWT claims. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: build a GroupMembershipEnricher backed by the given group member repository (pure)

func (*GroupMembershipEnricher) EnrichClaims

func (e *GroupMembershipEnricher) EnrichClaims(ctx context.Context, userInternalUUID string, provider string, groupNames []string) (bool, bool, []string, error)

EnrichClaims checks whether the user is a member of the Administrators and Security Reviewers built-in groups, and returns the user's TMI-managed group names. SEM@d73e23609ca9cefd9ef2feb0e43d87e4286ea6d6: resolve admin/security-reviewer flags and TMI group names for a user's JWT claims (reads DB)

type GroupNameQueryParam

type GroupNameQueryParam = string

GroupNameQueryParam defines model for GroupNameQueryParam.

type GroupRepository

type GroupRepository interface {
	// List returns groups with optional filtering and pagination.
	List(ctx context.Context, filter GroupFilter) ([]Group, error)

	// Get retrieves a group by internal UUID.
	Get(ctx context.Context, internalUUID uuid.UUID) (*Group, error)

	// GetByProviderAndName retrieves a group by provider and group_name.
	GetByProviderAndName(ctx context.Context, provider string, groupName string) (*Group, error)

	// Create creates a new group (primarily for provider-independent groups).
	Create(ctx context.Context, group Group) error

	// Update updates group metadata (name, description).
	Update(ctx context.Context, group Group) error

	// Count returns total count of groups matching the filter.
	Count(ctx context.Context, filter GroupFilter) (int, error)

	// EnrichGroups adds related data to groups (usage in authorizations/admin grants).
	EnrichGroups(ctx context.Context, groups []Group) ([]Group, error)

	// GetGroupsForProvider returns all groups for a specific provider (for UI autocomplete).
	GetGroupsForProvider(ctx context.Context, provider string) ([]Group, error)
}

GroupRepository defines the interface for group storage operations. This mirrors GroupStore but omits Delete (which is handled at the handler level via DeletionRepository) and uses repository-scoped typed errors. SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: interface for CRUD and enrichment operations on identity provider groups (reads DB)

var GlobalGroupRepository GroupRepository

Repository globals (new typed-error implementations)

type HTTPEmbeddingSource

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

HTTPEmbeddingSource fetches and extracts plain text from HTTP/HTTPS URLs. It enforces SSRF protection (including DNS-pin defense) via SafeHTTPClient and limits response body reads to 10 MiB. SEM@b554bb5371f70e0115912131e032671de29e8c09: content embedding source that fetches plain text from HTTP/HTTPS URLs with SSRF protection

func NewHTTPEmbeddingSource

func NewHTTPEmbeddingSource(ssrfValidator *URIValidator) *HTTPEmbeddingSource

NewHTTPEmbeddingSource creates a new HTTPEmbeddingSource with the given SSRF validator. SEM@80346558ce851de593c85a2d5660f92a649b1686: build an HTTPEmbeddingSource wired to an SSRF-safe HTTP client with OTel tracing

func (*HTTPEmbeddingSource) CanHandle

CanHandle returns true for entity references with an http:// or https:// URI. SEM@80346558ce851de593c85a2d5660f92a649b1686: report whether the entity reference URI uses an http or https scheme (pure)

func (*HTTPEmbeddingSource) Extract

Extract fetches the URL via the egress helper (DNS-pinned, SSRF-checked) and returns extracted plain text. HTML responses have tags stripped; other content types are returned as-is. SEM@80346558ce851de593c85a2d5660f92a649b1686: fetch a URL via SSRF-safe client and return extracted plain text content

func (*HTTPEmbeddingSource) Name

func (p *HTTPEmbeddingSource) Name() string

Name returns the provider name for logging. SEM@80346558ce851de593c85a2d5660f92a649b1686: return the provider's canonical name identifier (pure)

type HTTPSource

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

HTTPSource implements ContentSource for HTTP and HTTPS URIs. Outbound requests go through SafeHTTPClient which pins the validated IP at dial time (DNS-rebinding defense). Response bodies are capped at 50 MiB. SEM@b554bb5371f70e0115912131e032671de29e8c09: ContentSource that fetches HTTP/HTTPS URIs through an SSRF-safe HTTP client

func NewHTTPSource

func NewHTTPSource(ssrfValidator *URIValidator) *HTTPSource

NewHTTPSource creates a new HTTPSource with the given SSRF validator. SEM@b554bb5371f70e0115912131e032671de29e8c09: build an HTTPSource with SSRF validation, OTel instrumentation, and body size cap (pure)

func (*HTTPSource) CanHandle

func (s *HTTPSource) CanHandle(_ context.Context, uri string) bool

CanHandle returns true for URIs with an http:// or https:// scheme. SEM@7057b1db3902cd30e21b88d0e814025eff1c06f8: report whether the URI uses an http or https scheme (pure)

func (*HTTPSource) Fetch

func (s *HTTPSource) Fetch(ctx context.Context, uri string) ([]byte, string, error)

Fetch validates the URI against SSRF rules, fetches it via the egress helper (DNS-pinned), and returns the raw body bytes along with the Content-Type header value. Returns an error for non-2xx responses. SEM@b554bb5371f70e0115912131e032671de29e8c09: fetch a URI via the SSRF-safe HTTP client and return its body and content type

func (*HTTPSource) Name

func (s *HTTPSource) Name() string

Name returns the source name. SEM@b554bb5371f70e0115912131e032671de29e8c09: return the HTTP provider identifier string (pure)

type HandleOAuthCallbackParams

type HandleOAuthCallbackParams struct {
	// Code Authorization code from the OAuth provider
	Code CodeQueryParam `form:"code" json:"code"`

	// State CSRF protection state parameter. Recommended for security. Will be included in the callback response.
	State *StateQueryParam `form:"state,omitempty" json:"state,omitempty"`
}

HandleOAuthCallbackParams defines parameters for HandleOAuthCallback.

type HealthChecker

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

HealthChecker performs health checks on system components SEM@5775fac65ab5239fc263439d133089dda83af787: component that probes system dependencies within a configurable timeout (pure)

func NewHealthChecker

func NewHealthChecker(timeout time.Duration) *HealthChecker

NewHealthChecker creates a new health checker with the specified timeout SEM@5775fac65ab5239fc263439d133089dda83af787: build a HealthChecker with the given probe timeout (pure)

func (*HealthChecker) CheckHealth

func (h *HealthChecker) CheckHealth(ctx context.Context) SystemHealthResult

CheckHealth performs health checks on all system components SEM@034968fa0e0ba8c15e9af9052b475f4d5dd72d50: probe database and Redis health and return an aggregated system health result

type HistoryEntry

type HistoryEntry struct {
	SequenceNumber uint64
	OperationID    string
	UserID         string
	Timestamp      time.Time
	Operation      CellPatchOperation
	// State before this operation (for undo)
	PreviousState map[string]*DfdDiagram_Cells_Item
}

HistoryEntry represents a single operation in history SEM@be6cc4edcc9140493267132a7d584481845e0dfe: single recorded diagram cell operation with pre-state snapshot for undo (pure)

type HistoryOperationMessage

type HistoryOperationMessage struct {
	MessageType   MessageType `json:"message_type"`
	OperationType string      `json:"operation_type"`
	Message       string      `json:"message"`
}

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: WebSocket message carrying an undo or redo history operation notification (pure)

func (HistoryOperationMessage) GetMessageType

func (m HistoryOperationMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for HistoryOperationMessage (pure)

func (HistoryOperationMessage) Validate

func (m HistoryOperationMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a HistoryOperationMessage has correct type and undo/redo operation type (pure)

type HostResolver

type HostResolver interface {
	LookupHost(ctx context.Context, host string) ([]string, error)
}

HostResolver looks up the IPs for a hostname. Implementations must be safe for concurrent use. SEM@b554bb5371f70e0115912131e032671de29e8c09: interface for resolving a hostname to IP addresses, safe for concurrent use (pure)

type IPRateLimiter

type IPRateLimiter struct {
	SlidingWindowRateLimiter
	DefaultLimit         int // Requests per window (default: 10)
	DefaultWindowSeconds int // Window size in seconds (default: 60)
}

IPRateLimiter implements rate limiting based on IP address SEM@96060a8db0ddd49240156ad864036a242325d82e: sliding-window rate limiter keyed by IP address with configurable limit and window (mutates shared state)

func NewIPRateLimiter

func NewIPRateLimiter(redisClient *redis.Client) *IPRateLimiter

NewIPRateLimiter creates a new IP-based rate limiter SEM@96060a8db0ddd49240156ad864036a242325d82e: build an IP rate limiter backed by Redis with default 10 requests per 60-second window

func (*IPRateLimiter) CheckRateLimit

func (r *IPRateLimiter) CheckRateLimit(ctx context.Context, ipAddress string, limit int, windowSeconds int) (bool, int, error)

CheckRateLimit checks if an IP has exceeded its rate limit Returns allowed (bool), retryAfter (seconds), and error SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: validate whether an IP address is within its rate limit and return retry-after seconds (reads DB)

func (*IPRateLimiter) GetRateLimitInfo

func (r *IPRateLimiter) GetRateLimitInfo(ctx context.Context, ipAddress string, limit int, windowSeconds int) (remaining int, resetAt int64, err error)

GetRateLimitInfo returns current rate limit status for an IP SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: fetch remaining request quota and reset timestamp for an IP address (reads DB)

type IdentityLinkStartResponse

type IdentityLinkStartResponse struct {
	// AuthorizationUrl URL to redirect the user to for identity provider authorization (prompt=select_account)
	AuthorizationUrl string `json:"authorization_url"`

	// ExpiresAt When the link state expires (10 minutes from creation)
	ExpiresAt time.Time `json:"expires_at"`

	// LinkState Opaque state identifier for the link flow
	LinkState string `json:"link_state"`
}

IdentityLinkStartResponse defines model for IdentityLinkStartResponse.

type IdpPathParam

type IdpPathParam = string

IdpPathParam defines model for IdpPathParam.

type IdpQueryParam

type IdpQueryParam = string

IdpQueryParam defines model for IdpQueryParam.

type IfMatchHeader

type IfMatchHeader = int32

IfMatchHeader defines model for IfMatchHeader.

type InMemoryTicketStore

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

InMemoryTicketStore implements TicketStore using in-memory storage. SEM@c20da21da7db5dfa407cb89aae96e43a1e972644: in-memory TicketStore with background expiry cleanup (mutates shared state)

func NewInMemoryTicketStore

func NewInMemoryTicketStore() *InMemoryTicketStore

NewInMemoryTicketStore creates a new in-memory ticket store. SEM@c20da21da7db5dfa407cb89aae96e43a1e972644: build an InMemoryTicketStore and start its background expiry cleanup goroutine

func (*InMemoryTicketStore) Close

func (s *InMemoryTicketStore) Close()

Close stops the cleanup goroutine. SEM@c20da21da7db5dfa407cb89aae96e43a1e972644: stop the background cleanup goroutine for the ticket store

func (*InMemoryTicketStore) IssueTicket

func (s *InMemoryTicketStore) IssueTicket(_ context.Context, userID, provider, internalUUID, sessionID string, ttl time.Duration) (string, error)

IssueTicket creates a cryptographically random ticket bound to the given user, provider, internal UUID, and session. SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: generate a cryptographically random single-use ticket bound to a user session (mutates shared state)

func (*InMemoryTicketStore) ValidateTicket

func (s *InMemoryTicketStore) ValidateTicket(_ context.Context, ticket string) (string, string, string, string, error)

ValidateTicket validates and consumes a ticket. It is single-use: the ticket is deleted on first access. SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: consume and validate a single-use ticket, returning its bound identity claims (mutates shared state)

type IncludeDeletedQueryParam

type IncludeDeletedQueryParam = bool

IncludeDeletedQueryParam defines model for IncludeDeletedQueryParam.

type IngestEmbeddingsJSONRequestBody

type IngestEmbeddingsJSONRequestBody = EmbeddingIngestionRequest

IngestEmbeddingsJSONRequestBody defines body for IngestEmbeddings for application/json ContentType.

type InitiateSAMLLoginParams

type InitiateSAMLLoginParams struct {
	// ClientCallback Client callback URL where TMI should redirect after successful OAuth completion with tokens in URL fragment (#access_token=...). If not provided, tokens are returned as JSON response. Per OAuth 2.0 implicit flow spec, tokens are in fragments to prevent logging.
	ClientCallback *ClientCallbackQueryParam `form:"client_callback,omitempty" json:"client_callback,omitempty"`
}

InitiateSAMLLoginParams defines parameters for InitiateSAMLLogin.

type InternalAuditActor

type InternalAuditActor struct {
	Email       string `json:"email"`
	Provider    string `json:"provider"`
	ProviderID  string `json:"provider_id"`
	DisplayName string `json:"display_name"`
}

InternalAuditActor holds denormalized user information for audit entries in the internal service layer. Uses plain strings (not openapi_types). The generated AuditActor type from the OpenAPI spec is used for API responses. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: denormalized user identity for internal audit entries, avoiding generated API types (pure)

func ExtractAuditActor

func ExtractAuditActor(c *gin.Context) InternalAuditActor

ExtractAuditActor extracts denormalized user information from the Gin context for recording in audit entries. Uses the same context keys set by JWT middleware. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: extract denormalized user identity from Gin context for audit entries (pure)

type InternalServerError

type InternalServerError struct {
	// Error Error message describing what went wrong
	Error string `json:"error"`

	// RequestId Unique request identifier for troubleshooting
	RequestId *string `json:"request_id,omitempty"`
}

InternalServerError defines model for InternalServerError.

type InternalUuidPathParam

type InternalUuidPathParam = openapi_types.UUID

InternalUuidPathParam defines model for InternalUuidPathParam.

type IntrospectTokenFormdataRequestBody

type IntrospectTokenFormdataRequestBody = TokenIntrospectionRequest

IntrospectTokenFormdataRequestBody defines body for IntrospectToken for application/x-www-form-urlencoded ContentType.

type InvalidationEvent

type InvalidationEvent struct {
	EntityType    string
	EntityID      string
	ParentType    string
	ParentID      string
	OperationType string // create, update, delete
	Strategy      InvalidationStrategy
}

InvalidationEvent represents a cache invalidation event SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: descriptor for a cache invalidation event including entity, parent, operation, and strategy (pure)

type InvalidationStrategy

type InvalidationStrategy int

InvalidationStrategy defines different cache invalidation approaches SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: enum of cache invalidation timing strategies: immediate, async, or delayed (pure)

const (
	// InvalidateImmediately removes cache entries immediately
	InvalidateImmediately InvalidationStrategy = iota
	// InvalidateAsync removes cache entries asynchronously
	InvalidateAsync
	// InvalidateWithDelay removes cache entries after a short delay
	InvalidateWithDelay
)

type InvokeAddonJSONRequestBody

type InvokeAddonJSONRequestBody = InvokeAddonRequest

InvokeAddonJSONRequestBody defines body for InvokeAddon for application/json ContentType.

type InvokeAddonRequest

type InvokeAddonRequest struct {
	// Data User-provided data for the add-on (max 1KB JSON-serialized)
	Data *map[string]interface{} `json:"data,omitempty"`

	// ObjectId Optional: Specific object ID to operate on
	ObjectId *openapi_types.UUID `json:"object_id,omitempty"`

	// ObjectType Optional: Specific object type to operate on
	ObjectType *InvokeAddonRequestObjectType `json:"object_type,omitempty"`

	// ThreatModelId Threat model context for invocation
	ThreatModelId openapi_types.UUID `json:"threat_model_id"`
}

InvokeAddonRequest Request to invoke an addon with parameters and data

type InvokeAddonRequestObjectType

type InvokeAddonRequestObjectType string

InvokeAddonRequestObjectType Optional: Specific object type to operate on

const (
	InvokeAddonRequestObjectTypeAsset          InvokeAddonRequestObjectType = "asset"
	InvokeAddonRequestObjectTypeDiagram        InvokeAddonRequestObjectType = "diagram"
	InvokeAddonRequestObjectTypeDocument       InvokeAddonRequestObjectType = "document"
	InvokeAddonRequestObjectTypeMetadata       InvokeAddonRequestObjectType = "metadata"
	InvokeAddonRequestObjectTypeNote           InvokeAddonRequestObjectType = "note"
	InvokeAddonRequestObjectTypeRepository     InvokeAddonRequestObjectType = "repository"
	InvokeAddonRequestObjectTypeSurvey         InvokeAddonRequestObjectType = "survey"
	InvokeAddonRequestObjectTypeSurveyResponse InvokeAddonRequestObjectType = "survey_response"
	InvokeAddonRequestObjectTypeThreat         InvokeAddonRequestObjectType = "threat"
	InvokeAddonRequestObjectTypeThreatModel    InvokeAddonRequestObjectType = "threat_model"
)

Defines values for InvokeAddonRequestObjectType.

func (InvokeAddonRequestObjectType) Valid

Valid indicates whether the value is a known member of the InvokeAddonRequestObjectType enum.

type InvokeAddonResponse

type InvokeAddonResponse struct {
	// CreatedAt Invocation creation timestamp
	CreatedAt time.Time `json:"created_at"`

	// DeliveryId Delivery identifier for tracking
	DeliveryId openapi_types.UUID `json:"delivery_id"`

	// Status Current invocation status
	Status InvokeAddonResponseStatus `json:"status"`
}

InvokeAddonResponse Response from addon invocation including delivery ID

type InvokeAddonResponseStatus

type InvokeAddonResponseStatus string

InvokeAddonResponseStatus Current invocation status

const (
	InvokeAddonResponseStatusCompleted  InvokeAddonResponseStatus = "completed"
	InvokeAddonResponseStatusFailed     InvokeAddonResponseStatus = "failed"
	InvokeAddonResponseStatusInProgress InvokeAddonResponseStatus = "in_progress"
	InvokeAddonResponseStatusPending    InvokeAddonResponseStatus = "pending"
)

Defines values for InvokeAddonResponseStatus.

func (InvokeAddonResponseStatus) Valid

func (e InvokeAddonResponseStatus) Valid() bool

Valid indicates whether the value is a known member of the InvokeAddonResponseStatus enum.

type IsConfidentialQueryParam

type IsConfidentialQueryParam = bool

IsConfidentialQueryParam defines model for IsConfidentialQueryParam.

type IssueUriQueryParam

type IssueUriQueryParam = string

IssueUriQueryParam defines model for IssueUriQueryParam.

type JSONEmbeddingSource

type JSONEmbeddingSource struct{}

JSONEmbeddingSource extracts semantic text from DFD diagram JSON stored in DiagramStore. SEM@dd5e513aed5486dacac0dd6f321345e68c1b1efe: content provider that extracts semantic text from DFD diagram JSON in DiagramStore (pure)

func NewJSONEmbeddingSource

func NewJSONEmbeddingSource() *JSONEmbeddingSource

NewJSONEmbeddingSource creates a new JSONEmbeddingSource. SEM@80346558ce851de593c85a2d5660f92a649b1686: build a JSONEmbeddingSource content provider (pure)

func (*JSONEmbeddingSource) CanHandle

CanHandle returns true when the entity is a diagram with no external URI. SEM@80346558ce851de593c85a2d5660f92a649b1686: return true when the entity reference is a locally-stored diagram with no external URI (pure)

func (*JSONEmbeddingSource) Extract

Extract reads the diagram from DiagramStore and converts its cells to human-readable text. SEM@80346558ce851de593c85a2d5660f92a649b1686: convert a diagram's cells to human-readable text for semantic embedding (reads DB)

func (*JSONEmbeddingSource) Name

func (p *JSONEmbeddingSource) Name() string

Name returns the provider name for logging. SEM@80346558ce851de593c85a2d5660f92a649b1686: return the provider name identifier for logging (pure)

type JsonPatchDocument

type JsonPatchDocument = []struct {
	// Op Patch operation type
	Op JsonPatchDocumentOp `json:"op"`

	// Path JSON path to target
	Path string `json:"path"`

	// Value The value to use for add/replace/test operations. Can be any JSON value per RFC 6902 (string, number, boolean, object, array, or null).
	Value *JsonPatchDocument_Value `json:"value,omitempty"`
}

JsonPatchDocument JSON Patch document as defined in RFC 6902

type JsonPatchDocumentOp

type JsonPatchDocumentOp string

JsonPatchDocumentOp Patch operation type

const (
	Add     JsonPatchDocumentOp = "add"
	Copy    JsonPatchDocumentOp = "copy"
	Move    JsonPatchDocumentOp = "move"
	Remove  JsonPatchDocumentOp = "remove"
	Replace JsonPatchDocumentOp = "replace"
	Test    JsonPatchDocumentOp = "test"
)

Defines values for JsonPatchDocumentOp.

func (JsonPatchDocumentOp) Valid

func (e JsonPatchDocumentOp) Valid() bool

Valid indicates whether the value is a known member of the JsonPatchDocumentOp enum.

type JsonPatchDocumentValue0

type JsonPatchDocumentValue0 = string

JsonPatchDocumentValue0 defines model for .

type JsonPatchDocumentValue1

type JsonPatchDocumentValue1 = float32

JsonPatchDocumentValue1 defines model for .

type JsonPatchDocumentValue2

type JsonPatchDocumentValue2 = int

JsonPatchDocumentValue2 defines model for .

type JsonPatchDocumentValue3

type JsonPatchDocumentValue3 = bool

JsonPatchDocumentValue3 defines model for .

type JsonPatchDocumentValue4

type JsonPatchDocumentValue4 = map[string]interface{}

JsonPatchDocumentValue4 defines model for .

type JsonPatchDocumentValue5

type JsonPatchDocumentValue5 = []JsonPatchDocument_Value_5_Item

JsonPatchDocumentValue5 defines model for .

type JsonPatchDocumentValue50

type JsonPatchDocumentValue50 = string

JsonPatchDocumentValue50 defines model for .

type JsonPatchDocumentValue51

type JsonPatchDocumentValue51 = float32

JsonPatchDocumentValue51 defines model for .

type JsonPatchDocumentValue52

type JsonPatchDocumentValue52 = int

JsonPatchDocumentValue52 defines model for .

type JsonPatchDocumentValue53

type JsonPatchDocumentValue53 = bool

JsonPatchDocumentValue53 defines model for .

type JsonPatchDocumentValue54

type JsonPatchDocumentValue54 = map[string]interface{}

JsonPatchDocumentValue54 defines model for .

type JsonPatchDocument_Value

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

JsonPatchDocument_Value The value to use for add/replace/test operations. Can be any JSON value per RFC 6902 (string, number, boolean, object, array, or null).

func (JsonPatchDocument_Value) AsJsonPatchDocumentValue0

func (t JsonPatchDocument_Value) AsJsonPatchDocumentValue0() (JsonPatchDocumentValue0, error)

AsJsonPatchDocumentValue0 returns the union data inside the JsonPatchDocument_Value as a JsonPatchDocumentValue0

func (JsonPatchDocument_Value) AsJsonPatchDocumentValue1

func (t JsonPatchDocument_Value) AsJsonPatchDocumentValue1() (JsonPatchDocumentValue1, error)

AsJsonPatchDocumentValue1 returns the union data inside the JsonPatchDocument_Value as a JsonPatchDocumentValue1

func (JsonPatchDocument_Value) AsJsonPatchDocumentValue2

func (t JsonPatchDocument_Value) AsJsonPatchDocumentValue2() (JsonPatchDocumentValue2, error)

AsJsonPatchDocumentValue2 returns the union data inside the JsonPatchDocument_Value as a JsonPatchDocumentValue2

func (JsonPatchDocument_Value) AsJsonPatchDocumentValue3

func (t JsonPatchDocument_Value) AsJsonPatchDocumentValue3() (JsonPatchDocumentValue3, error)

AsJsonPatchDocumentValue3 returns the union data inside the JsonPatchDocument_Value as a JsonPatchDocumentValue3

func (JsonPatchDocument_Value) AsJsonPatchDocumentValue4

func (t JsonPatchDocument_Value) AsJsonPatchDocumentValue4() (JsonPatchDocumentValue4, error)

AsJsonPatchDocumentValue4 returns the union data inside the JsonPatchDocument_Value as a JsonPatchDocumentValue4

func (JsonPatchDocument_Value) AsJsonPatchDocumentValue5

func (t JsonPatchDocument_Value) AsJsonPatchDocumentValue5() (JsonPatchDocumentValue5, error)

AsJsonPatchDocumentValue5 returns the union data inside the JsonPatchDocument_Value as a JsonPatchDocumentValue5

func (*JsonPatchDocument_Value) FromJsonPatchDocumentValue0

func (t *JsonPatchDocument_Value) FromJsonPatchDocumentValue0(v JsonPatchDocumentValue0) error

FromJsonPatchDocumentValue0 overwrites any union data inside the JsonPatchDocument_Value as the provided JsonPatchDocumentValue0

func (*JsonPatchDocument_Value) FromJsonPatchDocumentValue1

func (t *JsonPatchDocument_Value) FromJsonPatchDocumentValue1(v JsonPatchDocumentValue1) error

FromJsonPatchDocumentValue1 overwrites any union data inside the JsonPatchDocument_Value as the provided JsonPatchDocumentValue1

func (*JsonPatchDocument_Value) FromJsonPatchDocumentValue2

func (t *JsonPatchDocument_Value) FromJsonPatchDocumentValue2(v JsonPatchDocumentValue2) error

FromJsonPatchDocumentValue2 overwrites any union data inside the JsonPatchDocument_Value as the provided JsonPatchDocumentValue2

func (*JsonPatchDocument_Value) FromJsonPatchDocumentValue3

func (t *JsonPatchDocument_Value) FromJsonPatchDocumentValue3(v JsonPatchDocumentValue3) error

FromJsonPatchDocumentValue3 overwrites any union data inside the JsonPatchDocument_Value as the provided JsonPatchDocumentValue3

func (*JsonPatchDocument_Value) FromJsonPatchDocumentValue4

func (t *JsonPatchDocument_Value) FromJsonPatchDocumentValue4(v JsonPatchDocumentValue4) error

FromJsonPatchDocumentValue4 overwrites any union data inside the JsonPatchDocument_Value as the provided JsonPatchDocumentValue4

func (*JsonPatchDocument_Value) FromJsonPatchDocumentValue5

func (t *JsonPatchDocument_Value) FromJsonPatchDocumentValue5(v JsonPatchDocumentValue5) error

FromJsonPatchDocumentValue5 overwrites any union data inside the JsonPatchDocument_Value as the provided JsonPatchDocumentValue5

func (JsonPatchDocument_Value) MarshalJSON

func (t JsonPatchDocument_Value) MarshalJSON() ([]byte, error)

func (*JsonPatchDocument_Value) MergeJsonPatchDocumentValue0

func (t *JsonPatchDocument_Value) MergeJsonPatchDocumentValue0(v JsonPatchDocumentValue0) error

MergeJsonPatchDocumentValue0 performs a merge with any union data inside the JsonPatchDocument_Value, using the provided JsonPatchDocumentValue0

func (*JsonPatchDocument_Value) MergeJsonPatchDocumentValue1

func (t *JsonPatchDocument_Value) MergeJsonPatchDocumentValue1(v JsonPatchDocumentValue1) error

MergeJsonPatchDocumentValue1 performs a merge with any union data inside the JsonPatchDocument_Value, using the provided JsonPatchDocumentValue1

func (*JsonPatchDocument_Value) MergeJsonPatchDocumentValue2

func (t *JsonPatchDocument_Value) MergeJsonPatchDocumentValue2(v JsonPatchDocumentValue2) error

MergeJsonPatchDocumentValue2 performs a merge with any union data inside the JsonPatchDocument_Value, using the provided JsonPatchDocumentValue2

func (*JsonPatchDocument_Value) MergeJsonPatchDocumentValue3

func (t *JsonPatchDocument_Value) MergeJsonPatchDocumentValue3(v JsonPatchDocumentValue3) error

MergeJsonPatchDocumentValue3 performs a merge with any union data inside the JsonPatchDocument_Value, using the provided JsonPatchDocumentValue3

func (*JsonPatchDocument_Value) MergeJsonPatchDocumentValue4

func (t *JsonPatchDocument_Value) MergeJsonPatchDocumentValue4(v JsonPatchDocumentValue4) error

MergeJsonPatchDocumentValue4 performs a merge with any union data inside the JsonPatchDocument_Value, using the provided JsonPatchDocumentValue4

func (*JsonPatchDocument_Value) MergeJsonPatchDocumentValue5

func (t *JsonPatchDocument_Value) MergeJsonPatchDocumentValue5(v JsonPatchDocumentValue5) error

MergeJsonPatchDocumentValue5 performs a merge with any union data inside the JsonPatchDocument_Value, using the provided JsonPatchDocumentValue5

func (*JsonPatchDocument_Value) UnmarshalJSON

func (t *JsonPatchDocument_Value) UnmarshalJSON(b []byte) error

type JsonPatchDocument_Value_5_Item

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

JsonPatchDocument_Value_5_Item Any JSON value (string, number, integer, boolean, object, or null)

func (JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue50

func (t JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue50() (JsonPatchDocumentValue50, error)

AsJsonPatchDocumentValue50 returns the union data inside the JsonPatchDocument_Value_5_Item as a JsonPatchDocumentValue50

func (JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue51

func (t JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue51() (JsonPatchDocumentValue51, error)

AsJsonPatchDocumentValue51 returns the union data inside the JsonPatchDocument_Value_5_Item as a JsonPatchDocumentValue51

func (JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue52

func (t JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue52() (JsonPatchDocumentValue52, error)

AsJsonPatchDocumentValue52 returns the union data inside the JsonPatchDocument_Value_5_Item as a JsonPatchDocumentValue52

func (JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue53

func (t JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue53() (JsonPatchDocumentValue53, error)

AsJsonPatchDocumentValue53 returns the union data inside the JsonPatchDocument_Value_5_Item as a JsonPatchDocumentValue53

func (JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue54

func (t JsonPatchDocument_Value_5_Item) AsJsonPatchDocumentValue54() (JsonPatchDocumentValue54, error)

AsJsonPatchDocumentValue54 returns the union data inside the JsonPatchDocument_Value_5_Item as a JsonPatchDocumentValue54

func (*JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue50

func (t *JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue50(v JsonPatchDocumentValue50) error

FromJsonPatchDocumentValue50 overwrites any union data inside the JsonPatchDocument_Value_5_Item as the provided JsonPatchDocumentValue50

func (*JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue51

func (t *JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue51(v JsonPatchDocumentValue51) error

FromJsonPatchDocumentValue51 overwrites any union data inside the JsonPatchDocument_Value_5_Item as the provided JsonPatchDocumentValue51

func (*JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue52

func (t *JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue52(v JsonPatchDocumentValue52) error

FromJsonPatchDocumentValue52 overwrites any union data inside the JsonPatchDocument_Value_5_Item as the provided JsonPatchDocumentValue52

func (*JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue53

func (t *JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue53(v JsonPatchDocumentValue53) error

FromJsonPatchDocumentValue53 overwrites any union data inside the JsonPatchDocument_Value_5_Item as the provided JsonPatchDocumentValue53

func (*JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue54

func (t *JsonPatchDocument_Value_5_Item) FromJsonPatchDocumentValue54(v JsonPatchDocumentValue54) error

FromJsonPatchDocumentValue54 overwrites any union data inside the JsonPatchDocument_Value_5_Item as the provided JsonPatchDocumentValue54

func (JsonPatchDocument_Value_5_Item) MarshalJSON

func (t JsonPatchDocument_Value_5_Item) MarshalJSON() ([]byte, error)

func (*JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue50

func (t *JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue50(v JsonPatchDocumentValue50) error

MergeJsonPatchDocumentValue50 performs a merge with any union data inside the JsonPatchDocument_Value_5_Item, using the provided JsonPatchDocumentValue50

func (*JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue51

func (t *JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue51(v JsonPatchDocumentValue51) error

MergeJsonPatchDocumentValue51 performs a merge with any union data inside the JsonPatchDocument_Value_5_Item, using the provided JsonPatchDocumentValue51

func (*JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue52

func (t *JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue52(v JsonPatchDocumentValue52) error

MergeJsonPatchDocumentValue52 performs a merge with any union data inside the JsonPatchDocument_Value_5_Item, using the provided JsonPatchDocumentValue52

func (*JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue53

func (t *JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue53(v JsonPatchDocumentValue53) error

MergeJsonPatchDocumentValue53 performs a merge with any union data inside the JsonPatchDocument_Value_5_Item, using the provided JsonPatchDocumentValue53

func (*JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue54

func (t *JsonPatchDocument_Value_5_Item) MergeJsonPatchDocumentValue54(v JsonPatchDocumentValue54) error

MergeJsonPatchDocumentValue54 performs a merge with any union data inside the JsonPatchDocument_Value_5_Item, using the provided JsonPatchDocumentValue54

func (*JsonPatchDocument_Value_5_Item) UnmarshalJSON

func (t *JsonPatchDocument_Value_5_Item) UnmarshalJSON(b []byte) error

type LLMQueryDecomposer

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

LLMQueryDecomposer implements QueryDecomposer using an LLM. SEM@f06df1eae94dd2ca361cfb88f9f58fdc2bbfced6: LLM-backed implementation of QueryDecomposer

func NewLLMQueryDecomposer

func NewLLMQueryDecomposer(llm DecomposerLLM) *LLMQueryDecomposer

NewLLMQueryDecomposer creates a new LLMQueryDecomposer backed by the given LLM. SEM@f06df1eae94dd2ca361cfb88f9f58fdc2bbfced6: build a new LLMQueryDecomposer backed by the given LLM client (pure)

func (*LLMQueryDecomposer) Decompose

func (d *LLMQueryDecomposer) Decompose(ctx context.Context, query string, hasCodeIndex bool) (*DecomposedQuery, error)

Decompose sends the query to the LLM and returns optimized sub-queries. On any LLM or parse error it logs a warning and returns a safe fallback using the original query for both sub-queries. SEM@f06df1eae94dd2ca361cfb88f9f58fdc2bbfced6: decompose a user query into optimized text and code sub-queries via LLM, falling back to the original query on error

type LastLoginAfterQueryParam

type LastLoginAfterQueryParam = time.Time

LastLoginAfterQueryParam defines model for LastLoginAfterQueryParam.

type LastLoginBeforeQueryParam

type LastLoginBeforeQueryParam = time.Time

LastLoginBeforeQueryParam defines model for LastLoginBeforeQueryParam.

type LimitQueryParam

type LimitQueryParam = int

LimitQueryParam defines model for LimitQueryParam.

type LinkedIdentity

type LinkedIdentity struct {
	// Email Cached email address from provider (display only)
	Email *openapi_types.Email `json:"email,omitempty"`

	// Id Linked identity unique identifier
	Id openapi_types.UUID `json:"id"`

	// LastUsedAt When this identity was last used to sign in
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`

	// LinkedAt When this identity was linked
	LinkedAt time.Time `json:"linked_at"`

	// Name Cached display name from provider
	Name *string `json:"name,omitempty"`

	// Provider Identity provider ID
	Provider string `json:"provider"`

	// ProviderUserId User identifier at the provider (truncated for display)
	ProviderUserId string `json:"provider_user_id"`
}

LinkedIdentity defines model for LinkedIdentity.

type LinkedProviderChecker

type LinkedProviderChecker interface {
	HasActiveToken(ctx context.Context, userID, providerID string) bool
}

LinkedProviderChecker reports whether a user has an active (non-failed) linked token for a given provider. Implementations typically consult the ContentTokenRepository. SEM@faff1a18afeac13e5f8de0f7b7b2e16ba77529af: interface for checking whether a user has an active linked token for a provider

type ListAddonInvocationQuotasParams

type ListAddonInvocationQuotasParams struct {
	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`
}

ListAddonInvocationQuotasParams defines parameters for ListAddonInvocationQuotas.

type ListAddonQuotasResponse

type ListAddonQuotasResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int                    `json:"offset"`
	Quotas []AddonInvocationQuota `json:"quotas"`

	// Total Total number of quotas matching criteria
	Total int `json:"total"`
}

ListAddonQuotasResponse Paginated list of addon quotas

type ListAddonsParams

type ListAddonsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// ThreatModelId Filter subscriptions by threat model ID
	ThreatModelId *ThreatModelIdQueryParam `form:"threat_model_id,omitempty" json:"threat_model_id,omitempty"`
}

ListAddonsParams defines parameters for ListAddons.

type ListAddonsResponse

type ListAddonsResponse struct {
	Addons []AddonResponse `json:"addons"`

	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of add-ons matching criteria
	Total int `json:"total"`
}

ListAddonsResponse Paginated list of registered addons

type ListAdminAuditEntriesResponse

type ListAdminAuditEntriesResponse struct {
	Entries []AuditEntry `json:"entries"`

	// Limit Page size used.
	Limit int `json:"limit"`

	// NextCursor Cursor for the next page; absent or null when exhausted.
	NextCursor *string `json:"next_cursor,omitempty"`

	// PrevCursor Cursor for the previous (newer) page; absent or null when at the newest end.
	PrevCursor *string `json:"prev_cursor,omitempty"`

	// Total Total entries matching the filter.
	Total int `json:"total"`
}

ListAdminAuditEntriesResponse Cursor-paginated cross-threat-model list of audit entries.

type ListAdminGroupsParams

type ListAdminGroupsParams struct {
	// Provider Filter by OAuth/SAML provider
	Provider *ProviderQueryParam `form:"provider,omitempty" json:"provider,omitempty"`

	// GroupName Filter by group name (case-insensitive substring match)
	GroupName *GroupNameQueryParam `form:"group_name,omitempty" json:"group_name,omitempty"`

	// UsedInAuthorizations Filter groups used (true) or not used (false) in authorizations
	UsedInAuthorizations *UsedInAuthorizationsQueryParam `form:"used_in_authorizations,omitempty" json:"used_in_authorizations,omitempty"`

	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`

	// SortBy Field to sort by
	SortBy *ListAdminGroupsParamsSortBy `form:"sort_by,omitempty" json:"sort_by,omitempty"`

	// SortOrder Sort direction
	SortOrder *ListAdminGroupsParamsSortOrder `form:"sort_order,omitempty" json:"sort_order,omitempty"`
}

ListAdminGroupsParams defines parameters for ListAdminGroups.

type ListAdminGroupsParamsSortBy

type ListAdminGroupsParamsSortBy string

ListAdminGroupsParamsSortBy defines parameters for ListAdminGroups.

const (
	ListAdminGroupsParamsSortByCreatedAt ListAdminGroupsParamsSortBy = "created_at"
	ListAdminGroupsParamsSortByEmail     ListAdminGroupsParamsSortBy = "email"
	ListAdminGroupsParamsSortByLastLogin ListAdminGroupsParamsSortBy = "last_login"
	ListAdminGroupsParamsSortByName      ListAdminGroupsParamsSortBy = "name"
)

Defines values for ListAdminGroupsParamsSortBy.

func (ListAdminGroupsParamsSortBy) Valid

Valid indicates whether the value is a known member of the ListAdminGroupsParamsSortBy enum.

type ListAdminGroupsParamsSortOrder

type ListAdminGroupsParamsSortOrder string

ListAdminGroupsParamsSortOrder defines parameters for ListAdminGroups.

const (
	ListAdminGroupsParamsSortOrderAsc  ListAdminGroupsParamsSortOrder = "asc"
	ListAdminGroupsParamsSortOrderDesc ListAdminGroupsParamsSortOrder = "desc"
)

Defines values for ListAdminGroupsParamsSortOrder.

func (ListAdminGroupsParamsSortOrder) Valid

Valid indicates whether the value is a known member of the ListAdminGroupsParamsSortOrder enum.

type ListAdminSurveysParams

type ListAdminSurveysParams struct {
	// Status Filter by survey status
	Status *SurveyStatusQueryParam `form:"status,omitempty" json:"status,omitempty"`

	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// Sort Sort order (e.g., created_at:desc, name:asc, severity:desc, score:desc)
	Sort *SortQueryParam `form:"sort,omitempty" json:"sort,omitempty"`

	// CreatedAfter Filter results created after this timestamp (ISO 8601)
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601)
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601)
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601)
	ModifiedBefore *ModifiedBefore `form:"modified_before,omitempty" json:"modified_before,omitempty"`
}

ListAdminSurveysParams defines parameters for ListAdminSurveys.

type ListAdminThreatModelAuditEntriesParams

type ListAdminThreatModelAuditEntriesParams struct {
	// ActorEmail Filter by actor email
	ActorEmail *AuditActorEmail `form:"actor_email,omitempty" json:"actor_email,omitempty"`

	// ActorProvider Filter by the actor identity provider.
	ActorProvider *AuditActorProvider `form:"actor_provider,omitempty" json:"actor_provider,omitempty"`

	// CreatedAfter Return only records created after this RFC 3339 timestamp.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp.
	CreatedBefore *CreatedBeforeQueryParam `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ChangeType Filter by change type
	ChangeType *ListAdminThreatModelAuditEntriesParamsChangeType `form:"change_type,omitempty" json:"change_type,omitempty"`

	// ObjectType Filter by object type
	ObjectType *ListAdminThreatModelAuditEntriesParamsObjectType `form:"object_type,omitempty" json:"object_type,omitempty"`

	// ThreatModelId Filter audit entries to a single threat model.
	ThreatModelId *AuditThreatModelId `form:"threat_model_id,omitempty" json:"threat_model_id,omitempty"`

	// Limit Maximum number of entries to return per page.
	Limit *AuditPageLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Cursor Opaque pagination cursor from the previous page next_cursor. Omit for the first page.
	Cursor *AuditCursor `form:"cursor,omitempty" json:"cursor,omitempty"`

	// Around Return a page centered on this entry id (~half newer, ~half older, entry included). Mutually exclusive with cursor.
	Around *AuditAround `form:"around,omitempty" json:"around,omitempty"`
}

ListAdminThreatModelAuditEntriesParams defines parameters for ListAdminThreatModelAuditEntries.

type ListAdminThreatModelAuditEntriesParamsChangeType

type ListAdminThreatModelAuditEntriesParamsChangeType string

ListAdminThreatModelAuditEntriesParamsChangeType defines parameters for ListAdminThreatModelAuditEntries.

const (
	ListAdminThreatModelAuditEntriesParamsChangeTypeCreated    ListAdminThreatModelAuditEntriesParamsChangeType = "created"
	ListAdminThreatModelAuditEntriesParamsChangeTypeDeleted    ListAdminThreatModelAuditEntriesParamsChangeType = "deleted"
	ListAdminThreatModelAuditEntriesParamsChangeTypePatched    ListAdminThreatModelAuditEntriesParamsChangeType = "patched"
	ListAdminThreatModelAuditEntriesParamsChangeTypeRestored   ListAdminThreatModelAuditEntriesParamsChangeType = "restored"
	ListAdminThreatModelAuditEntriesParamsChangeTypeRolledBack ListAdminThreatModelAuditEntriesParamsChangeType = "rolled_back"
	ListAdminThreatModelAuditEntriesParamsChangeTypeUpdated    ListAdminThreatModelAuditEntriesParamsChangeType = "updated"
)

Defines values for ListAdminThreatModelAuditEntriesParamsChangeType.

func (ListAdminThreatModelAuditEntriesParamsChangeType) Valid

Valid indicates whether the value is a known member of the ListAdminThreatModelAuditEntriesParamsChangeType enum.

type ListAdminThreatModelAuditEntriesParamsObjectType

type ListAdminThreatModelAuditEntriesParamsObjectType string

ListAdminThreatModelAuditEntriesParamsObjectType defines parameters for ListAdminThreatModelAuditEntries.

const (
	ListAdminThreatModelAuditEntriesParamsObjectTypeAsset       ListAdminThreatModelAuditEntriesParamsObjectType = "asset"
	ListAdminThreatModelAuditEntriesParamsObjectTypeDiagram     ListAdminThreatModelAuditEntriesParamsObjectType = "diagram"
	ListAdminThreatModelAuditEntriesParamsObjectTypeDocument    ListAdminThreatModelAuditEntriesParamsObjectType = "document"
	ListAdminThreatModelAuditEntriesParamsObjectTypeNote        ListAdminThreatModelAuditEntriesParamsObjectType = "note"
	ListAdminThreatModelAuditEntriesParamsObjectTypeRepository  ListAdminThreatModelAuditEntriesParamsObjectType = "repository"
	ListAdminThreatModelAuditEntriesParamsObjectTypeThreat      ListAdminThreatModelAuditEntriesParamsObjectType = "threat"
	ListAdminThreatModelAuditEntriesParamsObjectTypeThreatModel ListAdminThreatModelAuditEntriesParamsObjectType = "threat_model"
)

Defines values for ListAdminThreatModelAuditEntriesParamsObjectType.

func (ListAdminThreatModelAuditEntriesParamsObjectType) Valid

Valid indicates whether the value is a known member of the ListAdminThreatModelAuditEntriesParamsObjectType enum.

type ListAdminUserClientCredentialsParams

type ListAdminUserClientCredentialsParams struct {
	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`
}

ListAdminUserClientCredentialsParams defines parameters for ListAdminUserClientCredentials.

type ListAdminUsersParams

type ListAdminUsersParams struct {
	// Provider Filter by OAuth/SAML provider
	Provider *ProviderQueryParam `form:"provider,omitempty" json:"provider,omitempty"`

	// Email Filter by email (case-insensitive substring match)
	Email *EmailQueryParam `form:"email,omitempty" json:"email,omitempty"`

	// Name Filter by name (case-insensitive substring match)
	Name *NameQueryParam `form:"name,omitempty" json:"name,omitempty"`

	// CreatedAfter Return only records created after this RFC 3339 timestamp.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp.
	CreatedBefore *CreatedBeforeQueryParam `form:"created_before,omitempty" json:"created_before,omitempty"`

	// LastLoginAfter Filter users who logged in after this timestamp (RFC3339)
	LastLoginAfter *LastLoginAfterQueryParam `form:"last_login_after,omitempty" json:"last_login_after,omitempty"`

	// LastLoginBefore Filter users who logged in before this timestamp (RFC3339)
	LastLoginBefore *LastLoginBeforeQueryParam `form:"last_login_before,omitempty" json:"last_login_before,omitempty"`

	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`

	// SortBy Field to sort by
	SortBy *ListAdminUsersParamsSortBy `form:"sort_by,omitempty" json:"sort_by,omitempty"`

	// SortOrder Sort direction
	SortOrder *ListAdminUsersParamsSortOrder `form:"sort_order,omitempty" json:"sort_order,omitempty"`

	// Automation Filter by automation account status. True returns only automation accounts, false returns only non-automation accounts.
	Automation *AutomationQueryParam `form:"automation,omitempty" json:"automation,omitempty"`
}

ListAdminUsersParams defines parameters for ListAdminUsers.

type ListAdminUsersParamsSortBy

type ListAdminUsersParamsSortBy string

ListAdminUsersParamsSortBy defines parameters for ListAdminUsers.

const (
	CreatedAt ListAdminUsersParamsSortBy = "created_at"
	Email     ListAdminUsersParamsSortBy = "email"
	LastLogin ListAdminUsersParamsSortBy = "last_login"
	Name      ListAdminUsersParamsSortBy = "name"
)

Defines values for ListAdminUsersParamsSortBy.

func (ListAdminUsersParamsSortBy) Valid

func (e ListAdminUsersParamsSortBy) Valid() bool

Valid indicates whether the value is a known member of the ListAdminUsersParamsSortBy enum.

type ListAdminUsersParamsSortOrder

type ListAdminUsersParamsSortOrder string

ListAdminUsersParamsSortOrder defines parameters for ListAdminUsers.

const (
	Asc  ListAdminUsersParamsSortOrder = "asc"
	Desc ListAdminUsersParamsSortOrder = "desc"
)

Defines values for ListAdminUsersParamsSortOrder.

func (ListAdminUsersParamsSortOrder) Valid

Valid indicates whether the value is a known member of the ListAdminUsersParamsSortOrder enum.

type ListAssetsResponse

type ListAssetsResponse struct {
	Assets []Asset `json:"assets"`

	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of assets matching criteria
	Total int `json:"total"`
}

ListAssetsResponse Paginated list of assets

type ListAuditTrailResponse

type ListAuditTrailResponse struct {
	AuditEntries []AuditEntry `json:"audit_entries"`

	// Limit Maximum number of entries returned
	Limit int `json:"limit"`

	// Offset Offset from the beginning of the result set
	Offset int `json:"offset"`

	// Total Total number of matching audit entries
	Total int `json:"total"`
}

ListAuditTrailResponse Paginated list of audit trail entries

type ListClientCredentialsResponse

type ListClientCredentialsResponse struct {
	Credentials []ClientCredentialInfo `json:"credentials"`

	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of credentials matching criteria
	Total int `json:"total"`
}

ListClientCredentialsResponse Paginated list of client credentials

type ListContentFeedbackParams

type ListContentFeedbackParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset              *OffsetQueryParam                             `form:"offset,omitempty" json:"offset,omitempty"`
	TargetType          *ListContentFeedbackParamsTargetType          `form:"target_type,omitempty" json:"target_type,omitempty"`
	TargetId            *openapi_types.UUID                           `form:"target_id,omitempty" json:"target_id,omitempty"`
	Sentiment           *ListContentFeedbackParamsSentiment           `form:"sentiment,omitempty" json:"sentiment,omitempty"`
	FalsePositiveReason *ListContentFeedbackParamsFalsePositiveReason `form:"false_positive_reason,omitempty" json:"false_positive_reason,omitempty"`
}

ListContentFeedbackParams defines parameters for ListContentFeedback.

type ListContentFeedbackParamsFalsePositiveReason

type ListContentFeedbackParamsFalsePositiveReason string

ListContentFeedbackParamsFalsePositiveReason defines parameters for ListContentFeedback.

const (
	AlreadyRemediated     ListContentFeedbackParamsFalsePositiveReason = "already_remediated"
	DetectionMisfired     ListContentFeedbackParamsFalsePositiveReason = "detection_misfired"
	DetectionRuleFlawed   ListContentFeedbackParamsFalsePositiveReason = "detection_rule_flawed"
	Duplicate             ListContentFeedbackParamsFalsePositiveReason = "duplicate"
	IntendedBehavior      ListContentFeedbackParamsFalsePositiveReason = "intended_behavior"
	OutOfScope            ListContentFeedbackParamsFalsePositiveReason = "out_of_scope"
	RealButMitigated      ListContentFeedbackParamsFalsePositiveReason = "real_but_mitigated"
	RealButNotExploitable ListContentFeedbackParamsFalsePositiveReason = "real_but_not_exploitable"
)

Defines values for ListContentFeedbackParamsFalsePositiveReason.

func (ListContentFeedbackParamsFalsePositiveReason) Valid

Valid indicates whether the value is a known member of the ListContentFeedbackParamsFalsePositiveReason enum.

type ListContentFeedbackParamsSentiment

type ListContentFeedbackParamsSentiment string

ListContentFeedbackParamsSentiment defines parameters for ListContentFeedback.

const (
	ListContentFeedbackParamsSentimentDown ListContentFeedbackParamsSentiment = "down"
	ListContentFeedbackParamsSentimentUp   ListContentFeedbackParamsSentiment = "up"
)

Defines values for ListContentFeedbackParamsSentiment.

func (ListContentFeedbackParamsSentiment) Valid

Valid indicates whether the value is a known member of the ListContentFeedbackParamsSentiment enum.

type ListContentFeedbackParamsTargetType

type ListContentFeedbackParamsTargetType string

ListContentFeedbackParamsTargetType defines parameters for ListContentFeedback.

const (
	ListContentFeedbackParamsTargetTypeDiagram              ListContentFeedbackParamsTargetType = "diagram"
	ListContentFeedbackParamsTargetTypeNote                 ListContentFeedbackParamsTargetType = "note"
	ListContentFeedbackParamsTargetTypeThreat               ListContentFeedbackParamsTargetType = "threat"
	ListContentFeedbackParamsTargetTypeThreatClassification ListContentFeedbackParamsTargetType = "threat_classification"
)

Defines values for ListContentFeedbackParamsTargetType.

func (ListContentFeedbackParamsTargetType) Valid

Valid indicates whether the value is a known member of the ListContentFeedbackParamsTargetType enum.

type ListCurrentUserClientCredentialsParams

type ListCurrentUserClientCredentialsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

ListCurrentUserClientCredentialsParams defines parameters for ListCurrentUserClientCredentials.

type ListDiagramsResponse

type ListDiagramsResponse struct {
	Diagrams []DiagramListItem `json:"diagrams"`

	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of diagrams matching criteria
	Total int `json:"total"`
}

ListDiagramsResponse Paginated list of diagrams

type ListDocumentsResponse

type ListDocumentsResponse struct {
	Documents []Document `json:"documents"`

	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of documents matching criteria
	Total int `json:"total"`
}

ListDocumentsResponse Paginated list of documents

type ListGroupMembersParams

type ListGroupMembersParams struct {
	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`
}

ListGroupMembersParams defines parameters for ListGroupMembers.

type ListIntakeSurveyResponseTriageNotesParams

type ListIntakeSurveyResponseTriageNotesParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

ListIntakeSurveyResponseTriageNotesParams defines parameters for ListIntakeSurveyResponseTriageNotes.

type ListIntakeSurveyResponsesParams

type ListIntakeSurveyResponsesParams struct {
	// Status Filter by response status. Supports comma-separated values for multi-status filtering (e.g., status=submitted,ready_for_review).
	Status *SurveyResponseStatusQueryParam `form:"status,omitempty" json:"status,omitempty"`

	// SurveyId Filter by survey ID
	SurveyId *SurveyIdQueryParam `form:"survey_id,omitempty" json:"survey_id,omitempty"`

	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// Sort Sort order (e.g., created_at:desc, name:asc, severity:desc, score:desc)
	Sort *SortQueryParam `form:"sort,omitempty" json:"sort,omitempty"`

	// CreatedAfter Filter results created after this timestamp (ISO 8601)
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601)
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601)
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601)
	ModifiedBefore *ModifiedBefore `form:"modified_before,omitempty" json:"modified_before,omitempty"`
}

ListIntakeSurveyResponsesParams defines parameters for ListIntakeSurveyResponses.

type ListIntakeSurveysParams

type ListIntakeSurveysParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// CreatedAfter Filter results created after this timestamp (ISO 8601)
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601)
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601)
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601)
	ModifiedBefore *ModifiedBefore `form:"modified_before,omitempty" json:"modified_before,omitempty"`
}

ListIntakeSurveysParams defines parameters for ListIntakeSurveys.

type ListMyGroupMembersParams

type ListMyGroupMembersParams struct {
	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`
}

ListMyGroupMembersParams defines parameters for ListMyGroupMembers.

type ListNotesResponse

type ListNotesResponse struct {
	// Limit Pagination limit
	Limit int            `json:"limit"`
	Notes []NoteListItem `json:"notes"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of notes matching criteria
	Total int `json:"total"`
}

ListNotesResponse Paginated list of notes

type ListProjectNotesParams

type ListProjectNotesParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

ListProjectNotesParams defines parameters for ListProjectNotes.

type ListProjectNotesResponse

type ListProjectNotesResponse struct {
	// Limit Pagination limit
	Limit int                   `json:"limit"`
	Notes []ProjectNoteListItem `json:"notes"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of project notes matching criteria
	Total int `json:"total"`
}

ListProjectNotesResponse Paginated list of project notes

type ListProjectsParams

type ListProjectsParams struct {
	// Limit Maximum number of results per page
	Limit *int `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *int `form:"offset,omitempty" json:"offset,omitempty"`

	// Name Filter by project name (partial match)
	Name *string `form:"name,omitempty" json:"name,omitempty"`

	// Status Filter by status (exact match, comma-separated for multiple)
	Status *string `form:"status,omitempty" json:"status,omitempty"`

	// TeamId Filter by team
	TeamId *openapi_types.UUID `form:"team_id,omitempty" json:"team_id,omitempty"`

	// RelatedTo Include projects related to this project ID
	RelatedTo *openapi_types.UUID `form:"related_to,omitempty" json:"related_to,omitempty"`

	// Relationship Filter related projects by relationship type. Only used with related_to.
	Relationship *RelationshipType `form:"relationship,omitempty" json:"relationship,omitempty"`

	// Transitive When true with related_to + relationship, follow parent/child chains transitively (max depth 10)
	Transitive *bool `form:"transitive,omitempty" json:"transitive,omitempty"`
}

ListProjectsParams defines parameters for ListProjects.

type ListProjectsResponse

type ListProjectsResponse struct {
	// Limit Maximum number of results per page
	Limit int `json:"limit"`

	// Offset Number of results skipped
	Offset   int               `json:"offset"`
	Projects []ProjectListItem `json:"projects"`

	// Total Total number of projects matching the filter
	Total int `json:"total"`
}

ListProjectsResponse Paginated list of projects

type ListRepositoriesResponse

type ListRepositoriesResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset       int          `json:"offset"`
	Repositories []Repository `json:"repositories"`

	// Total Total number of repositories matching criteria
	Total int `json:"total"`
}

ListRepositoriesResponse Paginated list of repositories

type ListSurveyResponsesResponse

type ListSurveyResponsesResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset          int                      `json:"offset"`
	SurveyResponses []SurveyResponseListItem `json:"survey_responses"`

	// Total Total number of responses matching criteria
	Total int `json:"total"`
}

ListSurveyResponsesResponse Paginated list of survey responses

type ListSurveysResponse

type ListSurveysResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset  int              `json:"offset"`
	Surveys []SurveyListItem `json:"surveys"`

	// Total Total number of surveys matching criteria
	Total int `json:"total"`
}

ListSurveysResponse Paginated list of surveys

type ListSystemAuditEntriesParams

type ListSystemAuditEntriesParams struct {
	// ActorEmail Filter by actor email
	ActorEmail *AuditActorEmail `form:"actor_email,omitempty" json:"actor_email,omitempty"`

	// ActorProvider Filter by the actor identity provider.
	ActorProvider *AuditActorProvider `form:"actor_provider,omitempty" json:"actor_provider,omitempty"`

	// CreatedAfter Return only records created after this RFC 3339 timestamp.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp.
	CreatedBefore *CreatedBeforeQueryParam `form:"created_before,omitempty" json:"created_before,omitempty"`

	// HttpMethod Filter system audit entries by HTTP method.
	HttpMethod *ListSystemAuditEntriesParamsHttpMethod `form:"http_method,omitempty" json:"http_method,omitempty"`

	// PathPrefix Filter system audit entries whose request path starts with this prefix (matched literally).
	PathPrefix *AuditPathPrefix `form:"path_prefix,omitempty" json:"path_prefix,omitempty"`

	// FieldPath Filter system audit entries by exact field path.
	FieldPath *AuditFieldPath `form:"field_path,omitempty" json:"field_path,omitempty"`

	// Limit Maximum number of entries to return per page.
	Limit *AuditPageLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Cursor Opaque pagination cursor from the previous page next_cursor. Omit for the first page.
	Cursor *AuditCursor `form:"cursor,omitempty" json:"cursor,omitempty"`

	// Around Return a page centered on this entry id (~half newer, ~half older, entry included). Mutually exclusive with cursor.
	Around *AuditAround `form:"around,omitempty" json:"around,omitempty"`
}

ListSystemAuditEntriesParams defines parameters for ListSystemAuditEntries.

type ListSystemAuditEntriesParamsHttpMethod

type ListSystemAuditEntriesParamsHttpMethod string

ListSystemAuditEntriesParamsHttpMethod defines parameters for ListSystemAuditEntries.

const (
	ListSystemAuditEntriesParamsHttpMethodDELETE ListSystemAuditEntriesParamsHttpMethod = "DELETE"
	ListSystemAuditEntriesParamsHttpMethodPATCH  ListSystemAuditEntriesParamsHttpMethod = "PATCH"
	ListSystemAuditEntriesParamsHttpMethodPOST   ListSystemAuditEntriesParamsHttpMethod = "POST"
	ListSystemAuditEntriesParamsHttpMethodPUT    ListSystemAuditEntriesParamsHttpMethod = "PUT"
)

Defines values for ListSystemAuditEntriesParamsHttpMethod.

func (ListSystemAuditEntriesParamsHttpMethod) Valid

Valid indicates whether the value is a known member of the ListSystemAuditEntriesParamsHttpMethod enum.

type ListSystemAuditEntriesResponse

type ListSystemAuditEntriesResponse struct {
	Entries []SystemAuditEntry `json:"entries"`

	// Limit Page size used.
	Limit int `json:"limit"`

	// NextCursor Cursor for the next page; absent or null when exhausted.
	NextCursor *string `json:"next_cursor,omitempty"`

	// PrevCursor Cursor for the previous (newer) page; absent or null when at the newest end.
	PrevCursor *string `json:"prev_cursor,omitempty"`

	// Total Total entries matching the filter.
	Total int `json:"total"`
}

ListSystemAuditEntriesResponse Cursor-paginated list of system audit entries.

type ListTeamNotesParams

type ListTeamNotesParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

ListTeamNotesParams defines parameters for ListTeamNotes.

type ListTeamNotesResponse

type ListTeamNotesResponse struct {
	// Limit Pagination limit
	Limit int                `json:"limit"`
	Notes []TeamNoteListItem `json:"notes"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of team notes matching criteria
	Total int `json:"total"`
}

ListTeamNotesResponse Paginated list of team notes

type ListTeamsParams

type ListTeamsParams struct {
	// Limit Maximum number of results per page
	Limit *int `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *int `form:"offset,omitempty" json:"offset,omitempty"`

	// Name Filter by team name (partial match)
	Name *string `form:"name,omitempty" json:"name,omitempty"`

	// Status Filter by team lifecycle status (exact match, comma-separated for multiple). Valid values: active, on_hold, winding_down, archived, forming, merging, splitting
	Status *string `form:"status,omitempty" json:"status,omitempty"`

	// MemberUserId Filter teams that include this user as a member
	MemberUserId *openapi_types.UUID `form:"member_user_id,omitempty" json:"member_user_id,omitempty"`

	// RelatedTo Include teams related to this team ID
	RelatedTo *openapi_types.UUID `form:"related_to,omitempty" json:"related_to,omitempty"`

	// Relationship Filter related teams by relationship type. Only used with related_to.
	Relationship *RelationshipType `form:"relationship,omitempty" json:"relationship,omitempty"`

	// Transitive When true with related_to + relationship, follow parent/child chains transitively (max depth 10)
	Transitive *bool `form:"transitive,omitempty" json:"transitive,omitempty"`
}

ListTeamsParams defines parameters for ListTeams.

type ListTeamsResponse

type ListTeamsResponse struct {
	// Limit Maximum number of results per page
	Limit int `json:"limit"`

	// Offset Number of results skipped
	Offset int            `json:"offset"`
	Teams  []TeamListItem `json:"teams"`

	// Total Total number of teams matching the filter
	Total int `json:"total"`
}

ListTeamsResponse Paginated list of teams

type ListThreatModelAuditTrailResponse

type ListThreatModelAuditTrailResponse struct {
	AuditEntries []AuditEntry `json:"audit_entries"`

	// Limit Maximum number of entries returned
	Limit int `json:"limit"`

	// NextCursor Cursor for the next (older) page; absent or null when exhausted.
	NextCursor *string `json:"next_cursor,omitempty"`

	// PrevCursor Cursor for the previous (newer) page; absent or null when at the newest end.
	PrevCursor *string `json:"prev_cursor,omitempty"`

	// Total Total number of matching audit entries
	Total int `json:"total"`
}

ListThreatModelAuditTrailResponse Cursor-paginated list of audit trail entries for a threat model

type ListThreatModelsParams

type ListThreatModelsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// Owner Filter by owner name or email
	Owner *OwnerQueryParam `form:"owner,omitempty" json:"owner,omitempty"`

	// Name Filter by name (case-insensitive substring match)
	Name *NameQueryParam `form:"name,omitempty" json:"name,omitempty"`

	// Description Filter by threat model description (partial match)
	Description *DescriptionQueryParam `form:"description,omitempty" json:"description,omitempty"`

	// IssueUri Filter by issue URI (partial match)
	IssueUri *IssueUriQueryParam `form:"issue_uri,omitempty" json:"issue_uri,omitempty"`

	// CreatedAfter Filter results created after this timestamp (ISO 8601)
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601)
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601)
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601)
	ModifiedBefore *ModifiedBefore `form:"modified_before,omitempty" json:"modified_before,omitempty"`

	// Status Filter by status (OR logic). Returns threats matching ANY of the specified statuses. Example: ?status=identified&status=mitigated
	Status *StatusQueryParam `form:"status,omitempty" json:"status,omitempty"`

	// StatusUpdatedAfter Filter threat models where status was updated after this timestamp (RFC3339)
	StatusUpdatedAfter *StatusUpdatedAfterQueryParam `form:"status_updated_after,omitempty" json:"status_updated_after,omitempty"`

	// StatusUpdatedBefore Filter threat models where status was updated before this timestamp (RFC3339)
	StatusUpdatedBefore *StatusUpdatedBeforeQueryParam `form:"status_updated_before,omitempty" json:"status_updated_before,omitempty"`

	// IncludeDeleted Include soft-deleted (tombstoned) entities in the response. Requires owner or admin role.
	IncludeDeleted *IncludeDeletedQueryParam `form:"include_deleted,omitempty" json:"include_deleted,omitempty"`

	// SecurityReviewer Filter by security reviewer. Plain value performs case-insensitive partial match on reviewer email or display name. Use 'is:null' to find unassigned threat models (no security reviewer), 'is:notnull' to find assigned ones.
	SecurityReviewer *SecurityReviewerQueryParam `form:"security_reviewer,omitempty" json:"security_reviewer,omitempty"`
}

ListThreatModelsParams defines parameters for ListThreatModels.

type ListThreatModelsResponse

type ListThreatModelsResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset       int          `json:"offset"`
	ThreatModels []TMListItem `json:"threat_models"`

	// Total Total number of threat models matching criteria
	Total int `json:"total"`
}

ListThreatModelsResponse Paginated list of threat models

type ListThreatsResponse

type ListThreatsResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset  int      `json:"offset"`
	Threats []Threat `json:"threats"`

	// Total Total number of threats matching criteria
	Total int `json:"total"`
}

ListThreatsResponse Paginated list of threats

type ListTimmyChatMessagesParams

type ListTimmyChatMessagesParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

ListTimmyChatMessagesParams defines parameters for ListTimmyChatMessages.

type ListTimmyChatSessionsParams

type ListTimmyChatSessionsParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

ListTimmyChatSessionsParams defines parameters for ListTimmyChatSessions.

type ListTimmyMessagesResponse

type ListTimmyMessagesResponse struct {
	// Limit Pagination limit
	Limit    int                `json:"limit"`
	Messages []TimmyChatMessage `json:"messages"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of messages matching criteria
	Total int `json:"total"`
}

ListTimmyMessagesResponse Paginated list of Timmy chat messages

type ListTimmySessionsResponse

type ListTimmySessionsResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset   int                `json:"offset"`
	Sessions []TimmyChatSession `json:"sessions"`

	// Total Total number of sessions matching criteria
	Total int `json:"total"`
}

ListTimmySessionsResponse Paginated list of Timmy chat sessions

type ListTriageNotesResponse

type ListTriageNotesResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of triage notes
	Total       int                  `json:"total"`
	TriageNotes []TriageNoteListItem `json:"triage_notes"`
}

ListTriageNotesResponse Paginated list of triage notes

type ListTriageSurveyResponseTriageNotesParams

type ListTriageSurveyResponseTriageNotesParams struct {
	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`
}

ListTriageSurveyResponseTriageNotesParams defines parameters for ListTriageSurveyResponseTriageNotes.

type ListTriageSurveyResponsesParams

type ListTriageSurveyResponsesParams struct {
	// Status Filter by response status. Supports comma-separated values for multi-status filtering (e.g., status=submitted,ready_for_review).
	Status *SurveyResponseStatusQueryParam `form:"status,omitempty" json:"status,omitempty"`

	// SurveyId Filter by survey ID
	SurveyId *SurveyIdQueryParam `form:"survey_id,omitempty" json:"survey_id,omitempty"`

	// IsConfidential Filter by secret_project flag
	IsConfidential *IsConfidentialQueryParam `form:"is_confidential,omitempty" json:"is_confidential,omitempty"`

	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// Sort Sort order (e.g., created_at:desc, name:asc, severity:desc, score:desc)
	Sort *SortQueryParam `form:"sort,omitempty" json:"sort,omitempty"`

	// CreatedAfter Filter results created after this timestamp (ISO 8601)
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601)
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601)
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601)
	ModifiedBefore *ModifiedBefore `form:"modified_before,omitempty" json:"modified_before,omitempty"`
}

ListTriageSurveyResponsesParams defines parameters for ListTriageSurveyResponses.

type ListUsabilityFeedbackParams

type ListUsabilityFeedbackParams struct {
	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`

	// Sentiment Filter by sentiment
	Sentiment     *ListUsabilityFeedbackParamsSentiment `form:"sentiment,omitempty" json:"sentiment,omitempty"`
	ClientId      *string                               `form:"client_id,omitempty" json:"client_id,omitempty"`
	Surface       *string                               `form:"surface,omitempty" json:"surface,omitempty"`
	CreatedAfter  *time.Time                            `form:"created_after,omitempty" json:"created_after,omitempty"`
	CreatedBefore *time.Time                            `form:"created_before,omitempty" json:"created_before,omitempty"`
}

ListUsabilityFeedbackParams defines parameters for ListUsabilityFeedback.

type ListUsabilityFeedbackParamsSentiment

type ListUsabilityFeedbackParamsSentiment string

ListUsabilityFeedbackParamsSentiment defines parameters for ListUsabilityFeedback.

const (
	ListUsabilityFeedbackParamsSentimentDown ListUsabilityFeedbackParamsSentiment = "down"
	ListUsabilityFeedbackParamsSentimentUp   ListUsabilityFeedbackParamsSentiment = "up"
)

Defines values for ListUsabilityFeedbackParamsSentiment.

func (ListUsabilityFeedbackParamsSentiment) Valid

Valid indicates whether the value is a known member of the ListUsabilityFeedbackParamsSentiment enum.

type ListUserAPIQuotasParams

type ListUserAPIQuotasParams struct {
	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`
}

ListUserAPIQuotasParams defines parameters for ListUserAPIQuotas.

type ListUserQuotasResponse

type ListUserQuotasResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int            `json:"offset"`
	Quotas []UserAPIQuota `json:"quotas"`

	// Total Total number of quotas matching criteria
	Total int `json:"total"`
}

ListUserQuotasResponse Paginated list of user API quotas

type ListWebhookDeliveriesParams

type ListWebhookDeliveriesParams struct {
	// SubscriptionId Filter by subscription ID
	SubscriptionId *SubscriptionIdQueryParam `form:"subscription_id,omitempty" json:"subscription_id,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`
}

ListWebhookDeliveriesParams defines parameters for ListWebhookDeliveries.

type ListWebhookDeliveriesResponse

type ListWebhookDeliveriesResponse struct {
	Deliveries []WebhookDelivery `json:"deliveries"`

	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int `json:"offset"`

	// Total Total number of deliveries matching criteria
	Total int `json:"total"`
}

ListWebhookDeliveriesResponse Paginated list of webhook deliveries

type ListWebhookQuotasParams

type ListWebhookQuotasParams struct {
	// Limit Maximum number of results to return
	Limit *LimitQueryParam `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of results to skip
	Offset *OffsetQueryParam `form:"offset,omitempty" json:"offset,omitempty"`
}

ListWebhookQuotasParams defines parameters for ListWebhookQuotas.

type ListWebhookQuotasResponse

type ListWebhookQuotasResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset int            `json:"offset"`
	Quotas []WebhookQuota `json:"quotas"`

	// Total Total number of quotas matching criteria
	Total int `json:"total"`
}

ListWebhookQuotasResponse Paginated list of webhook quotas

type ListWebhookSubscriptionsParams

type ListWebhookSubscriptionsParams struct {
	// ThreatModelId Filter subscriptions by threat model ID
	ThreatModelId *ThreatModelIdQueryParam `form:"threat_model_id,omitempty" json:"threat_model_id,omitempty"`

	// Offset Number of results to skip
	Offset *PaginationOffset `form:"offset,omitempty" json:"offset,omitempty"`

	// Limit Maximum number of results to return
	Limit *PaginationLimit `form:"limit,omitempty" json:"limit,omitempty"`
}

ListWebhookSubscriptionsParams defines parameters for ListWebhookSubscriptions.

type ListWebhookSubscriptionsResponse

type ListWebhookSubscriptionsResponse struct {
	// Limit Pagination limit
	Limit int `json:"limit"`

	// Offset Pagination offset
	Offset        int                   `json:"offset"`
	Subscriptions []WebhookSubscription `json:"subscriptions"`

	// Total Total number of subscriptions matching criteria
	Total int `json:"total"`
}

ListWebhookSubscriptionsResponse Paginated list of webhook subscriptions

type LivePipelineEmbeddingSource

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

LivePipelineEmbeddingSource is like PipelineEmbeddingSource but resolves the content pipeline from a ContentSourceHolder on each call, so the embedding source stays current when the content-source registry is rebuilt at runtime. This avoids stale-pipeline reads when content sources are toggled without a restart. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: embedding source that resolves its content pipeline from a holder on each call to stay current (pure)

func NewLivePipelineEmbeddingSource

func NewLivePipelineEmbeddingSource(holder *ContentSourceHolder) *LivePipelineEmbeddingSource

NewLivePipelineEmbeddingSource creates an embedding source that resolves its pipeline from holder.Get on each call. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: build an embedding source that resolves its content pipeline live on each call (pure)

func (*LivePipelineEmbeddingSource) CanHandle

CanHandle returns true for entity references with a URI. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: report whether an entity reference has a URI and can be extracted (pure)

func (*LivePipelineEmbeddingSource) Extract

Extract resolves the live pipeline from the holder and delegates extraction. If the holder has no bundle or the bundle has no pipeline, returns an error. SEM@80346558ce851de593c85a2d5660f92a649b1686: fetch and extract text content via the live content pipeline for a given entity reference

func (*LivePipelineEmbeddingSource) Name

Name returns the adapter name. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: return the provider name for the live pipeline embedding source (pure)

type LoadedIndex

type LoadedIndex struct {
	ThreatModelID  string
	IndexType      string
	Index          *VectorIndex
	LastAccessed   time.Time
	ActiveSessions int
	MemoryBytes    int64
}

LoadedIndex represents an in-memory vector index for a threat model SEM@93f3b413fc45194106e4b8c0a3c1705ca53fa822: in-memory vector index entry for a threat model with access tracking and memory accounting (pure)

type LogLevel

type LogLevel int

LogLevel represents logging verbosity SEM@386eea01f3b66c35027bf3ca762efbc291419e20: enumerate logging verbosity levels (pure)

const (
	// LogLevelDebug includes detailed debug information
	LogLevelDebug LogLevel = iota
	// LogLevelInfo includes general request information
	LogLevelInfo
	// LogLevelWarn includes warnings and errors only
	LogLevelWarn
	// LogLevelError includes only errors
	LogLevelError
)

func ParseLogLevel

func ParseLogLevel(level string) LogLevel

ParseLogLevel converts a string log level to LogLevel SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: convert a log-level string to its LogLevel constant (pure)

type LoginHintQueryParam

type LoginHintQueryParam = string

LoginHintQueryParam defines model for LoginHintQueryParam.

type MemberUuidPathParam

type MemberUuidPathParam = openapi_types.UUID

MemberUuidPathParam defines model for MemberUuidPathParam.

type MembershipContext

type MembershipContext struct {
	Email      string
	UserUUID   uuid.UUID
	Provider   string
	GroupNames []string
	GroupUUIDs []uuid.UUID // IdP groups resolved to TMI group UUIDs
}

MembershipContext holds the resolved user identity for group membership checks. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: resolved user identity and group memberships for authorization checks (pure)

func ResolveMembershipContext

func ResolveMembershipContext(c *gin.Context) (*MembershipContext, error)

ResolveMembershipContext extracts user identity from the Gin context and resolves IdP group names to TMI group UUIDs. Returns nil with error if authentication is missing. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: extract user identity from a Gin context and resolve IdP group names to TMI group UUIDs (reads DB)

type MessageHandler

type MessageHandler interface {
	HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error
	MessageType() string
}

MessageHandler defines the interface for handling WebSocket messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: interface contract for handling a typed WebSocket message (pure)

type MessageRouter

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

MessageRouter handles routing of WebSocket messages to appropriate handlers SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: registry that routes WebSocket messages to registered handlers by type (pure)

func NewMessageRouter

func NewMessageRouter() *MessageRouter

NewMessageRouter creates a new message router with default handlers SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: build a message router pre-registered with all default WebSocket message handlers (pure)

func (*MessageRouter) RegisterHandler

func (r *MessageRouter) RegisterHandler(handler MessageHandler)

RegisterHandler registers a message handler for a specific message type SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: register a message handler for its declared message type (mutates shared state)

func (*MessageRouter) RouteMessage

func (r *MessageRouter) RouteMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

RouteMessage routes a message to the appropriate handler SEM@33253c50ca23589f6b0c77b5d12d8b653ac725e5: dispatch a raw WebSocket message to the appropriate handler, rejecting server-only types

type MessageStatusCallback

type MessageStatusCallback func(phase, entityType, entityName, detail string)

MessageStatusCallback reports pre-token-stream phase transitions during HandleMessage so the client can surface "Timmy is …" affordances (loading embeddings, querying, waiting for LLM, …) instead of a generic spinner. `phase` is a stable snake_case identifier; the rest are optional and may be empty. See OpenAPI `createTimmyChatMessage` for the documented shape. SEM@f904455aae213e6a2855645d19e4aa64e39619e6: callback type reporting pre-stream phase transitions during Timmy message handling (pure)

type MessageType

type MessageType string

MessageType represents the type of WebSocket message SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: typed string discriminator for WebSocket message categories (pure)

const (
	// Collaborative editing message types
	MessageTypeDiagramOperation       MessageType = "diagram_operation"
	MessageTypePresenterRequest       MessageType = "presenter_request"
	MessageTypePresenterDeniedRequest MessageType = "presenter_denied_request"
	MessageTypePresenterDeniedEvent   MessageType = "presenter_denied_event"
	MessageTypeChangePresenter        MessageType = "change_presenter"
	MessageTypeRemoveParticipant      MessageType = "remove_participant"
	MessageTypePresenterCursor        MessageType = "presenter_cursor"
	MessageTypePresenterSelection     MessageType = "presenter_selection"
	MessageTypeAuthorizationDenied    MessageType = "authorization_denied"
	MessageTypeHistoryOperation       MessageType = "history_operation"
	MessageTypeUndoRequest            MessageType = "undo_request"
	MessageTypeRedoRequest            MessageType = "redo_request"

	// Sync message types (new protocol)
	MessageTypeSyncStatusRequest  MessageType = "sync_status_request"
	MessageTypeSyncStatusResponse MessageType = "sync_status_response"
	MessageTypeSyncRequest        MessageType = "sync_request"
	MessageTypeDiagramState       MessageType = "diagram_state"

	// Request/Event pattern message types (Client→Server requests, Server→Client events)
	MessageTypeDiagramOperationRequest  MessageType = "diagram_operation_request"
	MessageTypeDiagramOperationEvent    MessageType = "diagram_operation_event"
	MessageTypePresenterRequestEvent    MessageType = "presenter_request_event"
	MessageTypeChangePresenterRequest   MessageType = "change_presenter_request"
	MessageTypeRemoveParticipantRequest MessageType = "remove_participant_request"

	// Session management message types
	MessageTypeParticipantsUpdate MessageType = "participants_update"
	MessageTypeError              MessageType = "error"
	MessageTypeOperationRejected  MessageType = "operation_rejected"
)

type Metadata

type Metadata struct {
	// Key Metadata key
	Key string `binding:"required" json:"key"`

	// Value Metadata value
	Value string `binding:"required" json:"value"`
}

Metadata A key-value pair for extensible metadata

type MetadataConflictError

type MetadataConflictError struct {
	ConflictingKeys []string
}

MetadataConflictError is returned by metadata Create/BulkCreate operations when one or more keys already exist. ConflictingKeys contains the key names that caused the conflict. Unwrap returns ErrMetadataKeyExists so callers can use errors.Is(err, ErrMetadataKeyExists) to detect this condition. SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: error type reporting which metadata keys already exist on a create conflict (pure)

func (*MetadataConflictError) Error

func (e *MetadataConflictError) Error() string

Error implements the error interface. SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: format the metadata conflict error message listing conflicting keys (pure)

func (*MetadataConflictError) Unwrap

func (e *MetadataConflictError) Unwrap() error

Unwrap returns ErrMetadataKeyExists so that errors.Is and errors.As work against the sentinel. SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: return the ErrMetadataKeyExists sentinel for errors.Is unwrapping (pure)

type MetadataItem

type MetadataItem struct {
	Key   string `json:"key" binding:"required"`
	Value string `json:"value" binding:"required"`
}

MetadataItem represents a metadata key-value pair SEM@386eea01f3b66c35027bf3ca762efbc291419e20: represent a single metadata key-value pair (pure)

type MetadataKey

type MetadataKey = string

MetadataKey defines model for MetadataKey.

type MetadataRepository

type MetadataRepository interface {
	// CRUD operations
	Create(ctx context.Context, entityType, entityID string, metadata *Metadata) error
	Get(ctx context.Context, entityType, entityID, key string) (*Metadata, error)
	Update(ctx context.Context, entityType, entityID string, metadata *Metadata) error
	Delete(ctx context.Context, entityType, entityID, key string) error

	// Collection operations
	List(ctx context.Context, entityType, entityID string) ([]Metadata, error)

	// POST operations — adding metadata without specifying key upfront
	Post(ctx context.Context, entityType, entityID string, metadata *Metadata) error

	// Bulk operations
	BulkCreate(ctx context.Context, entityType, entityID string, metadata []Metadata) error
	BulkUpdate(ctx context.Context, entityType, entityID string, metadata []Metadata) error
	BulkReplace(ctx context.Context, entityType, entityID string, metadata []Metadata) error
	BulkDelete(ctx context.Context, entityType, entityID string, keys []string) error

	// Key-based operations
	GetByKey(ctx context.Context, key string) ([]Metadata, error)
	ListKeys(ctx context.Context, entityType, entityID string) ([]string, error)

	// Cache management
	InvalidateCache(ctx context.Context, entityType, entityID string) error
	WarmCache(ctx context.Context, entityType, entityID string) error
}

MetadataRepository defines the interface for metadata storage operations. Method signatures match MetadataStore exactly. SEM@3c1a01558012bffd79e59f37ab15f2ccc823c29c: interface for CRUD, bulk, and cache operations on entity metadata (reads DB)

var GlobalMetadataRepository MetadataRepository

type MethodNotAllowed

type MethodNotAllowed = Error

MethodNotAllowed Standard error response format

type MicrosoftContentOAuthProvider

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

MicrosoftContentOAuthProvider wraps BaseContentOAuthProvider for Microsoft Entra ID. The base provider already understands Microsoft Graph's /me userinfo response shape (id + mail + displayName), so this wrapper is currently a thin pass-through. It exists as a stable extension point for future Graph-specific behavior (e.g., resolving tenant id from access tokens, decoding Microsoft-specific error payloads on refresh failures).

The TMI Entra app must be registered in the operator's tenant with the scopes listed in MicrosoftContentOAuthProvider.RequiredScopes() and a redirect URI matching ContentOAuthConfig.CallbackURL. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: thin wrapper around BaseContentOAuthProvider scoped to Microsoft Entra ID

func NewMicrosoftContentOAuthProvider

func NewMicrosoftContentOAuthProvider(base *BaseContentOAuthProvider) *MicrosoftContentOAuthProvider

NewMicrosoftContentOAuthProvider wraps base for the Microsoft provider id. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: build a MicrosoftContentOAuthProvider wrapping the given base provider

func (*MicrosoftContentOAuthProvider) AuthorizationURL

func (p *MicrosoftContentOAuthProvider) AuthorizationURL(state, pkceChallenge, redirectURI string) string

AuthorizationURL delegates to the base provider. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: build the Microsoft Entra OAuth authorization URL with PKCE challenge (pure)

func (*MicrosoftContentOAuthProvider) ExchangeCode

func (p *MicrosoftContentOAuthProvider) ExchangeCode(ctx context.Context, code, pkceVerifier, redirectURI string) (*ContentOAuthTokenResponse, error)

ExchangeCode delegates to the base provider. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: exchange an authorization code for Microsoft content OAuth tokens

func (*MicrosoftContentOAuthProvider) FetchAccountInfo

func (p *MicrosoftContentOAuthProvider) FetchAccountInfo(ctx context.Context, accessToken string) (string, string, error)

FetchAccountInfo delegates to the base provider. Microsoft Graph /me returns "id" (account_id) and "mail" or "userPrincipalName" (label), both handled by BaseContentOAuthProvider's stringField lookup over standard keys. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: fetch the Microsoft account ID and label from the Graph /me endpoint

func (*MicrosoftContentOAuthProvider) ID

ID returns "microsoft". SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: return the provider identifier string "microsoft" (pure)

func (*MicrosoftContentOAuthProvider) Refresh

Refresh delegates to the base provider. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: refresh a Microsoft content OAuth access token using the refresh token

func (*MicrosoftContentOAuthProvider) RequiredScopes

func (p *MicrosoftContentOAuthProvider) RequiredScopes() []string

RequiredScopes delegates to the base provider. Operators MUST include "offline_access" for refresh tokens to be issued, "Files.SelectedOperations.Selected" for read access to per-file-permissioned items, "Files.ReadWrite" for the picker-grant call, and "User.Read" for account labelling. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: return the OAuth scopes required for Microsoft Graph file access (pure)

func (*MicrosoftContentOAuthProvider) Revoke

Revoke delegates to the base provider. Microsoft Graph has no public RFC 7009 revocation endpoint as of 2026; operator config typically leaves revocation_url empty and the base provider treats this as a no-op. SEM@b6d7d9d8817f015d867e00e0c6a27668c4669eeb: revoke a Microsoft content OAuth token (no-op when no revocation endpoint is configured)

type MicrosoftPickerGrantHandler

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

MicrosoftPickerGrantHandler handles POST /me/microsoft/picker_grants.

After a user picks a file via the Microsoft File Picker, tmi-ux POSTs the (drive_id, item_id) here. The server then uses the user's stored delegated token (with Files.ReadWrite scope) to call Graph's

POST /drives/{driveId}/items/{itemId}/permissions

granting the configured TMI Entra app's identity the `read` role on this specific file. Subsequent fetches via DelegatedMicrosoftSource read the file under Files.SelectedOperations.Selected (the user's read scope).

Required wiring (see cmd/server/main.go):

  • tokens: ContentTokenRepository for the user's Microsoft delegated token
  • registry: ContentOAuthProviderRegistry containing the "microsoft" provider
  • applicationObjectID: the TMI Entra app's object id (used as Graph permission grantee)
  • graphBaseURL: defaults to graphV1Base when ""
  • userLookup: extracts the authenticated user id from the Gin context

SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: handler that grants the TMI app read permission on a user-picked Microsoft Graph file (pure)

func NewMicrosoftPickerGrantHandler

func NewMicrosoftPickerGrantHandler(
	tokens ContentTokenRepository,
	registry *ContentOAuthProviderRegistry,
	applicationObjectID string,
	graphBaseURL string,
	userLookup func(c *gin.Context) (string, bool),
	validator *URIValidator,
) *MicrosoftPickerGrantHandler

NewMicrosoftPickerGrantHandler creates the handler routing outbound Graph calls through SafeHTTPClient with a 30-second overall timeout. graphBaseURL defaults to https://graph.microsoft.com/v1.0 when "". validator MUST be non-nil; in production it is built from the operator's content-source allowlist (typically containing graph.microsoft.com). SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build a MicrosoftPickerGrantHandler with a 30-second SafeHTTPClient and URI validator (pure)

func (*MicrosoftPickerGrantHandler) Handle

func (h *MicrosoftPickerGrantHandler) Handle(c *gin.Context)

Handle processes POST /me/microsoft/picker_grants.

Flow:

  1. Verify applicationObjectID is configured → else 422 picker_grants_not_configured.
  2. Authenticate the caller → else 401 unauthenticated.
  3. Parse body; require non-empty drive_id and item_id → else 400 invalid_request.
  4. Look up the user's Microsoft token → else 404 not_linked.
  5. Short-circuit on failed_refresh → 401 token_refresh_failed.
  6. Refresh if expired → 401 (permanent) or 503 (transient) on failure.
  7. Call Graph permissions API → 200 / 422 grant_failed / 503 transient_failure.

SEM@16390049ed01287835d8186f860dadff9c8c9288: handle a Microsoft File Picker grant request, issuing a Graph permission and returning the permission ID

type MicrosoftPickerGrantRequest

type MicrosoftPickerGrantRequest struct {
	// DriveId OneDrive or SharePoint drive identifier returned by the Microsoft File Picker.
	DriveId string `json:"drive_id"`

	// ItemId Drive item identifier returned by the Microsoft File Picker.
	ItemId string `json:"item_id"`
}

MicrosoftPickerGrantRequest Request body for the Microsoft picker-grant endpoint. Carries the drive id and item id of the picked file.

type MicrosoftPickerGrantResponse

type MicrosoftPickerGrantResponse struct {
	// DriveId OneDrive or SharePoint drive identifier of the granted file.
	DriveId string `json:"drive_id"`

	// ItemId Drive item identifier of the granted file.
	ItemId string `json:"item_id"`

	// PermissionId Microsoft Graph permission id created by the grant call.
	PermissionId string `json:"permission_id"`
}

MicrosoftPickerGrantResponse Response body for the Microsoft picker-grant endpoint. Returns the Graph permission id created by the grant call (informational; not needed for subsequent fetches).

type MiddlewareAuthData

type MiddlewareAuthData struct {
	Owner         User            `json:"owner"`
	Authorization []Authorization `json:"authorization"`
}

MiddlewareAuthData holds authorization data needed by middleware. Cached separately from full threat model to avoid loading sub-resources. SEM@2ec29b7908cd546e20f3bbf1ad51b2c76e52c70d: lightweight owner and authorization data cached separately for middleware auth checks (pure)

type MiddlewareFunc

type MiddlewareFunc func(c *gin.Context)

type MiddlewareTestCase

type MiddlewareTestCase struct {
	Name           string
	Method         string
	Path           string
	Body           []byte
	ContentType    string
	SetupContext   func(*gin.Context)
	SetupHeaders   func(*http.Request)
	ExpectedStatus int
	ExpectedError  string
	CheckResponse  func(*testing.T, *httptest.ResponseRecorder)
	CheckContext   func(*testing.T, *gin.Context)
}

MiddlewareTestCase represents a test case for middleware testing SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: data container describing a single middleware test scenario and its expected outcomes (pure)

type MiddlewareTestHelper

type MiddlewareTestHelper struct {
	Router *gin.Engine
}

MiddlewareTestHelper provides utilities for testing middleware functions SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: test fixture holding a Gin engine for middleware unit tests (pure)

func NewMiddlewareTestHelper

func NewMiddlewareTestHelper() *MiddlewareTestHelper

NewMiddlewareTestHelper creates a new middleware test helper with a clean router SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: build a MiddlewareTestHelper with a fresh Gin engine in test mode (pure)

func (*MiddlewareTestHelper) RunMiddlewareChain

func (h *MiddlewareTestHelper) RunMiddlewareChain(middlewares []gin.HandlerFunc, method, path string, setupContext func(*gin.Context)) *httptest.ResponseRecorder

RunMiddlewareChain executes a chain of middleware functions SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: dispatch an ordered chain of middleware handlers, stopping on abort (pure)

func (*MiddlewareTestHelper) RunMiddlewareTest

func (h *MiddlewareTestHelper) RunMiddlewareTest(middleware gin.HandlerFunc, method, path string, setupContext func(*gin.Context)) *httptest.ResponseRecorder

RunMiddlewareTest executes middleware and returns the response SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: dispatch a single middleware handler against a synthetic request and return the response (pure)

type MigratableSetting

type MigratableSetting struct {
	Key         string
	Value       string
	Type        string
	Description string
	Secret      bool   // true = mask value in API responses
	Source      string // "config" or "environment"
}

MigratableSetting represents a setting that can be migrated from config to database SEM@33a84a2f45e6081d58584c7c6233564fb6bbf063: a typed key-value setting that can be promoted from config file to the database

type MinimalCell

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

MinimalCell Minimal diagram cell data for WebSocket collaboration updates

func (MinimalCell) AsMinimalEdge

func (t MinimalCell) AsMinimalEdge() (MinimalEdge, error)

AsMinimalEdge returns the union data inside the MinimalCell as a MinimalEdge

func (MinimalCell) AsMinimalNode

func (t MinimalCell) AsMinimalNode() (MinimalNode, error)

AsMinimalNode returns the union data inside the MinimalCell as a MinimalNode

func (MinimalCell) Discriminator

func (t MinimalCell) Discriminator() (string, error)

func (*MinimalCell) FromMinimalEdge

func (t *MinimalCell) FromMinimalEdge(v MinimalEdge) error

FromMinimalEdge overwrites any union data inside the MinimalCell as the provided MinimalEdge

func (*MinimalCell) FromMinimalNode

func (t *MinimalCell) FromMinimalNode(v MinimalNode) error

FromMinimalNode overwrites any union data inside the MinimalCell as the provided MinimalNode

func (MinimalCell) MarshalJSON

func (t MinimalCell) MarshalJSON() ([]byte, error)

func (*MinimalCell) MergeMinimalEdge

func (t *MinimalCell) MergeMinimalEdge(v MinimalEdge) error

MergeMinimalEdge performs a merge with any union data inside the MinimalCell, using the provided MinimalEdge

func (*MinimalCell) MergeMinimalNode

func (t *MinimalCell) MergeMinimalNode(v MinimalNode) error

MergeMinimalNode performs a merge with any union data inside the MinimalCell, using the provided MinimalNode

func (*MinimalCell) UnmarshalJSON

func (t *MinimalCell) UnmarshalJSON(b []byte) error

func (MinimalCell) ValueByDiscriminator

func (t MinimalCell) ValueByDiscriminator() (interface{}, error)

type MinimalDiagramModel

type MinimalDiagramModel struct {
	// Assets Asset objects referenced by cells in this diagram via data_asset_ids
	Assets []Asset `json:"assets"`

	// Cells Minimal cell data (nodes and edges) without visual styling
	Cells []MinimalCell `json:"cells"`

	// Description Threat model description
	Description string `json:"description"`

	// Id Threat model unique identifier
	Id openapi_types.UUID `json:"id"`

	// Metadata Flattened metadata from threat model (converted from array format to key-value pairs)
	Metadata map[string]string `json:"metadata"`

	// Name Threat model name
	Name string `json:"name"`
}

MinimalDiagramModel Minimal diagram representation optimized for automated threat modeling, containing threat model context and simplified cell data without visual styling

type MinimalEdge

type MinimalEdge struct {
	// DataAssetIds References to Asset IDs associated with this edge
	DataAssetIds *[]openapi_types.UUID `json:"data_asset_ids,omitempty"`

	// Id Cell unique identifier
	Id openapi_types.UUID `json:"id"`

	// Labels Text labels extracted from edge labels array
	Labels []string `json:"labels"`

	// Metadata Flattened edge metadata (converted from _metadata array in edge.data)
	Metadata map[string]string `json:"metadata"`

	// Shape Edge shape type
	Shape MinimalEdgeShape `json:"shape"`

	// Source Source node connection details
	Source EdgeTerminal `json:"source"`

	// Target Target node connection details
	Target EdgeTerminal `json:"target"`
}

MinimalEdge Minimal edge representation without visual styling or routing information

type MinimalEdgeShape

type MinimalEdgeShape string

MinimalEdgeShape Edge shape type

const (
	MinimalEdgeShapeFlow MinimalEdgeShape = "flow"
)

Defines values for MinimalEdgeShape.

func (MinimalEdgeShape) Valid

func (e MinimalEdgeShape) Valid() bool

Valid indicates whether the value is a known member of the MinimalEdgeShape enum.

type MinimalNode

type MinimalNode struct {
	// Children Child cell IDs (computed bidirectional relationship including reverse parent references)
	Children []openapi_types.UUID `json:"children"`

	// DataAssetIds References to Asset IDs associated with this node
	DataAssetIds *[]openapi_types.UUID `json:"data_asset_ids,omitempty"`

	// Id Cell unique identifier
	Id openapi_types.UUID `json:"id"`

	// Labels Text labels extracted from node attrs and embedded text-box children
	Labels []string `json:"labels"`

	// Metadata Flattened cell metadata (converted from _metadata array in cell.data)
	Metadata map[string]string `json:"metadata"`

	// Parent Parent cell ID for nested nodes (null for top-level nodes)
	Parent *openapi_types.UUID `json:"parent,omitempty"`

	// SecurityBoundary Indicates whether this node represents a security boundary. Always true for shape='security-boundary', otherwise derived from cell data.
	SecurityBoundary bool `json:"security_boundary"`

	// Shape Node shape type determining its semantic role in the diagram
	Shape MinimalNodeShape `json:"shape"`
}

MinimalNode Minimal node representation without visual styling or layout information

type MinimalNodeShape

type MinimalNodeShape string

MinimalNodeShape Node shape type determining its semantic role in the diagram

const (
	MinimalNodeShapeActor            MinimalNodeShape = "actor"
	MinimalNodeShapeProcess          MinimalNodeShape = "process"
	MinimalNodeShapeSecurityBoundary MinimalNodeShape = "security-boundary"
	MinimalNodeShapeStore            MinimalNodeShape = "store"
	MinimalNodeShapeTextBox          MinimalNodeShape = "text-box"
)

Defines values for MinimalNodeShape.

func (MinimalNodeShape) Valid

func (e MinimalNodeShape) Valid() bool

Valid indicates whether the value is a known member of the MinimalNodeShape enum.

type MitigatedQueryParam

type MitigatedQueryParam = bool

MitigatedQueryParam defines model for MitigatedQueryParam.

type MockDiagramStore

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

SEM@8fc3d262100f4b47c12ee2155e83e344babb1bd3: in-memory diagram store with threat-model mapping for unit tests

func (*MockDiagramStore) Count

func (m *MockDiagramStore) Count() int

SEM@9936be5037906d553ff6e5c579ca9f27d222d149: return the number of diagrams in the mock store (pure)

func (*MockDiagramStore) Create

func (m *MockDiagramStore) Create(item DfdDiagram, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)

SEM@5981ac53dd2229e2bb211a96f0b495fe72df5f32: store a diagram in the mock store, assigning a UUID if absent

func (*MockDiagramStore) CreateWithThreatModel

func (m *MockDiagramStore) CreateWithThreatModel(item DfdDiagram, threatModelID string, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)

SEM@8fc3d262100f4b47c12ee2155e83e344babb1bd3: store a diagram and record its parent threat model association in the mock store

func (*MockDiagramStore) Delete

func (m *MockDiagramStore) Delete(id string) error

SEM@9936be5037906d553ff6e5c579ca9f27d222d149: remove a diagram from the mock store by ID

func (*MockDiagramStore) Get

func (m *MockDiagramStore) Get(id string) (DfdDiagram, error)

SEM@e4005658033b63171bdc1130fb523d996fbff9a7: fetch a diagram from the mock store by ID

func (*MockDiagramStore) GetBatch

func (m *MockDiagramStore) GetBatch(ids []string) ([]DfdDiagram, error)

SEM@03d4456b06cc7df1a6c638286c7947c816ebd0e8: fetch multiple diagrams by ID list from the mock store, skipping missing entries

func (*MockDiagramStore) GetIncludingDeleted

func (m *MockDiagramStore) GetIncludingDeleted(id string) (DfdDiagram, error)

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: fetch a diagram from the mock store regardless of soft-delete status

func (*MockDiagramStore) GetThreatModelID

func (m *MockDiagramStore) GetThreatModelID(diagramID string) (string, error)

SEM@383547f0bee568a092d84a1f830f227b74f6d723: fetch the parent threat model ID for a diagram from the mock store

func (*MockDiagramStore) HardDelete

func (m *MockDiagramStore) HardDelete(id string) error

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently remove a diagram from the mock store by ID

func (*MockDiagramStore) List

func (m *MockDiagramStore) List(offset, limit int, filter func(DfdDiagram) bool) []DfdDiagram

SEM@9936be5037906d553ff6e5c579ca9f27d222d149: list diagrams from the mock store, optionally filtered by a predicate (pure)

func (*MockDiagramStore) Restore

func (m *MockDiagramStore) Restore(id string) error

SEM@e4005658033b63171bdc1130fb523d996fbff9a7: no-op restore for mock diagram store in unit tests (pure)

func (*MockDiagramStore) SoftDelete

func (m *MockDiagramStore) SoftDelete(_ context.Context, id string) error

SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: remove a diagram from the mock store (no-op soft-delete for tests)

func (*MockDiagramStore) Update

func (m *MockDiagramStore) Update(_ context.Context, id string, item DfdDiagram) error

SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: replace a diagram entry in the mock store by ID

type MockThreatModelStore

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

Simple mock stores for unit tests SEM@9936be5037906d553ff6e5c579ca9f27d222d149: in-memory threat model store implementation for unit tests (pure)

func (*MockThreatModelStore) Count

func (m *MockThreatModelStore) Count() int

SEM@9936be5037906d553ff6e5c579ca9f27d222d149: return the number of threat models in the mock store (pure)

func (*MockThreatModelStore) Create

func (m *MockThreatModelStore) Create(item ThreatModel, idSetter func(ThreatModel, string) ThreatModel) (ThreatModel, error)

SEM@5981ac53dd2229e2bb211a96f0b495fe72df5f32: store a threat model in the mock store, assigning a UUID and default status if absent

func (*MockThreatModelStore) Delete

func (m *MockThreatModelStore) Delete(id string) error

SEM@9936be5037906d553ff6e5c579ca9f27d222d149: remove a threat model from the mock store by ID

func (*MockThreatModelStore) Get

SEM@e4005658033b63171bdc1130fb523d996fbff9a7: fetch a threat model by ID from the in-memory store, loading diagrams dynamically (pure)

func (*MockThreatModelStore) GetAuthorization

func (m *MockThreatModelStore) GetAuthorization(id string) ([]Authorization, User, error)

SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: fetch the authorization list and owner for a threat model from the mock store

func (*MockThreatModelStore) GetAuthorizationIncludingDeleted

func (m *MockThreatModelStore) GetAuthorizationIncludingDeleted(id string) ([]Authorization, User, error)

SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: fetch authorization and owner for a threat model including soft-deleted records

func (*MockThreatModelStore) GetIncludingDeleted

func (m *MockThreatModelStore) GetIncludingDeleted(id string) (ThreatModel, error)

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: fetch a threat model from the mock store regardless of soft-delete status

func (*MockThreatModelStore) HardDelete

func (m *MockThreatModelStore) HardDelete(id string) error

SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: permanently remove a threat model from the mock store by ID

func (*MockThreatModelStore) List

func (m *MockThreatModelStore) List(offset, limit int, filter func(ThreatModel) bool) []ThreatModel

SEM@9936be5037906d553ff6e5c579ca9f27d222d149: list threat models from in-memory store with optional predicate filter (pure)

func (*MockThreatModelStore) ListWithCounts

func (m *MockThreatModelStore) ListWithCounts(offset, limit int, filter func(ThreatModel) bool, filters *ThreatModelFilters) ([]TMListItem, int)

SEM@ce7f0b599ec1a118c3d01ee48ad1e397e9f0c19d: list threat models as list items with query-param filters, pagination, and total count (pure)

func (*MockThreatModelStore) Restore

func (m *MockThreatModelStore) Restore(id string) error

SEM@e4005658033b63171bdc1130fb523d996fbff9a7: clear the deletion timestamp on a soft-deleted threat model in the mock store

func (*MockThreatModelStore) SoftDelete

func (m *MockThreatModelStore) SoftDelete(_ context.Context, id string) error

SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: mark a threat model as deleted by setting its deletion timestamp in the mock store

func (*MockThreatModelStore) Update

SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: replace a threat model entry in the mock store by ID

type ModifiedAfter

type ModifiedAfter = time.Time

ModifiedAfter defines model for ModifiedAfter.

type ModifiedBefore

type ModifiedBefore = time.Time

ModifiedBefore defines model for ModifiedBefore.

type MyGroupListResponse

type MyGroupListResponse struct {
	// Groups List of groups the user is a direct member of
	Groups []UserGroupMembership `json:"groups"`

	// Total Total number of groups
	Total int `json:"total"`
}

MyGroupListResponse List of TMI-managed groups that the authenticated user belongs to

type MyIdentitiesResponse

type MyIdentitiesResponse struct {
	// Linked Additional linked identities
	Linked  *[]LinkedIdentity `json:"linked,omitempty"`
	Primary struct {
		// Email Primary account email address
		Email string `json:"email"`

		// Name Primary account display name
		Name *string `json:"name,omitempty"`

		// Provider Primary identity provider ID
		Provider string `json:"provider"`
	} `json:"primary"`
}

MyIdentitiesResponse defines model for MyIdentitiesResponse.

type NameQueryParam

type NameQueryParam = string

NameQueryParam defines model for NameQueryParam.

type Node

type Node struct {
	// Angle Rotation angle in degrees
	Angle *float32 `json:"angle,omitempty"`

	// Attrs Visual styling attributes for the node
	Attrs *NodeAttrs `json:"attrs,omitempty"`

	// Children IDs of child cells contained within this node (UUIDs)
	Children *[]openapi_types.UUID `json:"children,omitempty"`

	// Data Flexible data storage compatible with X6, with reserved metadata namespace
	Data *Node_Data `json:"data,omitempty"`

	// Height Height in pixels (flat format)
	Height *float32 `json:"height,omitempty"`

	// Id Unique identifier of the cell (UUID)
	Id openapi_types.UUID `json:"id"`

	// Parent ID of the parent cell for nested/grouped nodes (UUID)
	Parent *openapi_types.UUID `json:"parent,omitempty"`

	// Ports Port configuration for connections
	Ports *PortConfiguration `json:"ports,omitempty"`

	// Position Node position in X6 nested format. Use either this with size object OR use flat x/y/width/height properties.
	Position *struct {
		// X X coordinate
		X float32 `json:"x"`

		// Y Y coordinate
		Y float32 `json:"y"`
	} `json:"position,omitempty"`

	// Shape Node type determining its visual representation and behavior
	Shape NodeShape `json:"shape"`

	// Size Node size in X6 nested format. Use either this with position object OR use flat x/y/width/height properties.
	Size *struct {
		// Height Height in pixels
		Height float32 `json:"height"`

		// Width Width in pixels
		Width float32 `json:"width"`
	} `json:"size,omitempty"`

	// Width Width in pixels (flat format)
	Width *float32 `json:"width,omitempty"`

	// X X coordinate (flat format). Use either this with y, width, height OR use position/size objects.
	X *float32 `json:"x,omitempty"`

	// Y Y coordinate (flat format)
	Y *float32 `json:"y,omitempty"`
}

Node defines model for Node.

func (Node) MarshalJSON

func (n Node) MarshalJSON() ([]byte, error)

MarshalJSON implements custom marshaling for Node to always output flat format (x, y, width, height) as per AntV/X6 Format 2. SEM@49946733e8621ef3f7037468e2464eb2dd5fc0df: serialize a Node to flat AntV/X6 format with top-level x/y/width/height fields (pure)

func (*Node) UnmarshalJSON

func (n *Node) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshaling for Node to support both nested format (position/size objects) and flat format (x/y/width/height). This allows the API to accept both AntV/X6 formats. SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: deserialize a Node from either flat or nested position/size JSON formats, validating minimum dimensions (pure)

type NodeAttrs

type NodeAttrs struct {
	// Body Body/shape styling attributes
	Body *struct {
		// Fill Fill color
		Fill *string `json:"fill,omitempty"`

		// FillOpacity Body fill opacity (0-1); typically transient drag-to-embed visual feedback
		FillOpacity *float32 `json:"fillOpacity,omitempty"`

		// Lateral Cylinder lateral parameter for the X6 'store' shape (drives the body 'd' path computation)
		Lateral *float32 `json:"lateral,omitempty"`

		// RefHeight X6 reference height (number or percentage string, e.g. '100%') used to size the body relative to the cell bounding box
		RefHeight *NodeAttrs_Body_RefHeight `json:"refHeight,omitempty"`

		// RefWidth X6 reference width (number or percentage string, e.g. '100%') used to size the body relative to the cell bounding box
		RefWidth *NodeAttrs_Body_RefWidth `json:"refWidth,omitempty"`

		// Rx Corner radius along the x-axis (set as default by X6 shape registrations, e.g., actor/process/security-boundary)
		Rx *float32 `json:"rx,omitempty"`

		// Ry Corner radius along the y-axis (set as default by X6 shape registrations)
		Ry *float32 `json:"ry,omitempty"`

		// Stroke Stroke color
		Stroke *string `json:"stroke,omitempty"`

		// StrokeDasharray Dash pattern for strokes
		StrokeDasharray *string `json:"strokeDasharray,omitempty"`

		// StrokeWidth Stroke width in pixels
		StrokeWidth *float32 `json:"strokeWidth,omitempty"`
	} `json:"body,omitempty"`

	// Text Text/label styling attributes
	Text *struct {
		// Fill Text color
		Fill *string `json:"fill,omitempty"`

		// FontFamily Font family
		FontFamily *string `json:"fontFamily,omitempty"`

		// FontSize Font size in pixels
		FontSize *float32 `json:"fontSize,omitempty"`

		// RefDx Horizontal offset from refX (corner-based, retained for back-compat; client uses refX2)
		RefDx *float32 `json:"refDx,omitempty"`

		// RefDy Vertical offset from refY (corner-based, retained for back-compat; client uses refY2)
		RefDy *float32 `json:"refDy,omitempty"`

		// RefX Horizontal position (0-1 relative, pixels, or percentage string e.g. '50%')
		RefX *NodeAttrs_Text_RefX `json:"refX,omitempty"`

		// RefX2 Origin-based horizontal offset (alias of refX in X6); used by the client for icon and label positioning
		RefX2 *NodeAttrs_Text_RefX2 `json:"refX2,omitempty"`

		// RefY Vertical position (0-1 relative, pixels, or percentage string e.g. '50%')
		RefY *NodeAttrs_Text_RefY `json:"refY,omitempty"`

		// RefY2 Origin-based vertical offset (alias of refY in X6); used by the client for icon and label positioning
		RefY2 *NodeAttrs_Text_RefY2 `json:"refY2,omitempty"`

		// Text Label text content
		Text *string `json:"text,omitempty"`

		// TextAnchor Horizontal text alignment anchor point
		TextAnchor *NodeAttrsTextTextAnchor `json:"textAnchor,omitempty"`

		// TextVerticalAnchor Vertical text alignment anchor point
		TextVerticalAnchor *NodeAttrsTextTextVerticalAnchor `json:"textVerticalAnchor,omitempty"`
	} `json:"text,omitempty"`
}

NodeAttrs Visual attributes for a node

type NodeAttrsBodyRefHeight0

type NodeAttrsBodyRefHeight0 = float32

NodeAttrsBodyRefHeight0 defines model for .

type NodeAttrsBodyRefHeight1

type NodeAttrsBodyRefHeight1 = string

NodeAttrsBodyRefHeight1 defines model for .

type NodeAttrsBodyRefWidth0

type NodeAttrsBodyRefWidth0 = float32

NodeAttrsBodyRefWidth0 defines model for .

type NodeAttrsBodyRefWidth1

type NodeAttrsBodyRefWidth1 = string

NodeAttrsBodyRefWidth1 defines model for .

type NodeAttrsTextRefX0

type NodeAttrsTextRefX0 = float32

NodeAttrsTextRefX0 defines model for .

type NodeAttrsTextRefX1

type NodeAttrsTextRefX1 = string

NodeAttrsTextRefX1 defines model for .

type NodeAttrsTextRefX20

type NodeAttrsTextRefX20 = float32

NodeAttrsTextRefX20 defines model for .

type NodeAttrsTextRefX21

type NodeAttrsTextRefX21 = string

NodeAttrsTextRefX21 defines model for .

type NodeAttrsTextRefY0

type NodeAttrsTextRefY0 = float32

NodeAttrsTextRefY0 defines model for .

type NodeAttrsTextRefY1

type NodeAttrsTextRefY1 = string

NodeAttrsTextRefY1 defines model for .

type NodeAttrsTextRefY20

type NodeAttrsTextRefY20 = float32

NodeAttrsTextRefY20 defines model for .

type NodeAttrsTextRefY21

type NodeAttrsTextRefY21 = string

NodeAttrsTextRefY21 defines model for .

type NodeAttrsTextTextAnchor

type NodeAttrsTextTextAnchor string

NodeAttrsTextTextAnchor Horizontal text alignment anchor point

const (
	End    NodeAttrsTextTextAnchor = "end"
	Middle NodeAttrsTextTextAnchor = "middle"
	Start  NodeAttrsTextTextAnchor = "start"
)

Defines values for NodeAttrsTextTextAnchor.

func (NodeAttrsTextTextAnchor) Valid

func (e NodeAttrsTextTextAnchor) Valid() bool

Valid indicates whether the value is a known member of the NodeAttrsTextTextAnchor enum.

type NodeAttrsTextTextVerticalAnchor

type NodeAttrsTextTextVerticalAnchor string

NodeAttrsTextTextVerticalAnchor Vertical text alignment anchor point

const (
	NodeAttrsTextTextVerticalAnchorBottom NodeAttrsTextTextVerticalAnchor = "bottom"
	NodeAttrsTextTextVerticalAnchorMiddle NodeAttrsTextTextVerticalAnchor = "middle"
	NodeAttrsTextTextVerticalAnchorTop    NodeAttrsTextTextVerticalAnchor = "top"
)

Defines values for NodeAttrsTextTextVerticalAnchor.

func (NodeAttrsTextTextVerticalAnchor) Valid

Valid indicates whether the value is a known member of the NodeAttrsTextTextVerticalAnchor enum.

type NodeAttrs_Body_RefHeight

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

NodeAttrs_Body_RefHeight X6 reference height (number or percentage string, e.g. '100%') used to size the body relative to the cell bounding box

func (NodeAttrs_Body_RefHeight) AsNodeAttrsBodyRefHeight0

func (t NodeAttrs_Body_RefHeight) AsNodeAttrsBodyRefHeight0() (NodeAttrsBodyRefHeight0, error)

AsNodeAttrsBodyRefHeight0 returns the union data inside the NodeAttrs_Body_RefHeight as a NodeAttrsBodyRefHeight0

func (NodeAttrs_Body_RefHeight) AsNodeAttrsBodyRefHeight1

func (t NodeAttrs_Body_RefHeight) AsNodeAttrsBodyRefHeight1() (NodeAttrsBodyRefHeight1, error)

AsNodeAttrsBodyRefHeight1 returns the union data inside the NodeAttrs_Body_RefHeight as a NodeAttrsBodyRefHeight1

func (*NodeAttrs_Body_RefHeight) FromNodeAttrsBodyRefHeight0

func (t *NodeAttrs_Body_RefHeight) FromNodeAttrsBodyRefHeight0(v NodeAttrsBodyRefHeight0) error

FromNodeAttrsBodyRefHeight0 overwrites any union data inside the NodeAttrs_Body_RefHeight as the provided NodeAttrsBodyRefHeight0

func (*NodeAttrs_Body_RefHeight) FromNodeAttrsBodyRefHeight1

func (t *NodeAttrs_Body_RefHeight) FromNodeAttrsBodyRefHeight1(v NodeAttrsBodyRefHeight1) error

FromNodeAttrsBodyRefHeight1 overwrites any union data inside the NodeAttrs_Body_RefHeight as the provided NodeAttrsBodyRefHeight1

func (NodeAttrs_Body_RefHeight) MarshalJSON

func (t NodeAttrs_Body_RefHeight) MarshalJSON() ([]byte, error)

func (*NodeAttrs_Body_RefHeight) MergeNodeAttrsBodyRefHeight0

func (t *NodeAttrs_Body_RefHeight) MergeNodeAttrsBodyRefHeight0(v NodeAttrsBodyRefHeight0) error

MergeNodeAttrsBodyRefHeight0 performs a merge with any union data inside the NodeAttrs_Body_RefHeight, using the provided NodeAttrsBodyRefHeight0

func (*NodeAttrs_Body_RefHeight) MergeNodeAttrsBodyRefHeight1

func (t *NodeAttrs_Body_RefHeight) MergeNodeAttrsBodyRefHeight1(v NodeAttrsBodyRefHeight1) error

MergeNodeAttrsBodyRefHeight1 performs a merge with any union data inside the NodeAttrs_Body_RefHeight, using the provided NodeAttrsBodyRefHeight1

func (*NodeAttrs_Body_RefHeight) UnmarshalJSON

func (t *NodeAttrs_Body_RefHeight) UnmarshalJSON(b []byte) error

type NodeAttrs_Body_RefWidth

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

NodeAttrs_Body_RefWidth X6 reference width (number or percentage string, e.g. '100%') used to size the body relative to the cell bounding box

func (NodeAttrs_Body_RefWidth) AsNodeAttrsBodyRefWidth0

func (t NodeAttrs_Body_RefWidth) AsNodeAttrsBodyRefWidth0() (NodeAttrsBodyRefWidth0, error)

AsNodeAttrsBodyRefWidth0 returns the union data inside the NodeAttrs_Body_RefWidth as a NodeAttrsBodyRefWidth0

func (NodeAttrs_Body_RefWidth) AsNodeAttrsBodyRefWidth1

func (t NodeAttrs_Body_RefWidth) AsNodeAttrsBodyRefWidth1() (NodeAttrsBodyRefWidth1, error)

AsNodeAttrsBodyRefWidth1 returns the union data inside the NodeAttrs_Body_RefWidth as a NodeAttrsBodyRefWidth1

func (*NodeAttrs_Body_RefWidth) FromNodeAttrsBodyRefWidth0

func (t *NodeAttrs_Body_RefWidth) FromNodeAttrsBodyRefWidth0(v NodeAttrsBodyRefWidth0) error

FromNodeAttrsBodyRefWidth0 overwrites any union data inside the NodeAttrs_Body_RefWidth as the provided NodeAttrsBodyRefWidth0

func (*NodeAttrs_Body_RefWidth) FromNodeAttrsBodyRefWidth1

func (t *NodeAttrs_Body_RefWidth) FromNodeAttrsBodyRefWidth1(v NodeAttrsBodyRefWidth1) error

FromNodeAttrsBodyRefWidth1 overwrites any union data inside the NodeAttrs_Body_RefWidth as the provided NodeAttrsBodyRefWidth1

func (NodeAttrs_Body_RefWidth) MarshalJSON

func (t NodeAttrs_Body_RefWidth) MarshalJSON() ([]byte, error)

func (*NodeAttrs_Body_RefWidth) MergeNodeAttrsBodyRefWidth0

func (t *NodeAttrs_Body_RefWidth) MergeNodeAttrsBodyRefWidth0(v NodeAttrsBodyRefWidth0) error

MergeNodeAttrsBodyRefWidth0 performs a merge with any union data inside the NodeAttrs_Body_RefWidth, using the provided NodeAttrsBodyRefWidth0

func (*NodeAttrs_Body_RefWidth) MergeNodeAttrsBodyRefWidth1

func (t *NodeAttrs_Body_RefWidth) MergeNodeAttrsBodyRefWidth1(v NodeAttrsBodyRefWidth1) error

MergeNodeAttrsBodyRefWidth1 performs a merge with any union data inside the NodeAttrs_Body_RefWidth, using the provided NodeAttrsBodyRefWidth1

func (*NodeAttrs_Body_RefWidth) UnmarshalJSON

func (t *NodeAttrs_Body_RefWidth) UnmarshalJSON(b []byte) error

type NodeAttrs_Text_RefX

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

NodeAttrs_Text_RefX Horizontal position (0-1 relative, pixels, or percentage string e.g. '50%')

func (NodeAttrs_Text_RefX) AsNodeAttrsTextRefX0

func (t NodeAttrs_Text_RefX) AsNodeAttrsTextRefX0() (NodeAttrsTextRefX0, error)

AsNodeAttrsTextRefX0 returns the union data inside the NodeAttrs_Text_RefX as a NodeAttrsTextRefX0

func (NodeAttrs_Text_RefX) AsNodeAttrsTextRefX1

func (t NodeAttrs_Text_RefX) AsNodeAttrsTextRefX1() (NodeAttrsTextRefX1, error)

AsNodeAttrsTextRefX1 returns the union data inside the NodeAttrs_Text_RefX as a NodeAttrsTextRefX1

func (*NodeAttrs_Text_RefX) FromNodeAttrsTextRefX0

func (t *NodeAttrs_Text_RefX) FromNodeAttrsTextRefX0(v NodeAttrsTextRefX0) error

FromNodeAttrsTextRefX0 overwrites any union data inside the NodeAttrs_Text_RefX as the provided NodeAttrsTextRefX0

func (*NodeAttrs_Text_RefX) FromNodeAttrsTextRefX1

func (t *NodeAttrs_Text_RefX) FromNodeAttrsTextRefX1(v NodeAttrsTextRefX1) error

FromNodeAttrsTextRefX1 overwrites any union data inside the NodeAttrs_Text_RefX as the provided NodeAttrsTextRefX1

func (NodeAttrs_Text_RefX) MarshalJSON

func (t NodeAttrs_Text_RefX) MarshalJSON() ([]byte, error)

func (*NodeAttrs_Text_RefX) MergeNodeAttrsTextRefX0

func (t *NodeAttrs_Text_RefX) MergeNodeAttrsTextRefX0(v NodeAttrsTextRefX0) error

MergeNodeAttrsTextRefX0 performs a merge with any union data inside the NodeAttrs_Text_RefX, using the provided NodeAttrsTextRefX0

func (*NodeAttrs_Text_RefX) MergeNodeAttrsTextRefX1

func (t *NodeAttrs_Text_RefX) MergeNodeAttrsTextRefX1(v NodeAttrsTextRefX1) error

MergeNodeAttrsTextRefX1 performs a merge with any union data inside the NodeAttrs_Text_RefX, using the provided NodeAttrsTextRefX1

func (*NodeAttrs_Text_RefX) UnmarshalJSON

func (t *NodeAttrs_Text_RefX) UnmarshalJSON(b []byte) error

type NodeAttrs_Text_RefX2

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

NodeAttrs_Text_RefX2 Origin-based horizontal offset (alias of refX in X6); used by the client for icon and label positioning

func (NodeAttrs_Text_RefX2) AsNodeAttrsTextRefX20

func (t NodeAttrs_Text_RefX2) AsNodeAttrsTextRefX20() (NodeAttrsTextRefX20, error)

AsNodeAttrsTextRefX20 returns the union data inside the NodeAttrs_Text_RefX2 as a NodeAttrsTextRefX20

func (NodeAttrs_Text_RefX2) AsNodeAttrsTextRefX21

func (t NodeAttrs_Text_RefX2) AsNodeAttrsTextRefX21() (NodeAttrsTextRefX21, error)

AsNodeAttrsTextRefX21 returns the union data inside the NodeAttrs_Text_RefX2 as a NodeAttrsTextRefX21

func (*NodeAttrs_Text_RefX2) FromNodeAttrsTextRefX20

func (t *NodeAttrs_Text_RefX2) FromNodeAttrsTextRefX20(v NodeAttrsTextRefX20) error

FromNodeAttrsTextRefX20 overwrites any union data inside the NodeAttrs_Text_RefX2 as the provided NodeAttrsTextRefX20

func (*NodeAttrs_Text_RefX2) FromNodeAttrsTextRefX21

func (t *NodeAttrs_Text_RefX2) FromNodeAttrsTextRefX21(v NodeAttrsTextRefX21) error

FromNodeAttrsTextRefX21 overwrites any union data inside the NodeAttrs_Text_RefX2 as the provided NodeAttrsTextRefX21

func (NodeAttrs_Text_RefX2) MarshalJSON

func (t NodeAttrs_Text_RefX2) MarshalJSON() ([]byte, error)

func (*NodeAttrs_Text_RefX2) MergeNodeAttrsTextRefX20

func (t *NodeAttrs_Text_RefX2) MergeNodeAttrsTextRefX20(v NodeAttrsTextRefX20) error

MergeNodeAttrsTextRefX20 performs a merge with any union data inside the NodeAttrs_Text_RefX2, using the provided NodeAttrsTextRefX20

func (*NodeAttrs_Text_RefX2) MergeNodeAttrsTextRefX21

func (t *NodeAttrs_Text_RefX2) MergeNodeAttrsTextRefX21(v NodeAttrsTextRefX21) error

MergeNodeAttrsTextRefX21 performs a merge with any union data inside the NodeAttrs_Text_RefX2, using the provided NodeAttrsTextRefX21

func (*NodeAttrs_Text_RefX2) UnmarshalJSON

func (t *NodeAttrs_Text_RefX2) UnmarshalJSON(b []byte) error

type NodeAttrs_Text_RefY

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

NodeAttrs_Text_RefY Vertical position (0-1 relative, pixels, or percentage string e.g. '50%')

func (NodeAttrs_Text_RefY) AsNodeAttrsTextRefY0

func (t NodeAttrs_Text_RefY) AsNodeAttrsTextRefY0() (NodeAttrsTextRefY0, error)

AsNodeAttrsTextRefY0 returns the union data inside the NodeAttrs_Text_RefY as a NodeAttrsTextRefY0

func (NodeAttrs_Text_RefY) AsNodeAttrsTextRefY1

func (t NodeAttrs_Text_RefY) AsNodeAttrsTextRefY1() (NodeAttrsTextRefY1, error)

AsNodeAttrsTextRefY1 returns the union data inside the NodeAttrs_Text_RefY as a NodeAttrsTextRefY1

func (*NodeAttrs_Text_RefY) FromNodeAttrsTextRefY0

func (t *NodeAttrs_Text_RefY) FromNodeAttrsTextRefY0(v NodeAttrsTextRefY0) error

FromNodeAttrsTextRefY0 overwrites any union data inside the NodeAttrs_Text_RefY as the provided NodeAttrsTextRefY0

func (*NodeAttrs_Text_RefY) FromNodeAttrsTextRefY1

func (t *NodeAttrs_Text_RefY) FromNodeAttrsTextRefY1(v NodeAttrsTextRefY1) error

FromNodeAttrsTextRefY1 overwrites any union data inside the NodeAttrs_Text_RefY as the provided NodeAttrsTextRefY1

func (NodeAttrs_Text_RefY) MarshalJSON

func (t NodeAttrs_Text_RefY) MarshalJSON() ([]byte, error)

func (*NodeAttrs_Text_RefY) MergeNodeAttrsTextRefY0

func (t *NodeAttrs_Text_RefY) MergeNodeAttrsTextRefY0(v NodeAttrsTextRefY0) error

MergeNodeAttrsTextRefY0 performs a merge with any union data inside the NodeAttrs_Text_RefY, using the provided NodeAttrsTextRefY0

func (*NodeAttrs_Text_RefY) MergeNodeAttrsTextRefY1

func (t *NodeAttrs_Text_RefY) MergeNodeAttrsTextRefY1(v NodeAttrsTextRefY1) error

MergeNodeAttrsTextRefY1 performs a merge with any union data inside the NodeAttrs_Text_RefY, using the provided NodeAttrsTextRefY1

func (*NodeAttrs_Text_RefY) UnmarshalJSON

func (t *NodeAttrs_Text_RefY) UnmarshalJSON(b []byte) error

type NodeAttrs_Text_RefY2

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

NodeAttrs_Text_RefY2 Origin-based vertical offset (alias of refY in X6); used by the client for icon and label positioning

func (NodeAttrs_Text_RefY2) AsNodeAttrsTextRefY20

func (t NodeAttrs_Text_RefY2) AsNodeAttrsTextRefY20() (NodeAttrsTextRefY20, error)

AsNodeAttrsTextRefY20 returns the union data inside the NodeAttrs_Text_RefY2 as a NodeAttrsTextRefY20

func (NodeAttrs_Text_RefY2) AsNodeAttrsTextRefY21

func (t NodeAttrs_Text_RefY2) AsNodeAttrsTextRefY21() (NodeAttrsTextRefY21, error)

AsNodeAttrsTextRefY21 returns the union data inside the NodeAttrs_Text_RefY2 as a NodeAttrsTextRefY21

func (*NodeAttrs_Text_RefY2) FromNodeAttrsTextRefY20

func (t *NodeAttrs_Text_RefY2) FromNodeAttrsTextRefY20(v NodeAttrsTextRefY20) error

FromNodeAttrsTextRefY20 overwrites any union data inside the NodeAttrs_Text_RefY2 as the provided NodeAttrsTextRefY20

func (*NodeAttrs_Text_RefY2) FromNodeAttrsTextRefY21

func (t *NodeAttrs_Text_RefY2) FromNodeAttrsTextRefY21(v NodeAttrsTextRefY21) error

FromNodeAttrsTextRefY21 overwrites any union data inside the NodeAttrs_Text_RefY2 as the provided NodeAttrsTextRefY21

func (NodeAttrs_Text_RefY2) MarshalJSON

func (t NodeAttrs_Text_RefY2) MarshalJSON() ([]byte, error)

func (*NodeAttrs_Text_RefY2) MergeNodeAttrsTextRefY20

func (t *NodeAttrs_Text_RefY2) MergeNodeAttrsTextRefY20(v NodeAttrsTextRefY20) error

MergeNodeAttrsTextRefY20 performs a merge with any union data inside the NodeAttrs_Text_RefY2, using the provided NodeAttrsTextRefY20

func (*NodeAttrs_Text_RefY2) MergeNodeAttrsTextRefY21

func (t *NodeAttrs_Text_RefY2) MergeNodeAttrsTextRefY21(v NodeAttrsTextRefY21) error

MergeNodeAttrsTextRefY21 performs a merge with any union data inside the NodeAttrs_Text_RefY2, using the provided NodeAttrsTextRefY21

func (*NodeAttrs_Text_RefY2) UnmarshalJSON

func (t *NodeAttrs_Text_RefY2) UnmarshalJSON(b []byte) error

type NodeShape

type NodeShape string

NodeShape Node type determining its visual representation and behavior

const (
	NodeShapeActor            NodeShape = "actor"
	NodeShapeProcess          NodeShape = "process"
	NodeShapeSecurityBoundary NodeShape = "security-boundary"
	NodeShapeStore            NodeShape = "store"
	NodeShapeTextBox          NodeShape = "text-box"
)

Defines values for NodeShape.

func (NodeShape) Valid

func (e NodeShape) Valid() bool

Valid indicates whether the value is a known member of the NodeShape enum.

type Node_Data

type Node_Data struct {
	// UnderscoreMetadata Reserved namespace for structured business metadata
	UnderscoreMetadata *[]Metadata `json:"_metadata,omitempty"`

	// DataAssets References to Asset IDs associated with this cell. Each UUID must reference an existing Asset in the same threat model.
	DataAssets *[]openapi_types.UUID `json:"data_assets,omitempty"`

	// SecurityBoundary Indicates whether this cell represents a security boundary in the threat model
	SecurityBoundary     *bool                  `json:"security_boundary,omitempty"`
	AdditionalProperties map[string]interface{} `json:"-"`
}

Node_Data Flexible data storage compatible with X6, with reserved metadata namespace

func (Node_Data) Get

func (a Node_Data) Get(fieldName string) (value interface{}, found bool)

Getter for additional properties for Node_Data. Returns the specified element and whether it was found

func (Node_Data) MarshalJSON

func (a Node_Data) MarshalJSON() ([]byte, error)

Override default JSON handling for Node_Data to handle AdditionalProperties

func (*Node_Data) Set

func (a *Node_Data) Set(fieldName string, value interface{})

Setter for additional properties for Node_Data

func (*Node_Data) UnmarshalJSON

func (a *Node_Data) UnmarshalJSON(b []byte) error

Override default JSON handling for Node_Data to handle AdditionalProperties

type NotAcceptable

type NotAcceptable = Error

NotAcceptable Standard error response format

type NotFound

type NotFound = Error

NotFound Standard error response format

type Note

type Note struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// AutoGenerated True when the note was created by an automation/service-account principal. Sticky from creation.
	AutoGenerated *bool `json:"auto_generated,omitempty"`

	// Content Note content in markdown format. Safe inline HTML (tables, SVG, formatting) is allowed and sanitized server-side; dangerous elements (script, iframe, event handlers) are stripped.
	Content string `binding:"required" json:"content"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the note
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Note name
	Name string `binding:"required" json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

Note defines model for Note.

type NoteBase

type NoteBase struct {
	// Content Note content in markdown format. Safe inline HTML (tables, SVG, formatting) is allowed and sanitized server-side; dangerous elements (script, iframe, event handlers) are stripped.
	Content string `binding:"required" json:"content"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Name Note name
	Name string `binding:"required" json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

NoteBase Base fields for Note (user-writable only)

type NoteId

type NoteId = openapi_types.UUID

NoteId defines model for NoteId.

type NoteInput

type NoteInput = NoteBase

NoteInput Base fields for Note (user-writable only)

type NoteListItem

type NoteListItem struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the note
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Key-value pairs for additional note metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Note name
	Name string `binding:"required" json:"name"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

NoteListItem Summary information for Note in list responses

type NoteRepository

type NoteRepository interface {
	// CRUD operations
	Create(ctx context.Context, note *Note, threatModelID string) error
	Get(ctx context.Context, id string) (*Note, error)
	Update(ctx context.Context, note *Note, threatModelID string) error
	Delete(ctx context.Context, id string) error
	SoftDelete(ctx context.Context, id string) error
	Restore(ctx context.Context, id string) error
	HardDelete(ctx context.Context, id string) error
	GetIncludingDeleted(ctx context.Context, id string) (*Note, error)
	Patch(ctx context.Context, id string, operations []PatchOperation) (*Note, error)

	// List operations with pagination
	List(ctx context.Context, threatModelID string, offset, limit int) ([]Note, error)
	// Count returns total number of notes for a threat model
	Count(ctx context.Context, threatModelID string) (int, error)

	// Cache management
	InvalidateCache(ctx context.Context, id string) error
	WarmCache(ctx context.Context, threatModelID string) error
}

NoteRepository defines the interface for note operations with caching support SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: interface for CRUD, patch, list, count, and cache operations on threat model notes

var GlobalNoteRepository NoteRepository

type NoteSubResourceHandler

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

NoteSubResourceHandler provides handlers for note sub-resource operations SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: handler struct holding note store, DB, cache, and cache invalidator dependencies

func NewNoteSubResourceHandler

func NewNoteSubResourceHandler(noteStore NoteRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *NoteSubResourceHandler

NewNoteSubResourceHandler creates a new note sub-resource handler SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a NoteSubResourceHandler wired to the given store and cache dependencies (pure)

func (*NoteSubResourceHandler) CreateNote

func (h *NoteSubResourceHandler) CreateNote(c *gin.Context)

CreateNote creates a new note in a threat model POST /threat_models/{threat_model_id}/notes SEM@f24c94ac3b48082482bcf5b8e9642017897fe3b6: store a new sanitized note under a threat model, emit audit record, and invalidate caches (mutates shared state)

func (*NoteSubResourceHandler) DeleteNote

func (h *NoteSubResourceHandler) DeleteNote(c *gin.Context)

DeleteNote deletes a note DELETE /threat_models/{threat_model_id}/notes/{note_id} SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: delete a note by ID, emit audit record, and invalidate threat model caches (mutates shared state)

func (*NoteSubResourceHandler) GetNote

func (h *NoteSubResourceHandler) GetNote(c *gin.Context)

GetNote retrieves a specific note by ID GET /threat_models/{threat_model_id}/notes/{note_id} SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a single note by ID within a threat model (reads DB)

func (*NoteSubResourceHandler) GetNotes

func (h *NoteSubResourceHandler) GetNotes(c *gin.Context)

GetNotes retrieves all notes for a threat model with pagination GET /threat_models/{threat_model_id}/notes SEM@2e11948b04b8dda021db61f3ee3dd536d0011789: list paginated notes for a threat model and return them with total count (reads DB)

func (*NoteSubResourceHandler) PatchNote

func (h *NoteSubResourceHandler) PatchNote(c *gin.Context)

PatchNote applies JSON patch operations to a note PATCH /threat_models/{threat_model_id}/notes/{note_id} SEM@270f55053109ed75ccf6cdf123884b9edf831d15: apply authorized JSON patch operations to a note, sanitizing content paths, and emit audit record (mutates shared state)

func (*NoteSubResourceHandler) UpdateNote

func (h *NoteSubResourceHandler) UpdateNote(c *gin.Context)

UpdateNote updates an existing note PUT /threat_models/{threat_model_id}/notes/{note_id} SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: replace an existing note with sanitized content, emit audit record, and invalidate caches (mutates shared state)

type NotificationClient

type NotificationClient struct {
	// Unique identifier for the client
	ID string

	// User information
	UserID    string
	UserEmail string
	UserName  string

	// WebSocket connection
	Conn *websocket.Conn

	// Send channel for messages
	Send chan []byte

	// Subscription preferences
	Subscription *NotificationSubscription

	// Hub reference
	Hub *NotificationHub

	// Connection metadata
	ConnectedAt time.Time
}

NotificationClient represents a client connected to the notification hub SEM@66b1e1515b82356913c8625edc8616772c3c70d3: represents a connected WebSocket notification subscriber with its user info and subscription

type NotificationHub

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

NotificationHub manages all notification WebSocket connections SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: central broker that routes notification messages to subscribed WebSocket clients (mutates shared state)

func GetNotificationHub

func GetNotificationHub() *NotificationHub

GetNotificationHub returns the global notification hub instance SEM@66b1e1515b82356913c8625edc8616772c3c70d3: return the global notification hub instance (pure)

func NewNotificationHub

func NewNotificationHub() *NotificationHub

NewNotificationHub creates a new notification hub SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: build an empty NotificationHub ready to dispatch messages

func (*NotificationHub) BroadcastCollaborationEvent

func (h *NotificationHub) BroadcastCollaborationEvent(eventType NotificationMessageType, userID, diagramID, diagramName, tmID, tmName, sessionID string)

BroadcastCollaborationEvent broadcasts a collaboration event to all connected clients SEM@66b1e1515b82356913c8625edc8616772c3c70d3: dispatch a diagram collaboration event to all subscribed notification clients

func (*NotificationHub) BroadcastSystemNotification

func (h *NotificationHub) BroadcastSystemNotification(severity, message string, actionRequired bool, actionURL string)

BroadcastSystemNotification broadcasts a system notification to all connected clients SEM@66b1e1515b82356913c8625edc8616772c3c70d3: dispatch a system-level announcement to all connected notification clients

func (*NotificationHub) BroadcastThreatModelEvent

func (h *NotificationHub) BroadcastThreatModelEvent(eventType NotificationMessageType, userID string, tmID, tmName, action string)

BroadcastThreatModelEvent broadcasts a threat model event to all connected clients SEM@66b1e1515b82356913c8625edc8616772c3c70d3: dispatch a threat model lifecycle event to all subscribed notification clients

func (*NotificationHub) GetConnectedUsers

func (h *NotificationHub) GetConnectedUsers() []string

GetConnectedUsers returns a list of currently connected user IDs SEM@66b1e1515b82356913c8625edc8616772c3c70d3: list user IDs that have at least one active notification connection (reads DB)

func (*NotificationHub) GetConnectionCount

func (h *NotificationHub) GetConnectionCount() int

GetConnectionCount returns the total number of active connections SEM@66b1e1515b82356913c8625edc8616772c3c70d3: return the total number of active notification client connections (pure)

func (*NotificationHub) Run

func (h *NotificationHub) Run()

Run starts the notification hub SEM@66b1e1515b82356913c8625edc8616772c3c70d3: process client registration, unregistration, broadcasts, and periodic heartbeats in a loop (mutates shared state)

type NotificationMessage

type NotificationMessage struct {
	MessageType NotificationMessageType `json:"message_type"`
	UserID      string                  `json:"user_id"` // internal_uuid of user who triggered the event
	Timestamp   time.Time               `json:"timestamp"`
	Data        any                     `json:"data,omitempty"` // Type-specific data
}

NotificationMessage is the base structure for all notification messages SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: envelope for all WebSocket notification messages with type, actor, and payload (pure)

type NotificationMessageType

type NotificationMessageType string

NotificationMessageType represents the type of notification message SEM@66b1e1515b82356913c8625edc8616772c3c70d3: string enum of WebSocket notification event types (pure)

const (
	// Threat model related notifications
	NotificationThreatModelCreated NotificationMessageType = "threat_model_created"
	NotificationThreatModelUpdated NotificationMessageType = "threat_model_updated"
	NotificationThreatModelDeleted NotificationMessageType = "threat_model_deleted"
	NotificationThreatModelShared  NotificationMessageType = "threat_model_shared"

	// Diagram collaboration notifications
	NotificationCollaborationStarted NotificationMessageType = "collaboration_started"
	NotificationCollaborationEnded   NotificationMessageType = "collaboration_ended"
	NotificationCollaborationInvite  NotificationMessageType = "collaboration_invite"

	// System notifications
	NotificationSystemAnnouncement NotificationMessageType = "system_announcement"
	NotificationSystemMaintenance  NotificationMessageType = "system_maintenance"
	NotificationSystemUpdate       NotificationMessageType = "system_update"

	// User activity notifications
	NotificationUserJoined NotificationMessageType = "user_joined"
	NotificationUserLeft   NotificationMessageType = "user_left"

	// Keep-alive
	NotificationHeartbeat NotificationMessageType = "heartbeat"
)

type NotificationSubscription

type NotificationSubscription struct {
	UserID             string                    `json:"user_id"`
	SubscribedTypes    []NotificationMessageType `json:"subscribed_types"`
	ThreatModelFilters []string                  `json:"threat_model_filters,omitempty"` // Specific threat model IDs to filter
	DiagramFilters     []string                  `json:"diagram_filters,omitempty"`      // Specific diagram IDs to filter
}

NotificationSubscription represents a user's notification preferences SEM@66b1e1515b82356913c8625edc8616772c3c70d3: user's notification preferences including subscribed types and resource filters (pure)

type OAuthProtectedResourceMetadata

type OAuthProtectedResourceMetadata struct {
	// AuthorizationServers List of authorization server issuer identifiers that can issue tokens for this resource
	AuthorizationServers *[]string `json:"authorization_servers,omitempty"`

	// BearerMethodsSupported Supported token presentation methods for bearer tokens
	BearerMethodsSupported *[]OAuthProtectedResourceMetadataBearerMethodsSupported `json:"bearer_methods_supported,omitempty"`

	// JwksUri URL of the protected resource's JSON Web Key Set (RFC 9728)
	JwksUri *string `json:"jwks_uri,omitempty"`

	// Resource The protected resource's resource identifier URL
	Resource string `json:"resource"`

	// ResourceDocumentation URL with information for developers on how to use this protected resource
	ResourceDocumentation *string `json:"resource_documentation,omitempty"`

	// ResourceName Human-readable name of the protected resource
	ResourceName *string `json:"resource_name,omitempty"`

	// ScopesSupported JSON array of OAuth scope values supported by this protected resource
	ScopesSupported *[]string `json:"scopes_supported,omitempty"`

	// TlsClientCertificateBoundAccessTokens Whether the protected resource supports TLS client certificate bound access tokens
	TlsClientCertificateBoundAccessTokens *bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`
}

OAuthProtectedResourceMetadata OAuth 2.0 protected resource metadata as defined in RFC 9728

type OAuthProtectedResourceMetadataBearerMethodsSupported

type OAuthProtectedResourceMetadataBearerMethodsSupported string

OAuthProtectedResourceMetadataBearerMethodsSupported OAuth 2.0 bearer token transmission method (RFC 6750)

Defines values for OAuthProtectedResourceMetadataBearerMethodsSupported.

func (OAuthProtectedResourceMetadataBearerMethodsSupported) Valid

Valid indicates whether the value is a known member of the OAuthProtectedResourceMetadataBearerMethodsSupported enum.

type OffsetQueryParam

type OffsetQueryParam = int

OffsetQueryParam defines model for OffsetQueryParam.

type OperationHistory

type OperationHistory struct {
	// Operations by sequence number
	Operations map[uint64]*HistoryEntry
	// Current diagram state snapshot for conflict detection
	CurrentState map[string]*DfdDiagram_Cells_Item
	// Maximum history entries to keep
	MaxEntries int
	// Current position in history for undo/redo (points to last applied operation)
	CurrentPosition uint64
	// contains filtered or unexported fields
}

OperationHistory tracks mutations for conflict resolution and undo/redo SEM@be6cc4edcc9140493267132a7d584481845e0dfe: bounded log of diagram cell mutations supporting undo/redo and conflict detection (pure)

func NewOperationHistory

func NewOperationHistory() *OperationHistory

NewOperationHistory creates a new operation history SEM@be6cc4edcc9140493267132a7d584481845e0dfe: build an empty operation history capped at 100 entries (pure)

func (*OperationHistory) AddOperation

func (h *OperationHistory) AddOperation(entry *HistoryEntry)

AddOperation adds a new operation to history and updates current position SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: append a cell operation to history, update current diagram state, and evict old entries (mutates shared state)

func (*OperationHistory) CanRedo

func (h *OperationHistory) CanRedo() bool

CanRedo returns true if there are operations to redo SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: report whether any operations are available to redo (pure)

func (*OperationHistory) CanUndo

func (h *OperationHistory) CanUndo() bool

CanUndo returns true if there are operations to undo SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: report whether any operations are available to undo (pure)

func (*OperationHistory) GetRedoOperation

func (h *OperationHistory) GetRedoOperation() (*HistoryEntry, bool)

GetRedoOperation returns the operation to redo SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: return the next history entry for redo, or false if none (pure)

func (*OperationHistory) GetUndoOperation

func (h *OperationHistory) GetUndoOperation() (*HistoryEntry, map[string]*DfdDiagram_Cells_Item, bool)

GetUndoOperation returns the operation to undo and the previous state SEM@be6cc4edcc9140493267132a7d584481845e0dfe: return the current history entry and its pre-state snapshot for undo, or false if none (pure)

func (*OperationHistory) MoveToPosition

func (h *OperationHistory) MoveToPosition(newPosition uint64)

MoveToPosition updates the current position in history (for undo/redo) SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: advance or rewind the history cursor to the given sequence position (mutates shared state)

type OperationRejectedMessage

type OperationRejectedMessage struct {
	MessageType    MessageType `json:"message_type"`
	OperationID    string      `json:"operation_id"`
	SequenceNumber *uint64     `json:"sequence_number,omitempty"` // May be assigned before rejection
	UpdateVector   int64       `json:"update_vector"`             // Current server update vector
	Reason         string      `json:"reason"`                    // Structured reason code
	Message        string      `json:"message"`                   // Human-readable description
	Details        *string     `json:"details,omitempty"`         // Optional technical details
	AffectedCells  []string    `json:"affected_cells,omitempty"`  // Cell IDs affected
	RequiresResync bool        `json:"requires_resync"`           // Whether client should resync
	Timestamp      time.Time   `json:"timestamp"`
}

OperationRejectedMessage represents a notification sent exclusively to the operation originator when their diagram operation is rejected SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: WebSocket message sent to the originator when their diagram operation is rejected (pure)

func (OperationRejectedMessage) GetMessageType

func (m OperationRejectedMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for an operation-rejected message (pure)

func (OperationRejectedMessage) Validate

func (m OperationRejectedMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate an operation-rejected message; reject invalid operation ID, reason code, or missing fields (pure)

type OperationValidationResult

type OperationValidationResult struct {
	Valid            bool
	Reason           string
	CorrectionNeeded bool
	ConflictDetected bool
	StateChanged     bool
	CellsModified    []string
	PreviousState    map[string]*DfdDiagram_Cells_Item
}

OperationValidationResult represents the result of operation validation SEM@be6cc4edcc9140493267132a7d584481845e0dfe: data type capturing the outcome of a cell operation validation including conflict and change flags (pure)

func ProcessDiagramCellOperations

func ProcessDiagramCellOperations(diagramID string, operations CellPatchOperation) (*OperationValidationResult, error)

ProcessDiagramCellOperations provides a shared interface for diagram cell operations This can be used by both REST PATCH handlers and WebSocket operations SEM@1266bb4768a3bd15fb079e5ce593b5d74f5689a7: dispatch a set of cell patch operations to the diagram store via the cell operation processor (reads DB)

type OwnerQueryParam

type OwnerQueryParam = string

OwnerQueryParam defines model for OwnerQueryParam.

type Ownership

type Ownership string

Ownership is the resource-level access tier required by an operation. SEM@e2de7c62a484c8859b1f6760addcf1b628ec49bb: enum of resource-level access tiers required by an operation (pure)

const (
	OwnershipNone   Ownership = "none"
	OwnershipReader Ownership = "reader"
	OwnershipWriter Ownership = "writer"
	OwnershipOwner  Ownership = "owner"
)

type OwnershipTransferHandler

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

OwnershipTransferHandler handles ownership transfer operations SEM@36c1f84217ecf3f5087ad65186cd974b9b4df275: handler that transfers resource ownership between users via the auth service

func NewOwnershipTransferHandler

func NewOwnershipTransferHandler(authService *auth.Service) *OwnershipTransferHandler

NewOwnershipTransferHandler creates a new ownership transfer handler SEM@36c1f84217ecf3f5087ad65186cd974b9b4df275: build an OwnershipTransferHandler backed by the given auth service

func (*OwnershipTransferHandler) TransferAdminUserOwnership

func (h *OwnershipTransferHandler) TransferAdminUserOwnership(c *gin.Context, internalUuid openapi_types.UUID)

TransferAdminUserOwnership handles POST /admin/users/{internal_uuid}/transfer SEM@36c1f84217ecf3f5087ad65186cd974b9b4df275: transfer a specified user's owned resources to a target user on behalf of an admin (reads DB)

func (*OwnershipTransferHandler) TransferCurrentUserOwnership

func (h *OwnershipTransferHandler) TransferCurrentUserOwnership(c *gin.Context)

TransferCurrentUserOwnership handles POST /me/transfer SEM@36c1f84217ecf3f5087ad65186cd974b9b4df275: transfer the authenticated user's owned resources to a target user (reads DB)

type PDFEmbeddingSource

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

PDFEmbeddingSource fetches PDF documents and extracts their text content. It uses SafeHTTPClient (DNS-pinned, SSRF-checked) and caps downloads at 50 MiB. SEM@b554bb5371f70e0115912131e032671de29e8c09: embedding source that fetches and extracts text from remote PDF documents (pure)

func NewPDFEmbeddingSource

func NewPDFEmbeddingSource(ssrfValidator *URIValidator) *PDFEmbeddingSource

NewPDFEmbeddingSource creates a new PDFEmbeddingSource with the given SSRF validator. SEM@80346558ce851de593c85a2d5660f92a649b1686: build a PDF embedding source with SSRF-safe HTTP client and 50 MiB download cap (pure)

func (*PDFEmbeddingSource) CanHandle

func (p *PDFEmbeddingSource) CanHandle(_ context.Context, ref EntityReference) bool

CanHandle returns true for entity references whose URI ends with ".pdf" (case-insensitive). SEM@80346558ce851de593c85a2d5660f92a649b1686: report whether an entity reference URI ends with .pdf (pure)

func (*PDFEmbeddingSource) Extract

Extract fetches a PDF from the given URI via the egress helper (DNS-pinned, SSRF-checked), writes it to a temp file, and extracts plain text. The download is limited to 50 MiB. SEM@80346558ce851de593c85a2d5660f92a649b1686: fetch a PDF from a URI via SSRF-checked client and extract its plain text

func (*PDFEmbeddingSource) Name

func (p *PDFEmbeddingSource) Name() string

Name returns the provider name for logging. SEM@80346558ce851de593c85a2d5660f92a649b1686: return the provider name for the PDF embedding source (pure)

type PaginationLimit

type PaginationLimit = int

PaginationLimit defines model for PaginationLimit.

type PaginationOffset

type PaginationOffset = int

PaginationOffset defines model for PaginationOffset.

type ParentVerifier

type ParentVerifier func(ctx context.Context, id uuid.UUID) error

ParentVerifier is a function that checks if a parent entity exists. It returns nil if the entity exists, or an error if not. SEM@59c58c6a840231ad2c078c9afd1e7bac7a07b651: function type that confirms a parent entity exists by UUID (reads DB)

type ParsedFilter

type ParsedFilter struct {
	Operator FilterOperator
	Value    string // Empty for is:null/is:notnull, populated for plain values
}

ParsedFilter holds the result of parsing a filter query parameter value. SEM@40d9903ef472b183a4ed2bcf0478562c757f255d: parsed filter holding an operator type and an optional plain value (pure)

func ParseFilterValue

func ParseFilterValue(paramName, rawValue string) (ParsedFilter, error)

ParseFilterValue parses a query parameter value for operator prefixes. Recognized operators: is:null, is:notnull. Unrecognized operators return a 400 RequestError. Values without a recognized operator prefix are returned as plain values. SEM@40d9903ef472b183a4ed2bcf0478562c757f255d: parse a filter query parameter value into an operator and value, rejecting unknown operators (pure)

type Participant

type Participant struct {
	// LastActivity Last activity timestamp
	LastActivity time.Time `json:"last_activity"`

	// Permissions Access permissions in the collaboration session
	Permissions ParticipantPermissions `json:"permissions"`

	// User User profile information retrieved from identity provider
	User User `json:"user"`
}

Participant A participant in a collaboration session

type ParticipantPermissions

type ParticipantPermissions string

ParticipantPermissions Access permissions in the collaboration session

const (
	ParticipantPermissionsReader ParticipantPermissions = "reader"
	ParticipantPermissionsWriter ParticipantPermissions = "writer"
)

Defines values for ParticipantPermissions.

func (ParticipantPermissions) Valid

func (e ParticipantPermissions) Valid() bool

Valid indicates whether the value is a known member of the ParticipantPermissions enum.

type ParticipantsUpdateMessage

type ParticipantsUpdateMessage struct {
	MessageType      MessageType        `json:"message_type"`
	Participants     []AsyncParticipant `json:"participants"`
	Host             User               `json:"host"`
	CurrentPresenter *User              `json:"current_presenter"`
}

ParticipantsUpdateMessage provides complete participant list with roles SEM@57c7fe4675f8c33d1349a00276ae1c9d7deff87b: WebSocket message broadcasting the full participant list with host and presenter (pure)

func (ParticipantsUpdateMessage) GetMessageType

func (m ParticipantsUpdateMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for a participants update message (pure)

func (ParticipantsUpdateMessage) Validate

func (m ParticipantsUpdateMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a participants update message; reject invalid host, presenter, or participant fields (pure)

type PatchAdminSurveyApplicationJSONPatchPlusJSONRequestBody

type PatchAdminSurveyApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchAdminSurveyApplicationJSONPatchPlusJSONRequestBody defines body for PatchAdminSurvey for application/json-patch+json ContentType.

type PatchAuthContext

type PatchAuthContext struct {
	IsOwner            bool
	IsSecurityReviewer bool
	IsServiceAccount   bool
}

PatchAuthContext carries the role bits the allowlist checker needs to arbitrate gated paths. All fields default to false. SEM@4072882890c92c6534c87aef6823363686786a56: caller role bits used to authorize access to gated PATCH paths (pure)

type PatchIntakeSurveyResponseApplicationJSONPatchPlusJSONRequestBody

type PatchIntakeSurveyResponseApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchIntakeSurveyResponseApplicationJSONPatchPlusJSONRequestBody defines body for PatchIntakeSurveyResponse for application/json-patch+json ContentType.

type PatchIntakeSurveyResponseParams

type PatchIntakeSurveyResponseParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchIntakeSurveyResponseParams defines parameters for PatchIntakeSurveyResponse.

type PatchOperation

type PatchOperation struct {
	Op    string `json:"op" binding:"required,oneof=add remove replace move copy test"`
	Path  string `json:"path" binding:"required"`
	Value any    `json:"value,omitempty"`
	From  string `json:"from,omitempty"`
}

PatchOperation represents a JSON Patch operation SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: represent a single JSON Patch operation with op, path, value, and from fields (pure)

func ParsePatchRequest

func ParsePatchRequest(c *gin.Context) ([]PatchOperation, error)

ParsePatchRequest parses JSON Patch operations from the request body SEM@59c58c6a840231ad2c078c9afd1e7bac7a07b651: parse and validate a JSON Patch operation array from the request body (pure)

type PatchPathAllowList

type PatchPathAllowList struct {
	// MutablePaths is the set of paths a request may freely target.
	// "/foo" matches "/foo" and any deeper path "/foo/...".
	MutablePaths []string

	// SecurityReviewerOnly is the set of paths a request may target ONLY
	// when the caller is a security reviewer or a service account. The
	// matching rule is identical to MutablePaths.
	SecurityReviewerOnly []string

	// OwnerCanClear is the subset of SecurityReviewerOnly paths that the
	// resource owner may also target, but only with a clearing op
	// (an "remove" op, or a "replace" whose value is JSON null). Setting
	// such a path to a non-null value still requires the security
	// reviewer or service account role. This allows an owner to release
	// reviewer-protected fields (e.g. clear /security_reviewer) without
	// granting them the ability to install or change a value.
	OwnerCanClear []string

	// OwnerOnly is the set of paths a request may target ONLY when the
	// caller has owner role on the resource. Same matching rule.
	OwnerOnly []string
}

PatchPathAllowList is the per-resource allowlist of JSON-Pointer prefixes a PATCH request may target. Default-deny: any operation whose path is not equal to or a child of an allowlisted prefix is rejected with a 400 invalid_input.

Replaces the historical "prohibitedPaths" deny-list which was prone to silent gaps when new fields were added to a resource (T2/T19/T27 in docs/THREAT_MODEL.md). SEM@9ec514da7fdbd094b7c66fd638baafb5c2c17f18: allowlist of JSON Pointer prefixes that a PATCH request may target, with role-gated subsets (pure)

type PatchProjectApplicationJSONPatchPlusJSONRequestBody

type PatchProjectApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchProjectApplicationJSONPatchPlusJSONRequestBody defines body for PatchProject for application/json-patch+json ContentType.

type PatchProjectNoteApplicationJSONPatchPlusJSONRequestBody

type PatchProjectNoteApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchProjectNoteApplicationJSONPatchPlusJSONRequestBody defines body for PatchProjectNote for application/json-patch+json ContentType.

type PatchProjectParams

type PatchProjectParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchProjectParams defines parameters for PatchProject.

type PatchTeamApplicationJSONPatchPlusJSONRequestBody

type PatchTeamApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchTeamApplicationJSONPatchPlusJSONRequestBody defines body for PatchTeam for application/json-patch+json ContentType.

type PatchTeamNoteApplicationJSONPatchPlusJSONRequestBody

type PatchTeamNoteApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchTeamNoteApplicationJSONPatchPlusJSONRequestBody defines body for PatchTeamNote for application/json-patch+json ContentType.

type PatchTeamParams

type PatchTeamParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchTeamParams defines parameters for PatchTeam.

type PatchThreatModelApplicationJSONPatchPlusJSONRequestBody

type PatchThreatModelApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchThreatModelApplicationJSONPatchPlusJSONRequestBody defines body for PatchThreatModel for application/json-patch+json ContentType.

type PatchThreatModelAssetApplicationJSONPatchPlusJSONRequestBody

type PatchThreatModelAssetApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchThreatModelAssetApplicationJSONPatchPlusJSONRequestBody defines body for PatchThreatModelAsset for application/json-patch+json ContentType.

type PatchThreatModelAssetParams

type PatchThreatModelAssetParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchThreatModelAssetParams defines parameters for PatchThreatModelAsset.

type PatchThreatModelDiagramApplicationJSONPatchPlusJSONRequestBody

type PatchThreatModelDiagramApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchThreatModelDiagramApplicationJSONPatchPlusJSONRequestBody defines body for PatchThreatModelDiagram for application/json-patch+json ContentType.

type PatchThreatModelDiagramParams

type PatchThreatModelDiagramParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchThreatModelDiagramParams defines parameters for PatchThreatModelDiagram.

type PatchThreatModelDocumentApplicationJSONPatchPlusJSONRequestBody

type PatchThreatModelDocumentApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchThreatModelDocumentApplicationJSONPatchPlusJSONRequestBody defines body for PatchThreatModelDocument for application/json-patch+json ContentType.

type PatchThreatModelDocumentParams

type PatchThreatModelDocumentParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchThreatModelDocumentParams defines parameters for PatchThreatModelDocument.

type PatchThreatModelNoteApplicationJSONPatchPlusJSONRequestBody

type PatchThreatModelNoteApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchThreatModelNoteApplicationJSONPatchPlusJSONRequestBody defines body for PatchThreatModelNote for application/json-patch+json ContentType.

type PatchThreatModelParams

type PatchThreatModelParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchThreatModelParams defines parameters for PatchThreatModel.

type PatchThreatModelRepositoryApplicationJSONPatchPlusJSONRequestBody

type PatchThreatModelRepositoryApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchThreatModelRepositoryApplicationJSONPatchPlusJSONRequestBody defines body for PatchThreatModelRepository for application/json-patch+json ContentType.

type PatchThreatModelThreatApplicationJSONPatchPlusJSONRequestBody

type PatchThreatModelThreatApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchThreatModelThreatApplicationJSONPatchPlusJSONRequestBody defines body for PatchThreatModelThreat for application/json-patch+json ContentType.

type PatchThreatModelThreatParams

type PatchThreatModelThreatParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

PatchThreatModelThreatParams defines parameters for PatchThreatModelThreat.

type PatchTriageSurveyResponseApplicationJSONPatchPlusJSONRequestBody

type PatchTriageSurveyResponseApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchTriageSurveyResponseApplicationJSONPatchPlusJSONRequestBody defines body for PatchTriageSurveyResponse for application/json-patch+json ContentType.

type PayloadTooLarge

type PayloadTooLarge = Error

PayloadTooLarge Standard error response format

type PendingIdentityLinkResponse

type PendingIdentityLinkResponse struct {
	Account struct {
		// Email Email address of this TMI account
		Email string `json:"email"`

		// Provider Primary identity provider of this TMI account
		Provider string `json:"provider"`
	} `json:"account"`
	Pending struct {
		// Email Cached email from the second identity (display only)
		Email *string `json:"email,omitempty"`

		// Name Cached display name from the second identity
		Name *string `json:"name,omitempty"`

		// Provider Identity provider of the second identity
		Provider string `json:"provider"`

		// ProviderUserId User identifier at the provider (first 8 chars + ellipsis)
		ProviderUserId string `json:"provider_user_id"`
	} `json:"pending"`
}

PendingIdentityLinkResponse defines model for PendingIdentityLinkResponse.

type PickerMetadata

type PickerMetadata struct {
	ProviderID *string
	FileID     *string
	MimeType   *string
}

PickerMetadata carries the picker-registration fields from a document row. When present, it indicates the client attached the document via Google Picker (or equivalent), and the FindSourceForDocument dispatch may route to the delegated source if the user has an active linked token.

All three fields are non-nil together or all nil together (invariant enforced at attach time). SEM@faff1a18afeac13e5f8de0f7b7b2e16ba77529af: picker-registration metadata (provider, file ID, MIME type) attached to a document row

type PickerRegistration

type PickerRegistration struct {
	// FileId Provider-native file identifier from the picker (e.g. Google Drive file ID, or Microsoft "{driveId}:{itemId}")
	FileId string `json:"file_id"`

	// MimeType MIME type returned by the picker
	MimeType string `json:"mime_type"`

	// ProviderId Content OAuth provider that issued the picker grant
	ProviderId PickerRegistrationProviderId `json:"provider_id"`
}

PickerRegistration Client-provided registration for a picker-mediated provider attachment. Supplied when a user attaches a file to a threat model via a picker flow (Google Picker, Microsoft File Picker); the server stores these fields on the document and uses them to dispatch fetch and access-validation operations through the matching delegated source.

type PickerRegistrationProviderId

type PickerRegistrationProviderId string

PickerRegistrationProviderId Content OAuth provider that issued the picker grant

const (
	GoogleWorkspace PickerRegistrationProviderId = "google_workspace"
	Microsoft       PickerRegistrationProviderId = "microsoft"
)

Defines values for PickerRegistrationProviderId.

func (PickerRegistrationProviderId) Valid

Valid indicates whether the value is a known member of the PickerRegistrationProviderId enum.

type PickerTokenConfig

type PickerTokenConfig struct {
	// ProviderConfig is the provider-specific picker-init payload. Keys vary
	// per provider — for google_workspace: developer_key, app_id; for
	// microsoft: client_id, tenant_id, picker_origin.
	ProviderConfig map[string]string

	// Deprecated: read from ProviderConfig["developer_key"] in new code.
	DeveloperKey string
	// Deprecated: read from ProviderConfig["app_id"] in new code.
	AppID string
}

PickerTokenConfig holds the public picker configuration values for one OAuth provider. These are not secrets; they are served to the browser client and used to initialize the provider's picker widget.

ProviderConfig is the canonical map; DeveloperKey and AppID are kept for backward-compat with the legacy Google-only response shape and are populated by the handler from ProviderConfig at response time when present. SEM@e7e7192ac48f48a91647243aafb7a9117b15e508: public picker OAuth configuration for one provider, including legacy and canonical fields (pure)

type PickerTokenHandler

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

PickerTokenHandler mints short-lived Google OAuth access tokens for browser-side Google Picker JS.

The route (POST /me/picker_tokens/{provider_id}) is registered in Task 9.1. This handler only validates inputs and delegates to the shared refresh logic. SEM@2ee0dcd2aa9cfc05225090376624012ff16557f2: HTTP handler that mints short-lived OAuth access tokens for browser picker widgets (pure)

func NewPickerTokenHandler

func NewPickerTokenHandler(
	tokens ContentTokenRepository,
	registry *ContentOAuthProviderRegistry,
	configs map[string]PickerTokenConfig,
	userLookup func(c *gin.Context) (string, bool),
) *PickerTokenHandler

NewPickerTokenHandler creates a new PickerTokenHandler. configs maps provider IDs to their picker configuration values. userLookup extracts the authenticated user ID from the Gin context. SEM@2ee0dcd2aa9cfc05225090376624012ff16557f2: build a PickerTokenHandler wired to a token repository, provider registry, and configs (pure)

func (*PickerTokenHandler) Handle

func (h *PickerTokenHandler) Handle(c *gin.Context)

Handle processes POST /me/picker_tokens/{provider_id}.

Validation order (mirrors task spec):

  1. configs[providerID] exists AND has at least one of {ProviderConfig, DeveloperKey, AppID} populated → else 422.
  2. registry.Get(providerID) exists → else 422 (provider_not_registered).
  3. User in context → else 401.
  4. Token repo lookup → 404 if not linked.
  5. Token status check → 401 if failed_refresh.
  6. refreshIfNeeded → 401/503 on error.
  7. 200 with access_token, expires_at, developer_key, app_id.

SEM@67569fbeb577336dd278978473f2ea666cf1543f: validate and dispatch a picker token request, refreshing the OAuth token if needed (reads DB)

type PickerTokenResponse

type PickerTokenResponse struct {
	// AccessToken Short-lived OAuth access token, scoped to the picker session.
	AccessToken string `json:"access_token"`

	// AppId Google Cloud app id. Deprecated — prefer provider_config.app_id. Populated only for provider_id=google_workspace.
	AppId *string `json:"app_id,omitempty"`

	// DeveloperKey Google Picker developer key. Deprecated — prefer provider_config.developer_key. Populated only for provider_id=google_workspace.
	DeveloperKey *string `json:"developer_key,omitempty"`

	// ExpiresAt Token expiration timestamp (RFC3339).
	ExpiresAt time.Time `json:"expires_at"`

	// ProviderConfig Provider-specific public configuration values for picker initialization. Keys vary by provider — see provider documentation. For google_workspace: developer_key, app_id. For microsoft: client_id, tenant_id, picker_origin.
	ProviderConfig *map[string]string `json:"provider_config,omitempty"`
}

PickerTokenResponse Response body for `POST /me/picker_tokens/{provider_id}`. Carries a short-lived access token and the public picker configuration values that the browser client needs to initialize the provider's picker widget.

type PipelineEmbeddingSource

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

PipelineEmbeddingSource adapts the two-layer ContentPipeline to the existing EmbeddingSource interface, bridging old and new code. SEM@dc7c0088604cc1a0974d51f13e10814917275372: adapter wrapping a fixed ContentPipeline as an EmbeddingSource (pure)

func NewPipelineEmbeddingSource

func NewPipelineEmbeddingSource(pipeline *ContentPipeline) *PipelineEmbeddingSource

NewPipelineEmbeddingSource creates an adapter. SEM@80346558ce851de593c85a2d5660f92a649b1686: build a PipelineEmbeddingSource adapter over a given ContentPipeline (pure)

func (*PipelineEmbeddingSource) CanHandle

CanHandle returns true for entity references with a URI. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: report whether an entity reference has a URI and can be extracted (pure)

func (*PipelineEmbeddingSource) Extract

Extract delegates to the content pipeline. For document entities the document-aware variant is used so the dev/test-only extracted-text dump hook (#337) fires; for non-document URI-bearing entities the plain Extract path is sufficient. SEM@80346558ce851de593c85a2d5660f92a649b1686: fetch and extract text content via the content pipeline for a given entity reference

func (*PipelineEmbeddingSource) Name

func (p *PipelineEmbeddingSource) Name() string

Name returns the adapter name. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: return the provider name for the static pipeline embedding source (pure)

type PipelineLimits

type PipelineLimits struct {
	WallClockBudget time.Duration
}

PipelineLimits is the subset of ContentExtractorsConfig the pipeline needs directly (not just the registered extractors). Today this is just the wall-clock budget; bringing in others as needed. SEM@d3cdf19de7c031cfdc661e3c7549c0c38a5ed523: configures wall-clock budget for content extraction (pure)

func DefaultPipelineLimits

func DefaultPipelineLimits() PipelineLimits

DefaultPipelineLimits returns the design-spec default budget; used by tests. SEM@d3cdf19de7c031cfdc661e3c7549c0c38a5ed523: build PipelineLimits with a 30-second wall-clock budget (pure)

type Point

type Point struct {
	// X X coordinate
	X float32 `json:"x"`

	// Y Y coordinate
	Y float32 `json:"y"`
}

Point A 2D point with x and y coordinates

type PortConfiguration

type PortConfiguration struct {
	// Groups Port group definitions
	Groups *map[string]struct {
		// Attrs Visual attributes for port group rendering (e.g., circle styling)
		Attrs *map[string]interface{} `json:"attrs,omitempty"`

		// Position Port position on the node
		Position *PortConfigurationGroupsPosition `json:"position,omitempty"`
	} `json:"groups,omitempty"`

	// Items Individual port instances
	Items *[]struct {
		// Attrs Visual attributes for port rendering (e.g., text visibility, circle styling)
		Attrs *map[string]interface{} `json:"attrs,omitempty"`

		// Group Port group this port belongs to
		Group string `json:"group"`

		// Id Unique port identifier
		Id string `json:"id"`
	} `json:"items,omitempty"`
}

PortConfiguration Port configuration for node connections

type PortConfigurationGroupsPosition

type PortConfigurationGroupsPosition string

PortConfigurationGroupsPosition Port position on the node

Defines values for PortConfigurationGroupsPosition.

func (PortConfigurationGroupsPosition) Valid

Valid indicates whether the value is a known member of the PortConfigurationGroupsPosition enum.

type PreconditionRequired

type PreconditionRequired = Error

PreconditionRequired Standard error response format

type PresenterCursorHandler

type PresenterCursorHandler struct{}

PresenterCursorHandler handles presenter cursor messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: handle a presenter_cursor WebSocket message for cursor position broadcast (pure)

func (*PresenterCursorHandler) HandleMessage

func (h *PresenterCursorHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: dispatch a presenter cursor WebSocket message to the diagram session (mutates shared state)

func (*PresenterCursorHandler) MessageType

func (h *PresenterCursorHandler) MessageType() string

SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: return the presenter_cursor message type discriminator (pure)

type PresenterCursorMessage

type PresenterCursorMessage struct {
	MessageType    MessageType    `json:"message_type"`
	CursorPosition CursorPosition `json:"cursor_position"`
}

SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: WebSocket message broadcasting the presenter's current cursor position (pure)

func (PresenterCursorMessage) GetMessageType

func (m PresenterCursorMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for PresenterCursorMessage (pure)

func (PresenterCursorMessage) Validate

func (m PresenterCursorMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a PresenterCursorMessage has the expected message type (pure)

type PresenterDeniedEvent

type PresenterDeniedEvent struct {
	MessageType MessageType `json:"message_type"`
	DeniedUser  User        `json:"denied_user"`
}

PresenterDeniedEvent is sent by server to the denied user SEM@15d7086fc0b3014fcf08da9f792833c9550907d0: server-to-client WebSocket event informing a user their presenter request was denied (pure)

func (PresenterDeniedEvent) GetMessageType

func (m PresenterDeniedEvent) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for PresenterDeniedEvent (pure)

func (PresenterDeniedEvent) Validate

func (m PresenterDeniedEvent) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a PresenterDeniedEvent has correct type and identifiable denied user (pure)

type PresenterDeniedRequest

type PresenterDeniedRequest struct {
	MessageType MessageType `json:"message_type"`
	DeniedUser  User        `json:"denied_user"`
}

PresenterDeniedRequest is sent by host to server to deny a presenter request SEM@15d7086fc0b3014fcf08da9f792833c9550907d0: host-to-server WebSocket message denying a participant's presenter request (pure)

func (PresenterDeniedRequest) GetMessageType

func (m PresenterDeniedRequest) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for PresenterDeniedRequest (pure)

func (PresenterDeniedRequest) Validate

func (m PresenterDeniedRequest) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a PresenterDeniedRequest has correct type and identifiable denied user (pure)

type PresenterDeniedRequestHandler

type PresenterDeniedRequestHandler struct{}

PresenterDeniedRequestHandler handles presenter denied request messages from host SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: handle a presenter_denied_request WebSocket message from the host (pure)

func (*PresenterDeniedRequestHandler) HandleMessage

func (h *PresenterDeniedRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: dispatch a presenter denied WebSocket message to the diagram session (mutates shared state)

func (*PresenterDeniedRequestHandler) MessageType

func (h *PresenterDeniedRequestHandler) MessageType() string

SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: return the presenter_denied_request message type discriminator (pure)

type PresenterRequestEvent

type PresenterRequestEvent struct {
	MessageType    MessageType `json:"message_type"`
	RequestingUser User        `json:"requesting_user"`
}

PresenterRequestEvent is sent by server to host when a participant requests presenter SEM@3c44b862a22a0ad321ed622392453ad48bae4799: server-to-host WebSocket event notifying of a participant's presenter request (pure)

func (PresenterRequestEvent) GetMessageType

func (m PresenterRequestEvent) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for PresenterRequestEvent (pure)

func (PresenterRequestEvent) Validate

func (m PresenterRequestEvent) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a PresenterRequestEvent has correct type and identifiable requesting user (pure)

type PresenterRequestHandler

type PresenterRequestHandler struct{}

PresenterRequestHandler handles presenter request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: handle a presenter_request WebSocket message by dispatching to the session (pure)

func (*PresenterRequestHandler) HandleMessage

func (h *PresenterRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: dispatch a presenter request WebSocket message to the diagram session (mutates shared state)

func (*PresenterRequestHandler) MessageType

func (h *PresenterRequestHandler) MessageType() string

SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: return the presenter_request message type discriminator (pure)

type PresenterRequestMessage

type PresenterRequestMessage struct {
	MessageType MessageType `json:"message_type"`
}

SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: client-to-server WebSocket message requesting presenter role (pure)

func (PresenterRequestMessage) GetMessageType

func (m PresenterRequestMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for PresenterRequestMessage (pure)

func (PresenterRequestMessage) Validate

func (m PresenterRequestMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a PresenterRequestMessage has the expected message type (pure)

type PresenterSelectionHandler

type PresenterSelectionHandler struct{}

PresenterSelectionHandler handles presenter selection messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: handle a presenter_selection WebSocket message for selection state broadcast (pure)

func (*PresenterSelectionHandler) HandleMessage

func (h *PresenterSelectionHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: dispatch a presenter selection WebSocket message to the diagram session (mutates shared state)

func (*PresenterSelectionHandler) MessageType

func (h *PresenterSelectionHandler) MessageType() string

SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: return the presenter_selection message type discriminator (pure)

type PresenterSelectionMessage

type PresenterSelectionMessage struct {
	MessageType   MessageType `json:"message_type"`
	SelectedCells []string    `json:"selected_cells"`
}

SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: WebSocket message broadcasting the presenter's currently selected cell UUIDs (pure)

func (PresenterSelectionMessage) GetMessageType

func (m PresenterSelectionMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for PresenterSelectionMessage (pure)

func (PresenterSelectionMessage) Validate

func (m PresenterSelectionMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a PresenterSelectionMessage has correct type and UUID-formatted cell IDs (pure)

type Principal

type Principal struct {
	// DisplayName Human-readable display name for UI presentation
	DisplayName *string `json:"display_name,omitempty"`

	// Email Email address (required for users, optional for groups)
	Email *openapi_types.Email `json:"email,omitempty"`

	// PrincipalType Type of principal: user (individual) or group
	PrincipalType PrincipalPrincipalType `json:"principal_type"`

	// Provider Identity provider name (e.g., "google", "github", "microsoft", "tmi"). Use "tmi" for TMI built-in groups.
	Provider string `json:"provider"`

	// ProviderId Provider-assigned identifier. For users: provider_user_id (e.g., email or OAuth sub). For groups: group_name.
	ProviderId string `json:"provider_id"`
}

Principal Base identity representation for users and groups with portable, globally-unique identifiers

type PrincipalPrincipalType

type PrincipalPrincipalType string

PrincipalPrincipalType Type of principal: user (individual) or group

const (
	PrincipalPrincipalTypeGroup PrincipalPrincipalType = "group"
	PrincipalPrincipalTypeUser  PrincipalPrincipalType = "user"
)

Defines values for PrincipalPrincipalType.

func (PrincipalPrincipalType) Valid

func (e PrincipalPrincipalType) Valid() bool

Valid indicates whether the value is a known member of the PrincipalPrincipalType enum.

type PriorityQueryParam

type PriorityQueryParam = []string

PriorityQueryParam defines model for PriorityQueryParam.

type ProcessSAMLLogoutParams

type ProcessSAMLLogoutParams struct {
	// SAMLRequest Base64-encoded SAML logout request
	SAMLRequest SamlrequestQueryParam `form:"SAMLRequest" json:"SAMLRequest"`
}

ProcessSAMLLogoutParams defines parameters for ProcessSAMLLogout.

type ProcessSAMLLogoutPostFormdataRequestBody

type ProcessSAMLLogoutPostFormdataRequestBody = SamlSingleLogoutRequest

ProcessSAMLLogoutPostFormdataRequestBody defines body for ProcessSAMLLogoutPost for application/x-www-form-urlencoded ContentType.

type ProcessSAMLResponseFormdataRequestBody

type ProcessSAMLResponseFormdataRequestBody = SamlAssertionConsumerRequest

ProcessSAMLResponseFormdataRequestBody defines body for ProcessSAMLResponse for application/x-www-form-urlencoded ContentType.

type Project

type Project struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// CreatedBy User who created the project
	CreatedBy *User `json:"created_by,omitempty"`

	// Description Project description
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the project (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// ModifiedBy User who last modified the project
	ModifiedBy *User `json:"modified_by,omitempty"`

	// Name Project name
	Name string `json:"name"`

	// Notes List of notes associated with the project
	Notes *[]ProjectNoteListItem `json:"notes,omitempty"`

	// RelatedProjects Relationships to other projects
	RelatedProjects *[]RelatedProject `json:"related_projects,omitempty"`

	// ResponsibleParties Responsible parties for this project
	ResponsibleParties *[]ResponsibleParty `json:"responsible_parties,omitempty"`

	// ReviewedAt Last review timestamp (RFC3339)
	ReviewedAt *time.Time `json:"reviewed_at,omitempty"`

	// ReviewedBy User who last reviewed the project
	ReviewedBy *User `json:"reviewed_by,omitempty"`

	// Status Project lifecycle status. Defaults to 'active' if not provided or set to null.
	Status *ProjectStatus `json:"status,omitempty"`

	// Team The team this project belongs to (resolved)
	Team *Team `json:"team,omitempty"`

	// TeamId UUID of the team this project belongs to
	TeamId openapi_types.UUID `json:"team_id"`

	// Uri URL or reference to internal project page
	Uri *string `json:"uri,omitempty"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

Project defines model for Project.

type ProjectBase

type ProjectBase struct {
	// Description Project description
	Description *string `json:"description,omitempty"`

	// Name Project name
	Name string `json:"name"`

	// RelatedProjects Relationships to other projects
	RelatedProjects *[]RelatedProject `json:"related_projects,omitempty"`

	// ResponsibleParties Responsible parties for this project
	ResponsibleParties *[]ResponsibleParty `json:"responsible_parties,omitempty"`

	// Status Project lifecycle status. Defaults to 'active' if not provided or set to null.
	Status *ProjectStatus `json:"status,omitempty"`

	// TeamId UUID of the team this project belongs to
	TeamId openapi_types.UUID `json:"team_id"`

	// Uri URL or reference to internal project page
	Uri *string `json:"uri,omitempty"`
}

ProjectBase Client-writable fields for a project

type ProjectFilters

type ProjectFilters struct {
	Name         *string
	Status       []string
	TeamID       *string
	RelatedTo    *string
	Relationship *string
	Transitive   *bool
}

ProjectFilters defines filtering criteria for listing projects SEM@8c7929da791c778ff88713684c47aa2a10911bba: filtering criteria for listing projects including name, status, team, and relationship traversal

type ProjectInput

type ProjectInput = ProjectBase

ProjectInput Client-writable fields for a project

type ProjectListItem

type ProjectListItem struct {
	CreatedAt   time.Time          `json:"created_at"`
	Description *string            `json:"description,omitempty"`
	Id          openapi_types.UUID `json:"id"`
	ModifiedAt  *time.Time         `json:"modified_at,omitempty"`
	Name        string             `json:"name"`

	// NoteCount Number of notes associated with this project
	NoteCount *int `json:"note_count,omitempty"`

	// Status Project lifecycle status.
	Status *ProjectStatus     `json:"status,omitempty"`
	TeamId openapi_types.UUID `json:"team_id"`

	// TeamName Name of the associated team
	TeamName *string `json:"team_name,omitempty"`
}

ProjectListItem Summary of a project for list views

type ProjectNote

type ProjectNote struct {
	// Content Note content in markdown format. Safe inline HTML (tables, SVG, formatting) is allowed and sanitized server-side; dangerous elements (script, iframe, event handlers) are stripped.
	Content string `binding:"required" json:"content"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the project note
	Id *openapi_types.UUID `json:"id,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Note name
	Name string `binding:"required" json:"name"`

	// Sharable Controls note visibility. When true, visible to all team/project members. When false, only visible to admins and security reviewers. Only admins and security reviewers can set this field; regular users who include this field in requests will receive a 403 error. Default: true for regular users, false for admins/security reviewers.
	Sharable *bool `json:"sharable,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

ProjectNote defines model for ProjectNote.

type ProjectNoteId

type ProjectNoteId = openapi_types.UUID

ProjectNoteId defines model for ProjectNoteId.

type ProjectNoteInput

type ProjectNoteInput = TeamProjectNoteBase

ProjectNoteInput Base fields for TeamProjectNote (user-writable only)

type ProjectNoteListItem

type ProjectNoteListItem struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the project note
	Id *openapi_types.UUID `json:"id,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Note name
	Name string `json:"name"`

	// Sharable Controls note visibility
	Sharable *bool `json:"sharable,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

ProjectNoteListItem Summary information for ProjectNote in list responses

type ProjectNoteStoreInterface

type ProjectNoteStoreInterface interface {
	Create(ctx context.Context, note *ProjectNote, projectID string) (*ProjectNote, error)
	Get(ctx context.Context, id string) (*ProjectNote, error)
	Update(ctx context.Context, id string, note *ProjectNote, projectID string) (*ProjectNote, error)
	Delete(ctx context.Context, id string) error
	Patch(ctx context.Context, id string, operations []PatchOperation) (*ProjectNote, error)
	List(ctx context.Context, projectID string, offset, limit int, includeNonSharable bool) ([]ProjectNoteListItem, int, error)
	Count(ctx context.Context, projectID string, includeNonSharable bool) (int, error)
}

ProjectNoteStoreInterface defines the store interface for project notes SEM@f860641a78901543e88ebd0a603a69bd4db1d696: define CRUD and patch operations for persistent project note storage

var GlobalProjectNoteStore ProjectNoteStoreInterface

type ProjectStatus

type ProjectStatus string

ProjectStatus Project lifecycle status. Defaults to 'active' if not provided or set to null.

const (
	ProjectStatusActive              ProjectStatus = "active"
	ProjectStatusArchived            ProjectStatus = "archived"
	ProjectStatusCancelled           ProjectStatus = "cancelled"
	ProjectStatusDeprecated          ProjectStatus = "deprecated"
	ProjectStatusEndOfLife           ProjectStatus = "end_of_life"
	ProjectStatusGeneralAvailability ProjectStatus = "general_availability"
	ProjectStatusInDevelopment       ProjectStatus = "in_development"
	ProjectStatusInReview            ProjectStatus = "in_review"
	ProjectStatusLimitedAvailability ProjectStatus = "limited_availability"
	ProjectStatusMvp                 ProjectStatus = "mvp"
	ProjectStatusOnHold              ProjectStatus = "on_hold"
	ProjectStatusPlanning            ProjectStatus = "planning"
)

Defines values for ProjectStatus.

func (ProjectStatus) Valid

func (e ProjectStatus) Valid() bool

Valid indicates whether the value is a known member of the ProjectStatus enum.

type ProjectStoreInterface

type ProjectStoreInterface interface {
	Create(ctx context.Context, project *Project, userInternalUUID string) (*Project, error)
	Get(ctx context.Context, id string) (*Project, error)
	Update(ctx context.Context, id string, project *Project, userInternalUUID string) (*Project, error)
	Delete(ctx context.Context, id string) error
	List(ctx context.Context, limit, offset int, filters *ProjectFilters, userInternalUUID string, isAdmin bool) ([]ProjectListItem, int, error)
	GetTeamID(ctx context.Context, projectID string) (string, error)
	HasThreatModels(ctx context.Context, projectID string) (bool, error)
}

ProjectStoreInterface defines the store interface for projects SEM@8c7929da791c778ff88713684c47aa2a10911bba: contract for CRUD and query operations on the project store (reads DB)

var GlobalProjectStore ProjectStoreInterface

type ProviderPathParam

type ProviderPathParam = string

ProviderPathParam defines model for ProviderPathParam.

type ProviderQueryParam

type ProviderQueryParam = string

ProviderQueryParam defines model for ProviderQueryParam.

type ProviderSettingsReaderAdapter

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

ProviderSettingsReaderAdapter adapts SettingsServiceInterface to auth.ProviderSettingsReader. SEM@18141a4245588ce0371c97df5c94e4ac7066ef7c: adapt SettingsServiceInterface to the auth.ProviderSettingsReader contract (pure)

func NewProviderSettingsReaderAdapter

func NewProviderSettingsReaderAdapter(settings SettingsServiceInterface) *ProviderSettingsReaderAdapter

NewProviderSettingsReaderAdapter creates a new adapter. SEM@18141a4245588ce0371c97df5c94e4ac7066ef7c: build a ProviderSettingsReaderAdapter wrapping a settings service (pure)

func (*ProviderSettingsReaderAdapter) ListByPrefix

func (a *ProviderSettingsReaderAdapter) ListByPrefix(ctx context.Context, prefix string) ([]auth.ProviderSetting, error)

ListByPrefix returns all settings whose key starts with the given prefix, converted to auth.ProviderSetting. SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: fetch provider settings whose key matches a given prefix, converted to auth types (reads DB)

type QueryDecomposer

type QueryDecomposer interface {
	Decompose(ctx context.Context, query string, hasCodeIndex bool) (*DecomposedQuery, error)
}

QueryDecomposer breaks a user query into sub-queries optimized for different indexes. SEM@f06df1eae94dd2ca361cfb88f9f58fdc2bbfced6: interface for breaking a user query into sub-queries optimized for different indexes (pure)

type QuotaCache

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

QuotaCache provides in-memory caching for quota lookups with TTL SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: in-memory TTL cache for user API and webhook quota lookups (mutates shared state)

var GlobalQuotaCache *QuotaCache

Global quota cache instance (60 second TTL for dynamic adjustment)

func NewQuotaCache

func NewQuotaCache(ttl time.Duration) *QuotaCache

NewQuotaCache creates a new quota cache with the specified TTL SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: build a quota cache with TTL and start its background cleanup goroutine (mutates shared state)

func (*QuotaCache) GetUserAPIQuota

func (c *QuotaCache) GetUserAPIQuota(ctx context.Context, userID string, store UserAPIQuotaStoreInterface) UserAPIQuota

GetUserAPIQuota retrieves a user API quota from cache or store SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: fetch a user API quota from cache, falling back to the store on miss (reads DB)

func (*QuotaCache) GetWebhookQuota

func (c *QuotaCache) GetWebhookQuota(ctx context.Context, userID string, store WebhookQuotaStoreInterface) DBWebhookQuota

GetWebhookQuota retrieves a webhook quota from cache or store SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: fetch a webhook quota from cache, falling back to the store on miss (reads DB)

func (*QuotaCache) InvalidateAll

func (c *QuotaCache) InvalidateAll()

InvalidateAll clears all cached quotas SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: evict all quota entries from cache (mutates shared state)

func (*QuotaCache) InvalidateUserAPIQuota

func (c *QuotaCache) InvalidateUserAPIQuota(userID string)

InvalidateUserAPIQuota removes a user API quota from cache SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: evict a user's API quota entry from cache (mutates shared state)

func (*QuotaCache) InvalidateWebhookQuota

func (c *QuotaCache) InvalidateWebhookQuota(userID string)

InvalidateWebhookQuota removes a webhook quota from cache SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: evict a user's webhook quota entry from cache (mutates shared state)

func (*QuotaCache) Stop

func (c *QuotaCache) Stop()

Stop stops the cleanup goroutine SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: stop the quota cache cleanup goroutine (mutates shared state)

type RateLimitResult

type RateLimitResult struct {
	Allowed        bool
	BlockedByScope string // "session", "ip", or "user"
	RetryAfter     int    // seconds
	Limit          int
	Remaining      int
	ResetAt        int64
}

RateLimitResult represents the result of a rate limit check SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: carry the outcome of a rate limit check including scope, remaining quota, and retry timing (pure)

type Redactor

type Redactor interface {
	Redact(fieldPath, value string) string
}

Redactor classifies a (fieldPath, value) pair into one of three tiers and returns a redaction-applied string suitable for storage in system_audit_entries.OldValueRedacted / NewValueRedacted (#355).

Tier 1 (total redaction): passwords/passphrases — {"redacted":true}. Tier 2 (hash + optional tail): API keys, secrets, tokens, signing keys, credentials, encryption-* fields. Output: {"redacted":true,"sha256_prefix":"...","tail":"..."} (tail only when value length >= 24 chars). Tier 3 (verbatim): everything else — value as-is (with empty-string sentinel "<empty>" so Oracle CLOB and PostgreSQL TEXT round-trip identically; Oracle treats "" as NULL on CLOB insert). SEM@ef5f479de370d769f902d18acce8c504f1db69c1: apply tiered redaction to a field value before storing it in an audit entry (pure)

func NewRedactor

func NewRedactor() Redactor

NewRedactor returns a Redactor configured with the deny-list from #355's design spec. SEM@9ae68dfcfd72172f631accb154ab99316045e047: build a Redactor pre-loaded with the canonical sensitive-field deny-list (pure)

type RedisTicketStore

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

RedisTicketStore implements TicketStore using Redis with atomic GETDEL for single-use semantics. SEM@7118d848c0cc54f6062c586bb5adde9c5aa9ae4f: Redis-backed store implementing single-use WebSocket upgrade tickets (pure)

func NewRedisTicketStore

func NewRedisTicketStore(redis *db.RedisDB) *RedisTicketStore

NewRedisTicketStore creates a new Redis-backed ticket store. SEM@7118d848c0cc54f6062c586bb5adde9c5aa9ae4f: build a RedisTicketStore from a Redis connection (pure)

func (*RedisTicketStore) IssueTicket

func (s *RedisTicketStore) IssueTicket(ctx context.Context, userID, provider, internalUUID, sessionID string, ttl time.Duration) (string, error)

IssueTicket creates a cryptographically random ticket and stores it in Redis with the given TTL. SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: generate a cryptographically random upgrade ticket and store it in Redis with a TTL (mutates shared state)

func (*RedisTicketStore) ValidateTicket

func (s *RedisTicketStore) ValidateTicket(ctx context.Context, ticket string) (string, string, string, string, error)

ValidateTicket atomically retrieves and deletes a ticket from Redis (single-use). Returns the bound userID, provider, internalUUID, and sessionID. SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: atomically consume and validate a single-use upgrade ticket from Redis (mutates shared state)

type RedoRequestHandler

type RedoRequestHandler struct{}

RedoRequestHandler handles redo request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: WebSocket handler that dispatches redo_request messages to the diagram session

func (*RedoRequestHandler) HandleMessage

func (h *RedoRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: dispatch a redo_request to the session with panic recovery

func (*RedoRequestHandler) MessageType

func (h *RedoRequestHandler) MessageType() string

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: return the redo_request message type identifier (pure)

type RedoRequestMessage

type RedoRequestMessage struct {
	MessageType    MessageType `json:"message_type"`
	InitiatingUser User        `json:"initiating_user"`
}

SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: WebSocket message struct carrying the initiating user for a redo request (pure)

func (RedoRequestMessage) GetMessageType

func (m RedoRequestMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for a redo request message (pure)

func (RedoRequestMessage) Validate

func (m RedoRequestMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a redo request message; reject if type or user identity is missing (pure)

type RefreshTokenJSONRequestBody

type RefreshTokenJSONRequestBody = TokenRefreshRequest

RefreshTokenJSONRequestBody defines body for RefreshToken for application/json ContentType.

type RelatedProject

type RelatedProject struct {
	// CustomRelationship Custom relationship description when relationship is 'other'
	CustomRelationship *string `json:"custom_relationship,omitempty"`

	// RelatedProjectId UUID of the related project
	RelatedProjectId openapi_types.UUID `json:"related_project_id"`

	// Relationship Type of relationship between teams or projects
	Relationship RelationshipType `json:"relationship"`
}

RelatedProject A relationship entry linking to another project

type RelatedTeam

type RelatedTeam struct {
	// CustomRelationship Custom relationship description when relationship is 'other'
	CustomRelationship *string `json:"custom_relationship,omitempty"`

	// RelatedTeamId UUID of the related team
	RelatedTeamId openapi_types.UUID `json:"related_team_id"`

	// Relationship Type of relationship between teams or projects
	Relationship RelationshipType `json:"relationship"`
}

RelatedTeam A relationship entry linking to another team

type RelationshipType

type RelationshipType string

RelationshipType Type of relationship between teams or projects

const (
	RelationshipTypeChild        RelationshipType = "child"
	RelationshipTypeDependency   RelationshipType = "dependency"
	RelationshipTypeDependent    RelationshipType = "dependent"
	RelationshipTypeOther        RelationshipType = "other"
	RelationshipTypeParent       RelationshipType = "parent"
	RelationshipTypeRelated      RelationshipType = "related"
	RelationshipTypeSupersededBy RelationshipType = "superseded_by"
	RelationshipTypeSupersedes   RelationshipType = "supersedes"
)

Defines values for RelationshipType.

func (RelationshipType) Valid

func (e RelationshipType) Valid() bool

Valid indicates whether the value is a known member of the RelationshipType enum.

type RemoveGroupMemberParams

type RemoveGroupMemberParams struct {
	// SubjectType Type of member to remove: 'user' (default) for a user member, 'group' for a nested group member
	SubjectType *RemoveGroupMemberParamsSubjectType `form:"subject_type,omitempty" json:"subject_type,omitempty"`
}

RemoveGroupMemberParams defines parameters for RemoveGroupMember.

type RemoveGroupMemberParamsSubjectType

type RemoveGroupMemberParamsSubjectType string

RemoveGroupMemberParamsSubjectType defines parameters for RemoveGroupMember.

const (
	RemoveGroupMemberParamsSubjectTypeGroup RemoveGroupMemberParamsSubjectType = "group"
	RemoveGroupMemberParamsSubjectTypeUser  RemoveGroupMemberParamsSubjectType = "user"
)

Defines values for RemoveGroupMemberParamsSubjectType.

func (RemoveGroupMemberParamsSubjectType) Valid

Valid indicates whether the value is a known member of the RemoveGroupMemberParamsSubjectType enum.

type RemoveParticipantMessage

type RemoveParticipantMessage struct {
	MessageType MessageType `json:"message_type"`
	RemovedUser User        `json:"removed_user"`
}

SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: server-to-client WebSocket event announcing a participant has been removed (pure)

func (RemoveParticipantMessage) GetMessageType

func (m RemoveParticipantMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for RemoveParticipantMessage (pure)

func (RemoveParticipantMessage) Validate

func (m RemoveParticipantMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a RemoveParticipantMessage has correct type and removed user provider ID (pure)

type RemoveParticipantRequest

type RemoveParticipantRequest struct {
	MessageType MessageType `json:"message_type"`
	RemovedUser User        `json:"removed_user"`
}

RemoveParticipantRequest is sent by client to remove a participant SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: client-to-server WebSocket request to remove a session participant (pure)

func (RemoveParticipantRequest) GetMessageType

func (m RemoveParticipantRequest) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for RemoveParticipantRequest (pure)

func (RemoveParticipantRequest) Validate

func (m RemoveParticipantRequest) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a RemoveParticipantRequest has correct type and identifiable removed user (pure)

type RemoveParticipantRequestHandler

type RemoveParticipantRequestHandler struct{}

RemoveParticipantRequestHandler handles remove participant request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: handle a remove_participant_request WebSocket message from the session host (pure)

func (*RemoveParticipantRequestHandler) HandleMessage

func (h *RemoveParticipantRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: dispatch a remove participant WebSocket message to the diagram session (mutates shared state)

func (*RemoveParticipantRequestHandler) MessageType

func (h *RemoveParticipantRequestHandler) MessageType() string

SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: return the remove_participant_request message type discriminator (pure)

type Repository

type Repository struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of the referenced source code
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the repository
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name for the source code reference
	Name *string `json:"name,omitempty"`

	// Parameters repo-specific parameters for retrieving the source
	Parameters *struct {
		// RefType Reference type (branch, tag, or commit)
		RefType RepositoryParametersRefType `json:"refType"`

		// RefValue Reference value (branch name, tag value, or commit id)
		RefValue string `json:"refValue"`

		// SubPath Sub-path within the repository
		SubPath *string `json:"subPath,omitempty"`
	} `json:"parameters,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Source code repository type
	Type *RepositoryType `json:"type,omitempty"`

	// Uri URL to retrieve the referenced source code
	Uri string `json:"uri"`
}

Repository defines model for Repository.

func CreateTestRepositoryWithMetadata

func CreateTestRepositoryWithMetadata(metadata []Metadata) Repository

CreateTestRepositoryWithMetadata creates a repository with associated metadata for testing SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: build a Repository with attached metadata for use in unit tests (pure)

type RepositoryBase

type RepositoryBase struct {
	// Description Description of the referenced source code
	Description *string `json:"description,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// Name Name for the source code reference
	Name *string `json:"name,omitempty"`

	// Parameters repo-specific parameters for retrieving the source
	Parameters *struct {
		// RefType Reference type (branch, tag, or commit)
		RefType RepositoryBaseParametersRefType `json:"refType"`

		// RefValue Reference value (branch name, tag value, or commit id)
		RefValue string `json:"refValue"`

		// SubPath Sub-path within the repository
		SubPath *string `json:"subPath,omitempty"`
	} `json:"parameters,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Type Source code repository type
	Type *RepositoryBaseType `json:"type,omitempty"`

	// Uri URL to retrieve the referenced source code
	Uri string `json:"uri"`
}

RepositoryBase Base fields for Repository (user-writable only)

type RepositoryBaseParametersRefType

type RepositoryBaseParametersRefType string

RepositoryBaseParametersRefType Reference type (branch, tag, or commit)

const (
	RepositoryBaseParametersRefTypeBranch RepositoryBaseParametersRefType = "branch"
	RepositoryBaseParametersRefTypeCommit RepositoryBaseParametersRefType = "commit"
	RepositoryBaseParametersRefTypeTag    RepositoryBaseParametersRefType = "tag"
)

Defines values for RepositoryBaseParametersRefType.

func (RepositoryBaseParametersRefType) Valid

Valid indicates whether the value is a known member of the RepositoryBaseParametersRefType enum.

type RepositoryBaseType

type RepositoryBaseType string

RepositoryBaseType Source code repository type

const (
	RepositoryBaseTypeGit         RepositoryBaseType = "git"
	RepositoryBaseTypeLessThannil RepositoryBaseType = "<nil>"
	RepositoryBaseTypeMercurial   RepositoryBaseType = "mercurial"
	RepositoryBaseTypeOther       RepositoryBaseType = "other"
	RepositoryBaseTypeSvn         RepositoryBaseType = "svn"
)

Defines values for RepositoryBaseType.

func (RepositoryBaseType) Valid

func (e RepositoryBaseType) Valid() bool

Valid indicates whether the value is a known member of the RepositoryBaseType enum.

type RepositoryId

type RepositoryId = openapi_types.UUID

RepositoryId defines model for RepositoryId.

type RepositoryInput

type RepositoryInput = RepositoryBase

RepositoryInput Base fields for Repository (user-writable only)

type RepositoryParametersRefType

type RepositoryParametersRefType string

RepositoryParametersRefType Reference type (branch, tag, or commit)

const (
	RepositoryParametersRefTypeBranch RepositoryParametersRefType = "branch"
	RepositoryParametersRefTypeCommit RepositoryParametersRefType = "commit"
	RepositoryParametersRefTypeTag    RepositoryParametersRefType = "tag"
)

Defines values for RepositoryParametersRefType.

func (RepositoryParametersRefType) Valid

Valid indicates whether the value is a known member of the RepositoryParametersRefType enum.

type RepositoryRepository

type RepositoryRepository interface {
	// CRUD operations
	Create(ctx context.Context, repository *Repository, threatModelID string) error
	Get(ctx context.Context, id string) (*Repository, error)
	Update(ctx context.Context, repository *Repository, threatModelID string) error
	Delete(ctx context.Context, id string) error
	SoftDelete(ctx context.Context, id string) error
	Restore(ctx context.Context, id string) error
	HardDelete(ctx context.Context, id string) error
	GetIncludingDeleted(ctx context.Context, id string) (*Repository, error)
	Patch(ctx context.Context, id string, operations []PatchOperation) (*Repository, error)

	// List operations with pagination
	List(ctx context.Context, threatModelID string, offset, limit int) ([]Repository, error)
	// Count returns total number of repositories for a threat model
	Count(ctx context.Context, threatModelID string) (int, error)

	// Bulk operations
	BulkCreate(ctx context.Context, repositorys []Repository, threatModelID string) error

	// Cache management
	InvalidateCache(ctx context.Context, id string) error
	WarmCache(ctx context.Context, threatModelID string) error
}

RepositoryRepository defines the interface for repository operations with caching support. (Yes, the doubled name is awkward; the entity is named "Repository" in the API spec.) SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: interface for CRUD, soft-delete, patch, pagination, bulk create, and cache operations on repository entities

var GlobalRepositoryRepository RepositoryRepository

type RepositorySubResourceHandler

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

RepositorySubResourceHandler provides handlers for repository code sub-resource operations SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: handler for repository code reference CRUD operations scoped to a threat model

func NewRepositorySubResourceHandler

func NewRepositorySubResourceHandler(repositoryStore RepositoryRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *RepositorySubResourceHandler

NewRepositorySubResourceHandler creates a new repository code sub-resource handler SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a RepositorySubResourceHandler wired to the given store, DB, and cache

func (*RepositorySubResourceHandler) BulkCreateRepositorys

func (h *RepositorySubResourceHandler) BulkCreateRepositorys(c *gin.Context)

BulkCreateRepositorys creates multiple repository code references in a single request POST /threat_models/{threat_model_id}/repositorys/bulk SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: bulk create up to 50 repository code references under a threat model (mutates DB)

func (*RepositorySubResourceHandler) BulkUpdateRepositorys

func (h *RepositorySubResourceHandler) BulkUpdateRepositorys(c *gin.Context)

BulkUpdateRepositorys updates or creates multiple repositories (upsert operation) PUT /threat_models/{threat_model_id}/repositories/bulk SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: upsert up to 50 repository code references under a threat model (mutates DB)

func (*RepositorySubResourceHandler) CreateRepository

func (h *RepositorySubResourceHandler) CreateRepository(c *gin.Context)

CreateRepository creates a new repository code reference in a threat model POST /threat_models/{threat_model_id}/repositorys SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: create and store a new repository code reference under a threat model (reads DB)

func (*RepositorySubResourceHandler) DeleteRepository

func (h *RepositorySubResourceHandler) DeleteRepository(c *gin.Context)

DeleteRepository deletes a repository code reference DELETE /threat_models/{threat_model_id}/repositorys/{repository_id} SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: delete a repository code reference by ID, with audit and cache invalidation (mutates DB)

func (*RepositorySubResourceHandler) GetRepository

func (h *RepositorySubResourceHandler) GetRepository(c *gin.Context)

GetRepository retrieves a specific repository code reference by ID GET /threat_models/{threat_model_id}/repositorys/{repository_id} SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a single repository code reference by ID within a threat model (reads DB)

func (*RepositorySubResourceHandler) GetRepositorys

func (h *RepositorySubResourceHandler) GetRepositorys(c *gin.Context)

GetRepositorys retrieves all repository code references for a threat model with pagination GET /threat_models/{threat_model_id}/repositorys SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: list paginated repository code references for a threat model (reads DB)

func (*RepositorySubResourceHandler) PatchRepository

func (h *RepositorySubResourceHandler) PatchRepository(c *gin.Context)

PatchRepository applies JSON patch operations to a repository PATCH /threat_models/{threat_model_id}/repositories/{repository_id} SEM@270f55053109ed75ccf6cdf123884b9edf831d15: apply JSON patch operations to a repository code reference, with authorization and audit (mutates DB)

func (*RepositorySubResourceHandler) SetRepositoryURIValidator

func (h *RepositorySubResourceHandler) SetRepositoryURIValidator(v *URIValidator)

SetRepositoryURIValidator sets the URI validator for repository uri fields SEM@5eacb6f5fd0d2a1861dafb4d1fc5a18f97ee8e40: attach a URI validator to guard against SSRF on repository URI fields (mutates shared state)

func (*RepositorySubResourceHandler) UpdateRepository

func (h *RepositorySubResourceHandler) UpdateRepository(c *gin.Context)

UpdateRepository updates an existing repository code reference PUT /threat_models/{threat_model_id}/repositorys/{repository_id} SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: update a repository code reference under a threat model, with audit and cache invalidation (mutates DB)

type RepositoryType

type RepositoryType string

RepositoryType Source code repository type

const (
	RepositoryTypeGit         RepositoryType = "git"
	RepositoryTypeLessThannil RepositoryType = "<nil>"
	RepositoryTypeMercurial   RepositoryType = "mercurial"
	RepositoryTypeOther       RepositoryType = "other"
	RepositoryTypeSvn         RepositoryType = "svn"
)

Defines values for RepositoryType.

func (RepositoryType) Valid

func (e RepositoryType) Valid() bool

Valid indicates whether the value is a known member of the RepositoryType enum.

type RequestError

type RequestError struct {
	Status  int
	Code    string
	Message string
	Details *ErrorDetails
}

RequestError represents an error that should be returned as an HTTP response SEM@ccde596a38d5a3032cf965f5fbc2a4ffb144e534: structured HTTP error carrying status code, machine code, and human message (pure)

func ConflictError

func ConflictError(message string) *RequestError

ConflictError creates a RequestError for resource conflicts SEM@8559837d482fde8e2f7e1a9ea5e99d2bb2414141: build a 409 RequestError for a resource conflict (pure)

func ForbiddenError

func ForbiddenError(message string) *RequestError

ForbiddenError creates a RequestError for forbidden access SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: build a 403 RequestError for forbidden access (pure)

func GoneError

func GoneError(message string) *RequestError

GoneError creates a RequestError for resources that have been pruned/removed. SEM@626c102e7b7f7ceffb64d01a6c51f618862c5f31: build a 410-Gone RequestError for a pruned or unavailable resource (pure)

func InvalidIDError

func InvalidIDError(message string) *RequestError

InvalidIDError creates a RequestError for invalid ID formats SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: build a 400 RequestError for invalid resource ID format (pure)

func InvalidInputError

func InvalidInputError(message string) *RequestError

InvalidInputError creates a RequestError for validation failures SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: build a 400 RequestError for input validation failures (pure)

func InvalidInputErrorWithDetails

func InvalidInputErrorWithDetails(message string, code string, context map[string]any, suggestion string) *RequestError

InvalidInputErrorWithDetails creates a RequestError for validation failures with additional context SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: build a 400 RequestError with structured diagnostic context (pure)

func MapVersionError

func MapVersionError(err error) *RequestError

MapVersionError converts a store-layer error into the appropriate HTTP RequestError for the optimistic-locking contract. Returns nil if the error is not a versioning error so callers can fall through to their existing error mapping. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: convert a version-mismatch store error to a 409 HTTP request error (pure)

func NotAcceptableError

func NotAcceptableError(message string) *RequestError

NotAcceptableError creates a RequestError for content negotiation failures (no offered response media type matches the request's Accept header). SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: build a 406 RequestError for an unsatisfiable Accept header (pure)

func NotFoundError

func NotFoundError(message string) *RequestError

NotFoundError creates a RequestError for resource not found SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: build a 404 RequestError for a missing resource (pure)

func NotFoundErrorWithDetails

func NotFoundErrorWithDetails(message string, code string, context map[string]any, suggestion string) *RequestError

NotFoundErrorWithDetails creates a RequestError for resource not found with additional context SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: build a 404 RequestError with structured diagnostic context (pure)

func NotImplementedError

func NotImplementedError(message string) *RequestError

NotImplementedError creates a RequestError for features not implemented (501) Use for features that are defined in the API but not yet implemented, or when a particular provider doesn't support a feature. SEM@93f28e44afc91d0a7917b5dc1aaed9a52b00529a: build a 501 RequestError for an unimplemented feature (pure)

func ServerError

func ServerError(message string) *RequestError

ServerError creates a RequestError for internal server errors SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: build a 500 RequestError for an internal server error (pure)

func ServerErrorWithDetails

func ServerErrorWithDetails(message string, code string, context map[string]any, suggestion string) *RequestError

ServerErrorWithDetails creates a RequestError for internal server errors with additional context SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: build a 500 RequestError with structured diagnostic context (pure)

func ServiceUnavailableError

func ServiceUnavailableError(message string) *RequestError

ServiceUnavailableError creates a RequestError for temporarily unavailable services (503) Use when a dependent service (database, Redis, external provider) is temporarily unavailable. SEM@93f28e44afc91d0a7917b5dc1aaed9a52b00529a: build a 503 RequestError for a temporarily unavailable dependency (pure)

func StoreErrorToRequestError

func StoreErrorToRequestError(err error, notFoundMsg, serverErrorMsg string) *RequestError

StoreErrorToRequestError converts a store error to an appropriate RequestError. If the error is already a *RequestError, it is returned as-is (preserving its status code). All store errors must use typed dberrors sentinels (#271 umbrella migration is complete). SEM@68d73fcadaf792000c17911f4a8fa4bfa931ac65: convert a store or dberrors error to the appropriate HTTP RequestError (pure)

func UnauthorizedError

func UnauthorizedError(message string) *RequestError

SEM@420d8bdd24035796662ee4234e3bfaa6ba1a73bf: build a 401 RequestError for unauthenticated access (pure)

func ValidatePaginationParams

func ValidatePaginationParams(limit, offset *int) *RequestError

ValidatePaginationParams validates limit and offset parameters Returns a RequestError if validation fails, nil otherwise SEM@d8e6843d222487b09e3f3ab6f1ce56ed7ab59ac6: validate limit and offset pagination parameters against allowed bounds (pure)

func ValidatePatchAllowlist

func ValidatePatchAllowlist(allow PatchPathAllowList, ops []PatchOperation, ac PatchAuthContext) *RequestError

ValidatePatchAllowlist returns an error for any operation whose path is not in the allowlist for the given resource type, or that targets a gated path without the required role. Returns nil when every operation is permitted.

The error wraps a *RequestError with HTTP 400 (path not allowed) or 403 (path is gated and caller lacks the role). Paths are checked in this order: OwnerOnly → SecurityReviewerOnly → MutablePaths → reject. Empty path operations and operations whose path lacks a leading "/" are rejected as malformed. SEM@9ec514da7fdbd094b7c66fd638baafb5c2c17f18: validate all PATCH operations against the allowlist and caller roles, rejecting unauthorized paths (pure)

func ValidatePatchProhibitedPaths

func ValidatePatchProhibitedPaths(operations []PatchOperation) *RequestError

ValidatePatchProhibitedPaths rejects any PATCH operation that targets a server-managed (read-only) path. Returns a *RequestError with HTTP 400 on the first prohibited path found, or nil when all paths are allowed. SEM@270f55053109ed75ccf6cdf123884b9edf831d15: reject patch operations that target read-only fields such as id or created_at (pure)

func (*RequestError) Error

func (e *RequestError) Error() string

SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: return the error message string for a RequestError (pure)

type RerankResult

type RerankResult struct {
	Index    int     // original index in the documents slice
	Score    float64 // relevance score (higher = more relevant)
	Document string  // the document text
}

RerankResult holds a single document's reranking outcome. SEM@907448abd6162d78125a4d628a7b26110fe7939d: holds a document's original index, relevance score, and text after reranking (pure)

type Reranker

type Reranker interface {
	Rerank(ctx context.Context, query string, documents []string) ([]RerankResult, error)
}

Reranker reorders a list of documents by relevance to a query. SEM@907448abd6162d78125a4d628a7b26110fe7939d: interface for reordering documents by relevance to a query (pure)

type ResolvedUser

type ResolvedUser struct {
	InternalUUID string // System-assigned UUID from users table (may be empty if unresolved)
	Provider     string // Identity provider name (e.g., "google", "github", "tmi")
	ProviderID   string // Provider-assigned unique identifier (OAuth sub / SAML NameID)
	Email        string // User's email address (mutable contact attribute, not identity)
	DisplayName  string // Human-readable display name
}

ResolvedUser is the internal canonical representation of an authenticated user identity. It is the ONLY type that should be passed between functions for identity operations. It is never serialized to wire format directly — convert to/from API types (User, Principal) at system boundaries. SEM@bdd626ede818b573d8e556f49930fac9f87be4f2: canonical internal identity type carrying UUID, provider, provider ID, email, and display name (pure)

func GetAuthenticatedUser

func GetAuthenticatedUser(c *gin.Context) (ResolvedUser, error)

GetAuthenticatedUser extracts the authenticated user identity from the Gin context. Returns a ResolvedUser populated from JWT claims set by auth middleware. Requires userID (provider ID) and userEmail to be present; returns 401 if missing. Provider, InternalUUID, and DisplayName are populated if available.

This replaces ValidateAuthenticatedUser. Role is NOT included — use GetResourceRole separately. SEM@4c02975792d1bdeac3eeb81454da517814040317: extract the authenticated user identity from JWT claims in the Gin context; return 401 if missing

func ResolveUser

func ResolveUser(ctx context.Context, partial ResolvedUser, resolver UserResolver) (ResolvedUser, error)

ResolveUser resolves a partially-known identity to a fully-resolved user via database lookup.

Algorithm priority:

  1. If InternalUUID is set: lookup by UUID (hard error if not found, no fallthrough)
  2. If Provider and ProviderID are set: lookup by (provider, provider_id)
  3. If ProviderID and Email are set (no Provider): lookup by any provider ID, verify email
  4. If Provider and Email are set (no ProviderID): lookup by (provider, email)
  5. If only Email is set: lookup by email

After a successful match, if partial.Email is non-empty it is substituted into the result to reflect the most current email asserted by the IdP. SEM@c189a53ba583916876378527997b8c11ab450f46: resolve a partial user identity to a fully-known user via prioritized DB lookup strategies

func ResolvedUserFromAuthorization

func ResolvedUserFromAuthorization(auth Authorization) ResolvedUser

ResolvedUserFromAuthorization creates a ResolvedUser from an Authorization entry. InternalUUID will be empty since the API Authorization type does not carry it. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: build a resolved user from an Authorization entry, leaving internal UUID empty (pure)

func ResolvedUserFromPrincipal

func ResolvedUserFromPrincipal(p Principal) ResolvedUser

ResolvedUserFromPrincipal creates a ResolvedUser from an API Principal. InternalUUID will be empty since the API Principal type does not carry it. SEM@bdd626ede818b573d8e556f49930fac9f87be4f2: build a resolved user from an API Principal, leaving internal UUID empty (pure)

func ResolvedUserFromUser

func ResolvedUserFromUser(u User) ResolvedUser

ResolvedUserFromUser creates a ResolvedUser from an API User. InternalUUID will be empty since the API User type does not carry it. SEM@bdd626ede818b573d8e556f49930fac9f87be4f2: build a resolved user from an API User, leaving internal UUID empty (pure)

func ResolvedUserFromWebSocketClient

func ResolvedUserFromWebSocketClient(client *WebSocketClient) ResolvedUser

ResolvedUserFromWebSocketClient creates a ResolvedUser from a WebSocketClient. SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: build a resolved user from a WebSocket client's identity fields (pure)

func (ResolvedUser) IsEmpty

func (u ResolvedUser) IsEmpty() bool

IsEmpty returns true if the ResolvedUser has no identity fields set. SEM@bdd626ede818b573d8e556f49930fac9f87be4f2: report whether a resolved user has no identity fields set (pure)

func (ResolvedUser) ToPrincipal

func (u ResolvedUser) ToPrincipal() Principal

ToPrincipal converts a ResolvedUser to the API Principal type for wire format serialization. SEM@bdd626ede818b573d8e556f49930fac9f87be4f2: convert a resolved user to the API Principal wire type (pure)

func (ResolvedUser) ToUser

func (u ResolvedUser) ToUser() User

ToUser converts a ResolvedUser to the API User type for wire format serialization. SEM@bdd626ede818b573d8e556f49930fac9f87be4f2: convert a resolved user to the API User wire type (pure)

type ResponsibleParty

type ResponsibleParty struct {
	// CustomRole Custom role description when role is 'other'
	CustomRole *string `json:"custom_role,omitempty"`

	// Role Role of a team member or responsible party
	Role *TeamMemberRole `json:"role,omitempty"`

	// User Resolved user details (read-only, populated by server)
	User *User `json:"user,omitempty"`

	// UserId UUID of the responsible party user
	UserId openapi_types.UUID `json:"user_id"`
}

ResponsibleParty A responsible party for a team or project with their role

type ResultConsumer

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

ResultConsumer subscribes to the TMI_RESULTS JetStream stream and, per result message, upserts the extraction_jobs terminal state, updates the document's access_status, emits a webhook event, and deletes the result blob. It is safe to use concurrently; the JetStream callback is invoked serially (single goroutine) by the nats.go library.

DLQ note: the dead-letter path is now wired. The DLQ producer (api/dlq_producer.go) republishes the original Job envelope of any job that exhausted redelivery to SubjectDLQ ("jobs.dlq"); this consumer binds the TMI_DLQ stream (see makeDLQCallback) and turns each dead-lettered Job into a failed terminal transition. SEM@28a744a1501431680450f9ab9c4d57cdf9bebd2d: consume JetStream extraction results and DLQ messages, updating job state and emitting webhooks (mutates shared state)

func NewResultConsumer

func NewResultConsumer(
	conn *worker.Conn,
	jobStore *ExtractionJobStore,
	docs DocumentRepository,
) *ResultConsumer

NewResultConsumer constructs a ResultConsumer wired to real dependencies. Pass conn, the ExtractionJobStore, and the DocumentRepository; the constructor wires the emit closure and the lookupDocument function.

lookupDocument enrichment: the function queries extraction_jobs for the document_ref, then fetches the document's ThreatModelID via DocumentRepository.GetThreatModelID and the owner via DocumentRepository.GetPickerDispatch. If either secondary lookup fails the function degrades gracefully: the access_status update (which only needs document_ref) still proceeds; the webhook's threat_model_id / owner_id fields are left empty. SEM@1ae01f28fb1a539b36294e7e11378fe6eb89ebcc: build a ResultConsumer wired to the job store, document repository, and event emitter (pure)

func (*ResultConsumer) Start

func (rc *ResultConsumer) Start(ctx context.Context) error

Start subscribes to the TMI_RESULTS stream and begins processing result messages in the background. It returns nil immediately after the JetStream consumer is created; actual message processing happens in the consume callback goroutine managed by the nats.go library.

If the TMI_RESULTS stream does not yet exist (e.g. no workers have run), Start logs a warning and returns nil — the async result path is simply unavailable until a worker creates the stream.

The provided ctx controls the lifetime of the consumer; call Stop() to release resources explicitly. SEM@1d6cb26c4ce932c84cd95e891bc5cc5dfc019186: subscribe to TMI_RESULTS and TMI_DLQ JetStream streams and begin background result processing (mutates shared state)

func (*ResultConsumer) Stop

func (rc *ResultConsumer) Stop()

Stop cancels the consumer's context, which causes the background goroutine to call cc.Stop() and release JetStream resources. Safe to call when Start was never called or when the stream was not found (no-op). SEM@28a744a1501431680450f9ab9c4d57cdf9bebd2d: cancel the consumer context and release JetStream resources (mutates shared state)

type RevokeTokenFormdataRequestBody

type RevokeTokenFormdataRequestBody = TokenRevocationRequest

RevokeTokenFormdataRequestBody defines body for RevokeToken for application/x-www-form-urlencoded ContentType.

type RevokeTokenJSONRequestBody

type RevokeTokenJSONRequestBody = TokenRevocationRequest

RevokeTokenJSONRequestBody defines body for RevokeToken for application/json ContentType.

type Role

type Role = AuthorizationRole

Role represents a user role with permission levels

const (
	// RoleOwner has full control over the resource
	RoleOwner Role = AuthorizationRoleOwner
	// RoleWriter can edit but not delete or change ownership
	RoleWriter Role = AuthorizationRoleWriter
	// RoleReader can only view the resource
	RoleReader Role = AuthorizationRoleReader
)

func GetResourceRole

func GetResourceRole(c *gin.Context) (Role, error)

GetResourceRole extracts the resource-scoped role from the Gin context. Returns empty role if not set (some endpoints don't have resource middleware). Errors only on type assertion failure, not on absence. SEM@693a6777129b0cd776e0622001bdecdd2457d4c9: extract the resource-scoped role from the Gin context set by resource middleware (pure)

func GetUserRole

func GetUserRole(user ResolvedUser, groups []string, threatModel ThreatModel) Role

GetUserRole determines the role of the user for a given threat model. Uses SamePrincipal for identity matching via AccessCheckWithGroups. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: compute the highest role a user holds on a threat model (pure)

func GetUserRoleForDiagram

func GetUserRoleForDiagram(user ResolvedUser, groups []string, diagram DfdDiagram) Role

GetUserRoleForDiagram determines the role of the user for a given diagram. Uses SamePrincipal for identity matching via GetUserRole. SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: compute the user's role on a diagram by inheriting from its parent threat model (reads DB)

type RollbackResponse

type RollbackResponse struct {
	// AuditEntry The new audit entry recording the rollback
	AuditEntry AuditEntry `json:"audit_entry"`

	// RestoredEntity The entity restored to its previous state
	RestoredEntity *map[string]interface{} `json:"restored_entity,omitempty"`
}

RollbackResponse Result of a rollback operation

type RuntimeConfigReaderAdapter

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

RuntimeConfigReaderAdapter adapts SettingsServiceInterface to auth.RuntimeConfigReader so the auth package can read DB-backed operational config at request time without importing api or internal/config (#419). SEM@08e19a77d4d2c499f116e1a1ee3c875c06407335: adapter bridging SettingsService to the auth package's RuntimeConfigReader interface (pure)

func NewRuntimeConfigReaderAdapter

func NewRuntimeConfigReaderAdapter(settings SettingsServiceInterface) *RuntimeConfigReaderAdapter

NewRuntimeConfigReaderAdapter constructs an adapter over the given SettingsService. SEM@08e19a77d4d2c499f116e1a1ee3c875c06407335: build a RuntimeConfigReaderAdapter over the given settings service (pure)

func (*RuntimeConfigReaderAdapter) GetClientCallbackAllowList

func (a *RuntimeConfigReaderAdapter) GetClientCallbackAllowList(ctx context.Context) ([]string, bool, error)

GetClientCallbackAllowList reads the operator-configured client_callback allowlist for /oauth2/authorize and /oauth2/step_up. The DB row holds a JSON-encoded []string. Returns (list, exists, err) per the interface contract:

  • exists=false: no DB row → caller falls back to YAML.
  • exists=true, err==nil: parsed allowlist returned.
  • exists=true, err!=nil: DB row present but unusable → caller MUST fail-closed to prevent open-redirect against a corrupt row.

SEM@08e19a77d4d2c499f116e1a1ee3c875c06407335: fetch the OAuth client callback allowlist from DB settings; fail-closed on corrupt or missing row (reads DB)

func (*RuntimeConfigReaderAdapter) GetOAuthCallbackURL

func (a *RuntimeConfigReaderAdapter) GetOAuthCallbackURL(ctx context.Context) string

GetOAuthCallbackURL reads auth.oauth_callback_url. An empty string is returned on error/missing row; the caller falls back to the YAML snapshot in h.config.OAuth.CallbackURL. SEM@08e19a77d4d2c499f116e1a1ee3c875c06407335: fetch the OAuth callback URL from DB settings; return empty string on error (reads DB)

func (*RuntimeConfigReaderAdapter) IsSAMLEnabled

func (a *RuntimeConfigReaderAdapter) IsSAMLEnabled(ctx context.Context) bool

IsSAMLEnabled reads features.saml_enabled. A read error or missing row returns false (fail-closed). SEM@08e19a77d4d2c499f116e1a1ee3c875c06407335: fetch the SAML-enabled feature flag from DB settings; fail-closed on error (reads DB)

type SAMLProviderInfo

type SAMLProviderInfo struct {
	// AcsUrl Assertion Consumer Service URL
	AcsUrl string `json:"acs_url"`

	// AuthUrl TMI SAML login endpoint URL
	AuthUrl string `json:"auth_url"`

	// EntityId Service Provider entity ID
	EntityId string `json:"entity_id"`

	// Icon Icon identifier for the provider (Font Awesome class, URL, or path)
	Icon string `json:"icon"`

	// Id Provider identifier
	Id string `json:"id"`

	// Initialized Whether the SAML provider was successfully initialized and is available for authentication
	Initialized bool `json:"initialized"`

	// MetadataUrl SAML service provider metadata URL
	MetadataUrl string `json:"metadata_url"`

	// Name Display name of the provider
	Name string `json:"name"`

	// SloUrl Single Logout URL
	SloUrl *string `json:"slo_url,omitempty"`
}

SAMLProviderInfo SAML identity provider configuration and metadata

type SSEWriter

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

SSEWriter provides helpers for writing Server-Sent Events to a Gin response SEM@4c239c4f250b659952e70e3af2276d2651e420e9: holds a Gin context and flush function for writing Server-Sent Events (pure)

func NewSSEWriter

func NewSSEWriter(c *gin.Context) *SSEWriter

NewSSEWriter initializes an SSE response stream SEM@4c239c4f250b659952e70e3af2276d2651e420e9: initialize an SSE response stream with required headers on the Gin response

func (*SSEWriter) IsClientGone

func (w *SSEWriter) IsClientGone() bool

IsClientGone checks if the client has disconnected SEM@4c239c4f250b659952e70e3af2276d2651e420e9: report whether the SSE client has disconnected by checking request context cancellation (pure)

func (*SSEWriter) SendError

func (w *SSEWriter) SendError(code, message string) error

SendError sends an error event SEM@4c239c4f250b659952e70e3af2276d2651e420e9: send an error code and message as an SSE error event

func (*SSEWriter) SendEvent

func (w *SSEWriter) SendEvent(event string, data any) error

SendEvent sends a named SSE event with JSON data SEM@de94ca8de4d9f1541750217c9a701b38bf923214: serialize data as JSON and send a named SSE event to the client

func (*SSEWriter) SendToken

func (w *SSEWriter) SendToken(content string) error

SendToken sends a single token event for LLM streaming SEM@4c239c4f250b659952e70e3af2276d2651e420e9: send a streaming LLM token as an SSE token event

type SSVCScore

type SSVCScore struct {
	// Decision SSVC decision outcome
	Decision SSVCScoreDecision `json:"decision"`

	// Methodology The SSVC stakeholder perspective used for assessment
	Methodology string `json:"methodology"`

	// Vector SSVC vector string following CERT/CC convention (e.g., SSVCv2/E:A/U:S/T:T/P:S/2026-04-08/)
	Vector string `json:"vector"`
}

SSVCScore SSVC (Stakeholder-Specific Vulnerability Categorization) assessment result

type SSVCScoreDecision

type SSVCScoreDecision string

SSVCScoreDecision SSVC decision outcome

const (
	Defer      SSVCScoreDecision = "Defer"
	Immediate  SSVCScoreDecision = "Immediate"
	OutOfCycle SSVCScoreDecision = "Out-of-Cycle"
	Scheduled  SSVCScoreDecision = "Scheduled"
)

Defines values for SSVCScoreDecision.

func (SSVCScoreDecision) Valid

func (e SSVCScoreDecision) Valid() bool

Valid indicates whether the value is a known member of the SSVCScoreDecision enum.

type SafeFetchOptions

type SafeFetchOptions struct {
	Method                string
	Body                  io.Reader
	Headers               http.Header
	Timeout               time.Duration
	ResponseHeaderTimeout time.Duration
	MaxBodyBytes          int64
	AllowRedirects        bool
	// RejectIfBodyExceedsMax causes Fetch to return ErrSafeHTTPBodyTooLarge
	// when the response carries a Content-Length header that exceeds
	// MaxBodyBytes (or the client default). Without this flag the body
	// is silently truncated. Useful for callers that prefer fast-fail
	// over partial reads (e.g., webhook deliveries where a response
	// larger than the cap is treated as a hostile target).
	RejectIfBodyExceedsMax bool
}

SafeFetchOptions controls a single Fetch / FetchStreaming call. Zero values fall back to client-level defaults. SEM@0aee687bf1c2b4e1819bf1c183575104459a14d4: per-request configuration for method, headers, timeouts, body cap, and redirect policy (pure)

type SafeFetchResult

type SafeFetchResult struct {
	StatusCode int
	Header     http.Header
	Body       []byte
	Truncated  bool
}

SafeFetchResult is returned by Fetch. SEM@b554bb5371f70e0115912131e032671de29e8c09: hold the status code, headers, body, and truncation flag from a safe HTTP fetch (pure)

type SafeHTTPClient

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

SafeHTTPClient is the single egress path for server-originated outbound HTTP. It validates the request URL against scheme/allowlist/SSRF rules, resolves the hostname **once**, walks every resolved IP through the blocklist, and pins subsequent dial(s) to the validated IP. This closes the DNS-rebinding window between validation and connection that arises when callers re-resolve the hostname inside http.Client.

Callers MUST route all server-originated outbound HTTP through a SafeHTTPClient. A repository-level lint check enforces this. SEM@b554bb5371f70e0115912131e032671de29e8c09: SSRF-safe outbound HTTP client that validates URLs, resolves and pins IPs, and caps response bodies

func NewSafeHTTPClient

func NewSafeHTTPClient(validator *URIValidator, opts ...SafeHTTPClientOption) *SafeHTTPClient

NewSafeHTTPClient builds a SafeHTTPClient backed by the given URIValidator. The validator's scheme and allowlist policy are reused; this client adds the IP-pinning, header timeout, and body-cap controls on top. SEM@b554bb5371f70e0115912131e032671de29e8c09: build a SafeHTTPClient with SSRF protection using the given URI validator and options (pure)

func (*SafeHTTPClient) Fetch

func (c *SafeHTTPClient) Fetch(ctx context.Context, rawURL string, opts SafeFetchOptions) (*SafeFetchResult, error)

Fetch issues the request and reads the body into memory, capped at opts.MaxBodyBytes (or the client default). The body is always returned (possibly truncated) when no transport-level error occurred.

When opts.RejectIfBodyExceedsMax is set and the response carries a Content-Length header strictly greater than the configured cap, the body is not read and the call returns ErrSafeHTTPBodyTooLarge. SEM@0aee687bf1c2b4e1819bf1c183575104459a14d4: issue an SSRF-safe HTTP request and return the response body buffered in memory

func (*SafeHTTPClient) FetchStreaming

func (c *SafeHTTPClient) FetchStreaming(ctx context.Context, rawURL string, opts SafeFetchOptions) (*http.Response, error)

FetchStreaming issues the request and returns the open *http.Response. The response body is wrapped so that reads never exceed opts.MaxBodyBytes. The caller MUST close resp.Body. SEM@b554bb5371f70e0115912131e032671de29e8c09: issue an SSRF-safe HTTP request and return the response for streaming; caller must close body

type SafeHTTPClientOption

type SafeHTTPClientOption func(*SafeHTTPClient)

SafeHTTPClientOption configures a SafeHTTPClient. SEM@b554bb5371f70e0115912131e032671de29e8c09: functional option type for configuring a SafeHTTPClient (pure)

func WithDefaultTimeouts

func WithDefaultTimeouts(overall, headerWait time.Duration, maxBody int64) SafeHTTPClientOption

WithDefaultTimeouts overrides the per-fetch defaults applied when SafeFetchOptions leaves the corresponding field zero. SEM@b554bb5371f70e0115912131e032671de29e8c09: override the default overall, header-wait, and body-cap limits on a SafeHTTPClient (pure)

func WithResolver

func WithResolver(r HostResolver) SafeHTTPClientOption

WithResolver overrides the host resolver. Used in tests to drive deterministic resolution. SEM@b554bb5371f70e0115912131e032671de29e8c09: override the host resolver on a SafeHTTPClient, for test determinism (pure)

func WithTransportWrapper

func WithTransportWrapper(f func(http.RoundTripper) http.RoundTripper) SafeHTTPClientOption

WithTransportWrapper registers a wrapper around the pinned transport (e.g. otelhttp.NewTransport). SEM@b554bb5371f70e0115912131e032671de29e8c09: register a transport wrapper such as an OTel transport on a SafeHTTPClient (pure)

func WithUserAgent

func WithUserAgent(ua string) SafeHTTPClientOption

WithUserAgent sets a default User-Agent header applied when the request has none. SEM@b554bb5371f70e0115912131e032671de29e8c09: set a default User-Agent header on a SafeHTTPClient (pure)

type SamlAssertionConsumerRequest

type SamlAssertionConsumerRequest struct {
	// RelayState State parameter for CSRF protection
	RelayState *string `json:"RelayState,omitempty"`

	// SAMLResponse Base64-encoded SAML response
	SAMLResponse string `json:"SAMLResponse"`
}

SamlAssertionConsumerRequest SAML assertion consumer service POST request

type SamlSingleLogoutRequest

type SamlSingleLogoutRequest struct {
	// SAMLRequest Base64-encoded SAML logout request
	SAMLRequest string `json:"SAMLRequest"`
}

SamlSingleLogoutRequest SAML single logout request

type SamlrequestQueryParam

type SamlrequestQueryParam = string

SamlrequestQueryParam defines model for SamlrequestQueryParam.

type ScopeQueryParam

type ScopeQueryParam = string

ScopeQueryParam defines model for ScopeQueryParam.

type ScoreEqQueryParam

type ScoreEqQueryParam = float32

ScoreEqQueryParam defines model for ScoreEqQueryParam.

type ScoreGeQueryParam

type ScoreGeQueryParam = float32

ScoreGeQueryParam defines model for ScoreGeQueryParam.

type ScoreGtQueryParam

type ScoreGtQueryParam = float32

ScoreGtQueryParam defines model for ScoreGtQueryParam.

type ScoreLeQueryParam

type ScoreLeQueryParam = float32

ScoreLeQueryParam defines model for ScoreLeQueryParam.

type ScoreLtQueryParam

type ScoreLtQueryParam = float32

ScoreLtQueryParam defines model for ScoreLtQueryParam.

type SecurityReviewerQueryParam

type SecurityReviewerQueryParam = string

SecurityReviewerQueryParam defines model for SecurityReviewerQueryParam.

type Server

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

Server is the main API server instance SEM@d89a562535e2240eeb7f556a3f619d28fe9c5613: main API server holding all handlers, services, and subsystem dependencies

func NewServer

func NewServer(wsLoggingConfig slogging.WebSocketLoggingConfig, inactivityTimeout time.Duration) *Server

NewServer creates a new API server instance SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: build a fully wired Server with WebSocket hub and all sub-resource handlers (mutates shared state)

func NewServerForTests

func NewServerForTests() *Server

NewServerForTests creates a server with default test configuration SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: build a Server with minimal test-safe defaults and a short inactivity timeout (pure)

func (*Server) AddGroupMember

func (s *Server) AddGroupMember(c *gin.Context, internalUuid openapi_types.UUID)

AddGroupMember handles POST /admin/groups/{internal_uuid}/members SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: add a user or group as a member of an admin group (mutates shared state)

func (*Server) AdminDeleteUserContentToken

func (s *Server) AdminDeleteUserContentToken(c *gin.Context, internalUuid openapi_types.UUID, providerId string)

AdminDeleteUserContentToken implements ServerInterface.AdminDeleteUserContentToken. SEM@e1c025d7bed50b42c0eaa2b0deee98f338e4353a: delete a user's content provider OAuth token as an admin, or 404 if the feature is disabled

func (*Server) AdminListUserContentTokens

func (s *Server) AdminListUserContentTokens(c *gin.Context, internalUuid openapi_types.UUID)

AdminListUserContentTokens implements ServerInterface.AdminListUserContentTokens. SEM@e1c025d7bed50b42c0eaa2b0deee98f338e4353a: list a user's content provider OAuth tokens as an admin, or 404 if the feature is disabled

func (*Server) AsyncExtractionAvailable

func (s *Server) AsyncExtractionAvailable() bool

AsyncExtractionAvailable reports whether the async worker path can be used. It is false when no NATS connection is wired, which forces the inline path regardless of the extraction.async_enabled setting (fail-safe). SEM@a0abba4563581c2c2d54d1df58750d51e83e3e43: report whether a NATS connection is wired for async extraction (pure)

func (*Server) AuthorizeContentToken

func (s *Server) AuthorizeContentToken(c *gin.Context, providerId string)

AuthorizeContentToken implements ServerInterface.AuthorizeContentToken. SEM@74d36522781dcfd28cfc8f5f32ed5cd9dd62a25e: initiate the OAuth authorization flow for a content provider token, or 404 if the feature is disabled

func (*Server) AuthorizeOAuthProvider

func (s *Server) AuthorizeOAuthProvider(c *gin.Context, params AuthorizeOAuthProviderParams)

AuthorizeOAuthProvider initiates OAuth flow SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route OAuth authorization request to the auth service to initiate an OAuth flow

func (*Server) BulkCreateAdminSurveyMetadata

func (s *Server) BulkCreateAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

BulkCreateAdminSurveyMetadata bulk creates survey metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to bulk-store multiple survey metadata entries (mutates shared state)

func (*Server) BulkCreateDiagramMetadata

func (s *Server) BulkCreateDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

BulkCreateDiagramMetadata bulk creates diagram metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: store multiple new metadata entries on a diagram in bulk (mutates shared state)

func (*Server) BulkCreateDocumentMetadata

func (s *Server) BulkCreateDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

BulkCreateDocumentMetadata bulk creates document metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: bulk store metadata entries for a document (reads DB)

func (*Server) BulkCreateIntakeSurveyResponseMetadata

func (s *Server) BulkCreateIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

BulkCreateIntakeSurveyResponseMetadata bulk creates intake survey response metadata SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize writer access then bulk-store intake survey response metadata entries (mutates shared state)

func (*Server) BulkCreateNoteMetadata

func (s *Server) BulkCreateNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

BulkCreateNoteMetadata bulk creates note metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-create-metadata request for a note to the metadata handler

func (*Server) BulkCreateProjectMetadata

func (s *Server) BulkCreateProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: bulk-create metadata entries for a project, delegating to the generic metadata handler (reads DB)

func (*Server) BulkCreateRepositoryMetadata

func (s *Server) BulkCreateRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

BulkCreateRepositoryMetadata bulk creates repository metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk repository metadata creation request to the metadata handler

func (*Server) BulkCreateTeamMetadata

func (s *Server) BulkCreateTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: store multiple new metadata entries for a team via the generic metadata handler

func (*Server) BulkCreateThreatMetadata

func (s *Server) BulkCreateThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

BulkCreateThreatMetadata bulk creates threat metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: bulk-create metadata entries on a threat

func (*Server) BulkCreateThreatModelAssetMetadata

func (s *Server) BulkCreateThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

BulkCreateThreatModelAssetMetadata bulk creates asset metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-create-asset-metadata request to the metadata handler

func (*Server) BulkCreateThreatModelAssets

func (s *Server) BulkCreateThreatModelAssets(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelAssets bulk creates assets SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-create-assets request to the asset handler for a given threat model

func (*Server) BulkCreateThreatModelDocuments

func (s *Server) BulkCreateThreatModelDocuments(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelDocuments bulk creates documents SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk document creation to the document handler under a threat model (reads DB)

func (*Server) BulkCreateThreatModelMetadata

func (s *Server) BulkCreateThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelMetadata bulk creates threat model metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: store multiple new metadata entries on a threat model in bulk (mutates shared state)

func (*Server) BulkCreateThreatModelRepositories

func (s *Server) BulkCreateThreatModelRepositories(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelRepositories bulk creates repositories SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk repository creation request to the repository handler

func (*Server) BulkCreateThreatModelThreats

func (s *Server) BulkCreateThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelThreats bulk creates threats SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk threat creation to the threat handler

func (*Server) BulkDeleteThreatModelThreats

func (s *Server) BulkDeleteThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID, params BulkDeleteThreatModelThreatsParams)

BulkDeleteThreatModelThreats bulk deletes threats SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk threat deletion to the threat handler

func (*Server) BulkPatchThreatModelThreats

func (s *Server) BulkPatchThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID)

BulkPatchThreatModelThreats bulk patches threats SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk threat patch to the threat handler

func (*Server) BulkReplaceAdminSurveyMetadata

func (s *Server) BulkReplaceAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

BulkReplaceAdminSurveyMetadata replaces all survey metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to replace all survey metadata entries atomically (mutates shared state)

func (*Server) BulkReplaceDiagramMetadata

func (s *Server) BulkReplaceDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

BulkReplaceDiagramMetadata replaces all diagram metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: replace all metadata entries on a diagram atomically (mutates shared state)

func (*Server) BulkReplaceDocumentMetadata

func (s *Server) BulkReplaceDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

BulkReplaceDocumentMetadata replaces all document metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: replace all metadata entries for a document atomically (reads DB)

func (*Server) BulkReplaceIntakeSurveyResponseMetadata

func (s *Server) BulkReplaceIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

BulkReplaceIntakeSurveyResponseMetadata replaces all survey response metadata (PUT) SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize writer access then replace all intake survey response metadata entries atomically (mutates shared state)

func (*Server) BulkReplaceNoteMetadata

func (s *Server) BulkReplaceNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

BulkReplaceNoteMetadata replaces all note metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-replace-metadata request for a note to the metadata handler

func (*Server) BulkReplaceProjectMetadata

func (s *Server) BulkReplaceProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: bulk-replace all metadata entries for a project, delegating to the generic metadata handler (reads DB)

func (*Server) BulkReplaceRepositoryMetadata

func (s *Server) BulkReplaceRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

BulkReplaceRepositoryMetadata replaces all repository metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk repository metadata replacement (PUT) request to the metadata handler

func (*Server) BulkReplaceTeamMetadata

func (s *Server) BulkReplaceTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: replace all metadata entries for a team via the generic metadata handler

func (*Server) BulkReplaceThreatMetadata

func (s *Server) BulkReplaceThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

BulkReplaceThreatMetadata replaces all threat metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: replace all metadata entries on a threat (PUT)

func (*Server) BulkReplaceThreatModelAssetMetadata

func (s *Server) BulkReplaceThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

BulkReplaceThreatModelAssetMetadata replaces all asset metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-replace-asset-metadata (PUT) request to the metadata handler

func (*Server) BulkReplaceThreatModelMetadata

func (s *Server) BulkReplaceThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

BulkReplaceThreatModelMetadata replaces all threat model metadata (PUT) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: replace all metadata entries on a threat model atomically (mutates shared state)

func (*Server) BulkUpdateThreatModelThreats

func (s *Server) BulkUpdateThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpdateThreatModelThreats bulk updates threats SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk threat replacement to the threat handler

func (*Server) BulkUpsertAdminSurveyMetadata

func (s *Server) BulkUpsertAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

BulkUpsertAdminSurveyMetadata upserts survey metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to upsert multiple survey metadata entries (mutates shared state)

func (*Server) BulkUpsertDiagramMetadata

func (s *Server) BulkUpsertDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

BulkUpsertDiagramMetadata upserts diagram metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: upsert multiple metadata entries on a diagram (mutates shared state)

func (*Server) BulkUpsertDocumentMetadata

func (s *Server) BulkUpsertDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

BulkUpsertDocumentMetadata upserts document metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: upsert metadata entries for a document (reads DB)

func (*Server) BulkUpsertIntakeSurveyResponseMetadata

func (s *Server) BulkUpsertIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

BulkUpsertIntakeSurveyResponseMetadata upserts survey response metadata (PATCH) SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize writer access then upsert intake survey response metadata entries (mutates shared state)

func (*Server) BulkUpsertNoteMetadata

func (s *Server) BulkUpsertNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

BulkUpsertNoteMetadata upserts note metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-upsert-metadata request for a note to the metadata handler

func (*Server) BulkUpsertProjectMetadata

func (s *Server) BulkUpsertProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: bulk-upsert metadata entries for a project, delegating to the generic metadata handler (reads DB)

func (*Server) BulkUpsertRepositoryMetadata

func (s *Server) BulkUpsertRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

BulkUpsertRepositoryMetadata upserts repository metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk repository metadata upsert (PATCH) request to the metadata handler

func (*Server) BulkUpsertTeamMetadata

func (s *Server) BulkUpsertTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: upsert multiple metadata entries for a team via the generic metadata handler

func (*Server) BulkUpsertThreatMetadata

func (s *Server) BulkUpsertThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

BulkUpsertThreatMetadata upserts threat metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: upsert metadata entries on a threat (PATCH)

func (*Server) BulkUpsertThreatModelAssetMetadata

func (s *Server) BulkUpsertThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

BulkUpsertThreatModelAssetMetadata upserts asset metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-upsert-asset-metadata (PATCH) request to the metadata handler

func (*Server) BulkUpsertThreatModelAssets

func (s *Server) BulkUpsertThreatModelAssets(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelAssets bulk upserts assets SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk-upsert-assets request to the asset handler for a given threat model

func (*Server) BulkUpsertThreatModelDocuments

func (s *Server) BulkUpsertThreatModelDocuments(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelDocuments bulk upserts documents SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk document upsert to the document handler under a threat model (reads DB)

func (*Server) BulkUpsertThreatModelMetadata

func (s *Server) BulkUpsertThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelMetadata upserts threat model metadata (PATCH) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: upsert multiple metadata entries on a threat model (mutates shared state)

func (*Server) BulkUpsertThreatModelRepositories

func (s *Server) BulkUpsertThreatModelRepositories(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelRepositories bulk upserts repositories SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route bulk repository upsert request to the repository handler

func (*Server) CloseExtractionNATS

func (s *Server) CloseExtractionNATS()

CloseExtractionNATS closes the monolith NATS connection if one is wired. Safe to call when no connection is set (no-op). SEM@a0abba4563581c2c2d54d1df58750d51e83e3e43: close the NATS connection if one is wired; no-op otherwise (mutates shared state)

func (s *Server) ConfirmIdentityLink(c *gin.Context)

ConfirmIdentityLink handles POST /me/identities/link/confirm (#383). SEM@d89a562535e2240eeb7f556a3f619d28fe9c5613: route identity link confirmation request to the auth handler

func (*Server) ContentOAuthCallback

func (s *Server) ContentOAuthCallback(c *gin.Context, _ ContentOAuthCallbackParams)

ContentOAuthCallback implements ServerInterface.ContentOAuthCallback. The generated typed params are unused here because the underlying handler reads the query string directly via c.Query. SEM@74d36522781dcfd28cfc8f5f32ed5cd9dd62a25e: handle the OAuth callback from a content provider, or 404 if the feature is disabled

func (*Server) ContentOAuthHandlers

func (s *Server) ContentOAuthHandlers() *ContentOAuthHandlers

ContentOAuthHandlers returns the attached content-OAuth handler bundle (nil when none is wired). Exposed so callers such as the pre-user-delete hook wiring can register without tripping the unused-field lint. SEM@74d36522781dcfd28cfc8f5f32ed5cd9dd62a25e: return the attached content-OAuth handler bundle, or nil if not wired (pure)

func (*Server) CreateAddon

func (s *Server) CreateAddon(c *gin.Context)

CreateAddon creates a new add-on (admin only) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate addon creation to the standalone admin handler (mutates shared state)

func (*Server) CreateAdminGroup

func (s *Server) CreateAdminGroup(c *gin.Context)

CreateAdminGroup handles POST /admin/groups SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: store a new built-in provider group and emit an audit log entry (mutates shared state)

func (*Server) CreateAdminSurvey

func (s *Server) CreateAdminSurvey(c *gin.Context)

CreateAdminSurvey creates a new survey. POST /admin/surveys SEM@00add3d4f7dc1c0a9cc072d7e6ca32ace4d03641: store a new survey template and emit a webhook event (mutates shared state)

func (*Server) CreateAdminSurveyMetadata

func (s *Server) CreateAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

CreateAdminSurveyMetadata creates survey metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to store a new survey metadata entry (mutates shared state)

func (*Server) CreateAdminUserClientCredential

func (s *Server) CreateAdminUserClientCredential(c *gin.Context, internalUuid openapi_types.UUID)

CreateAdminUserClientCredential handles POST /admin/users/{internal_uuid}/client_credentials SEM@469dc723f406bfcd7fd46bc19ba3a1f279f40f25: build and store a new client credential for an automation user account, bypassing quota (mutates shared state)

func (*Server) CreateAutomationAccount

func (s *Server) CreateAutomationAccount(c *gin.Context)

CreateAutomationAccount handles POST /admin/users/automation Creates an automation (service) account with TMI provider, sets automation=true, adds to TMI Automation group, and creates a client credential. SEM@1aa36c06c7b700d3f00bf6f4b22125d673b1070a: handle POST /admin/users/automation: create a service account with group membership and client credential (reads DB)

func (*Server) CreateContentFeedback

func (s *Server) CreateContentFeedback(c *gin.Context, threatModelId ThreatModelId)

CreateContentFeedback creates a content feedback entry for a threat model. SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: route create content feedback requests for a threat model to the feedback handler

func (*Server) CreateCurrentUserClientCredential

func (s *Server) CreateCurrentUserClientCredential(c *gin.Context)

CreateCurrentUserClientCredential handles POST /me/client_credentials Creates a new OAuth 2.0 client credential for machine-to-machine authentication SEM@469dc723f406bfcd7fd46bc19ba3a1f279f40f25: create a client credential for the authenticated user; enforces admin/reviewer authorization and quota (reads DB)

func (*Server) CreateCurrentUserPreferences

func (s *Server) CreateCurrentUserPreferences(c *gin.Context)

CreateCurrentUserPreferences handles POST /me/preferences SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: store new preferences for the authenticated user, rejecting duplicates (reads DB)

func (*Server) CreateDiagramCollaborationSession

func (s *Server) CreateDiagramCollaborationSession(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

CreateDiagramCollaborationSession creates a new collaboration session for a diagram SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: create a collaboration session for a diagram

func (*Server) CreateDiagramMetadata

func (s *Server) CreateDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

CreateDiagramMetadata creates diagram metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: store a new metadata entry on a diagram (mutates shared state)

func (*Server) CreateDocumentMetadata

func (s *Server) CreateDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

CreateDocumentMetadata creates document metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: store a new metadata entry for a document (reads DB)

func (*Server) CreateIntakeSurveyResponse

func (s *Server) CreateIntakeSurveyResponse(c *gin.Context)

CreateIntakeSurveyResponse creates a new survey response in draft status. POST /intake/survey_responses SEM@b11b7d1f947994479701d4db877ed4964b3bfaa6: store a new draft survey response and extract answers (mutates shared state)

func (*Server) CreateIntakeSurveyResponseMetadata

func (s *Server) CreateIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

CreateIntakeSurveyResponseMetadata creates intake survey response metadata SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize writer access then store a new survey response metadata entry (mutates shared state)

func (*Server) CreateNoteMetadata

func (s *Server) CreateNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

CreateNoteMetadata creates note metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route create-metadata request for a note to the metadata handler

func (*Server) CreateProject

func (s *Server) CreateProject(c *gin.Context)

CreateProject creates a new project. Requires membership in the referenced team. POST /projects SEM@00add3d4f7dc1c0a9cc072d7e6ca32ace4d03641: create a project under a team the caller is a member of (reads DB)

func (*Server) CreateProjectMetadata

func (s *Server) CreateProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: create a metadata entry for a project, delegating to the generic metadata handler (reads DB)

func (*Server) CreateProjectNote

func (s *Server) CreateProjectNote(c *gin.Context, projectId openapi_types.UUID)

CreateProjectNote creates a new note for a project. POST /projects/{project_id}/notes SEM@8a8c018ad8b1686dd4e43f736f31431743de5393: store a new sanitized project note, enforcing sharable field restrictions by role (reads DB)

func (*Server) CreateRepositoryMetadata

func (s *Server) CreateRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

CreateRepositoryMetadata creates repository metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route repository metadata creation request to the metadata handler

func (*Server) CreateTeam

func (s *Server) CreateTeam(c *gin.Context)

CreateTeam creates a new team. Any authenticated user can create a team. The creator is auto-added as a member. POST /teams SEM@00add3d4f7dc1c0a9cc072d7e6ca32ace4d03641: store a new team and auto-add the creator as a member (writes DB)

func (*Server) CreateTeamMetadata

func (s *Server) CreateTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: store a new metadata entry for a team via the generic metadata handler

func (*Server) CreateTeamNote

func (s *Server) CreateTeamNote(c *gin.Context, teamId openapi_types.UUID)

CreateTeamNote creates a new note for a team. POST /teams/{team_id}/notes SEM@1ce00faf902914340ca54f7376e355c547163dda: create a team note, enforcing sharable-field privilege rules (mutates shared state)

func (*Server) CreateThreatMetadata

func (s *Server) CreateThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

CreateThreatMetadata creates threat metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: create a new metadata entry on a threat

func (*Server) CreateThreatModel

func (s *Server) CreateThreatModel(c *gin.Context)

CreateThreatModel creates a new threat model SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route create threat model request to the threat model handler

func (*Server) CreateThreatModelAsset

func (s *Server) CreateThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelAsset creates an asset SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route create-asset request to the asset handler for a given threat model

func (*Server) CreateThreatModelAssetMetadata

func (s *Server) CreateThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

CreateThreatModelAssetMetadata creates asset metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route create-asset-metadata request to the metadata handler

func (*Server) CreateThreatModelDiagram

func (s *Server) CreateThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelDiagram creates a new diagram SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route create diagram request to the diagram handler with WebSocket hub

func (*Server) CreateThreatModelDocument

func (s *Server) CreateThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelDocument creates a document SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route document creation request to the document handler under a threat model (reads DB)

func (*Server) CreateThreatModelFromSurveyResponse

func (s *Server) CreateThreatModelFromSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)

CreateThreatModelFromSurveyResponse creates a threat model from an approved survey response. POST /triage/survey_responses/{response_id}/create_threat_model SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: create a threat model from a ready-for-review survey response and emit webhooks (mutates shared state)

func (*Server) CreateThreatModelMetadata

func (s *Server) CreateThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelMetadata creates threat model metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: store a new metadata entry on a threat model (mutates shared state)

func (*Server) CreateThreatModelNote

func (s *Server) CreateThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelNote creates a note SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route create-note request for a threat model to the note handler

func (*Server) CreateThreatModelRepository

func (s *Server) CreateThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelRepository creates a repository SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route repository creation request to the repository handler

func (*Server) CreateThreatModelThreat

func (s *Server) CreateThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelThreat creates a threat SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route threat creation to the threat handler

func (*Server) CreateTimmyChatMessage

func (s *Server) CreateTimmyChatMessage(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)

CreateTimmyChatMessage sends a message and streams the assistant's response via SSE. SEM@c309061af96f4db6e2d3a7da1d077b6a6f2f3c75: send a user message to Timmy and stream the assistant response token-by-token via SSE

func (*Server) CreateTimmyChatSession

func (s *Server) CreateTimmyChatSession(c *gin.Context, threatModelId ThreatModelId)

CreateTimmyChatSession creates a new chat session and streams preparation progress via SSE. SEM@c309061af96f4db6e2d3a7da1d077b6a6f2f3c75: create a new Timmy chat session and stream preparation progress to the caller via SSE

func (*Server) CreateTriageSurveyResponseTriageNote

func (s *Server) CreateTriageSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId)

CreateTriageSurveyResponseTriageNote creates a triage note SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: store a new triage note for a survey response via the triage stage (mutates shared state)

func (*Server) CreateUsabilityFeedback

func (s *Server) CreateUsabilityFeedback(c *gin.Context)

CreateUsabilityFeedback creates a usability feedback entry. SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: route create usability feedback requests to the feedback handler

func (*Server) CreateWebhookSubscription

func (s *Server) CreateWebhookSubscription(c *gin.Context)

CreateWebhookSubscription creates a new webhook subscription (admin only) SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: validate and store a new webhook subscription, enforcing rate limits and URL safety (reads DB)

func (*Server) DeleteAddon

func (s *Server) DeleteAddon(c *gin.Context, id openapi_types.UUID)

DeleteAddon deletes an add-on (admin only) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate addon deletion to the standalone admin handler (mutates shared state)

func (*Server) DeleteAddonInvocationQuota

func (s *Server) DeleteAddonInvocationQuota(c *gin.Context, userId openapi_types.UUID)

DeleteAddonInvocationQuota deletes the addon invocation quota for a specific user, reverting to defaults (admin only) SEM@9214f003590204e62d98bd62c10b96602d3ef503: delete the custom addon invocation quota for a user, reverting to system defaults (mutates shared state)

func (*Server) DeleteAdminGroup

func (s *Server) DeleteAdminGroup(c *gin.Context, internalUuid openapi_types.UUID)

DeleteAdminGroup handles DELETE /admin/groups/{internal_uuid} SEM@70b575a9e0ec7ae8f154644ac025dce6e14acb51: delete a group and its associated data, rejecting protected built-in groups (mutates shared state)

func (*Server) DeleteAdminSurvey

func (s *Server) DeleteAdminSurvey(c *gin.Context, surveyId SurveyId, params DeleteAdminSurveyParams)

DeleteAdminSurvey deletes a survey. DELETE /admin/surveys/{survey_id} SEM@00add3d4f7dc1c0a9cc072d7e6ca32ace4d03641: delete a survey that has no responses and emit a webhook event (mutates shared state)

func (*Server) DeleteAdminSurveyMetadataByKey

func (s *Server) DeleteAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)

DeleteAdminSurveyMetadataByKey deletes survey metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to delete a survey metadata entry by key (mutates shared state)

func (*Server) DeleteAdminUser

func (s *Server) DeleteAdminUser(c *gin.Context, internalUuid openapi_types.UUID)

DeleteAdminUser handles DELETE /admin/users/{internal_uuid} SEM@a870b93778753735e380098f91f8c25076bbb50a: delete a user account by internal UUID, preventing self-deletion (mutates shared state)

func (*Server) DeleteAdminUserClientCredential

func (s *Server) DeleteAdminUserClientCredential(c *gin.Context, internalUuid openapi_types.UUID, credentialId openapi_types.UUID)

DeleteAdminUserClientCredential handles DELETE /admin/users/{internal_uuid}/client_credentials/{credential_id} SEM@469dc723f406bfcd7fd46bc19ba3a1f279f40f25: delete a client credential belonging to an automation user account (mutates shared state)

func (*Server) DeleteCurrentUserClientCredential

func (s *Server) DeleteCurrentUserClientCredential(c *gin.Context, credentialId openapi_types.UUID)

DeleteCurrentUserClientCredential handles DELETE /me/client_credentials/{credential_id} Permanently deletes a client credential SEM@469dc723f406bfcd7fd46bc19ba3a1f279f40f25: delete and revoke a client credential owned by the authenticated user (reads DB)

func (*Server) DeleteDiagramMetadataByKey

func (s *Server) DeleteDiagramMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID, key string)

DeleteDiagramMetadataByKey deletes diagram metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delete a diagram metadata entry by key (mutates shared state)

func (*Server) DeleteDocumentMetadataByKey

func (s *Server) DeleteDocumentMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID, key string)

DeleteDocumentMetadataByKey deletes document metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delete a metadata entry for a document by key (reads DB)

func (*Server) DeleteEmbeddings

func (s *Server) DeleteEmbeddings(c *gin.Context, threatModelId ThreatModelId, params DeleteEmbeddingsParams)

DeleteEmbeddings deletes embeddings for a threat model, optionally filtered. DELETE /automation/embeddings/{threat_model_id} SEM@12a333f6f1d8bf16f9daa952af09057188c98cdc: delete embeddings for a threat model filtered by entity or index type and invalidate the vector index (reads DB)

func (*Server) DeleteIntakeSurveyResponse

func (s *Server) DeleteIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)

DeleteIntakeSurveyResponse deletes a survey response. DELETE /intake/survey_responses/{response_id} SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: delete an owned survey response and emit a webhook event (mutates shared state)

func (*Server) DeleteIntakeSurveyResponseMetadataByKey

func (s *Server) DeleteIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

DeleteIntakeSurveyResponseMetadataByKey deletes intake survey response metadata by key SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize writer access then delete intake survey response metadata by key (mutates shared state)

func (*Server) DeleteMyContentToken

func (s *Server) DeleteMyContentToken(c *gin.Context, providerId string)

DeleteMyContentToken implements ServerInterface.DeleteMyContentToken. SEM@74d36522781dcfd28cfc8f5f32ed5cd9dd62a25e: delete the current user's content provider OAuth token, or 404 if the feature is disabled

func (*Server) DeleteMyIdentity

func (s *Server) DeleteMyIdentity(c *gin.Context, id openapi_types.UUID)

DeleteMyIdentity handles DELETE /me/identities/{id}. Removes a linked identity from the authenticated user's account. Returns 404 for unknown or foreign IDs (no distinguishable response). SEM@fc8e2c83f6aaba09d10a2ed6f6e78a5075d278ba: delete a linked identity from the authenticated user's account and emit an audit event (mutates shared state)

func (*Server) DeleteNoteMetadataByKey

func (s *Server) DeleteNoteMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID, key string)

DeleteNoteMetadataByKey deletes note metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route delete-metadata-by-key request for a note to the metadata handler

func (*Server) DeleteProject

func (s *Server) DeleteProject(c *gin.Context, projectId openapi_types.UUID)

DeleteProject deletes a project. Requires team owner/creator role or admin. Returns 409 if threat models reference it. DELETE /projects/{project_id} SEM@63220a9061c9f3350c3ad8fc0c180619bb4fc3bf: delete a project, rejecting with 409 if threat models still reference it (reads DB)

func (*Server) DeleteProjectMetadata

func (s *Server) DeleteProjectMetadata(c *gin.Context, projectId openapi_types.UUID, key string)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: delete a metadata entry by key for a project, delegating to the generic metadata handler (reads DB)

func (*Server) DeleteProjectNote

func (s *Server) DeleteProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)

DeleteProjectNote deletes a project note. DELETE /projects/{project_id}/notes/{project_note_id} SEM@8a8c018ad8b1686dd4e43f736f31431743de5393: delete a project note, hiding non-sharable notes from unprivileged users as 404 (reads DB)

func (*Server) DeleteRepositoryMetadataByKey

func (s *Server) DeleteRepositoryMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID, key string)

DeleteRepositoryMetadataByKey deletes repository metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delete a repository metadata entry by key

func (*Server) DeleteSystemSetting

func (s *Server) DeleteSystemSetting(c *gin.Context, key string)

DeleteSystemSetting deletes a system setting (admin only) SEM@dcb09b6afcb6a3a78ce7ba3c345e459ba9cf55a2: delete a system setting by key, rejecting reserved or internal-visibility keys (reads DB)

func (*Server) DeleteTeam

func (s *Server) DeleteTeam(c *gin.Context, teamId openapi_types.UUID)

DeleteTeam deletes a team. Requires owner role or admin. Returns 409 if team has projects. DELETE /teams/{team_id} SEM@63220a9061c9f3350c3ad8fc0c180619bb4fc3bf: delete a team after verifying owner or admin role, emitting a deletion event (reads DB)

func (*Server) DeleteTeamMetadata

func (s *Server) DeleteTeamMetadata(c *gin.Context, teamId openapi_types.UUID, key string)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: delete a single metadata entry for a team via the generic metadata handler

func (*Server) DeleteTeamNote

func (s *Server) DeleteTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)

DeleteTeamNote deletes a team note. DELETE /teams/{team_id}/notes/{team_note_id} SEM@1ce00faf902914340ca54f7376e355c547163dda: delete a team note, hiding non-sharable notes from unprivileged users (mutates shared state)

func (*Server) DeleteThreatMetadataByKey

func (s *Server) DeleteThreatMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID, key string)

DeleteThreatMetadataByKey deletes threat metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delete a single threat metadata entry by key

func (*Server) DeleteThreatModel

func (s *Server) DeleteThreatModel(c *gin.Context, threatModelId openapi_types.UUID)

DeleteThreatModel deletes a threat model SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route delete threat model request to the threat model handler

func (*Server) DeleteThreatModelAsset

func (s *Server) DeleteThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

DeleteThreatModelAsset deletes an asset SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route delete-asset request to the asset handler for a given threat model and asset

func (*Server) DeleteThreatModelAssetMetadata

func (s *Server) DeleteThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID, key string)

DeleteThreatModelAssetMetadata deletes asset metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route delete-asset-metadata-by-key request to the metadata handler

func (*Server) DeleteThreatModelDiagram

func (s *Server) DeleteThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

DeleteThreatModelDiagram deletes a diagram SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route delete diagram request to the diagram handler with WebSocket hub

func (*Server) DeleteThreatModelDocument

func (s *Server) DeleteThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

DeleteThreatModelDocument deletes a document SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route document deletion to the document handler, scoped to a threat model (reads DB)

func (*Server) DeleteThreatModelMetadataByKey

func (s *Server) DeleteThreatModelMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, key string)

DeleteThreatModelMetadataByKey deletes threat model metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delete a threat model metadata entry by key (mutates shared state)

func (*Server) DeleteThreatModelNote

func (s *Server) DeleteThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

DeleteThreatModelNote deletes a note SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route delete-note request for a threat model note to the note handler

func (*Server) DeleteThreatModelRepository

func (s *Server) DeleteThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

DeleteThreatModelRepository deletes a repository SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route repository delete request to the repository handler

func (*Server) DeleteThreatModelThreat

func (s *Server) DeleteThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

DeleteThreatModelThreat deletes a threat SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route single threat deletion to the threat handler

func (*Server) DeleteTimmyChatSession

func (s *Server) DeleteTimmyChatSession(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)

DeleteTimmyChatSession soft-deletes a session. SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: soft-delete a Timmy chat session after verifying ownership (reads DB)

func (*Server) DeleteUserAPIQuota

func (s *Server) DeleteUserAPIQuota(c *gin.Context, userId openapi_types.UUID)

DeleteUserAPIQuota deletes the API quota for a specific user, reverting to defaults (admin only) SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: delete the custom API rate quota for a user, reverting to system defaults (mutates shared state)

func (*Server) DeleteUserAccount

func (s *Server) DeleteUserAccount(c *gin.Context, params DeleteUserAccountParams)

DeleteUserAccount handles user account deletion (two-step challenge-response) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route account deletion request to the user deletion handler via challenge-response

func (*Server) DeleteWebhookQuota

func (s *Server) DeleteWebhookQuota(c *gin.Context, userId openapi_types.UUID)

DeleteWebhookQuota deletes the webhook quota for a specific user, reverting to defaults (admin only) SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: delete the custom webhook quota for a user, reverting to system defaults (mutates shared state)

func (*Server) DeleteWebhookSubscription

func (s *Server) DeleteWebhookSubscription(c *gin.Context, webhookId openapi_types.UUID)

DeleteWebhookSubscription deletes a webhook subscription (admin only) SEM@4c446bfacf6eb966a03bc2a174728d73b8a6d41e: delete a webhook subscription and cascade-delete its addons, blocking pinned rows (reads DB)

func (*Server) EndDiagramCollaborationSession

func (s *Server) EndDiagramCollaborationSession(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

EndDiagramCollaborationSession ends a collaboration session for a diagram SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: end and delete a diagram's active collaboration session

func (*Server) ExchangeOAuthCode

func (s *Server) ExchangeOAuthCode(c *gin.Context, params ExchangeOAuthCodeParams)

ExchangeOAuthCode exchanges auth code for tokens SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route OAuth token exchange request to the auth service supporting multiple grant types

func (*Server) GetAddon

func (s *Server) GetAddon(c *gin.Context, id openapi_types.UUID)

GetAddon gets a single add-on by ID SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate addon fetch by ID to the standalone handler (reads DB)

func (*Server) GetAddonInvocationQuota

func (s *Server) GetAddonInvocationQuota(c *gin.Context, userId openapi_types.UUID)

GetAddonInvocationQuota retrieves the addon invocation quota for a specific user (admin only) SEM@84c7489e38c8e3adddcd6cfc1a87d93077d0e98f: fetch the custom addon invocation quota for a specific user (reads DB)

func (*Server) GetAdminGroup

func (s *Server) GetAdminGroup(c *gin.Context, internalUuid openapi_types.UUID)

GetAdminGroup handles GET /admin/groups/{internal_uuid} SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: fetch a single admin group by UUID with enriched authorization data (reads DB)

func (*Server) GetAdminSurvey

func (s *Server) GetAdminSurvey(c *gin.Context, surveyId SurveyId)

GetAdminSurvey returns a specific survey. GET /admin/surveys/{survey_id} SEM@0bd9c0e0e0c0649294d164b9dc945b801cfd507c: fetch a survey template by ID (reads DB)

func (*Server) GetAdminSurveyMetadata

func (s *Server) GetAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

GetAdminSurveyMetadata gets survey metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to list all survey metadata entries (reads DB)

func (*Server) GetAdminSurveyMetadataByKey

func (s *Server) GetAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)

GetAdminSurveyMetadataByKey gets survey metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to fetch a single survey metadata entry by key (reads DB)

func (*Server) GetAdminThreatModelAuditEntry

func (s *Server) GetAdminThreatModelAuditEntry(c *gin.Context, entryId openapi_types.UUID)

GetAdminThreatModelAuditEntry handles GET /admin/audit/threat_models/{entry_id} (#398). SEM@7bac1ed632ff8929eff543daec4372c53d51283a: handle GET /admin/audit/threat_models/{entry_id}, fetching a single threat-model audit entry by ID (reads DB)

func (*Server) GetAdminUser

func (s *Server) GetAdminUser(c *gin.Context, internalUuid openapi_types.UUID)

GetAdminUser handles GET /admin/users/{internal_uuid} SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: fetch a single user record by internal UUID via admin API (reads DB)

func (*Server) GetApiInfo

func (s *Server) GetApiInfo(c *gin.Context)

GetApiInfo returns API information SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route API info request to the API info handler

func (*Server) GetAssetAuditTrail

func (s *Server) GetAssetAuditTrail(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, params GetAssetAuditTrailParams)

GetAssetAuditTrail lists audit entries for a specific asset. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate asset audit trail listing to the audit handler (reads DB)

func (*Server) GetAuditEntry

func (s *Server) GetAuditEntry(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

GetAuditEntry returns a single audit entry. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate single audit entry fetch to the audit handler (reads DB)

func (*Server) GetAuthProviders

func (s *Server) GetAuthProviders(c *gin.Context)

GetAuthProviders lists OAuth providers SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route request listing configured OAuth providers to the auth service

func (*Server) GetClientConfig

func (s *Server) GetClientConfig(c *gin.Context)

GetClientConfig returns public configuration for client applications This is a public endpoint that does not require authentication. SEM@fe6575f1c15d84b67ee9853a0e59055c1ebe44b6: fetch public client configuration including feature flags, limits, and content providers

func (*Server) GetContentFeedback

func (s *Server) GetContentFeedback(c *gin.Context, threatModelId ThreatModelId, feedbackId openapi_types.UUID)

GetContentFeedback retrieves a content feedback entry by ID within a threat model. SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: route content feedback fetch request to the content feedback handler

func (*Server) GetCurrentUser

func (s *Server) GetCurrentUser(c *gin.Context)

GetCurrentUser gets current user information SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route OIDC userinfo request to the auth service for the current user

func (*Server) GetCurrentUserPreferences

func (s *Server) GetCurrentUserPreferences(c *gin.Context)

GetCurrentUserPreferences handles GET /me/preferences SEM@cdbe48c974fb76e1161972733b30bb0d1c02c3b1: fetch the authenticated user's stored preferences (reads DB)

func (*Server) GetCurrentUserProfile

func (s *Server) GetCurrentUserProfile(c *gin.Context)

GetCurrentUserProfile gets current user profile with groups and admin status (from /me endpoint) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route /me profile request to the auth service, including admin status

func (*Server) GetCurrentUserSessions

func (s *Server) GetCurrentUserSessions(c *gin.Context)

GetCurrentUserSessions returns all active collaboration sessions that the user has access to SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: list active collaboration sessions visible to the authenticated user

func (*Server) GetDiagramAuditTrail

func (s *Server) GetDiagramAuditTrail(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, params GetDiagramAuditTrailParams)

GetDiagramAuditTrail lists audit entries for a specific diagram. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate diagram audit trail listing to the audit handler (reads DB)

func (*Server) GetDiagramCollaborationSession

func (s *Server) GetDiagramCollaborationSession(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

GetDiagramCollaborationSession retrieves the current collaboration session for a diagram SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch the active collaboration session for a diagram

func (*Server) GetDiagramMetadata

func (s *Server) GetDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

GetDiagramMetadata gets diagram metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list all metadata entries for a diagram (reads DB)

func (*Server) GetDiagramMetadataByKey

func (s *Server) GetDiagramMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID, key string)

GetDiagramMetadataByKey gets diagram metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch a single diagram metadata entry by key (reads DB)

func (*Server) GetDiagramModel

func (s *Server) GetDiagramModel(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

GetDiagramModel gets minimal diagram model for automated analysis SEM@29f63eb500c26288d0d3fe23737adf6fd94bdf9c: route diagram model request to the diagram handler

func (*Server) GetDocumentAuditTrail

func (s *Server) GetDocumentAuditTrail(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, params GetDocumentAuditTrailParams)

GetDocumentAuditTrail lists audit entries for a specific document. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch paginated audit entries for a specific document (reads DB)

func (*Server) GetDocumentMetadata

func (s *Server) GetDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

GetDocumentMetadata gets document metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list all metadata entries for a document (reads DB)

func (*Server) GetDocumentMetadataByKey

func (s *Server) GetDocumentMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID, key string)

GetDocumentMetadataByKey gets document metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch a single metadata entry for a document by key (reads DB)

func (*Server) GetEmbeddingConfig

func (s *Server) GetEmbeddingConfig(c *gin.Context, threatModelId ThreatModelId)

GetEmbeddingConfig returns the embedding provider configuration for a threat model. GET /automation/embeddings/{threat_model_id}/config SEM@c309061af96f4db6e2d3a7da1d077b6a6f2f3c75: fetch the active embedding provider configuration for a threat model

func (*Server) GetIntakeSurvey

func (s *Server) GetIntakeSurvey(c *gin.Context, surveyId SurveyId)

GetIntakeSurvey returns a specific active survey for filling. GET /intake/surveys/{survey_id} SEM@0bd9c0e0e0c0649294d164b9dc945b801cfd507c: fetch an active survey by ID for intake; 404 if inactive (reads DB)

func (*Server) GetIntakeSurveyResponse

func (s *Server) GetIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)

GetIntakeSurveyResponse returns a specific survey response. GET /intake/survey_responses/{response_id} SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: fetch an authorized survey response for the requesting user (reads DB)

func (*Server) GetIntakeSurveyResponseMetadata

func (s *Server) GetIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

GetIntakeSurveyResponseMetadata gets intake survey response metadata SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize reader access then list all metadata for a survey response (reads DB)

func (*Server) GetIntakeSurveyResponseMetadataByKey

func (s *Server) GetIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

GetIntakeSurveyResponseMetadataByKey gets intake survey response metadata by key SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize reader access then fetch intake survey response metadata by key (reads DB)

func (*Server) GetIntakeSurveyResponseTriageNote

func (s *Server) GetIntakeSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId, triageNoteId TriageNoteId)

GetIntakeSurveyResponseTriageNote gets a specific triage note for submitter (read-only) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch a single triage note for a survey response via the intake stage (read-only) (reads DB)

func (*Server) GetJWKS

func (s *Server) GetJWKS(c *gin.Context)

GetJWKS returns the JSON Web Key Set for JWT signature verification SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route JWKS request to the auth service for JWT signature verification

func (*Server) GetNoteAuditTrail

func (s *Server) GetNoteAuditTrail(c *gin.Context, threatModelId ThreatModelId, noteId NoteId, params GetNoteAuditTrailParams)

GetNoteAuditTrail lists audit entries for a specific note. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch paginated audit entries for a specific note (reads DB)

func (*Server) GetNoteMetadata

func (s *Server) GetNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

GetNoteMetadata gets note metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route list-metadata request for a note to the metadata handler

func (*Server) GetNoteMetadataByKey

func (s *Server) GetNoteMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID, key string)

GetNoteMetadataByKey gets note metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route fetch-metadata-by-key request for a note to the metadata handler

func (*Server) GetOAuthAuthorizationServerMetadata

func (s *Server) GetOAuthAuthorizationServerMetadata(c *gin.Context)

GetOAuthAuthorizationServerMetadata returns OAuth 2.0 Authorization Server Metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route OAuth 2.0 authorization server metadata request to the auth service

func (*Server) GetOAuthProtectedResourceMetadata

func (s *Server) GetOAuthProtectedResourceMetadata(c *gin.Context)

GetOAuthProtectedResourceMetadata returns OAuth 2.0 protected resource metadata as per RFC 9728 SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route OAuth 2.0 protected resource metadata request to the auth service per RFC 9728

func (*Server) GetOpenIDConfiguration

func (s *Server) GetOpenIDConfiguration(c *gin.Context)

GetOpenIDConfiguration returns OpenID Connect configuration SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route OpenID Connect discovery document request to the auth service

func (s *Server) GetPendingIdentityLink(c *gin.Context, linkId string)

GetPendingIdentityLink handles GET /me/identities/link/pending/{link_id} (#383). SEM@053baa340d412aa135be32953dfcb6133af89b4d: route fetch-pending-identity-link request to the auth handler by link ID

func (*Server) GetProject

func (s *Server) GetProject(c *gin.Context, projectId openapi_types.UUID)

GetProject retrieves a project by ID. Requires team membership or admin. GET /projects/{project_id} SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: fetch a project by ID, including its notes, enforcing team-membership authorization (reads DB)

func (*Server) GetProjectMetadata

func (s *Server) GetProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: list metadata entries for a project, delegating to the generic metadata handler (reads DB)

func (*Server) GetProjectNote

func (s *Server) GetProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)

GetProjectNote returns a specific project note. GET /projects/{project_id}/notes/{project_note_id} SEM@8a8c018ad8b1686dd4e43f736f31431743de5393: fetch a single project note, hiding non-sharable notes from unprivileged users as 404 (reads DB)

func (*Server) GetProviderGroups

func (s *Server) GetProviderGroups(c *gin.Context, idp string)

GetProviderGroups returns groups available from a specific identity provider SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch cached groups for a given identity provider and annotate which are used in authorizations (reads DB)

func (*Server) GetRepositoryAuditTrail

func (s *Server) GetRepositoryAuditTrail(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, params GetRepositoryAuditTrailParams)

GetRepositoryAuditTrail lists audit entries for a specific repository. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch paginated audit entries for a specific repository (reads DB)

func (*Server) GetRepositoryMetadata

func (s *Server) GetRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

GetRepositoryMetadata gets repository metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list all metadata entries for a repository

func (*Server) GetRepositoryMetadataByKey

func (s *Server) GetRepositoryMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID, key string)

GetRepositoryMetadataByKey gets repository metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch a single repository metadata entry by key

func (*Server) GetSAMLMetadata

func (s *Server) GetSAMLMetadata(c *gin.Context, provider string)

GetSAMLMetadata returns SAML service provider metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route SAML SP metadata request to the auth adapter for a given SAML provider

func (*Server) GetSAMLProviders

func (s *Server) GetSAMLProviders(c *gin.Context)

GetSAMLProviders implements ServerInterface SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route request listing configured SAML providers to the auth service

func (*Server) GetSystemAuditEntry

func (s *Server) GetSystemAuditEntry(c *gin.Context, entryId openapi_types.UUID)

GetSystemAuditEntry handles GET /admin/audit/system/{entry_id} (#398). SEM@7bac1ed632ff8929eff543daec4372c53d51283a: handle GET /admin/audit/system/{entry_id}, fetching a single system audit entry by ID (reads DB)

func (*Server) GetSystemSetting

func (s *Server) GetSystemSetting(c *gin.Context, key string)

GetSystemSetting returns a specific system setting by key (admin only) SEM@d056a3ea026249d40d05ab6af7f092a043f72c7a: fetch a single system setting by key, masking secrets and hiding internal keys (reads DB)

func (*Server) GetTeam

func (s *Server) GetTeam(c *gin.Context, teamId openapi_types.UUID)

GetTeam retrieves a team by ID. Requires team membership or admin. GET /teams/{team_id} SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: fetch a team by ID, requiring membership or admin role (reads DB)

func (*Server) GetTeamMetadata

func (s *Server) GetTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: list metadata entries for a team by delegating to the generic metadata handler

func (*Server) GetTeamNote

func (s *Server) GetTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)

GetTeamNote returns a specific team note. GET /teams/{team_id}/notes/{team_note_id} SEM@1ce00faf902914340ca54f7376e355c547163dda: fetch a team note, hiding non-sharable notes from unprivileged users (reads DB)

func (*Server) GetThreatAuditTrail

func (s *Server) GetThreatAuditTrail(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, params GetThreatAuditTrailParams)

GetThreatAuditTrail lists audit entries for a specific threat. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate threat audit trail listing to the audit handler (reads DB)

func (*Server) GetThreatMetadata

func (s *Server) GetThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

GetThreatMetadata gets threat metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list all metadata entries for a threat

func (*Server) GetThreatMetadataByKey

func (s *Server) GetThreatMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID, key string)

GetThreatMetadataByKey gets threat metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch a single threat metadata entry by key

func (*Server) GetThreatModel

func (s *Server) GetThreatModel(c *gin.Context, threatModelId openapi_types.UUID)

GetThreatModel gets a specific threat model SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route fetch threat model by ID to the threat model handler

func (*Server) GetThreatModelAsset

func (s *Server) GetThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

GetThreatModelAsset gets an asset SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route fetch-asset request to the asset handler for a given threat model and asset

func (*Server) GetThreatModelAssetMetadata

func (s *Server) GetThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

GetThreatModelAssetMetadata gets asset metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route list-asset-metadata request to the metadata handler

func (*Server) GetThreatModelAssetMetadataByKey

func (s *Server) GetThreatModelAssetMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID, key string)

GetThreatModelAssetMetadataByKey gets asset metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route fetch-asset-metadata-by-key request to the metadata handler

func (*Server) GetThreatModelAssets

func (s *Server) GetThreatModelAssets(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelAssetsParams)

GetThreatModelAssets lists assets SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route list-assets request to the asset handler, enforcing include-deleted authorization

func (*Server) GetThreatModelAuditTrail

func (s *Server) GetThreatModelAuditTrail(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelAuditTrailParams)

GetThreatModelAuditTrail lists audit entries for a threat model and all sub-objects. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate threat model audit trail listing to the audit handler (reads DB)

func (*Server) GetThreatModelDiagram

func (s *Server) GetThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

GetThreatModelDiagram gets a specific diagram SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route fetch diagram by ID to the diagram handler with WebSocket hub

func (*Server) GetThreatModelDiagrams

func (s *Server) GetThreatModelDiagrams(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelDiagramsParams)

GetThreatModelDiagrams lists diagrams for a threat model SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list diagrams for a threat model, enforcing include-deleted authorization

func (*Server) GetThreatModelDocument

func (s *Server) GetThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

GetThreatModelDocument gets a document SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route single document fetch to the document handler, scoped to a threat model (reads DB)

func (*Server) GetThreatModelDocuments

func (s *Server) GetThreatModelDocuments(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelDocumentsParams)

GetThreatModelDocuments lists documents SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list documents for a threat model, enforcing include-deleted authorization (reads DB)

func (*Server) GetThreatModelMetadata

func (s *Server) GetThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

GetThreatModelMetadata gets threat model metadata SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list all metadata entries for a threat model (reads DB)

func (*Server) GetThreatModelMetadataByKey

func (s *Server) GetThreatModelMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, key string)

GetThreatModelMetadataByKey gets threat model metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch a single threat model metadata entry by key (reads DB)

func (*Server) GetThreatModelNote

func (s *Server) GetThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

GetThreatModelNote gets a note SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route fetch-note request for a threat model note to the note handler

func (*Server) GetThreatModelNotes

func (s *Server) GetThreatModelNotes(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelNotesParams)

GetThreatModelNotes lists notes SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route list-notes request for a threat model to the note handler

func (*Server) GetThreatModelRepositories

func (s *Server) GetThreatModelRepositories(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelRepositoriesParams)

GetThreatModelRepositories lists repositories SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list repositories for a threat model, authorizing include-deleted access (reads DB)

func (*Server) GetThreatModelRepository

func (s *Server) GetThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

GetThreatModelRepository gets a repository SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route single repository fetch request to the repository handler

func (*Server) GetThreatModelThreat

func (s *Server) GetThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

GetThreatModelThreat gets a threat SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route single threat fetch to the threat handler

func (*Server) GetThreatModelThreats

func (s *Server) GetThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelThreatsParams)

GetThreatModelThreats lists threats SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list threats for a threat model, enforcing include-deleted authorization

func (*Server) GetTimmyChatSession

func (s *Server) GetTimmyChatSession(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)

GetTimmyChatSession retrieves a specific session. SEM@773397b4fdff89166751fd8b5643ac59abce3367: fetch a single Timmy chat session, verifying ownership and threat model match (reads DB)

func (*Server) GetTimmyStatus

func (s *Server) GetTimmyStatus(c *gin.Context)

GetTimmyStatus returns current memory and index status (admin only). SEM@c309061af96f4db6e2d3a7da1d077b6a6f2f3c75: return current Timmy vector memory and session status metrics (reads DB)

func (*Server) GetTimmyUsage

func (s *Server) GetTimmyUsage(c *gin.Context, params GetTimmyUsageParams)

GetTimmyUsage returns aggregated usage statistics (admin only). SEM@5b38b9a109d5e10e1a9a58a35a692f19c30a0ed5: fetch aggregated Timmy token usage statistics for an optional user and threat model over a date range (reads DB)

func (*Server) GetTriageSurveyResponse

func (s *Server) GetTriageSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)

GetTriageSurveyResponse returns a specific survey response for triage. GET /triage/survey_responses/{response_id} SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: fetch an authorized survey response for triage review (reads DB)

func (*Server) GetTriageSurveyResponseMetadata

func (s *Server) GetTriageSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

GetTriageSurveyResponseMetadata gets triage survey response metadata SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize reader access then list all triage survey response metadata entries (reads DB)

func (*Server) GetTriageSurveyResponseMetadataByKey

func (s *Server) GetTriageSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

GetTriageSurveyResponseMetadataByKey gets triage survey response metadata by key SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize reader access then fetch triage survey response metadata by key (reads DB)

func (*Server) GetTriageSurveyResponseTriageNote

func (s *Server) GetTriageSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId, triageNoteId TriageNoteId)

GetTriageSurveyResponseTriageNote gets a specific triage note SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch a single triage note for a survey response via the triage stage (reads DB)

func (*Server) GetUsabilityFeedback

func (s *Server) GetUsabilityFeedback(c *gin.Context, id openapi_types.UUID)

GetUsabilityFeedback retrieves a usability feedback entry by ID. SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: route fetch usability feedback by ID requests to the feedback handler

func (*Server) GetUserAPIQuota

func (s *Server) GetUserAPIQuota(c *gin.Context, userId openapi_types.UUID)

GetUserAPIQuota retrieves the API quota for a specific user (admin only) SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: fetch the custom API rate quota for a specific user (reads DB)

func (*Server) GetWebSocketHub

func (s *Server) GetWebSocketHub() *WebSocketHub

GetWebSocketHub returns the WebSocket hub instance SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: fetch the server's WebSocket hub instance (pure)

func (*Server) GetWebhookDelivery

func (s *Server) GetWebhookDelivery(c *gin.Context, deliveryId openapi_types.UUID)

GetWebhookDelivery gets a specific webhook delivery (admin only) SEM@5ab9bc35c2a66a8d16c0ac1b58f3d345958c9c34: fetch a single delivery record by ID with pinned-URL redaction applied (reads DB)

func (*Server) GetWebhookDeliveryStatus

func (s *Server) GetWebhookDeliveryStatus(c *gin.Context, deliveryId DeliveryId, params GetWebhookDeliveryStatusParams)

GetWebhookDeliveryStatus retrieves a webhook delivery record (dual auth: JWT or HMAC) SEM@ca61a567c4babc9270ee913396aaa4fb530505a3: fetch the delivery status record for a webhook delivery by ID (reads DB)

func (*Server) GetWebhookQuota

func (s *Server) GetWebhookQuota(c *gin.Context, userId openapi_types.UUID)

GetWebhookQuota retrieves the webhook quota for a specific user (admin only) SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: fetch the custom webhook quota for a specific user (reads DB)

func (*Server) GetWebhookSubscription

func (s *Server) GetWebhookSubscription(c *gin.Context, webhookId openapi_types.UUID)

GetWebhookSubscription gets a specific webhook subscription (admin only) SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: fetch a single webhook subscription by ID, redacting the URL if operator-pinned (reads DB)

func (*Server) GetWsTicket

func (s *Server) GetWsTicket(c *gin.Context, params GetWsTicketParams)

GetWsTicket issues a short-lived WebSocket authentication ticket. SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: issue a short-lived WebSocket authentication ticket for an authorized collaboration session participant

func (*Server) GrantMicrosoftFilePermission

func (s *Server) GrantMicrosoftFilePermission(c *gin.Context)

GrantMicrosoftFilePermission implements ServerInterface.GrantMicrosoftFilePermission. Stub until Task 10 attaches the real handler. When unwired, returns a structured 404 ("feature_not_available") via the shared contentOAuthUnavailable helper. SEM@8fd7f29e24352406748fc94d4c81959f59d433fd: delegate Microsoft file permission grant to the registered handler, or 404 if unregistered

func (*Server) HandleNotificationWebSocket

func (s *Server) HandleNotificationWebSocket(c *gin.Context)

HandleNotificationWebSocket handles WebSocket connections for notifications SEM@212287c6c02d99be7f8071b21a50666223646bec: upgrade an authenticated HTTP connection to a notification WebSocket and register the client (mutates shared state)

func (*Server) HandleOAuthCallback

func (s *Server) HandleOAuthCallback(c *gin.Context, params HandleOAuthCallbackParams)

HandleOAuthCallback handles OAuth callback SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route OAuth callback to the auth service for token exchange

func (*Server) HandleServerInfo

func (s *Server) HandleServerInfo(c *gin.Context)

HandleServerInfo provides server configuration information to clients SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: return server TLS and WebSocket configuration to clients

func (*Server) HandleWebSocket

func (s *Server) HandleWebSocket(c *gin.Context)

HandleWebSocket handles WebSocket connections SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: authenticate and upgrade an HTTP request to a diagram collaboration WebSocket connection

func (*Server) IngestEmbeddings

func (s *Server) IngestEmbeddings(c *gin.Context, threatModelId ThreatModelId)

IngestEmbeddings accepts a batch of pre-computed embeddings for a threat model. POST /automation/embeddings/{threat_model_id} SEM@12a333f6f1d8bf16f9daa952af09057188c98cdc: store a validated batch of pre-computed embeddings for a threat model and invalidate the vector index (reads DB)

func (*Server) InitiateSAMLLogin

func (s *Server) InitiateSAMLLogin(c *gin.Context, provider string, params InitiateSAMLLoginParams)

InitiateSAMLLogin starts SAML authentication flow SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route SAML login initiation to the auth adapter for a given provider

func (*Server) IntrospectToken

func (s *Server) IntrospectToken(c *gin.Context)

IntrospectToken handles token introspection requests per RFC 7662 SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route token introspection request to the auth service per RFC 7662

func (*Server) InvokeAddon

func (s *Server) InvokeAddon(c *gin.Context, id openapi_types.UUID)

InvokeAddon invokes an add-on SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate addon invocation to the standalone handler (mutates shared state)

func (*Server) ListAddonInvocationQuotas

func (s *Server) ListAddonInvocationQuotas(c *gin.Context, params ListAddonInvocationQuotasParams)

ListAddonInvocationQuotas retrieves all custom addon invocation quotas (admin only) SEM@503212a05958ba0c15d423fab4dbceb92b747ed9: list all custom per-user addon invocation quotas with pagination (reads DB)

func (*Server) ListAddons

func (s *Server) ListAddons(c *gin.Context, params ListAddonsParams)

ListAddons lists all add-ons SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate addon listing to the standalone handler (reads DB)

func (*Server) ListAdminGroups

func (s *Server) ListAdminGroups(c *gin.Context, params ListAdminGroupsParams)

ListAdminGroups handles GET /admin/groups SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: list admin groups with pagination, filtering, and enriched membership data (reads DB)

func (*Server) ListAdminSurveys

func (s *Server) ListAdminSurveys(c *gin.Context, params ListAdminSurveysParams)

ListAdminSurveys returns a paginated list of all surveys. GET /admin/surveys SEM@0bd9c0e0e0c0649294d164b9dc945b801cfd507c: list all surveys with pagination and optional status filter (reads DB)

func (*Server) ListAdminThreatModelAuditEntries

func (s *Server) ListAdminThreatModelAuditEntries(c *gin.Context, params ListAdminThreatModelAuditEntriesParams)

ListAdminThreatModelAuditEntries handles GET /admin/audit/threat_models (#398). SEM@2c1d4cb3d8cc963743f568bc4f17a46154cb2c43: handle GET /admin/audit/threat_models, listing threat-model audit entries with filters and keyset pagination (reads DB)

func (*Server) ListAdminUserClientCredentials

func (s *Server) ListAdminUserClientCredentials(c *gin.Context, internalUuid openapi_types.UUID, params ListAdminUserClientCredentialsParams)

ListAdminUserClientCredentials handles GET /admin/users/{internal_uuid}/client_credentials SEM@469dc723f406bfcd7fd46bc19ba3a1f279f40f25: list client credentials for an automation user account with pagination (reads DB)

func (*Server) ListAdminUsers

func (s *Server) ListAdminUsers(c *gin.Context, params ListAdminUsersParams)

ListAdminUsers handles GET /admin/users SEM@6b85a6fabc237d03c99bf64a10eb26dfeaf09d3b: list all users with pagination and optional filtering via admin API (reads DB)

func (*Server) ListContentFeedback

func (s *Server) ListContentFeedback(c *gin.Context, threatModelId ThreatModelId, params ListContentFeedbackParams)

ListContentFeedback lists content feedback entries for a threat model. SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: route list content feedback requests for a threat model to the feedback handler

func (*Server) ListCurrentUserClientCredentials

func (s *Server) ListCurrentUserClientCredentials(c *gin.Context, params ListCurrentUserClientCredentialsParams)

ListCurrentUserClientCredentials handles GET /me/client_credentials Retrieves all client credentials owned by the authenticated user (without secrets) SEM@469dc723f406bfcd7fd46bc19ba3a1f279f40f25: list all client credentials owned by the authenticated user with pagination, omitting secrets (reads DB)

func (*Server) ListGroupMembers

func (s *Server) ListGroupMembers(c *gin.Context, internalUuid openapi_types.UUID, params ListGroupMembersParams)

ListGroupMembers handles GET /admin/groups/{internal_uuid}/members SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: list paginated members of a group (reads DB)

func (*Server) ListIntakeSurveyResponseTriageNotes

func (s *Server) ListIntakeSurveyResponseTriageNotes(c *gin.Context, surveyResponseId SurveyResponseId, params ListIntakeSurveyResponseTriageNotesParams)

ListIntakeSurveyResponseTriageNotes lists triage notes for submitter (read-only) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list triage notes for a survey response via the intake stage (read-only) (reads DB)

func (*Server) ListIntakeSurveyResponses

func (s *Server) ListIntakeSurveyResponses(c *gin.Context, params ListIntakeSurveyResponsesParams)

ListIntakeSurveyResponses returns the current user's survey responses. GET /intake/survey_responses SEM@a1d7f44f9fbf44b654abfc81c5b3770eb540ecb0: list the authenticated user's own survey responses with pagination (reads DB)

func (*Server) ListIntakeSurveys

func (s *Server) ListIntakeSurveys(c *gin.Context, params ListIntakeSurveysParams)

ListIntakeSurveys returns a list of active surveys. GET /intake/surveys SEM@bd26290d65c881980433c4a4b599847bb68193d1: list active surveys available for intake with pagination (reads DB)

func (*Server) ListMyContentTokens

func (s *Server) ListMyContentTokens(c *gin.Context)

ListMyContentTokens implements ServerInterface.ListMyContentTokens. SEM@74d36522781dcfd28cfc8f5f32ed5cd9dd62a25e: list the current user's content provider OAuth tokens, or 404 if the feature is disabled

func (*Server) ListMyGroupMembers

func (s *Server) ListMyGroupMembers(c *gin.Context, internalUuid openapi_types.UUID, params ListMyGroupMembersParams)

ListMyGroupMembers handles GET /me/groups/{internal_uuid}/members Returns a paginated list of members for a group the authenticated user belongs to. Admin audit fields (added_by, notes) are redacted from the response. SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: list paginated members of a group the authenticated user belongs to, redacting admin audit fields (reads DB)

func (*Server) ListMyGroups

func (s *Server) ListMyGroups(c *gin.Context)

ListMyGroups handles GET /me/groups Returns the TMI-managed groups that the authenticated user belongs to. SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: list the built-in groups the authenticated user belongs to (reads DB)

func (*Server) ListMyIdentities

func (s *Server) ListMyIdentities(c *gin.Context)

ListMyIdentities handles GET /me/identities. Returns the primary identity from JWT claims and all linked identities for the authenticated user. SEM@fc8e2c83f6aaba09d10a2ed6f6e78a5075d278ba: list the primary and all linked OAuth identities for the authenticated user (reads DB)

func (*Server) ListProjectNotes

func (s *Server) ListProjectNotes(c *gin.Context, projectId openapi_types.UUID, params ListProjectNotesParams)

ListProjectNotes returns a paginated list of notes for a project. GET /projects/{project_id}/notes SEM@8a8c018ad8b1686dd4e43f736f31431743de5393: fetch a paginated list of project notes, filtering non-sharable notes for unprivileged users (reads DB)

func (*Server) ListProjects

func (s *Server) ListProjects(c *gin.Context, params ListProjectsParams)

ListProjects returns a paginated list of projects. Non-admins see only projects from teams they are members of. GET /projects SEM@8c7929da791c778ff88713684c47aa2a10911bba: list projects visible to the authenticated user with pagination and optional filters (reads DB)

func (*Server) ListSAMLUsers

func (s *Server) ListSAMLUsers(c *gin.Context, idp string)

ListSAMLUsers handles GET /saml/providers/{idp}/users SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: list SAML users from the caller's own identity provider with pagination and email filter (reads DB)

func (*Server) ListSystemAuditEntries

func (s *Server) ListSystemAuditEntries(c *gin.Context, params ListSystemAuditEntriesParams)

ListSystemAuditEntries handles GET /admin/audit/system (#398). SEM@29f63eb500c26288d0d3fe23737adf6fd94bdf9c: list or stream system audit entries with optional filters (reads DB)

func (*Server) ListSystemSettings

func (s *Server) ListSystemSettings(c *gin.Context)

ListSystemSettings returns all system settings (admin only) SEM@91dca85b52bdc03010be6f156c266607fa22df98: list all admin-visible system settings merged from config and database (reads DB)

func (*Server) ListTeamNotes

func (s *Server) ListTeamNotes(c *gin.Context, teamId openapi_types.UUID, params ListTeamNotesParams)

ListTeamNotes returns a paginated list of notes for a team. GET /teams/{team_id}/notes SEM@1ce00faf902914340ca54f7376e355c547163dda: list paginated team notes, filtering non-sharable notes for unprivileged users (reads DB)

func (*Server) ListTeams

func (s *Server) ListTeams(c *gin.Context, params ListTeamsParams)

ListTeams returns a paginated list of teams. Non-admins see only teams they are members of. GET /teams SEM@8c7929da791c778ff88713684c47aa2a10911bba: list teams visible to the caller with pagination and optional filters (reads DB)

func (*Server) ListThreatModels

func (s *Server) ListThreatModels(c *gin.Context, params ListThreatModelsParams)

ListThreatModels lists threat models SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route list threat models request to the threat model handler

func (*Server) ListTimmyChatMessages

func (s *Server) ListTimmyChatMessages(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId, params ListTimmyChatMessagesParams)

ListTimmyChatMessages lists message history for a session. SEM@773397b4fdff89166751fd8b5643ac59abce3367: list paginated message history for a Timmy chat session (reads DB)

func (*Server) ListTimmyChatSessions

func (s *Server) ListTimmyChatSessions(c *gin.Context, threatModelId ThreatModelId, params ListTimmyChatSessionsParams)

ListTimmyChatSessions lists the current user's sessions for a threat model. SEM@773397b4fdff89166751fd8b5643ac59abce3367: list the authenticated user's Timmy chat sessions for a threat model with pagination (reads DB)

func (*Server) ListTriageSurveyResponseTriageNotes

func (s *Server) ListTriageSurveyResponseTriageNotes(c *gin.Context, surveyResponseId SurveyResponseId, params ListTriageSurveyResponseTriageNotesParams)

ListTriageSurveyResponseTriageNotes lists triage notes for a survey response SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: list triage notes for a survey response via the triage stage (reads DB)

func (*Server) ListTriageSurveyResponses

func (s *Server) ListTriageSurveyResponses(c *gin.Context, params ListTriageSurveyResponsesParams)

ListTriageSurveyResponses returns survey responses for triage. GET /triage/survey_responses SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: list survey responses visible to the triage reviewer, filtered by per-row ACL (reads DB)

func (*Server) ListUsabilityFeedback

func (s *Server) ListUsabilityFeedback(c *gin.Context, params ListUsabilityFeedbackParams)

ListUsabilityFeedback lists usability feedback entries. SEM@cd6b617fb7aaaeb6491d79c87b09839f94b0fc3e: route list usability feedback requests to the feedback handler

func (*Server) ListUserAPIQuotas

func (s *Server) ListUserAPIQuotas(c *gin.Context, params ListUserAPIQuotasParams)

ListUserAPIQuotas retrieves all custom user API quotas (admin only) SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: list all custom per-user API rate quotas with pagination (reads DB)

func (*Server) ListWebhookDeliveries

func (s *Server) ListWebhookDeliveries(c *gin.Context, params ListWebhookDeliveriesParams)

ListWebhookDeliveries lists webhook deliveries (admin only) SEM@a870b93778753735e380098f91f8c25076bbb50a: list delivery records with pagination, optionally filtered by subscription (reads DB)

func (*Server) ListWebhookQuotas

func (s *Server) ListWebhookQuotas(c *gin.Context, params ListWebhookQuotasParams)

ListWebhookQuotas retrieves all custom webhook quotas (admin only) SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list all custom per-user webhook quotas with pagination (reads DB)

func (*Server) ListWebhookSubscriptions

func (s *Server) ListWebhookSubscriptions(c *gin.Context, params ListWebhookSubscriptionsParams)

ListWebhookSubscriptions lists webhook subscriptions (admin only) SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: list all webhook subscriptions with pagination, optionally filtered by threat model (reads DB)

func (*Server) LogoutCurrentUser

func (s *Server) LogoutCurrentUser(c *gin.Context)

LogoutCurrentUser logs out the current user (POST /me/logout) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route logout request to the auth service for the current user's session

func (*Server) MintPickerToken

func (s *Server) MintPickerToken(c *gin.Context, providerId string)

MintPickerToken implements ServerInterface.MintPickerToken by delegating to the attached *PickerTokenHandler. When the handler is not wired the picker subsystem is unavailable and a 404 ("feature_not_available") is returned via the shared contentOAuthUnavailable helper. SEM@7d1de945e5ad1f7bf6019e4c44631eb202e3ca54: route a picker token request to the provider-specific handler or return 503 if unconfigured

func (*Server) PatchAdminSurvey

func (s *Server) PatchAdminSurvey(c *gin.Context, surveyId SurveyId)

PatchAdminSurvey partially updates a survey. PATCH /admin/surveys/{survey_id} SEM@d79355f5eb3a2b2254ea6aa04da1cd81a55a4297: partially update a non-archived survey via JSON Patch and emit a webhook event (mutates shared state)

func (*Server) PatchIntakeSurveyResponse

func (s *Server) PatchIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId, _ PatchIntakeSurveyResponseParams)

PatchIntakeSurveyResponse partially updates a survey response. PATCH /intake/survey_responses/{response_id} Supports status transitions: draft->submitted, needs_revision->submitted SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: partially update a draft or needs-revision survey response and handle status transitions (mutates shared state)

func (*Server) PatchProject

func (s *Server) PatchProject(c *gin.Context, projectId openapi_types.UUID, _ PatchProjectParams)

PatchProject partially updates a project via JSON Patch. Requires team membership or admin. PATCH /projects/{project_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: partially update a project via JSON Patch with optimistic-locking enforcement (reads DB)

func (*Server) PatchProjectNote

func (s *Server) PatchProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)

PatchProjectNote partially updates a project note using JSON Patch. PATCH /projects/{project_id}/notes/{project_note_id} SEM@8a8c018ad8b1686dd4e43f736f31431743de5393: apply JSON Patch to a project note, blocking sharable field changes for unprivileged users (reads DB)

func (*Server) PatchTeam

func (s *Server) PatchTeam(c *gin.Context, teamId openapi_types.UUID, _ PatchTeamParams)

PatchTeam partially updates a team via JSON Patch. Requires team membership or admin. PATCH /teams/{team_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: partially update a team via JSON Patch, requiring membership or admin role with optimistic locking (writes DB)

func (*Server) PatchTeamNote

func (s *Server) PatchTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)

PatchTeamNote partially updates a team note using JSON Patch. PATCH /teams/{team_id}/notes/{team_note_id} SEM@1ce00faf902914340ca54f7376e355c547163dda: apply JSON Patch to a team note, enforcing sharable-field and visibility privilege rules (mutates shared state)

func (*Server) PatchThreatModel

func (s *Server) PatchThreatModel(c *gin.Context, threatModelId openapi_types.UUID, _ PatchThreatModelParams)

PatchThreatModel partially updates a threat model SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route partial update of a threat model to the threat model handler

func (*Server) PatchThreatModelAsset

func (s *Server) PatchThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID, _ PatchThreatModelAssetParams)

PatchThreatModelAsset patches an asset SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route patch-asset request to the asset handler

func (*Server) PatchThreatModelDiagram

func (s *Server) PatchThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID, _ PatchThreatModelDiagramParams)

PatchThreatModelDiagram partially updates a diagram SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route partial update of a diagram to the diagram handler with WebSocket hub

func (*Server) PatchThreatModelDocument

func (s *Server) PatchThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID, _ PatchThreatModelDocumentParams)

PatchThreatModelDocument patches a document SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route document patch to the document handler (reads DB)

func (*Server) PatchThreatModelNote

func (s *Server) PatchThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

PatchThreatModelNote patches a note SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route patch-note request for a threat model note to the note handler

func (*Server) PatchThreatModelRepository

func (s *Server) PatchThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

PatchThreatModelRepository patches a repository SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route partial repository patch request to the repository handler

func (*Server) PatchThreatModelThreat

func (s *Server) PatchThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID, _ PatchThreatModelThreatParams)

PatchThreatModelThreat patches a threat SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route single threat patch to the threat handler

func (*Server) PatchTriageSurveyResponse

func (s *Server) PatchTriageSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)

PatchTriageSurveyResponse partially updates a survey response for triage. PATCH /triage/survey_responses/{response_id} Supports status transitions: submitted->ready_for_review, submitted->needs_revision, ready_for_review->needs_revision SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: partially update a survey response status in triage via JSON Patch (mutates shared state)

func (*Server) ProcessSAMLLogout

func (s *Server) ProcessSAMLLogout(c *gin.Context, params ProcessSAMLLogoutParams)

ProcessSAMLLogout handles SAML single logout (GET) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route SAML single logout GET to the auth adapter for session termination

func (*Server) ProcessSAMLLogoutPost

func (s *Server) ProcessSAMLLogoutPost(c *gin.Context)

ProcessSAMLLogoutPost handles SAML single logout (POST) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route SAML single logout POST to the auth adapter for session termination

func (*Server) ProcessSAMLResponse

func (s *Server) ProcessSAMLResponse(c *gin.Context)

ProcessSAMLResponse handles SAML assertion consumer service SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route SAML assertion consumer service POST to the auth adapter for session establishment

func (*Server) ReencryptSystemSettings

func (s *Server) ReencryptSystemSettings(c *gin.Context)

ReencryptSystemSettings re-encrypts all system settings with the current encryption key (admin only) SEM@91dca85b52bdc03010be6f156c266607fa22df98: re-encrypt all stored system settings with the current encryption key (reads DB)

func (*Server) RefreshTimmySources

func (s *Server) RefreshTimmySources(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)

RefreshTimmySources re-scans sources for an active session, picking up any documents whose access_status has changed to "accessible". SEM@c309061af96f4db6e2d3a7da1d077b6a6f2f3c75: re-snapshot content sources for a session, updating the stored source snapshot (reads DB)

func (*Server) RefreshToken

func (s *Server) RefreshToken(c *gin.Context)

RefreshToken refreshes JWT token SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route token refresh request to the auth service

func (*Server) RegisterHandlers

func (s *Server) RegisterHandlers(r *gin.Engine)

RegisterHandlers registers custom API handlers with the router SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: register custom WebSocket and server-info routes outside the OpenAPI spec (mutates shared state)

func (*Server) RemoveGroupMember

func (s *Server) RemoveGroupMember(c *gin.Context, internalUuid openapi_types.UUID, memberUuid openapi_types.UUID, params RemoveGroupMemberParams)

RemoveGroupMember handles DELETE /admin/groups/{internal_uuid}/members/{member_uuid} SEM@0734f383e8c73aef4842c88dc88e90d0440f048a: delete a user or group membership from an admin group (mutates shared state)

func (*Server) RequestDocumentAccess

func (s *Server) RequestDocumentAccess(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)

RequestDocumentAccess re-sends the access request for a pending_access document. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: re-send an access request for a pending_access document via its content source

func (*Server) RestoreAsset

func (s *Server) RestoreAsset(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)

RestoreAsset restores a soft-deleted asset. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: restore a soft-deleted asset within a threat model

func (*Server) RestoreDiagram

func (s *Server) RestoreDiagram(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)

RestoreDiagram restores a soft-deleted diagram. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: restore a soft-deleted diagram within a threat model

func (*Server) RestoreDocument

func (s *Server) RestoreDocument(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)

RestoreDocument restores a soft-deleted document. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: restore a soft-deleted document within a threat model

func (*Server) RestoreNote

func (s *Server) RestoreNote(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)

RestoreNote restores a soft-deleted note. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: restore a soft-deleted note within a threat model

func (*Server) RestoreRepository

func (s *Server) RestoreRepository(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)

RestoreRepository restores a soft-deleted repository. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: restore a soft-deleted repository within a threat model

func (*Server) RestoreThreat

func (s *Server) RestoreThreat(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)

RestoreThreat restores a soft-deleted threat. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: restore a soft-deleted threat within a threat model

func (*Server) RestoreThreatModel

func (s *Server) RestoreThreatModel(c *gin.Context, threatModelId ThreatModelId)

RestoreThreatModel restores a soft-deleted threat model and all its children. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: restore a soft-deleted threat model and all its children

func (*Server) RevokeToken

func (s *Server) RevokeToken(c *gin.Context)

RevokeToken revokes a token per RFC 7009 (POST /oauth2/revoke) SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route token revocation request to the auth service per RFC 7009

func (*Server) RollbackToVersion

func (s *Server) RollbackToVersion(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

RollbackToVersion restores an entity to a previous version. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: delegate entity rollback to a prior audit version to the audit handler (mutates shared state)

func (*Server) SetAPIRateLimiter

func (s *Server) SetAPIRateLimiter(rateLimiter *APIRateLimiter)

SetAPIRateLimiter sets the API rate limiter SEM@922d880b24abd3da8955ba05fd9038f3ec43e512: register the API rate limiter on the server (mutates shared state)

func (*Server) SetAllowHTTPWebhooks

func (s *Server) SetAllowHTTPWebhooks(allow bool)

SetAllowHTTPWebhooks sets whether non-HTTPS webhook URLs are permitted SEM@baf9ecb79a22da23c9922e1df63b14cb07d01523: configure whether non-HTTPS webhook URLs are permitted (mutates shared state)

func (*Server) SetAuthFlowRateLimiter

func (s *Server) SetAuthFlowRateLimiter(rateLimiter *AuthFlowRateLimiter)

SetAuthFlowRateLimiter sets the auth flow rate limiter SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: register the auth-flow rate limiter on the server (mutates shared state)

func (*Server) SetAuthService

func (s *Server) SetAuthService(authService AuthService)

SetAuthService sets the auth service for delegating auth-related methods SEM@36c1f84217ecf3f5087ad65186cd974b9b4df275: register the auth service and derive user-deletion and ownership-transfer handlers from it (mutates shared state)

func (*Server) SetConfigProvider

func (s *Server) SetConfigProvider(provider ConfigProvider)

SetConfigProvider sets the config provider for settings migration SEM@600cc6a8afb0ea9ee0881874c4e9197f9d5288e7: register the config provider used for settings migration (mutates shared state)

func (*Server) SetContentOAuthHandlers

func (s *Server) SetContentOAuthHandlers(h *ContentOAuthHandlers)

SetContentOAuthHandlers attaches the content-OAuth handler bundle used to service the /me/content_tokens/*, /admin/users/{internal_uuid}/content_tokens/*, and /oauth2/content_callback endpoints. Called from cmd/server/main.go after the handler is constructed. Passing nil leaves the subsystem disabled — the delegation wrappers will return 503. SEM@74d36522781dcfd28cfc8f5f32ed5cd9dd62a25e: attach the content-OAuth handler bundle to the server, enabling token endpoints (mutates shared state)

func (*Server) SetContentPickerConfigs

func (s *Server) SetContentPickerConfigs(m map[string]map[string]string)

SetContentPickerConfigs attaches browser-safe picker bootstrap values that the /config handler advertises as ContentProvider.picker_config for the matching source id. Pass nil or an empty map to clear. SEM@f2e01937e40c91e87ac47a34d11870fde716d093: register browser-safe picker bootstrap values advertised by the /config handler (mutates shared state)

func (*Server) SetContentPipeline

func (s *Server) SetContentPipeline(p *ContentPipeline)

SetContentPipeline sets the content pipeline on the document handler for content source detection and access validation during document creation. It also stores the pipeline on the Server for use by other handlers. SEM@8b1d546fd508a1785e88877c4937ea02e5f125bc: register the content pipeline on the document handler and server for source detection (mutates shared state)

func (*Server) SetContentSourceHolder

func (s *Server) SetContentSourceHolder(h *ContentSourceHolder)

SetContentSourceHolder wires the runtime content-source holder. When set, getContentSourceBundle resolves (and lazily rebuilds) the registry + poller from the holder instead of the startup-wired contentSourceRegistry field. SEM@8429fbdd74c6f347eff47e11551b900e16a1dc06: register the runtime content-source holder for lazy registry and poller resolution (mutates shared state)

func (*Server) SetContentSourceRegistry

func (s *Server) SetContentSourceRegistry(r *ContentSourceRegistry)

SetContentSourceRegistry attaches the content source registry so the /config handler can advertise configured providers. Mirrors the SetDocumentContentOAuthRegistry pattern. SEM@55c4ae37a85b26aa93d5a93470c1e46bd53d5e19: register the content source registry for the /config handler to advertise providers (mutates shared state)

func (*Server) SetDLQProducer

func (s *Server) SetDLQProducer(p *DLQProducer)

SetDLQProducer injects the dead-letter producer for orderly shutdown. The producer must already have been started. SEM@a8006cf44cfcde106890cf0e06d51a99145807b1: register a pre-started dead-letter queue producer for orderly shutdown (mutates shared state)

func (*Server) SetDocumentAsyncExtraction

func (s *Server) SetDocumentAsyncExtraction(publisher *ExtractionPublisher, decider func(context.Context) bool)

SetDocumentAsyncExtraction wires the async extraction publisher and decider into the document handler. When both are non-nil and the decider returns true, CreateDocument returns 202 Accepted with a job_id instead of the usual 201. Pass nil publisher to disable the async path. SEM@d994c2f113f9e0997f83a0815018638cc94111f7: wire an async extraction publisher and decider into the document handler (mutates shared state)

func (*Server) SetDocumentContentOAuthRegistry

func (s *Server) SetDocumentContentOAuthRegistry(r *ContentOAuthProviderRegistry)

SetDocumentContentOAuthRegistry wires the content-OAuth provider registry onto the document handler so it can validate picker_registration payloads at attach time. Optional — when omitted, picker_registration is rejected with 422 (provider_not_registered). SEM@29c52159f07dd40fc350bf7cfe912f7a3a3def4b: register the content OAuth provider registry so the document handler can validate picker payloads (mutates shared state)

func (*Server) SetDocumentDiagnosticsDeps

func (s *Server) SetDocumentDiagnosticsDeps(tokens ContentTokenRepository, serviceAccountEmail, microsoftApplicationObjectID string)

SetDocumentDiagnosticsDeps wires the dependencies the document GET handler uses to assemble per-viewer access_diagnostics. All arguments are optional — when omitted, diagnostics still serialize but without linked-provider, service-account, or Microsoft application context. microsoftApplicationObjectID is the TMI Entra app's object id used to build the share_with_application remediation; pass "" when not configured (Task 12 will populate it from config). SEM@fe4cf07a3a2b954860a8df90ba211cb0919d71de: wire per-viewer access diagnostics dependencies into the document handler (mutates shared state)

func (*Server) SetExtractionJobStore

func (s *Server) SetExtractionJobStore(store *ExtractionJobStore)

SetExtractionJobStore injects the extraction_jobs repository. SEM@a0abba4563581c2c2d54d1df58750d51e83e3e43: register the extraction job repository on the server (mutates shared state)

func (*Server) SetExtractionNATS

func (s *Server) SetExtractionNATS(conn *worker.Conn)

SetExtractionNATS injects the monolith's NATS connection used to publish extraction jobs and run the result-consumer. A nil conn disables the async path. SEM@a0abba4563581c2c2d54d1df58750d51e83e3e43: register the NATS connection used to publish extraction jobs (mutates shared state)

func (*Server) SetIPRateLimiter

func (s *Server) SetIPRateLimiter(rateLimiter *IPRateLimiter)

SetIPRateLimiter sets the IP rate limiter SEM@f5e41f0bdd3e5075ef62036d28d486bd0ef0286b: register the IP rate limiter on the server (mutates shared state)

func (*Server) SetIdentityLinkAuditor

func (s *Server) SetIdentityLinkAuditor(a *auth.IdentityLinkAuditor)

SetIdentityLinkAuditor injects the identity-link audit writer used to record unlink events from /me/identities/{id} (#383). Nil disables auditing (fail-open). SEM@d89a562535e2240eeb7f556a3f619d28fe9c5613: register the identity-link auditor to record unlink events (mutates shared state)

func (*Server) SetLinkedIdentityStore

func (s *Server) SetLinkedIdentityStore(store auth.LinkedIdentityStore)

SetLinkedIdentityStore injects the linked-identity store used by the /me/identities/* endpoints (#383). A nil store leaves those endpoints returning 500. SEM@d89a562535e2240eeb7f556a3f619d28fe9c5613: register the linked-identity store for the /me/identities endpoints (mutates shared state)

func (*Server) SetMicrosoftPickerGrantHandler

func (s *Server) SetMicrosoftPickerGrantHandler(h microsoftPickerGrantHandlerInterface)

SetMicrosoftPickerGrantHandler attaches the Microsoft picker-grant handler. When unset, GrantMicrosoftFilePermission returns 503. SEM@381a47a882e241c075287ba07805b46c737fcc0e: register the Microsoft file picker grant handler on the server (mutates shared state)

func (*Server) SetPickerTokenHandler

func (s *Server) SetPickerTokenHandler(h *PickerTokenHandler)

SetPickerTokenHandler attaches the picker-token handler that services POST /me/picker_tokens/{provider_id}. Called from cmd/server/main.go after the handler is constructed. Passing nil leaves the subsystem disabled — MintPickerToken will return 503. SEM@5fe247aef5f2eedfc42d4adf9058c24de12eb56e: attach the picker-token handler to the server, enabling picker mint endpoints (mutates shared state)

func (*Server) SetProviderRegistry

func (s *Server) SetProviderRegistry(registry auth.ProviderRegistry)

SetProviderRegistry sets the provider registry for cache invalidation from settings handlers. SEM@452dd7163303f0bb5c5b2acf7c3960183b22bb7b: register the auth provider registry for cache invalidation from settings handlers (mutates shared state)

func (*Server) SetRateLimitingDisabled

func (s *Server) SetRateLimitingDisabled(disabled bool)

SetRateLimitingDisabled disables all rate limiting (dev/test mode only) SEM@c70d49ed2d6089c24d05f8bc287ba5711c73abde: disable or enable all rate limiting for dev/test mode (mutates shared state)

func (*Server) SetResultConsumer

func (s *Server) SetResultConsumer(rc *ResultConsumer)

SetResultConsumer injects the result-consumer goroutine. The consumer must already have been started before calling this; the server only uses it for orderly shutdown via StopResultConsumer. SEM@28a744a1501431680450f9ab9c4d57cdf9bebd2d: register a pre-started result consumer for orderly shutdown (mutates shared state)

func (*Server) SetSettingsService

func (s *Server) SetSettingsService(settingsService SettingsServiceInterface)

SetSettingsService sets the settings service for database-stored configuration SEM@c937c5d55bdeac26bea04acd0677ed742a8d9eab: register the database-backed settings service on the server (mutates shared state)

func (*Server) SetSystemAuditRepo

func (s *Server) SetSystemAuditRepo(repo SystemAuditRepository)

SetSystemAuditRepo injects the system audit repository used by the admin audit query endpoints (#398). Pass the same instance used by NewAdminAuditMiddleware to avoid duplicate DB handles. SEM@7bac1ed632ff8929eff543daec4372c53d51283a: register the system audit repository for admin audit query endpoints (mutates shared state)

func (*Server) SetTicketStore

func (s *Server) SetTicketStore(ticketStore TicketStore)

SetTicketStore sets the ticket store for WebSocket authentication SEM@e9c06824054dff110125e003301c169f002e9392: register the ticket store used for WebSocket authentication (mutates shared state)

func (*Server) SetTimmyCore

func (s *Server) SetTimmyCore(core *TimmyCore)

SetTimmyCore wires the runtime Timmy core. When set, getTimmyRuntime resolves the session manager from it (DB-backed, lazy rebuild) instead of the startup-injected timmySessionManager. SEM@19300f7e812ceaf4be6cadb0fe31123e70ddb707: register the Timmy core for DB-backed lazy session resolution (mutates shared state)

func (*Server) SetTimmySessionManager

func (s *Server) SetTimmySessionManager(manager *TimmySessionManager)

SetTimmySessionManager sets the Timmy session manager for AI assistant endpoints SEM@773397b4fdff89166751fd8b5643ac59abce3367: register the Timmy AI session manager on the server (mutates shared state)

func (*Server) SetTrustedProxiesConfigured

func (s *Server) SetTrustedProxiesConfigured(configured bool)

SetTrustedProxiesConfigured marks whether trusted proxies have been configured SEM@7cb03e52faae718087b1ee56a6023e9f7bddaea0: mark whether trusted proxies have been configured on the server (mutates shared state)

func (*Server) SetURIValidators

func (s *Server) SetURIValidators(issueURI, documentURI, repositoryURI *URIValidator)

SetURIValidators sets the URI validators for SSRF protection. It also propagates validators to the sub-resource handlers. SEM@5eacb6f5fd0d2a1861dafb4d1fc5a18f97ee8e40: register SSRF-protection URI validators and propagate them to sub-resource handlers (mutates shared state)

func (*Server) SetVectorManager

func (s *Server) SetVectorManager(manager *VectorIndexManager)

SetVectorManager sets the vector index manager for Timmy AI assistant SEM@773397b4fdff89166751fd8b5643ac59abce3367: register the vector index manager for the Timmy AI assistant (mutates shared state)

func (*Server) SetWebhookRateLimiter

func (s *Server) SetWebhookRateLimiter(rateLimiter *WebhookRateLimiter)

SetWebhookRateLimiter sets the webhook rate limiter SEM@922d880b24abd3da8955ba05fd9038f3ec43e512: register the webhook rate limiter on the server (mutates shared state)

func (*Server) StartAuditPruner

func (s *Server) StartAuditPruner()

StartAuditPruner starts the background audit pruning goroutine. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: start the background audit trail pruning goroutine (mutates shared state)

func (s *Server) StartIdentityLink(c *gin.Context, params StartIdentityLinkParams)

StartIdentityLink handles POST /me/identities/link/start (#383). Delegates to the auth.Handlers.StartIdentityLink method via the AuthServiceAdapter. SEM@d89a562535e2240eeb7f556a3f619d28fe9c5613: route identity link initiation request to the auth handler

func (*Server) StartWebSocketHub

func (s *Server) StartWebSocketHub(ctx context.Context)

StartWebSocketHub starts the WebSocket hub cleanup timer SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: initialize and start the WebSocket hub cleanup timer on server startup (mutates shared state)

func (*Server) StepUpAuthenticate

func (s *Server) StepUpAuthenticate(c *gin.Context, params StepUpAuthenticateParams)

StepUpAuthenticate handles GET /oauth2/step_up — fresh-prompt step-up re-authentication. Delegates to the auth service. #397. SEM@3b3ce007aac967644943c133123d85a9a1525644: route step-up re-authentication request to the auth service

func (*Server) StopAuditPruner

func (s *Server) StopAuditPruner()

StopAuditPruner stops the background audit pruning goroutine. SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: stop the background audit trail pruning goroutine (mutates shared state)

func (*Server) StopDLQProducer

func (s *Server) StopDLQProducer()

StopDLQProducer gracefully stops the DLQ producer if one is wired. Safe to call when none is set (no-op). Call before CloseExtractionNATS. SEM@a8006cf44cfcde106890cf0e06d51a99145807b1: gracefully stop the DLQ producer if one is wired; no-op otherwise (mutates shared state)

func (*Server) StopResultConsumer

func (s *Server) StopResultConsumer()

StopResultConsumer gracefully stops the result-consumer if one is wired. Safe to call when no consumer is set (no-op). Must be called before CloseExtractionNATS so the consumer can finish in-flight acks. SEM@28a744a1501431680450f9ab9c4d57cdf9bebd2d: gracefully stop the result consumer if one is wired; no-op otherwise (mutates shared state)

func (*Server) TestWebhookSubscription

func (s *Server) TestWebhookSubscription(c *gin.Context, webhookId openapi_types.UUID)

TestWebhookSubscription sends a test event to the webhook (admin only) SEM@a870b93778753735e380098f91f8c25076bbb50a: enqueue a test delivery for a webhook subscription and return its delivery ID (reads DB)

func (*Server) TransferAdminUserOwnership

func (s *Server) TransferAdminUserOwnership(c *gin.Context, internalUuid InternalUuidPathParam)

TransferAdminUserOwnership handles POST /admin/users/{internal_uuid}/transfer SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin ownership transfer for a target user to the transfer handler

func (*Server) TransferCurrentUserOwnership

func (s *Server) TransferCurrentUserOwnership(c *gin.Context)

TransferCurrentUserOwnership handles POST /me/transfer SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route ownership transfer request for the current user to the transfer handler

func (*Server) UpdateAddonInvocationQuota

func (s *Server) UpdateAddonInvocationQuota(c *gin.Context, userId openapi_types.UUID)

UpdateAddonInvocationQuota creates or updates the addon invocation quota for a specific user (admin only) SEM@9745b416c50726fc3ca5d4637364ba55d6ba0699: upsert the addon invocation quota for a user, returning 201 on creation (mutates shared state)

func (*Server) UpdateAdminGroup

func (s *Server) UpdateAdminGroup(c *gin.Context, internalUuid openapi_types.UUID)

UpdateAdminGroup handles PATCH /admin/groups/{internal_uuid} SEM@70b575a9e0ec7ae8f154644ac025dce6e14acb51: update a group's name or description and emit an audit log entry (mutates shared state)

func (*Server) UpdateAdminSurvey

func (s *Server) UpdateAdminSurvey(c *gin.Context, surveyId SurveyId)

UpdateAdminSurvey fully updates a survey. PUT /admin/surveys/{survey_id} SEM@00add3d4f7dc1c0a9cc072d7e6ca32ace4d03641: fully replace a non-archived survey and emit a webhook event (mutates shared state)

func (*Server) UpdateAdminSurveyMetadataByKey

func (s *Server) UpdateAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)

UpdateAdminSurveyMetadataByKey updates survey metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route admin request to update a survey metadata entry by key (mutates shared state)

func (*Server) UpdateAdminUser

func (s *Server) UpdateAdminUser(c *gin.Context, internalUuid openapi_types.UUID)

UpdateAdminUser handles PATCH /admin/users/{internal_uuid} SEM@6a6c15749391c2817c30c64c8b54f8e0a4082a91: update a user's admin-managed fields by internal UUID (mutates shared state)

func (*Server) UpdateCurrentUserPreferences

func (s *Server) UpdateCurrentUserPreferences(c *gin.Context)

UpdateCurrentUserPreferences handles PUT /me/preferences SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: upsert preferences for the authenticated user via full replacement (mutates shared state)

func (*Server) UpdateDiagramMetadataByKey

func (s *Server) UpdateDiagramMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID, key string)

UpdateDiagramMetadataByKey updates diagram metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: update a diagram metadata entry by key (mutates shared state)

func (*Server) UpdateDocumentMetadataByKey

func (s *Server) UpdateDocumentMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID, key string)

UpdateDocumentMetadataByKey updates document metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: update a metadata entry for a document by key (reads DB)

func (*Server) UpdateIntakeSurveyResponse

func (s *Server) UpdateIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId, _ UpdateIntakeSurveyResponseParams)

UpdateIntakeSurveyResponse fully updates a survey response. PUT /intake/survey_responses/{response_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: fully replace a draft or needs-revision survey response with optimistic locking (mutates shared state)

func (*Server) UpdateIntakeSurveyResponseMetadataByKey

func (s *Server) UpdateIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

UpdateIntakeSurveyResponseMetadataByKey updates intake survey response metadata by key SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize writer access then update intake survey response metadata by key (mutates shared state)

func (*Server) UpdateNoteMetadataByKey

func (s *Server) UpdateNoteMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID, key string)

UpdateNoteMetadataByKey updates note metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route update-metadata-by-key request for a note to the metadata handler

func (*Server) UpdateProject

func (s *Server) UpdateProject(c *gin.Context, projectId openapi_types.UUID, _ UpdateProjectParams)

UpdateProject fully updates a project. Requires team membership or admin. PUT /projects/{project_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: fully replace a project's fields with optimistic-locking enforcement (reads DB)

func (*Server) UpdateProjectMetadata

func (s *Server) UpdateProjectMetadata(c *gin.Context, projectId openapi_types.UUID, key string)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: update a metadata entry by key for a project, delegating to the generic metadata handler (reads DB)

func (*Server) UpdateProjectNote

func (s *Server) UpdateProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)

UpdateProjectNote replaces a project note. PUT /projects/{project_id}/notes/{project_note_id} SEM@8a8c018ad8b1686dd4e43f736f31431743de5393: replace a project note, enforcing sharable field and non-sharable visibility restrictions by role (reads DB)

func (*Server) UpdateRepositoryMetadataByKey

func (s *Server) UpdateRepositoryMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID, key string)

UpdateRepositoryMetadataByKey updates repository metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: update a repository metadata entry by key

func (*Server) UpdateSystemSetting

func (s *Server) UpdateSystemSetting(c *gin.Context, key string)

UpdateSystemSetting creates or updates a system setting (admin only) SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: create or update a database system setting, validating provider enables and invalidating cache (reads DB)

func (*Server) UpdateTeam

func (s *Server) UpdateTeam(c *gin.Context, teamId openapi_types.UUID, _ UpdateTeamParams)

UpdateTeam fully updates a team. Requires team membership or admin. PUT /teams/{team_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: fully replace a team's fields, requiring membership or admin role with optimistic locking (writes DB)

func (*Server) UpdateTeamMetadata

func (s *Server) UpdateTeamMetadata(c *gin.Context, teamId openapi_types.UUID, key string)

SEM@8c7929da791c778ff88713684c47aa2a10911bba: update a single metadata entry for a team via the generic metadata handler

func (*Server) UpdateTeamNote

func (s *Server) UpdateTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)

UpdateTeamNote replaces a team note. PUT /teams/{team_id}/notes/{team_note_id} SEM@1ce00faf902914340ca54f7376e355c547163dda: replace a team note, enforcing sharable-field and visibility privilege rules (mutates shared state)

func (*Server) UpdateThreatMetadataByKey

func (s *Server) UpdateThreatMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID, key string)

UpdateThreatMetadataByKey updates threat metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: replace a single threat metadata entry by key

func (*Server) UpdateThreatModel

func (s *Server) UpdateThreatModel(c *gin.Context, threatModelId openapi_types.UUID, _ UpdateThreatModelParams)

UpdateThreatModel updates a threat model SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route full update of a threat model to the threat model handler

func (*Server) UpdateThreatModelAsset

func (s *Server) UpdateThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID, _ UpdateThreatModelAssetParams)

UpdateThreatModelAsset updates an asset SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route update-asset request to the asset handler for a given threat model and asset

func (*Server) UpdateThreatModelAssetMetadata

func (s *Server) UpdateThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID, key string)

UpdateThreatModelAssetMetadata updates asset metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route update-asset-metadata-by-key request to the metadata handler

func (*Server) UpdateThreatModelDiagram

func (s *Server) UpdateThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID, _ UpdateThreatModelDiagramParams)

UpdateThreatModelDiagram updates a diagram SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route full update of a diagram to the diagram handler with WebSocket hub

func (*Server) UpdateThreatModelDocument

func (s *Server) UpdateThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID, _ UpdateThreatModelDocumentParams)

UpdateThreatModelDocument updates a document SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route document update to the document handler, scoped to a threat model (reads DB)

func (*Server) UpdateThreatModelMetadataByKey

func (s *Server) UpdateThreatModelMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, key string)

UpdateThreatModelMetadataByKey updates threat model metadata by key SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: update a threat model metadata entry by key (mutates shared state)

func (*Server) UpdateThreatModelNote

func (s *Server) UpdateThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

UpdateThreatModelNote updates a note SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route update-note request for a threat model note to the note handler

func (*Server) UpdateThreatModelRepository

func (s *Server) UpdateThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

UpdateThreatModelRepository updates a repository SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: route full repository update request to the repository handler

func (*Server) UpdateThreatModelThreat

func (s *Server) UpdateThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID, _ UpdateThreatModelThreatParams)

UpdateThreatModelThreat updates a threat SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: route single threat replacement to the threat handler

func (*Server) UpdateUserAPIQuota

func (s *Server) UpdateUserAPIQuota(c *gin.Context, userId openapi_types.UUID)

UpdateUserAPIQuota creates or updates the API quota for a specific user (admin only) SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: upsert the API rate quota for a user and invalidate its cache entry (mutates shared state)

func (*Server) UpdateWebhookDeliveryStatus

func (s *Server) UpdateWebhookDeliveryStatus(c *gin.Context, deliveryId DeliveryId, params UpdateWebhookDeliveryStatusParams)

UpdateWebhookDeliveryStatus updates delivery status (HMAC authenticated) SEM@ca61a567c4babc9270ee913396aaa4fb530505a3: update the delivery status of a webhook delivery record (reads DB)

func (*Server) UpdateWebhookQuota

func (s *Server) UpdateWebhookQuota(c *gin.Context, userId openapi_types.UUID)

UpdateWebhookQuota creates or updates the webhook quota for a specific user (admin only) SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: upsert the webhook quota for a user and invalidate its cache entry (mutates shared state)

func (*Server) UseAsyncExtraction

func (s *Server) UseAsyncExtraction(ctx context.Context) bool

UseAsyncExtraction reports whether extraction should route through the worker pipeline: the setting is on AND a NATS connection is available. When the setting is on but NATS is absent, it logs and returns false (fail-safe to inline) so extractions are never silently dropped. SEM@d994c2f113f9e0997f83a0815018638cc94111f7: report whether async extraction is enabled and a NATS connection is available; fails safe to inline (reads DB)

type ServerInfo

type ServerInfo struct {
	// Whether TLS is enabled
	TLSEnabled bool `json:"tls_enabled"`
	// Subject name for TLS certificate
	TLSSubjectName string `json:"tls_subject_name,omitempty"`
	// WebSocket base URL
	WebSocketBaseURL string `json:"websocket_base_url"`
}

ServerInfo provides information about the server configuration SEM@28792aa3991e394010e49c040d3db2d5f14a6eff: struct carrying TLS and WebSocket base URL configuration for clients (pure)

type ServerInterface

type ServerInterface interface {
	// Get API information
	// (GET /)
	GetApiInfo(c *gin.Context)
	// JSON Web Key Set
	// (GET /.well-known/jwks.json)
	GetJWKS(c *gin.Context)
	// OAuth 2.0 Authorization Server Metadata
	// (GET /.well-known/oauth-authorization-server)
	GetOAuthAuthorizationServerMetadata(c *gin.Context)
	// OAuth 2.0 Protected Resource Metadata
	// (GET /.well-known/oauth-protected-resource)
	GetOAuthProtectedResourceMetadata(c *gin.Context)
	// OpenID Connect Discovery Configuration
	// (GET /.well-known/openid-configuration)
	GetOpenIDConfiguration(c *gin.Context)
	// List add-ons
	// (GET /addons)
	ListAddons(c *gin.Context, params ListAddonsParams)
	// Create add-on
	// (POST /addons)
	CreateAddon(c *gin.Context)
	// Delete add-on
	// (DELETE /addons/{id})
	DeleteAddon(c *gin.Context, id GenericId)
	// Get add-on
	// (GET /addons/{id})
	GetAddon(c *gin.Context, id GenericId)
	// Invoke add-on
	// (POST /addons/{id}/invoke)
	InvokeAddon(c *gin.Context, id GenericId)
	// List system audit entries
	// (GET /admin/audit/system)
	ListSystemAuditEntries(c *gin.Context, params ListSystemAuditEntriesParams)
	// Get a system audit entry
	// (GET /admin/audit/system/{entry_id})
	GetSystemAuditEntry(c *gin.Context, entryId openapi_types.UUID)
	// List threat-model audit entries across all threat models
	// (GET /admin/audit/threat_models)
	ListAdminThreatModelAuditEntries(c *gin.Context, params ListAdminThreatModelAuditEntriesParams)
	// Get a threat-model audit entry by id (admin)
	// (GET /admin/audit/threat_models/{entry_id})
	GetAdminThreatModelAuditEntry(c *gin.Context, entryId openapi_types.UUID)
	// List groups
	// (GET /admin/groups)
	ListAdminGroups(c *gin.Context, params ListAdminGroupsParams)
	// Create TMI built-in group
	// (POST /admin/groups)
	CreateAdminGroup(c *gin.Context)
	// Delete group
	// (DELETE /admin/groups/{internal_uuid})
	DeleteAdminGroup(c *gin.Context, internalUuid InternalUuidPathParam)
	// Get group details
	// (GET /admin/groups/{internal_uuid})
	GetAdminGroup(c *gin.Context, internalUuid InternalUuidPathParam)
	// Update group metadata
	// (PATCH /admin/groups/{internal_uuid})
	UpdateAdminGroup(c *gin.Context, internalUuid InternalUuidPathParam)
	// List group members
	// (GET /admin/groups/{internal_uuid}/members)
	ListGroupMembers(c *gin.Context, internalUuid InternalUuidPathParam, params ListGroupMembersParams)
	// Add member to group
	// (POST /admin/groups/{internal_uuid}/members)
	AddGroupMember(c *gin.Context, internalUuid InternalUuidPathParam)
	// Remove member from group
	// (DELETE /admin/groups/{internal_uuid}/members/{member_uuid})
	RemoveGroupMember(c *gin.Context, internalUuid InternalUuidPathParam, memberUuid MemberUuidPathParam, params RemoveGroupMemberParams)
	// List all addon invocation quotas
	// (GET /admin/quotas/addons)
	ListAddonInvocationQuotas(c *gin.Context, params ListAddonInvocationQuotasParams)
	// Delete addon invocation quota
	// (DELETE /admin/quotas/addons/{user_id})
	DeleteAddonInvocationQuota(c *gin.Context, userId UserIdPathParam)
	// Get addon invocation quota
	// (GET /admin/quotas/addons/{user_id})
	GetAddonInvocationQuota(c *gin.Context, userId UserIdPathParam)
	// Update addon invocation quota
	// (PUT /admin/quotas/addons/{user_id})
	UpdateAddonInvocationQuota(c *gin.Context, userId UserIdPathParam)
	// List all user API quotas
	// (GET /admin/quotas/users)
	ListUserAPIQuotas(c *gin.Context, params ListUserAPIQuotasParams)
	// Delete user API quota
	// (DELETE /admin/quotas/users/{user_id})
	DeleteUserAPIQuota(c *gin.Context, userId UserIdPathParam)
	// Get user API quota
	// (GET /admin/quotas/users/{user_id})
	GetUserAPIQuota(c *gin.Context, userId UserIdPathParam)
	// Update user API quota
	// (PUT /admin/quotas/users/{user_id})
	UpdateUserAPIQuota(c *gin.Context, userId UserIdPathParam)
	// List all webhook quotas
	// (GET /admin/quotas/webhooks)
	ListWebhookQuotas(c *gin.Context, params ListWebhookQuotasParams)
	// Delete webhook quota
	// (DELETE /admin/quotas/webhooks/{user_id})
	DeleteWebhookQuota(c *gin.Context, userId UserIdPathParam)
	// Get webhook quota
	// (GET /admin/quotas/webhooks/{user_id})
	GetWebhookQuota(c *gin.Context, userId UserIdPathParam)
	// Update webhook quota
	// (PUT /admin/quotas/webhooks/{user_id})
	UpdateWebhookQuota(c *gin.Context, userId UserIdPathParam)
	// List system settings
	// (GET /admin/settings)
	ListSystemSettings(c *gin.Context)
	// Re-encrypt all system settings
	// (POST /admin/settings/reencrypt)
	ReencryptSystemSettings(c *gin.Context)
	// Delete system setting
	// (DELETE /admin/settings/{key})
	DeleteSystemSetting(c *gin.Context, key string)
	// Get system setting
	// (GET /admin/settings/{key})
	GetSystemSetting(c *gin.Context, key string)
	// Update system setting
	// (PUT /admin/settings/{key})
	UpdateSystemSetting(c *gin.Context, key string)
	// List surveys
	// (GET /admin/surveys)
	ListAdminSurveys(c *gin.Context, params ListAdminSurveysParams)
	// Create a survey
	// (POST /admin/surveys)
	CreateAdminSurvey(c *gin.Context)
	// Delete a survey
	// (DELETE /admin/surveys/{survey_id})
	DeleteAdminSurvey(c *gin.Context, surveyId SurveyId, params DeleteAdminSurveyParams)
	// Get a survey
	// (GET /admin/surveys/{survey_id})
	GetAdminSurvey(c *gin.Context, surveyId SurveyId)
	// Partially update a survey
	// (PATCH /admin/surveys/{survey_id})
	PatchAdminSurvey(c *gin.Context, surveyId SurveyId)
	// Update a survey
	// (PUT /admin/surveys/{survey_id})
	UpdateAdminSurvey(c *gin.Context, surveyId SurveyId)
	// Get all metadata for a survey
	// (GET /admin/surveys/{survey_id}/metadata)
	GetAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)
	// Add metadata to a survey
	// (POST /admin/surveys/{survey_id}/metadata)
	CreateAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)
	// Bulk upsert metadata for a survey
	// (PATCH /admin/surveys/{survey_id}/metadata/bulk)
	BulkUpsertAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)
	// Bulk create metadata for a survey
	// (POST /admin/surveys/{survey_id}/metadata/bulk)
	BulkCreateAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)
	// Bulk replace metadata for a survey
	// (PUT /admin/surveys/{survey_id}/metadata/bulk)
	BulkReplaceAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)
	// Delete metadata by key for a survey
	// (DELETE /admin/surveys/{survey_id}/metadata/{key})
	DeleteAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)
	// Get metadata by key for a survey
	// (GET /admin/surveys/{survey_id}/metadata/{key})
	GetAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)
	// Update metadata by key for a survey
	// (PUT /admin/surveys/{survey_id}/metadata/{key})
	UpdateAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)
	// Get Timmy system status
	// (GET /admin/timmy/status)
	GetTimmyStatus(c *gin.Context)
	// Get Timmy usage statistics
	// (GET /admin/timmy/usage)
	GetTimmyUsage(c *gin.Context, params GetTimmyUsageParams)
	// List users
	// (GET /admin/users)
	ListAdminUsers(c *gin.Context, params ListAdminUsersParams)
	// Create an automation (service) account
	// (POST /admin/users/automation)
	CreateAutomationAccount(c *gin.Context)
	// Delete user
	// (DELETE /admin/users/{internal_uuid})
	DeleteAdminUser(c *gin.Context, internalUuid InternalUuidPathParam)
	// Get user details
	// (GET /admin/users/{internal_uuid})
	GetAdminUser(c *gin.Context, internalUuid InternalUuidPathParam)
	// Update user metadata
	// (PATCH /admin/users/{internal_uuid})
	UpdateAdminUser(c *gin.Context, internalUuid InternalUuidPathParam)
	// List client credentials for an automation user
	// (GET /admin/users/{internal_uuid}/client_credentials)
	ListAdminUserClientCredentials(c *gin.Context, internalUuid InternalUuidPathParam, params ListAdminUserClientCredentialsParams)
	// Create a client credential for an automation user
	// (POST /admin/users/{internal_uuid}/client_credentials)
	CreateAdminUserClientCredential(c *gin.Context, internalUuid InternalUuidPathParam)
	// Delete a client credential for an automation user
	// (DELETE /admin/users/{internal_uuid}/client_credentials/{credential_id})
	DeleteAdminUserClientCredential(c *gin.Context, internalUuid InternalUuidPathParam, credentialId CredentialIdPathParam)
	// List a user's linked content provider tokens (admin)
	// (GET /admin/users/{internal_uuid}/content_tokens)
	AdminListUserContentTokens(c *gin.Context, internalUuid openapi_types.UUID)
	// Revoke a user's linked content provider token (admin)
	// (DELETE /admin/users/{internal_uuid}/content_tokens/{provider_id})
	AdminDeleteUserContentToken(c *gin.Context, internalUuid openapi_types.UUID, providerId string)
	// Transfer user ownership to another user
	// (POST /admin/users/{internal_uuid}/transfer)
	TransferAdminUserOwnership(c *gin.Context, internalUuid InternalUuidPathParam)
	// List webhook deliveries
	// (GET /admin/webhooks/deliveries)
	ListWebhookDeliveries(c *gin.Context, params ListWebhookDeliveriesParams)
	// Get webhook delivery
	// (GET /admin/webhooks/deliveries/{delivery_id})
	GetWebhookDelivery(c *gin.Context, deliveryId DeliveryId)
	// List webhook subscriptions
	// (GET /admin/webhooks/subscriptions)
	ListWebhookSubscriptions(c *gin.Context, params ListWebhookSubscriptionsParams)
	// Create webhook subscription
	// (POST /admin/webhooks/subscriptions)
	CreateWebhookSubscription(c *gin.Context)
	// Delete webhook subscription
	// (DELETE /admin/webhooks/subscriptions/{webhook_id})
	DeleteWebhookSubscription(c *gin.Context, webhookId WebhookId)
	// Get webhook subscription
	// (GET /admin/webhooks/subscriptions/{webhook_id})
	GetWebhookSubscription(c *gin.Context, webhookId WebhookId)
	// Test webhook subscription
	// (POST /admin/webhooks/subscriptions/{webhook_id}/test)
	TestWebhookSubscription(c *gin.Context, webhookId WebhookId)
	// Delete embeddings
	// (DELETE /automation/embeddings/{threat_model_id})
	DeleteEmbeddings(c *gin.Context, threatModelId ThreatModelId, params DeleteEmbeddingsParams)
	// Ingest pre-computed embeddings
	// (POST /automation/embeddings/{threat_model_id})
	IngestEmbeddings(c *gin.Context, threatModelId ThreatModelId)
	// Get embedding provider configuration
	// (GET /automation/embeddings/{threat_model_id}/config)
	GetEmbeddingConfig(c *gin.Context, threatModelId ThreatModelId)
	// Get client configuration
	// (GET /config)
	GetClientConfig(c *gin.Context)
	// List user's survey responses
	// (GET /intake/survey_responses)
	ListIntakeSurveyResponses(c *gin.Context, params ListIntakeSurveyResponsesParams)
	// Create survey response
	// (POST /intake/survey_responses)
	CreateIntakeSurveyResponse(c *gin.Context)
	// Delete survey response
	// (DELETE /intake/survey_responses/{survey_response_id})
	DeleteIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)
	// Get survey response
	// (GET /intake/survey_responses/{survey_response_id})
	GetIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)
	// Partial update survey response
	// (PATCH /intake/survey_responses/{survey_response_id})
	PatchIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId, params PatchIntakeSurveyResponseParams)
	// Update survey response
	// (PUT /intake/survey_responses/{survey_response_id})
	UpdateIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId, params UpdateIntakeSurveyResponseParams)
	// Get all metadata for a survey response
	// (GET /intake/survey_responses/{survey_response_id}/metadata)
	GetIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)
	// Add metadata to a survey response
	// (POST /intake/survey_responses/{survey_response_id}/metadata)
	CreateIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)
	// Bulk upsert metadata for a survey response
	// (PATCH /intake/survey_responses/{survey_response_id}/metadata/bulk)
	BulkUpsertIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)
	// Bulk create metadata for a survey response
	// (POST /intake/survey_responses/{survey_response_id}/metadata/bulk)
	BulkCreateIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)
	// Bulk replace metadata for a survey response
	// (PUT /intake/survey_responses/{survey_response_id}/metadata/bulk)
	BulkReplaceIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)
	// Delete metadata by key for a survey response
	// (DELETE /intake/survey_responses/{survey_response_id}/metadata/{key})
	DeleteIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)
	// Get metadata by key for a survey response
	// (GET /intake/survey_responses/{survey_response_id}/metadata/{key})
	GetIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)
	// Update metadata by key for a survey response
	// (PUT /intake/survey_responses/{survey_response_id}/metadata/{key})
	UpdateIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)
	// List triage notes for a survey response
	// (GET /intake/survey_responses/{survey_response_id}/triage_notes)
	ListIntakeSurveyResponseTriageNotes(c *gin.Context, surveyResponseId SurveyResponseId, params ListIntakeSurveyResponseTriageNotesParams)
	// Get a specific triage note
	// (GET /intake/survey_responses/{survey_response_id}/triage_notes/{triage_note_id})
	GetIntakeSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId, triageNoteId TriageNoteId)
	// List available surveys
	// (GET /intake/surveys)
	ListIntakeSurveys(c *gin.Context, params ListIntakeSurveysParams)
	// Get an available survey
	// (GET /intake/surveys/{survey_id})
	GetIntakeSurvey(c *gin.Context, surveyId SurveyId)
	// Delete authenticated user account and all data
	// (DELETE /me)
	DeleteUserAccount(c *gin.Context, params DeleteUserAccountParams)
	// Get current user profile
	// (GET /me)
	GetCurrentUserProfile(c *gin.Context)
	// List client credentials
	// (GET /me/client_credentials)
	ListCurrentUserClientCredentials(c *gin.Context, params ListCurrentUserClientCredentialsParams)
	// Create client credential
	// (POST /me/client_credentials)
	CreateCurrentUserClientCredential(c *gin.Context)
	// Delete client credential
	// (DELETE /me/client_credentials/{credential_id})
	DeleteCurrentUserClientCredential(c *gin.Context, credentialId CredentialIdPathParam)
	// List linked content provider tokens
	// (GET /me/content_tokens)
	ListMyContentTokens(c *gin.Context)
	// Revoke linked content provider token
	// (DELETE /me/content_tokens/{provider_id})
	DeleteMyContentToken(c *gin.Context, providerId string)
	// Start content provider authorization
	// (POST /me/content_tokens/{provider_id}/authorize)
	AuthorizeContentToken(c *gin.Context, providerId string)
	// List my groups
	// (GET /me/groups)
	ListMyGroups(c *gin.Context)
	// List members of my group
	// (GET /me/groups/{internal_uuid}/members)
	ListMyGroupMembers(c *gin.Context, internalUuid InternalUuidPathParam, params ListMyGroupMembersParams)
	// List current user identities
	// (GET /me/identities)
	ListMyIdentities(c *gin.Context)
	// Confirm and complete an identity link
	// (POST /me/identities/link/confirm)
	ConfirmIdentityLink(c *gin.Context)
	// Get pending identity link details
	// (GET /me/identities/link/pending/{link_id})
	GetPendingIdentityLink(c *gin.Context, linkId string)
	// Start an identity link flow
	// (POST /me/identities/link/start)
	StartIdentityLink(c *gin.Context, params StartIdentityLinkParams)
	// Unlink a linked identity
	// (DELETE /me/identities/{id})
	DeleteMyIdentity(c *gin.Context, id openapi_types.UUID)
	// Logout current user
	// (POST /me/logout)
	LogoutCurrentUser(c *gin.Context)
	// Grant the TMI Entra app per-file read access to a picked OneDrive/SharePoint file.
	// (POST /me/microsoft/picker_grants)
	GrantMicrosoftFilePermission(c *gin.Context)
	// Mint a short-lived access token for the Google Picker browser client
	// (POST /me/picker_tokens/{provider_id})
	MintPickerToken(c *gin.Context, providerId string)
	// Get user preferences
	// (GET /me/preferences)
	GetCurrentUserPreferences(c *gin.Context)
	// Create user preferences
	// (POST /me/preferences)
	CreateCurrentUserPreferences(c *gin.Context)
	// Update user preferences
	// (PUT /me/preferences)
	UpdateCurrentUserPreferences(c *gin.Context)
	// List active collaboration sessions
	// (GET /me/sessions)
	GetCurrentUserSessions(c *gin.Context)
	// Transfer ownership of all owned resources
	// (POST /me/transfer)
	TransferCurrentUserOwnership(c *gin.Context)
	// Initiate OAuth authorization flow
	// (GET /oauth2/authorize)
	AuthorizeOAuthProvider(c *gin.Context, params AuthorizeOAuthProviderParams)
	// Handle OAuth callback
	// (GET /oauth2/callback)
	HandleOAuthCallback(c *gin.Context, params HandleOAuthCallbackParams)
	// Delegated content provider OAuth callback
	// (GET /oauth2/content_callback)
	ContentOAuthCallback(c *gin.Context, params ContentOAuthCallbackParams)
	// Token Introspection
	// (POST /oauth2/introspect)
	IntrospectToken(c *gin.Context)
	// List available OAuth providers
	// (GET /oauth2/providers)
	GetAuthProviders(c *gin.Context)
	// Get groups for identity provider
	// (GET /oauth2/providers/{idp}/groups)
	GetProviderGroups(c *gin.Context, idp IdpPathParam)
	// Refresh JWT token
	// (POST /oauth2/refresh)
	RefreshToken(c *gin.Context)
	// Revoke token
	// (POST /oauth2/revoke)
	RevokeToken(c *gin.Context)
	// Initiate fresh-prompt step-up re-authentication
	// (GET /oauth2/step_up)
	StepUpAuthenticate(c *gin.Context, params StepUpAuthenticateParams)
	// Exchange OAuth credentials for JWT tokens
	// (POST /oauth2/token)
	ExchangeOAuthCode(c *gin.Context, params ExchangeOAuthCodeParams)
	// Get current user information
	// (GET /oauth2/userinfo)
	GetCurrentUser(c *gin.Context)
	// List projects
	// (GET /projects)
	ListProjects(c *gin.Context, params ListProjectsParams)
	// Create a project
	// (POST /projects)
	CreateProject(c *gin.Context)
	// Delete a project
	// (DELETE /projects/{project_id})
	DeleteProject(c *gin.Context, projectId openapi_types.UUID)
	// Get a project
	// (GET /projects/{project_id})
	GetProject(c *gin.Context, projectId openapi_types.UUID)
	// Patch a project
	// (PATCH /projects/{project_id})
	PatchProject(c *gin.Context, projectId openapi_types.UUID, params PatchProjectParams)
	// Update a project
	// (PUT /projects/{project_id})
	UpdateProject(c *gin.Context, projectId openapi_types.UUID, params UpdateProjectParams)
	// Get project metadata
	// (GET /projects/{project_id}/metadata)
	GetProjectMetadata(c *gin.Context, projectId openapi_types.UUID)
	// Create project metadata
	// (POST /projects/{project_id}/metadata)
	CreateProjectMetadata(c *gin.Context, projectId openapi_types.UUID)
	// Bulk upsert project metadata
	// (PATCH /projects/{project_id}/metadata/bulk)
	BulkUpsertProjectMetadata(c *gin.Context, projectId openapi_types.UUID)
	// Bulk create project metadata
	// (POST /projects/{project_id}/metadata/bulk)
	BulkCreateProjectMetadata(c *gin.Context, projectId openapi_types.UUID)
	// Bulk replace project metadata
	// (PUT /projects/{project_id}/metadata/bulk)
	BulkReplaceProjectMetadata(c *gin.Context, projectId openapi_types.UUID)
	// Delete project metadata
	// (DELETE /projects/{project_id}/metadata/{key})
	DeleteProjectMetadata(c *gin.Context, projectId openapi_types.UUID, key string)
	// Update project metadata
	// (PUT /projects/{project_id}/metadata/{key})
	UpdateProjectMetadata(c *gin.Context, projectId openapi_types.UUID, key string)
	// List notes in a project
	// (GET /projects/{project_id}/notes)
	ListProjectNotes(c *gin.Context, projectId openapi_types.UUID, params ListProjectNotesParams)
	// Create a new project note
	// (POST /projects/{project_id}/notes)
	CreateProjectNote(c *gin.Context, projectId openapi_types.UUID)
	// Delete a project note
	// (DELETE /projects/{project_id}/notes/{project_note_id})
	DeleteProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)
	// Get a specific project note
	// (GET /projects/{project_id}/notes/{project_note_id})
	GetProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)
	// Partially update a project note
	// (PATCH /projects/{project_id}/notes/{project_note_id})
	PatchProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)
	// Update a project note
	// (PUT /projects/{project_id}/notes/{project_note_id})
	UpdateProjectNote(c *gin.Context, projectId openapi_types.UUID, projectNoteId ProjectNoteId)
	// SAML Assertion Consumer Service
	// (POST /saml/acs)
	ProcessSAMLResponse(c *gin.Context)
	// List available SAML providers
	// (GET /saml/providers)
	GetSAMLProviders(c *gin.Context)
	// List SAML users for UI autocomplete
	// (GET /saml/providers/{idp}/users)
	ListSAMLUsers(c *gin.Context, idp IdpPathParam)
	// SAML Single Logout
	// (GET /saml/slo)
	ProcessSAMLLogout(c *gin.Context, params ProcessSAMLLogoutParams)
	// SAML Single Logout (POST)
	// (POST /saml/slo)
	ProcessSAMLLogoutPost(c *gin.Context)
	// Initiate SAML authentication
	// (GET /saml/{provider}/login)
	InitiateSAMLLogin(c *gin.Context, provider ProviderPathParam, params InitiateSAMLLoginParams)
	// Get SAML service provider metadata
	// (GET /saml/{provider}/metadata)
	GetSAMLMetadata(c *gin.Context, provider ProviderPathParam)
	// List teams
	// (GET /teams)
	ListTeams(c *gin.Context, params ListTeamsParams)
	// Create a team
	// (POST /teams)
	CreateTeam(c *gin.Context)
	// Delete a team
	// (DELETE /teams/{team_id})
	DeleteTeam(c *gin.Context, teamId openapi_types.UUID)
	// Get a team
	// (GET /teams/{team_id})
	GetTeam(c *gin.Context, teamId openapi_types.UUID)
	// Patch a team
	// (PATCH /teams/{team_id})
	PatchTeam(c *gin.Context, teamId openapi_types.UUID, params PatchTeamParams)
	// Update a team
	// (PUT /teams/{team_id})
	UpdateTeam(c *gin.Context, teamId openapi_types.UUID, params UpdateTeamParams)
	// Get team metadata
	// (GET /teams/{team_id}/metadata)
	GetTeamMetadata(c *gin.Context, teamId openapi_types.UUID)
	// Create team metadata
	// (POST /teams/{team_id}/metadata)
	CreateTeamMetadata(c *gin.Context, teamId openapi_types.UUID)
	// Bulk upsert team metadata
	// (PATCH /teams/{team_id}/metadata/bulk)
	BulkUpsertTeamMetadata(c *gin.Context, teamId openapi_types.UUID)
	// Bulk create team metadata
	// (POST /teams/{team_id}/metadata/bulk)
	BulkCreateTeamMetadata(c *gin.Context, teamId openapi_types.UUID)
	// Bulk replace team metadata
	// (PUT /teams/{team_id}/metadata/bulk)
	BulkReplaceTeamMetadata(c *gin.Context, teamId openapi_types.UUID)
	// Delete team metadata
	// (DELETE /teams/{team_id}/metadata/{key})
	DeleteTeamMetadata(c *gin.Context, teamId openapi_types.UUID, key string)
	// Update team metadata
	// (PUT /teams/{team_id}/metadata/{key})
	UpdateTeamMetadata(c *gin.Context, teamId openapi_types.UUID, key string)
	// List notes in a team
	// (GET /teams/{team_id}/notes)
	ListTeamNotes(c *gin.Context, teamId openapi_types.UUID, params ListTeamNotesParams)
	// Create a new team note
	// (POST /teams/{team_id}/notes)
	CreateTeamNote(c *gin.Context, teamId openapi_types.UUID)
	// Delete a team note
	// (DELETE /teams/{team_id}/notes/{team_note_id})
	DeleteTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)
	// Get a specific team note
	// (GET /teams/{team_id}/notes/{team_note_id})
	GetTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)
	// Partially update a team note
	// (PATCH /teams/{team_id}/notes/{team_note_id})
	PatchTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)
	// Update a team note
	// (PUT /teams/{team_id}/notes/{team_note_id})
	UpdateTeamNote(c *gin.Context, teamId openapi_types.UUID, teamNoteId TeamNoteId)
	// List threat models
	// (GET /threat_models)
	ListThreatModels(c *gin.Context, params ListThreatModelsParams)
	// Create a threat model
	// (POST /threat_models)
	CreateThreatModel(c *gin.Context)
	// Delete a threat model
	// (DELETE /threat_models/{threat_model_id})
	DeleteThreatModel(c *gin.Context, threatModelId ThreatModelId)
	// Retrieve a threat model
	// (GET /threat_models/{threat_model_id})
	GetThreatModel(c *gin.Context, threatModelId ThreatModelId)
	// Partially update a threat model
	// (PATCH /threat_models/{threat_model_id})
	PatchThreatModel(c *gin.Context, threatModelId ThreatModelId, params PatchThreatModelParams)
	// Update a threat model
	// (PUT /threat_models/{threat_model_id})
	UpdateThreatModel(c *gin.Context, threatModelId ThreatModelId, params UpdateThreatModelParams)
	// List assets in a threat model
	// (GET /threat_models/{threat_model_id}/assets)
	GetThreatModelAssets(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelAssetsParams)
	// Create a new asset
	// (POST /threat_models/{threat_model_id}/assets)
	CreateThreatModelAsset(c *gin.Context, threatModelId ThreatModelId)
	// Bulk create assets
	// (POST /threat_models/{threat_model_id}/assets/bulk)
	BulkCreateThreatModelAssets(c *gin.Context, threatModelId ThreatModelId)
	// Bulk upsert assets
	// (PUT /threat_models/{threat_model_id}/assets/bulk)
	BulkUpsertThreatModelAssets(c *gin.Context, threatModelId ThreatModelId)
	// Delete an asset
	// (DELETE /threat_models/{threat_model_id}/assets/{asset_id})
	DeleteThreatModelAsset(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// Get a specific asset
	// (GET /threat_models/{threat_model_id}/assets/{asset_id})
	GetThreatModelAsset(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// Partially update asset
	// (PATCH /threat_models/{threat_model_id}/assets/{asset_id})
	PatchThreatModelAsset(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, params PatchThreatModelAssetParams)
	// Update an asset
	// (PUT /threat_models/{threat_model_id}/assets/{asset_id})
	UpdateThreatModelAsset(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, params UpdateThreatModelAssetParams)
	// List audit trail for an asset
	// (GET /threat_models/{threat_model_id}/assets/{asset_id}/audit_trail)
	GetAssetAuditTrail(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, params GetAssetAuditTrailParams)
	// Get all metadata for an asset
	// (GET /threat_models/{threat_model_id}/assets/{asset_id}/metadata)
	GetThreatModelAssetMetadata(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// Add metadata to an asset
	// (POST /threat_models/{threat_model_id}/assets/{asset_id}/metadata)
	CreateThreatModelAssetMetadata(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// Bulk upsert asset metadata
	// (PATCH /threat_models/{threat_model_id}/assets/{asset_id}/metadata/bulk)
	BulkUpsertThreatModelAssetMetadata(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// Bulk create asset metadata
	// (POST /threat_models/{threat_model_id}/assets/{asset_id}/metadata/bulk)
	BulkCreateThreatModelAssetMetadata(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// Bulk replace asset metadata
	// (PUT /threat_models/{threat_model_id}/assets/{asset_id}/metadata/bulk)
	BulkReplaceThreatModelAssetMetadata(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// Delete asset metadata
	// (DELETE /threat_models/{threat_model_id}/assets/{asset_id}/metadata/{key})
	DeleteThreatModelAssetMetadata(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, key MetadataKey)
	// Get specific metadata for an asset
	// (GET /threat_models/{threat_model_id}/assets/{asset_id}/metadata/{key})
	GetThreatModelAssetMetadataByKey(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, key MetadataKey)
	// Update asset metadata
	// (PUT /threat_models/{threat_model_id}/assets/{asset_id}/metadata/{key})
	UpdateThreatModelAssetMetadata(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, key MetadataKey)
	// Restore a soft-deleted asset
	// (POST /threat_models/{threat_model_id}/assets/{asset_id}/restore)
	RestoreAsset(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)
	// List audit trail for a threat model and all sub-objects
	// (GET /threat_models/{threat_model_id}/audit_trail)
	GetThreatModelAuditTrail(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelAuditTrailParams)
	// Get a single audit trail entry
	// (GET /threat_models/{threat_model_id}/audit_trail/{entry_id})
	GetAuditEntry(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)
	// Rollback an entity to a previous version
	// (POST /threat_models/{threat_model_id}/audit_trail/{entry_id}/rollback)
	RollbackToVersion(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)
	// List Timmy chat sessions
	// (GET /threat_models/{threat_model_id}/chat/sessions)
	ListTimmyChatSessions(c *gin.Context, threatModelId ThreatModelId, params ListTimmyChatSessionsParams)
	// Create a new Timmy chat session
	// (POST /threat_models/{threat_model_id}/chat/sessions)
	CreateTimmyChatSession(c *gin.Context, threatModelId ThreatModelId)
	// Delete a Timmy chat session
	// (DELETE /threat_models/{threat_model_id}/chat/sessions/{session_id})
	DeleteTimmyChatSession(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)
	// Get a Timmy chat session
	// (GET /threat_models/{threat_model_id}/chat/sessions/{session_id})
	GetTimmyChatSession(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)
	// List messages in a Timmy chat session
	// (GET /threat_models/{threat_model_id}/chat/sessions/{session_id}/messages)
	ListTimmyChatMessages(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId, params ListTimmyChatMessagesParams)
	// Send a message to Timmy
	// (POST /threat_models/{threat_model_id}/chat/sessions/{session_id}/messages)
	CreateTimmyChatMessage(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)
	// Refresh session sources
	// (POST /threat_models/{threat_model_id}/chat/sessions/{session_id}/refresh_sources)
	RefreshTimmySources(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)
	// List threat model diagrams
	// (GET /threat_models/{threat_model_id}/diagrams)
	GetThreatModelDiagrams(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelDiagramsParams)
	// Create a new diagram
	// (POST /threat_models/{threat_model_id}/diagrams)
	CreateThreatModelDiagram(c *gin.Context, threatModelId ThreatModelId)
	// Delete a diagram
	// (DELETE /threat_models/{threat_model_id}/diagrams/{diagram_id})
	DeleteThreatModelDiagram(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Get a specific diagram
	// (GET /threat_models/{threat_model_id}/diagrams/{diagram_id})
	GetThreatModelDiagram(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Partially update a diagram
	// (PATCH /threat_models/{threat_model_id}/diagrams/{diagram_id})
	PatchThreatModelDiagram(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, params PatchThreatModelDiagramParams)
	// Update a diagram
	// (PUT /threat_models/{threat_model_id}/diagrams/{diagram_id})
	UpdateThreatModelDiagram(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, params UpdateThreatModelDiagramParams)
	// List audit trail for a diagram
	// (GET /threat_models/{threat_model_id}/diagrams/{diagram_id}/audit_trail)
	GetDiagramAuditTrail(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, params GetDiagramAuditTrailParams)
	// End diagram collaboration session
	// (DELETE /threat_models/{threat_model_id}/diagrams/{diagram_id}/collaborate)
	EndDiagramCollaborationSession(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Get diagram collaboration session
	// (GET /threat_models/{threat_model_id}/diagrams/{diagram_id}/collaborate)
	GetDiagramCollaborationSession(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Create diagram collaboration session
	// (POST /threat_models/{threat_model_id}/diagrams/{diagram_id}/collaborate)
	CreateDiagramCollaborationSession(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Get diagram metadata
	// (GET /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata)
	GetDiagramMetadata(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Create diagram metadata
	// (POST /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata)
	CreateDiagramMetadata(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Bulk upsert diagram metadata
	// (PATCH /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata/bulk)
	BulkUpsertDiagramMetadata(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Bulk create diagram metadata
	// (POST /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata/bulk)
	BulkCreateDiagramMetadata(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Bulk replace diagram metadata
	// (PUT /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata/bulk)
	BulkReplaceDiagramMetadata(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// Delete diagram metadata by key
	// (DELETE /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata/{key})
	DeleteDiagramMetadataByKey(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, key MetadataKey)
	// Get diagram metadata by key
	// (GET /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata/{key})
	GetDiagramMetadataByKey(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, key MetadataKey)
	// Update diagram metadata by key
	// (PUT /threat_models/{threat_model_id}/diagrams/{diagram_id}/metadata/{key})
	UpdateDiagramMetadataByKey(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, key MetadataKey)
	// Get minimal diagram model for automated analysis
	// (GET /threat_models/{threat_model_id}/diagrams/{diagram_id}/model)
	GetDiagramModel(c *gin.Context, threatModelId ThreatModelIdPathParam, diagramId DiagramIdPathParam)
	// Restore a soft-deleted diagram
	// (POST /threat_models/{threat_model_id}/diagrams/{diagram_id}/restore)
	RestoreDiagram(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)
	// List documents in a threat model
	// (GET /threat_models/{threat_model_id}/documents)
	GetThreatModelDocuments(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelDocumentsParams)
	// Create a new document
	// (POST /threat_models/{threat_model_id}/documents)
	CreateThreatModelDocument(c *gin.Context, threatModelId ThreatModelId)
	// Bulk create documents
	// (POST /threat_models/{threat_model_id}/documents/bulk)
	BulkCreateThreatModelDocuments(c *gin.Context, threatModelId ThreatModelId)
	// Bulk upsert documents
	// (PUT /threat_models/{threat_model_id}/documents/bulk)
	BulkUpsertThreatModelDocuments(c *gin.Context, threatModelId ThreatModelId)
	// Delete a document
	// (DELETE /threat_models/{threat_model_id}/documents/{document_id})
	DeleteThreatModelDocument(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Get a specific document
	// (GET /threat_models/{threat_model_id}/documents/{document_id})
	GetThreatModelDocument(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Partially update document
	// (PATCH /threat_models/{threat_model_id}/documents/{document_id})
	PatchThreatModelDocument(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, params PatchThreatModelDocumentParams)
	// Update a document
	// (PUT /threat_models/{threat_model_id}/documents/{document_id})
	UpdateThreatModelDocument(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, params UpdateThreatModelDocumentParams)
	// List audit trail for a document
	// (GET /threat_models/{threat_model_id}/documents/{document_id}/audit_trail)
	GetDocumentAuditTrail(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, params GetDocumentAuditTrailParams)
	// Get document metadata
	// (GET /threat_models/{threat_model_id}/documents/{document_id}/metadata)
	GetDocumentMetadata(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Create document metadata
	// (POST /threat_models/{threat_model_id}/documents/{document_id}/metadata)
	CreateDocumentMetadata(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Bulk upsert document metadata
	// (PATCH /threat_models/{threat_model_id}/documents/{document_id}/metadata/bulk)
	BulkUpsertDocumentMetadata(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Bulk create document metadata
	// (POST /threat_models/{threat_model_id}/documents/{document_id}/metadata/bulk)
	BulkCreateDocumentMetadata(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Bulk replace document metadata
	// (PUT /threat_models/{threat_model_id}/documents/{document_id}/metadata/bulk)
	BulkReplaceDocumentMetadata(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Delete document metadata by key
	// (DELETE /threat_models/{threat_model_id}/documents/{document_id}/metadata/{key})
	DeleteDocumentMetadataByKey(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, key MetadataKey)
	// Get document metadata by key
	// (GET /threat_models/{threat_model_id}/documents/{document_id}/metadata/{key})
	GetDocumentMetadataByKey(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, key MetadataKey)
	// Update document metadata by key
	// (PUT /threat_models/{threat_model_id}/documents/{document_id}/metadata/{key})
	UpdateDocumentMetadataByKey(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, key MetadataKey)
	// Request document access
	// (POST /threat_models/{threat_model_id}/documents/{document_id}/request_access)
	RequestDocumentAccess(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// Restore a soft-deleted document
	// (POST /threat_models/{threat_model_id}/documents/{document_id}/restore)
	RestoreDocument(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)
	// List content feedback for a threat model
	// (GET /threat_models/{threat_model_id}/feedback)
	ListContentFeedback(c *gin.Context, threatModelId ThreatModelId, params ListContentFeedbackParams)
	// Submit content feedback on an AI-generated artifact
	// (POST /threat_models/{threat_model_id}/feedback)
	CreateContentFeedback(c *gin.Context, threatModelId ThreatModelId)
	// Get a single content feedback entry
	// (GET /threat_models/{threat_model_id}/feedback/{feedback_id})
	GetContentFeedback(c *gin.Context, threatModelId ThreatModelId, feedbackId openapi_types.UUID)
	// Get threat model metadata
	// (GET /threat_models/{threat_model_id}/metadata)
	GetThreatModelMetadata(c *gin.Context, threatModelId ThreatModelId)
	// Create threat model metadata
	// (POST /threat_models/{threat_model_id}/metadata)
	CreateThreatModelMetadata(c *gin.Context, threatModelId ThreatModelId)
	// Bulk upsert threat model metadata
	// (PATCH /threat_models/{threat_model_id}/metadata/bulk)
	BulkUpsertThreatModelMetadata(c *gin.Context, threatModelId ThreatModelId)
	// Bulk create threat model metadata
	// (POST /threat_models/{threat_model_id}/metadata/bulk)
	BulkCreateThreatModelMetadata(c *gin.Context, threatModelId ThreatModelId)
	// Bulk replace threat model metadata
	// (PUT /threat_models/{threat_model_id}/metadata/bulk)
	BulkReplaceThreatModelMetadata(c *gin.Context, threatModelId ThreatModelId)
	// Delete threat model metadata by key
	// (DELETE /threat_models/{threat_model_id}/metadata/{key})
	DeleteThreatModelMetadataByKey(c *gin.Context, threatModelId ThreatModelId, key MetadataKey)
	// Get threat model metadata by key
	// (GET /threat_models/{threat_model_id}/metadata/{key})
	GetThreatModelMetadataByKey(c *gin.Context, threatModelId ThreatModelId, key MetadataKey)
	// Update threat model metadata by key
	// (PUT /threat_models/{threat_model_id}/metadata/{key})
	UpdateThreatModelMetadataByKey(c *gin.Context, threatModelId ThreatModelId, key MetadataKey)
	// List notes in a threat model
	// (GET /threat_models/{threat_model_id}/notes)
	GetThreatModelNotes(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelNotesParams)
	// Create a new note
	// (POST /threat_models/{threat_model_id}/notes)
	CreateThreatModelNote(c *gin.Context, threatModelId ThreatModelId)
	// Delete a note
	// (DELETE /threat_models/{threat_model_id}/notes/{note_id})
	DeleteThreatModelNote(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Get a specific note
	// (GET /threat_models/{threat_model_id}/notes/{note_id})
	GetThreatModelNote(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Partially update note
	// (PATCH /threat_models/{threat_model_id}/notes/{note_id})
	PatchThreatModelNote(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Update a note
	// (PUT /threat_models/{threat_model_id}/notes/{note_id})
	UpdateThreatModelNote(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// List audit trail for a note
	// (GET /threat_models/{threat_model_id}/notes/{note_id}/audit_trail)
	GetNoteAuditTrail(c *gin.Context, threatModelId ThreatModelId, noteId NoteId, params GetNoteAuditTrailParams)
	// Get note metadata
	// (GET /threat_models/{threat_model_id}/notes/{note_id}/metadata)
	GetNoteMetadata(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Create note metadata
	// (POST /threat_models/{threat_model_id}/notes/{note_id}/metadata)
	CreateNoteMetadata(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Bulk upsert note metadata
	// (PATCH /threat_models/{threat_model_id}/notes/{note_id}/metadata/bulk)
	BulkUpsertNoteMetadata(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Bulk create note metadata
	// (POST /threat_models/{threat_model_id}/notes/{note_id}/metadata/bulk)
	BulkCreateNoteMetadata(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Bulk replace note metadata
	// (PUT /threat_models/{threat_model_id}/notes/{note_id}/metadata/bulk)
	BulkReplaceNoteMetadata(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// Delete note metadata by key
	// (DELETE /threat_models/{threat_model_id}/notes/{note_id}/metadata/{key})
	DeleteNoteMetadataByKey(c *gin.Context, threatModelId ThreatModelId, noteId NoteId, key MetadataKey)
	// Get note metadata by key
	// (GET /threat_models/{threat_model_id}/notes/{note_id}/metadata/{key})
	GetNoteMetadataByKey(c *gin.Context, threatModelId ThreatModelId, noteId NoteId, key MetadataKey)
	// Update note metadata by key
	// (PUT /threat_models/{threat_model_id}/notes/{note_id}/metadata/{key})
	UpdateNoteMetadataByKey(c *gin.Context, threatModelId ThreatModelId, noteId NoteId, key MetadataKey)
	// Restore a soft-deleted note
	// (POST /threat_models/{threat_model_id}/notes/{note_id}/restore)
	RestoreNote(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)
	// List sources in a threat model
	// (GET /threat_models/{threat_model_id}/repositories)
	GetThreatModelRepositories(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelRepositoriesParams)
	// Create a new source reference
	// (POST /threat_models/{threat_model_id}/repositories)
	CreateThreatModelRepository(c *gin.Context, threatModelId ThreatModelId)
	// Bulk create sources
	// (POST /threat_models/{threat_model_id}/repositories/bulk)
	BulkCreateThreatModelRepositories(c *gin.Context, threatModelId ThreatModelId)
	// Bulk upsert repositories
	// (PUT /threat_models/{threat_model_id}/repositories/bulk)
	BulkUpsertThreatModelRepositories(c *gin.Context, threatModelId ThreatModelId)
	// Delete a source reference
	// (DELETE /threat_models/{threat_model_id}/repositories/{repository_id})
	DeleteThreatModelRepository(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Get a specific source reference
	// (GET /threat_models/{threat_model_id}/repositories/{repository_id})
	GetThreatModelRepository(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Partially update repository
	// (PATCH /threat_models/{threat_model_id}/repositories/{repository_id})
	PatchThreatModelRepository(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Update a source reference
	// (PUT /threat_models/{threat_model_id}/repositories/{repository_id})
	UpdateThreatModelRepository(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// List audit trail for a repository
	// (GET /threat_models/{threat_model_id}/repositories/{repository_id}/audit_trail)
	GetRepositoryAuditTrail(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, params GetRepositoryAuditTrailParams)
	// Get source metadata
	// (GET /threat_models/{threat_model_id}/repositories/{repository_id}/metadata)
	GetRepositoryMetadata(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Create source metadata
	// (POST /threat_models/{threat_model_id}/repositories/{repository_id}/metadata)
	CreateRepositoryMetadata(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Bulk upsert repository metadata
	// (PATCH /threat_models/{threat_model_id}/repositories/{repository_id}/metadata/bulk)
	BulkUpsertRepositoryMetadata(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Bulk create source metadata
	// (POST /threat_models/{threat_model_id}/repositories/{repository_id}/metadata/bulk)
	BulkCreateRepositoryMetadata(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Bulk replace repository metadata
	// (PUT /threat_models/{threat_model_id}/repositories/{repository_id}/metadata/bulk)
	BulkReplaceRepositoryMetadata(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Delete source metadata by key
	// (DELETE /threat_models/{threat_model_id}/repositories/{repository_id}/metadata/{key})
	DeleteRepositoryMetadataByKey(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, key MetadataKey)
	// Get source metadata by key
	// (GET /threat_models/{threat_model_id}/repositories/{repository_id}/metadata/{key})
	GetRepositoryMetadataByKey(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, key MetadataKey)
	// Update source metadata by key
	// (PUT /threat_models/{threat_model_id}/repositories/{repository_id}/metadata/{key})
	UpdateRepositoryMetadataByKey(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, key MetadataKey)
	// Restore a soft-deleted repository
	// (POST /threat_models/{threat_model_id}/repositories/{repository_id}/restore)
	RestoreRepository(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)
	// Restore a soft-deleted threat model
	// (POST /threat_models/{threat_model_id}/restore)
	RestoreThreatModel(c *gin.Context, threatModelId ThreatModelId)
	// List threats in a threat model
	// (GET /threat_models/{threat_model_id}/threats)
	GetThreatModelThreats(c *gin.Context, threatModelId ThreatModelId, params GetThreatModelThreatsParams)
	// Create a new threat
	// (POST /threat_models/{threat_model_id}/threats)
	CreateThreatModelThreat(c *gin.Context, threatModelId ThreatModelId)
	// Bulk DELETE threats
	// (DELETE /threat_models/{threat_model_id}/threats/bulk)
	BulkDeleteThreatModelThreats(c *gin.Context, threatModelId ThreatModelId, params BulkDeleteThreatModelThreatsParams)
	// Bulk PATCH threats
	// (PATCH /threat_models/{threat_model_id}/threats/bulk)
	BulkPatchThreatModelThreats(c *gin.Context, threatModelId ThreatModelId)
	// Bulk create threats
	// (POST /threat_models/{threat_model_id}/threats/bulk)
	BulkCreateThreatModelThreats(c *gin.Context, threatModelId ThreatModelId)
	// Bulk update threats
	// (PUT /threat_models/{threat_model_id}/threats/bulk)
	BulkUpdateThreatModelThreats(c *gin.Context, threatModelId ThreatModelId)
	// Delete a threat
	// (DELETE /threat_models/{threat_model_id}/threats/{threat_id})
	DeleteThreatModelThreat(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// Get a specific threat
	// (GET /threat_models/{threat_model_id}/threats/{threat_id})
	GetThreatModelThreat(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// Partially update a threat
	// (PATCH /threat_models/{threat_model_id}/threats/{threat_id})
	PatchThreatModelThreat(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, params PatchThreatModelThreatParams)
	// Update a threat
	// (PUT /threat_models/{threat_model_id}/threats/{threat_id})
	UpdateThreatModelThreat(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, params UpdateThreatModelThreatParams)
	// List audit trail for a threat
	// (GET /threat_models/{threat_model_id}/threats/{threat_id}/audit_trail)
	GetThreatAuditTrail(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, params GetThreatAuditTrailParams)
	// Get threat metadata
	// (GET /threat_models/{threat_model_id}/threats/{threat_id}/metadata)
	GetThreatMetadata(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// Create threat metadata
	// (POST /threat_models/{threat_model_id}/threats/{threat_id}/metadata)
	CreateThreatMetadata(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// Bulk upsert threat metadata
	// (PATCH /threat_models/{threat_model_id}/threats/{threat_id}/metadata/bulk)
	BulkUpsertThreatMetadata(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// Bulk create threat metadata
	// (POST /threat_models/{threat_model_id}/threats/{threat_id}/metadata/bulk)
	BulkCreateThreatMetadata(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// Bulk replace threat metadata
	// (PUT /threat_models/{threat_model_id}/threats/{threat_id}/metadata/bulk)
	BulkReplaceThreatMetadata(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// Delete threat metadata by key
	// (DELETE /threat_models/{threat_model_id}/threats/{threat_id}/metadata/{key})
	DeleteThreatMetadataByKey(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, key MetadataKey)
	// Get threat metadata by key
	// (GET /threat_models/{threat_model_id}/threats/{threat_id}/metadata/{key})
	GetThreatMetadataByKey(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, key MetadataKey)
	// Update threat metadata by key
	// (PUT /threat_models/{threat_model_id}/threats/{threat_id}/metadata/{key})
	UpdateThreatMetadataByKey(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, key MetadataKey)
	// Restore a soft-deleted threat
	// (POST /threat_models/{threat_model_id}/threats/{threat_id}/restore)
	RestoreThreat(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)
	// List survey responses for triage
	// (GET /triage/survey_responses)
	ListTriageSurveyResponses(c *gin.Context, params ListTriageSurveyResponsesParams)
	// Get survey response for triage
	// (GET /triage/survey_responses/{survey_response_id})
	GetTriageSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)
	// Partial update survey response for triage
	// (PATCH /triage/survey_responses/{survey_response_id})
	PatchTriageSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)
	// Create threat model from survey response
	// (POST /triage/survey_responses/{survey_response_id}/create_threat_model)
	CreateThreatModelFromSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)
	// Get all metadata for a survey response
	// (GET /triage/survey_responses/{survey_response_id}/metadata)
	GetTriageSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)
	// Get metadata by key for a survey response
	// (GET /triage/survey_responses/{survey_response_id}/metadata/{key})
	GetTriageSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)
	// List triage notes for a survey response
	// (GET /triage/survey_responses/{survey_response_id}/triage_notes)
	ListTriageSurveyResponseTriageNotes(c *gin.Context, surveyResponseId SurveyResponseId, params ListTriageSurveyResponseTriageNotesParams)
	// Create a triage note
	// (POST /triage/survey_responses/{survey_response_id}/triage_notes)
	CreateTriageSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId)
	// Get a specific triage note
	// (GET /triage/survey_responses/{survey_response_id}/triage_notes/{triage_note_id})
	GetTriageSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId, triageNoteId TriageNoteId)
	// List usability feedback (admin)
	// (GET /usability_feedback)
	ListUsabilityFeedback(c *gin.Context, params ListUsabilityFeedbackParams)
	// Submit usability feedback
	// (POST /usability_feedback)
	CreateUsabilityFeedback(c *gin.Context)
	// Get a single usability feedback entry (admin)
	// (GET /usability_feedback/{id})
	GetUsabilityFeedback(c *gin.Context, id openapi_types.UUID)
	// Get webhook delivery status
	// (GET /webhook-deliveries/{delivery_id})
	GetWebhookDeliveryStatus(c *gin.Context, deliveryId DeliveryId, params GetWebhookDeliveryStatusParams)
	// Update webhook delivery status
	// (POST /webhook-deliveries/{delivery_id}/status)
	UpdateWebhookDeliveryStatus(c *gin.Context, deliveryId DeliveryId, params UpdateWebhookDeliveryStatusParams)
	// Get a WebSocket authentication ticket
	// (GET /ws/ticket)
	GetWsTicket(c *gin.Context, params GetWsTicketParams)
}

ServerInterface represents all server handlers.

type ServerInterfaceWrapper

type ServerInterfaceWrapper struct {
	Handler            ServerInterface
	HandlerMiddlewares []MiddlewareFunc
	ErrorHandler       func(*gin.Context, error, int)
}

ServerInterfaceWrapper converts contexts to parameters.

func (*ServerInterfaceWrapper) AddGroupMember

func (siw *ServerInterfaceWrapper) AddGroupMember(c *gin.Context)

AddGroupMember operation middleware

func (*ServerInterfaceWrapper) AdminDeleteUserContentToken

func (siw *ServerInterfaceWrapper) AdminDeleteUserContentToken(c *gin.Context)

AdminDeleteUserContentToken operation middleware

func (*ServerInterfaceWrapper) AdminListUserContentTokens

func (siw *ServerInterfaceWrapper) AdminListUserContentTokens(c *gin.Context)

AdminListUserContentTokens operation middleware

func (*ServerInterfaceWrapper) AuthorizeContentToken

func (siw *ServerInterfaceWrapper) AuthorizeContentToken(c *gin.Context)

AuthorizeContentToken operation middleware

func (*ServerInterfaceWrapper) AuthorizeOAuthProvider

func (siw *ServerInterfaceWrapper) AuthorizeOAuthProvider(c *gin.Context)

AuthorizeOAuthProvider operation middleware

func (*ServerInterfaceWrapper) BulkCreateAdminSurveyMetadata

func (siw *ServerInterfaceWrapper) BulkCreateAdminSurveyMetadata(c *gin.Context)

BulkCreateAdminSurveyMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateDiagramMetadata

func (siw *ServerInterfaceWrapper) BulkCreateDiagramMetadata(c *gin.Context)

BulkCreateDiagramMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateDocumentMetadata

func (siw *ServerInterfaceWrapper) BulkCreateDocumentMetadata(c *gin.Context)

BulkCreateDocumentMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateIntakeSurveyResponseMetadata

func (siw *ServerInterfaceWrapper) BulkCreateIntakeSurveyResponseMetadata(c *gin.Context)

BulkCreateIntakeSurveyResponseMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateNoteMetadata

func (siw *ServerInterfaceWrapper) BulkCreateNoteMetadata(c *gin.Context)

BulkCreateNoteMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateProjectMetadata

func (siw *ServerInterfaceWrapper) BulkCreateProjectMetadata(c *gin.Context)

BulkCreateProjectMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateRepositoryMetadata

func (siw *ServerInterfaceWrapper) BulkCreateRepositoryMetadata(c *gin.Context)

BulkCreateRepositoryMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateTeamMetadata

func (siw *ServerInterfaceWrapper) BulkCreateTeamMetadata(c *gin.Context)

BulkCreateTeamMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateThreatMetadata

func (siw *ServerInterfaceWrapper) BulkCreateThreatMetadata(c *gin.Context)

BulkCreateThreatMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateThreatModelAssetMetadata

func (siw *ServerInterfaceWrapper) BulkCreateThreatModelAssetMetadata(c *gin.Context)

BulkCreateThreatModelAssetMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateThreatModelAssets

func (siw *ServerInterfaceWrapper) BulkCreateThreatModelAssets(c *gin.Context)

BulkCreateThreatModelAssets operation middleware

func (*ServerInterfaceWrapper) BulkCreateThreatModelDocuments

func (siw *ServerInterfaceWrapper) BulkCreateThreatModelDocuments(c *gin.Context)

BulkCreateThreatModelDocuments operation middleware

func (*ServerInterfaceWrapper) BulkCreateThreatModelMetadata

func (siw *ServerInterfaceWrapper) BulkCreateThreatModelMetadata(c *gin.Context)

BulkCreateThreatModelMetadata operation middleware

func (*ServerInterfaceWrapper) BulkCreateThreatModelRepositories

func (siw *ServerInterfaceWrapper) BulkCreateThreatModelRepositories(c *gin.Context)

BulkCreateThreatModelRepositories operation middleware

func (*ServerInterfaceWrapper) BulkCreateThreatModelThreats

func (siw *ServerInterfaceWrapper) BulkCreateThreatModelThreats(c *gin.Context)

BulkCreateThreatModelThreats operation middleware

func (*ServerInterfaceWrapper) BulkDeleteThreatModelThreats

func (siw *ServerInterfaceWrapper) BulkDeleteThreatModelThreats(c *gin.Context)

BulkDeleteThreatModelThreats operation middleware

func (*ServerInterfaceWrapper) BulkPatchThreatModelThreats

func (siw *ServerInterfaceWrapper) BulkPatchThreatModelThreats(c *gin.Context)

BulkPatchThreatModelThreats operation middleware

func (*ServerInterfaceWrapper) BulkReplaceAdminSurveyMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceAdminSurveyMetadata(c *gin.Context)

BulkReplaceAdminSurveyMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceDiagramMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceDiagramMetadata(c *gin.Context)

BulkReplaceDiagramMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceDocumentMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceDocumentMetadata(c *gin.Context)

BulkReplaceDocumentMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceIntakeSurveyResponseMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceIntakeSurveyResponseMetadata(c *gin.Context)

BulkReplaceIntakeSurveyResponseMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceNoteMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceNoteMetadata(c *gin.Context)

BulkReplaceNoteMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceProjectMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceProjectMetadata(c *gin.Context)

BulkReplaceProjectMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceRepositoryMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceRepositoryMetadata(c *gin.Context)

BulkReplaceRepositoryMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceTeamMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceTeamMetadata(c *gin.Context)

BulkReplaceTeamMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceThreatMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceThreatMetadata(c *gin.Context)

BulkReplaceThreatMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceThreatModelAssetMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceThreatModelAssetMetadata(c *gin.Context)

BulkReplaceThreatModelAssetMetadata operation middleware

func (*ServerInterfaceWrapper) BulkReplaceThreatModelMetadata

func (siw *ServerInterfaceWrapper) BulkReplaceThreatModelMetadata(c *gin.Context)

BulkReplaceThreatModelMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpdateThreatModelThreats

func (siw *ServerInterfaceWrapper) BulkUpdateThreatModelThreats(c *gin.Context)

BulkUpdateThreatModelThreats operation middleware

func (*ServerInterfaceWrapper) BulkUpsertAdminSurveyMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertAdminSurveyMetadata(c *gin.Context)

BulkUpsertAdminSurveyMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertDiagramMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertDiagramMetadata(c *gin.Context)

BulkUpsertDiagramMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertDocumentMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertDocumentMetadata(c *gin.Context)

BulkUpsertDocumentMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertIntakeSurveyResponseMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertIntakeSurveyResponseMetadata(c *gin.Context)

BulkUpsertIntakeSurveyResponseMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertNoteMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertNoteMetadata(c *gin.Context)

BulkUpsertNoteMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertProjectMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertProjectMetadata(c *gin.Context)

BulkUpsertProjectMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertRepositoryMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertRepositoryMetadata(c *gin.Context)

BulkUpsertRepositoryMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertTeamMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertTeamMetadata(c *gin.Context)

BulkUpsertTeamMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertThreatMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertThreatMetadata(c *gin.Context)

BulkUpsertThreatMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertThreatModelAssetMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertThreatModelAssetMetadata(c *gin.Context)

BulkUpsertThreatModelAssetMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertThreatModelAssets

func (siw *ServerInterfaceWrapper) BulkUpsertThreatModelAssets(c *gin.Context)

BulkUpsertThreatModelAssets operation middleware

func (*ServerInterfaceWrapper) BulkUpsertThreatModelDocuments

func (siw *ServerInterfaceWrapper) BulkUpsertThreatModelDocuments(c *gin.Context)

BulkUpsertThreatModelDocuments operation middleware

func (*ServerInterfaceWrapper) BulkUpsertThreatModelMetadata

func (siw *ServerInterfaceWrapper) BulkUpsertThreatModelMetadata(c *gin.Context)

BulkUpsertThreatModelMetadata operation middleware

func (*ServerInterfaceWrapper) BulkUpsertThreatModelRepositories

func (siw *ServerInterfaceWrapper) BulkUpsertThreatModelRepositories(c *gin.Context)

BulkUpsertThreatModelRepositories operation middleware

func (siw *ServerInterfaceWrapper) ConfirmIdentityLink(c *gin.Context)

ConfirmIdentityLink operation middleware

func (*ServerInterfaceWrapper) ContentOAuthCallback

func (siw *ServerInterfaceWrapper) ContentOAuthCallback(c *gin.Context)

ContentOAuthCallback operation middleware

func (*ServerInterfaceWrapper) CreateAddon

func (siw *ServerInterfaceWrapper) CreateAddon(c *gin.Context)

CreateAddon operation middleware

func (*ServerInterfaceWrapper) CreateAdminGroup

func (siw *ServerInterfaceWrapper) CreateAdminGroup(c *gin.Context)

CreateAdminGroup operation middleware

func (*ServerInterfaceWrapper) CreateAdminSurvey

func (siw *ServerInterfaceWrapper) CreateAdminSurvey(c *gin.Context)

CreateAdminSurvey operation middleware

func (*ServerInterfaceWrapper) CreateAdminSurveyMetadata

func (siw *ServerInterfaceWrapper) CreateAdminSurveyMetadata(c *gin.Context)

CreateAdminSurveyMetadata operation middleware

func (*ServerInterfaceWrapper) CreateAdminUserClientCredential

func (siw *ServerInterfaceWrapper) CreateAdminUserClientCredential(c *gin.Context)

CreateAdminUserClientCredential operation middleware

func (*ServerInterfaceWrapper) CreateAutomationAccount

func (siw *ServerInterfaceWrapper) CreateAutomationAccount(c *gin.Context)

CreateAutomationAccount operation middleware

func (*ServerInterfaceWrapper) CreateContentFeedback

func (siw *ServerInterfaceWrapper) CreateContentFeedback(c *gin.Context)

CreateContentFeedback operation middleware

func (*ServerInterfaceWrapper) CreateCurrentUserClientCredential

func (siw *ServerInterfaceWrapper) CreateCurrentUserClientCredential(c *gin.Context)

CreateCurrentUserClientCredential operation middleware

func (*ServerInterfaceWrapper) CreateCurrentUserPreferences

func (siw *ServerInterfaceWrapper) CreateCurrentUserPreferences(c *gin.Context)

CreateCurrentUserPreferences operation middleware

func (*ServerInterfaceWrapper) CreateDiagramCollaborationSession

func (siw *ServerInterfaceWrapper) CreateDiagramCollaborationSession(c *gin.Context)

CreateDiagramCollaborationSession operation middleware

func (*ServerInterfaceWrapper) CreateDiagramMetadata

func (siw *ServerInterfaceWrapper) CreateDiagramMetadata(c *gin.Context)

CreateDiagramMetadata operation middleware

func (*ServerInterfaceWrapper) CreateDocumentMetadata

func (siw *ServerInterfaceWrapper) CreateDocumentMetadata(c *gin.Context)

CreateDocumentMetadata operation middleware

func (*ServerInterfaceWrapper) CreateIntakeSurveyResponse

func (siw *ServerInterfaceWrapper) CreateIntakeSurveyResponse(c *gin.Context)

CreateIntakeSurveyResponse operation middleware

func (*ServerInterfaceWrapper) CreateIntakeSurveyResponseMetadata

func (siw *ServerInterfaceWrapper) CreateIntakeSurveyResponseMetadata(c *gin.Context)

CreateIntakeSurveyResponseMetadata operation middleware

func (*ServerInterfaceWrapper) CreateNoteMetadata

func (siw *ServerInterfaceWrapper) CreateNoteMetadata(c *gin.Context)

CreateNoteMetadata operation middleware

func (*ServerInterfaceWrapper) CreateProject

func (siw *ServerInterfaceWrapper) CreateProject(c *gin.Context)

CreateProject operation middleware

func (*ServerInterfaceWrapper) CreateProjectMetadata

func (siw *ServerInterfaceWrapper) CreateProjectMetadata(c *gin.Context)

CreateProjectMetadata operation middleware

func (*ServerInterfaceWrapper) CreateProjectNote

func (siw *ServerInterfaceWrapper) CreateProjectNote(c *gin.Context)

CreateProjectNote operation middleware

func (*ServerInterfaceWrapper) CreateRepositoryMetadata

func (siw *ServerInterfaceWrapper) CreateRepositoryMetadata(c *gin.Context)

CreateRepositoryMetadata operation middleware

func (*ServerInterfaceWrapper) CreateTeam

func (siw *ServerInterfaceWrapper) CreateTeam(c *gin.Context)

CreateTeam operation middleware

func (*ServerInterfaceWrapper) CreateTeamMetadata

func (siw *ServerInterfaceWrapper) CreateTeamMetadata(c *gin.Context)

CreateTeamMetadata operation middleware

func (*ServerInterfaceWrapper) CreateTeamNote

func (siw *ServerInterfaceWrapper) CreateTeamNote(c *gin.Context)

CreateTeamNote operation middleware

func (*ServerInterfaceWrapper) CreateThreatMetadata

func (siw *ServerInterfaceWrapper) CreateThreatMetadata(c *gin.Context)

CreateThreatMetadata operation middleware

func (*ServerInterfaceWrapper) CreateThreatModel

func (siw *ServerInterfaceWrapper) CreateThreatModel(c *gin.Context)

CreateThreatModel operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelAsset

func (siw *ServerInterfaceWrapper) CreateThreatModelAsset(c *gin.Context)

CreateThreatModelAsset operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelAssetMetadata

func (siw *ServerInterfaceWrapper) CreateThreatModelAssetMetadata(c *gin.Context)

CreateThreatModelAssetMetadata operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelDiagram

func (siw *ServerInterfaceWrapper) CreateThreatModelDiagram(c *gin.Context)

CreateThreatModelDiagram operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelDocument

func (siw *ServerInterfaceWrapper) CreateThreatModelDocument(c *gin.Context)

CreateThreatModelDocument operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelFromSurveyResponse

func (siw *ServerInterfaceWrapper) CreateThreatModelFromSurveyResponse(c *gin.Context)

CreateThreatModelFromSurveyResponse operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelMetadata

func (siw *ServerInterfaceWrapper) CreateThreatModelMetadata(c *gin.Context)

CreateThreatModelMetadata operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelNote

func (siw *ServerInterfaceWrapper) CreateThreatModelNote(c *gin.Context)

CreateThreatModelNote operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelRepository

func (siw *ServerInterfaceWrapper) CreateThreatModelRepository(c *gin.Context)

CreateThreatModelRepository operation middleware

func (*ServerInterfaceWrapper) CreateThreatModelThreat

func (siw *ServerInterfaceWrapper) CreateThreatModelThreat(c *gin.Context)

CreateThreatModelThreat operation middleware

func (*ServerInterfaceWrapper) CreateTimmyChatMessage

func (siw *ServerInterfaceWrapper) CreateTimmyChatMessage(c *gin.Context)

CreateTimmyChatMessage operation middleware

func (*ServerInterfaceWrapper) CreateTimmyChatSession

func (siw *ServerInterfaceWrapper) CreateTimmyChatSession(c *gin.Context)

CreateTimmyChatSession operation middleware

func (*ServerInterfaceWrapper) CreateTriageSurveyResponseTriageNote

func (siw *ServerInterfaceWrapper) CreateTriageSurveyResponseTriageNote(c *gin.Context)

CreateTriageSurveyResponseTriageNote operation middleware

func (*ServerInterfaceWrapper) CreateUsabilityFeedback

func (siw *ServerInterfaceWrapper) CreateUsabilityFeedback(c *gin.Context)

CreateUsabilityFeedback operation middleware

func (*ServerInterfaceWrapper) CreateWebhookSubscription

func (siw *ServerInterfaceWrapper) CreateWebhookSubscription(c *gin.Context)

CreateWebhookSubscription operation middleware

func (*ServerInterfaceWrapper) DeleteAddon

func (siw *ServerInterfaceWrapper) DeleteAddon(c *gin.Context)

DeleteAddon operation middleware

func (*ServerInterfaceWrapper) DeleteAddonInvocationQuota

func (siw *ServerInterfaceWrapper) DeleteAddonInvocationQuota(c *gin.Context)

DeleteAddonInvocationQuota operation middleware

func (*ServerInterfaceWrapper) DeleteAdminGroup

func (siw *ServerInterfaceWrapper) DeleteAdminGroup(c *gin.Context)

DeleteAdminGroup operation middleware

func (*ServerInterfaceWrapper) DeleteAdminSurvey

func (siw *ServerInterfaceWrapper) DeleteAdminSurvey(c *gin.Context)

DeleteAdminSurvey operation middleware

func (*ServerInterfaceWrapper) DeleteAdminSurveyMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteAdminSurveyMetadataByKey(c *gin.Context)

DeleteAdminSurveyMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteAdminUser

func (siw *ServerInterfaceWrapper) DeleteAdminUser(c *gin.Context)

DeleteAdminUser operation middleware

func (*ServerInterfaceWrapper) DeleteAdminUserClientCredential

func (siw *ServerInterfaceWrapper) DeleteAdminUserClientCredential(c *gin.Context)

DeleteAdminUserClientCredential operation middleware

func (*ServerInterfaceWrapper) DeleteCurrentUserClientCredential

func (siw *ServerInterfaceWrapper) DeleteCurrentUserClientCredential(c *gin.Context)

DeleteCurrentUserClientCredential operation middleware

func (*ServerInterfaceWrapper) DeleteDiagramMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteDiagramMetadataByKey(c *gin.Context)

DeleteDiagramMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteDocumentMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteDocumentMetadataByKey(c *gin.Context)

DeleteDocumentMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteEmbeddings

func (siw *ServerInterfaceWrapper) DeleteEmbeddings(c *gin.Context)

DeleteEmbeddings operation middleware

func (*ServerInterfaceWrapper) DeleteIntakeSurveyResponse

func (siw *ServerInterfaceWrapper) DeleteIntakeSurveyResponse(c *gin.Context)

DeleteIntakeSurveyResponse operation middleware

func (*ServerInterfaceWrapper) DeleteIntakeSurveyResponseMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteIntakeSurveyResponseMetadataByKey(c *gin.Context)

DeleteIntakeSurveyResponseMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteMyContentToken

func (siw *ServerInterfaceWrapper) DeleteMyContentToken(c *gin.Context)

DeleteMyContentToken operation middleware

func (*ServerInterfaceWrapper) DeleteMyIdentity

func (siw *ServerInterfaceWrapper) DeleteMyIdentity(c *gin.Context)

DeleteMyIdentity operation middleware

func (*ServerInterfaceWrapper) DeleteNoteMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteNoteMetadataByKey(c *gin.Context)

DeleteNoteMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteProject

func (siw *ServerInterfaceWrapper) DeleteProject(c *gin.Context)

DeleteProject operation middleware

func (*ServerInterfaceWrapper) DeleteProjectMetadata

func (siw *ServerInterfaceWrapper) DeleteProjectMetadata(c *gin.Context)

DeleteProjectMetadata operation middleware

func (*ServerInterfaceWrapper) DeleteProjectNote

func (siw *ServerInterfaceWrapper) DeleteProjectNote(c *gin.Context)

DeleteProjectNote operation middleware

func (*ServerInterfaceWrapper) DeleteRepositoryMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteRepositoryMetadataByKey(c *gin.Context)

DeleteRepositoryMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteSystemSetting

func (siw *ServerInterfaceWrapper) DeleteSystemSetting(c *gin.Context)

DeleteSystemSetting operation middleware

func (*ServerInterfaceWrapper) DeleteTeam

func (siw *ServerInterfaceWrapper) DeleteTeam(c *gin.Context)

DeleteTeam operation middleware

func (*ServerInterfaceWrapper) DeleteTeamMetadata

func (siw *ServerInterfaceWrapper) DeleteTeamMetadata(c *gin.Context)

DeleteTeamMetadata operation middleware

func (*ServerInterfaceWrapper) DeleteTeamNote

func (siw *ServerInterfaceWrapper) DeleteTeamNote(c *gin.Context)

DeleteTeamNote operation middleware

func (*ServerInterfaceWrapper) DeleteThreatMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteThreatMetadataByKey(c *gin.Context)

DeleteThreatMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModel

func (siw *ServerInterfaceWrapper) DeleteThreatModel(c *gin.Context)

DeleteThreatModel operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelAsset

func (siw *ServerInterfaceWrapper) DeleteThreatModelAsset(c *gin.Context)

DeleteThreatModelAsset operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelAssetMetadata

func (siw *ServerInterfaceWrapper) DeleteThreatModelAssetMetadata(c *gin.Context)

DeleteThreatModelAssetMetadata operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelDiagram

func (siw *ServerInterfaceWrapper) DeleteThreatModelDiagram(c *gin.Context)

DeleteThreatModelDiagram operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelDocument

func (siw *ServerInterfaceWrapper) DeleteThreatModelDocument(c *gin.Context)

DeleteThreatModelDocument operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelMetadataByKey

func (siw *ServerInterfaceWrapper) DeleteThreatModelMetadataByKey(c *gin.Context)

DeleteThreatModelMetadataByKey operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelNote

func (siw *ServerInterfaceWrapper) DeleteThreatModelNote(c *gin.Context)

DeleteThreatModelNote operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelRepository

func (siw *ServerInterfaceWrapper) DeleteThreatModelRepository(c *gin.Context)

DeleteThreatModelRepository operation middleware

func (*ServerInterfaceWrapper) DeleteThreatModelThreat

func (siw *ServerInterfaceWrapper) DeleteThreatModelThreat(c *gin.Context)

DeleteThreatModelThreat operation middleware

func (*ServerInterfaceWrapper) DeleteTimmyChatSession

func (siw *ServerInterfaceWrapper) DeleteTimmyChatSession(c *gin.Context)

DeleteTimmyChatSession operation middleware

func (*ServerInterfaceWrapper) DeleteUserAPIQuota

func (siw *ServerInterfaceWrapper) DeleteUserAPIQuota(c *gin.Context)

DeleteUserAPIQuota operation middleware

func (*ServerInterfaceWrapper) DeleteUserAccount

func (siw *ServerInterfaceWrapper) DeleteUserAccount(c *gin.Context)

DeleteUserAccount operation middleware

func (*ServerInterfaceWrapper) DeleteWebhookQuota

func (siw *ServerInterfaceWrapper) DeleteWebhookQuota(c *gin.Context)

DeleteWebhookQuota operation middleware

func (*ServerInterfaceWrapper) DeleteWebhookSubscription

func (siw *ServerInterfaceWrapper) DeleteWebhookSubscription(c *gin.Context)

DeleteWebhookSubscription operation middleware

func (*ServerInterfaceWrapper) EndDiagramCollaborationSession

func (siw *ServerInterfaceWrapper) EndDiagramCollaborationSession(c *gin.Context)

EndDiagramCollaborationSession operation middleware

func (*ServerInterfaceWrapper) ExchangeOAuthCode

func (siw *ServerInterfaceWrapper) ExchangeOAuthCode(c *gin.Context)

ExchangeOAuthCode operation middleware

func (*ServerInterfaceWrapper) GetAddon

func (siw *ServerInterfaceWrapper) GetAddon(c *gin.Context)

GetAddon operation middleware

func (*ServerInterfaceWrapper) GetAddonInvocationQuota

func (siw *ServerInterfaceWrapper) GetAddonInvocationQuota(c *gin.Context)

GetAddonInvocationQuota operation middleware

func (*ServerInterfaceWrapper) GetAdminGroup

func (siw *ServerInterfaceWrapper) GetAdminGroup(c *gin.Context)

GetAdminGroup operation middleware

func (*ServerInterfaceWrapper) GetAdminSurvey

func (siw *ServerInterfaceWrapper) GetAdminSurvey(c *gin.Context)

GetAdminSurvey operation middleware

func (*ServerInterfaceWrapper) GetAdminSurveyMetadata

func (siw *ServerInterfaceWrapper) GetAdminSurveyMetadata(c *gin.Context)

GetAdminSurveyMetadata operation middleware

func (*ServerInterfaceWrapper) GetAdminSurveyMetadataByKey

func (siw *ServerInterfaceWrapper) GetAdminSurveyMetadataByKey(c *gin.Context)

GetAdminSurveyMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetAdminThreatModelAuditEntry

func (siw *ServerInterfaceWrapper) GetAdminThreatModelAuditEntry(c *gin.Context)

GetAdminThreatModelAuditEntry operation middleware

func (*ServerInterfaceWrapper) GetAdminUser

func (siw *ServerInterfaceWrapper) GetAdminUser(c *gin.Context)

GetAdminUser operation middleware

func (*ServerInterfaceWrapper) GetApiInfo

func (siw *ServerInterfaceWrapper) GetApiInfo(c *gin.Context)

GetApiInfo operation middleware

func (*ServerInterfaceWrapper) GetAssetAuditTrail

func (siw *ServerInterfaceWrapper) GetAssetAuditTrail(c *gin.Context)

GetAssetAuditTrail operation middleware

func (*ServerInterfaceWrapper) GetAuditEntry

func (siw *ServerInterfaceWrapper) GetAuditEntry(c *gin.Context)

GetAuditEntry operation middleware

func (*ServerInterfaceWrapper) GetAuthProviders

func (siw *ServerInterfaceWrapper) GetAuthProviders(c *gin.Context)

GetAuthProviders operation middleware

func (*ServerInterfaceWrapper) GetClientConfig

func (siw *ServerInterfaceWrapper) GetClientConfig(c *gin.Context)

GetClientConfig operation middleware

func (*ServerInterfaceWrapper) GetContentFeedback

func (siw *ServerInterfaceWrapper) GetContentFeedback(c *gin.Context)

GetContentFeedback operation middleware

func (*ServerInterfaceWrapper) GetCurrentUser

func (siw *ServerInterfaceWrapper) GetCurrentUser(c *gin.Context)

GetCurrentUser operation middleware

func (*ServerInterfaceWrapper) GetCurrentUserPreferences

func (siw *ServerInterfaceWrapper) GetCurrentUserPreferences(c *gin.Context)

GetCurrentUserPreferences operation middleware

func (*ServerInterfaceWrapper) GetCurrentUserProfile

func (siw *ServerInterfaceWrapper) GetCurrentUserProfile(c *gin.Context)

GetCurrentUserProfile operation middleware

func (*ServerInterfaceWrapper) GetCurrentUserSessions

func (siw *ServerInterfaceWrapper) GetCurrentUserSessions(c *gin.Context)

GetCurrentUserSessions operation middleware

func (*ServerInterfaceWrapper) GetDiagramAuditTrail

func (siw *ServerInterfaceWrapper) GetDiagramAuditTrail(c *gin.Context)

GetDiagramAuditTrail operation middleware

func (*ServerInterfaceWrapper) GetDiagramCollaborationSession

func (siw *ServerInterfaceWrapper) GetDiagramCollaborationSession(c *gin.Context)

GetDiagramCollaborationSession operation middleware

func (*ServerInterfaceWrapper) GetDiagramMetadata

func (siw *ServerInterfaceWrapper) GetDiagramMetadata(c *gin.Context)

GetDiagramMetadata operation middleware

func (*ServerInterfaceWrapper) GetDiagramMetadataByKey

func (siw *ServerInterfaceWrapper) GetDiagramMetadataByKey(c *gin.Context)

GetDiagramMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetDiagramModel

func (siw *ServerInterfaceWrapper) GetDiagramModel(c *gin.Context)

GetDiagramModel operation middleware

func (*ServerInterfaceWrapper) GetDocumentAuditTrail

func (siw *ServerInterfaceWrapper) GetDocumentAuditTrail(c *gin.Context)

GetDocumentAuditTrail operation middleware

func (*ServerInterfaceWrapper) GetDocumentMetadata

func (siw *ServerInterfaceWrapper) GetDocumentMetadata(c *gin.Context)

GetDocumentMetadata operation middleware

func (*ServerInterfaceWrapper) GetDocumentMetadataByKey

func (siw *ServerInterfaceWrapper) GetDocumentMetadataByKey(c *gin.Context)

GetDocumentMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetEmbeddingConfig

func (siw *ServerInterfaceWrapper) GetEmbeddingConfig(c *gin.Context)

GetEmbeddingConfig operation middleware

func (*ServerInterfaceWrapper) GetIntakeSurvey

func (siw *ServerInterfaceWrapper) GetIntakeSurvey(c *gin.Context)

GetIntakeSurvey operation middleware

func (*ServerInterfaceWrapper) GetIntakeSurveyResponse

func (siw *ServerInterfaceWrapper) GetIntakeSurveyResponse(c *gin.Context)

GetIntakeSurveyResponse operation middleware

func (*ServerInterfaceWrapper) GetIntakeSurveyResponseMetadata

func (siw *ServerInterfaceWrapper) GetIntakeSurveyResponseMetadata(c *gin.Context)

GetIntakeSurveyResponseMetadata operation middleware

func (*ServerInterfaceWrapper) GetIntakeSurveyResponseMetadataByKey

func (siw *ServerInterfaceWrapper) GetIntakeSurveyResponseMetadataByKey(c *gin.Context)

GetIntakeSurveyResponseMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetIntakeSurveyResponseTriageNote

func (siw *ServerInterfaceWrapper) GetIntakeSurveyResponseTriageNote(c *gin.Context)

GetIntakeSurveyResponseTriageNote operation middleware

func (*ServerInterfaceWrapper) GetJWKS

func (siw *ServerInterfaceWrapper) GetJWKS(c *gin.Context)

GetJWKS operation middleware

func (*ServerInterfaceWrapper) GetNoteAuditTrail

func (siw *ServerInterfaceWrapper) GetNoteAuditTrail(c *gin.Context)

GetNoteAuditTrail operation middleware

func (*ServerInterfaceWrapper) GetNoteMetadata

func (siw *ServerInterfaceWrapper) GetNoteMetadata(c *gin.Context)

GetNoteMetadata operation middleware

func (*ServerInterfaceWrapper) GetNoteMetadataByKey

func (siw *ServerInterfaceWrapper) GetNoteMetadataByKey(c *gin.Context)

GetNoteMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetOAuthAuthorizationServerMetadata

func (siw *ServerInterfaceWrapper) GetOAuthAuthorizationServerMetadata(c *gin.Context)

GetOAuthAuthorizationServerMetadata operation middleware

func (*ServerInterfaceWrapper) GetOAuthProtectedResourceMetadata

func (siw *ServerInterfaceWrapper) GetOAuthProtectedResourceMetadata(c *gin.Context)

GetOAuthProtectedResourceMetadata operation middleware

func (*ServerInterfaceWrapper) GetOpenIDConfiguration

func (siw *ServerInterfaceWrapper) GetOpenIDConfiguration(c *gin.Context)

GetOpenIDConfiguration operation middleware

func (siw *ServerInterfaceWrapper) GetPendingIdentityLink(c *gin.Context)

GetPendingIdentityLink operation middleware

func (*ServerInterfaceWrapper) GetProject

func (siw *ServerInterfaceWrapper) GetProject(c *gin.Context)

GetProject operation middleware

func (*ServerInterfaceWrapper) GetProjectMetadata

func (siw *ServerInterfaceWrapper) GetProjectMetadata(c *gin.Context)

GetProjectMetadata operation middleware

func (*ServerInterfaceWrapper) GetProjectNote

func (siw *ServerInterfaceWrapper) GetProjectNote(c *gin.Context)

GetProjectNote operation middleware

func (*ServerInterfaceWrapper) GetProviderGroups

func (siw *ServerInterfaceWrapper) GetProviderGroups(c *gin.Context)

GetProviderGroups operation middleware

func (*ServerInterfaceWrapper) GetRepositoryAuditTrail

func (siw *ServerInterfaceWrapper) GetRepositoryAuditTrail(c *gin.Context)

GetRepositoryAuditTrail operation middleware

func (*ServerInterfaceWrapper) GetRepositoryMetadata

func (siw *ServerInterfaceWrapper) GetRepositoryMetadata(c *gin.Context)

GetRepositoryMetadata operation middleware

func (*ServerInterfaceWrapper) GetRepositoryMetadataByKey

func (siw *ServerInterfaceWrapper) GetRepositoryMetadataByKey(c *gin.Context)

GetRepositoryMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetSAMLMetadata

func (siw *ServerInterfaceWrapper) GetSAMLMetadata(c *gin.Context)

GetSAMLMetadata operation middleware

func (*ServerInterfaceWrapper) GetSAMLProviders

func (siw *ServerInterfaceWrapper) GetSAMLProviders(c *gin.Context)

GetSAMLProviders operation middleware

func (*ServerInterfaceWrapper) GetSystemAuditEntry

func (siw *ServerInterfaceWrapper) GetSystemAuditEntry(c *gin.Context)

GetSystemAuditEntry operation middleware

func (*ServerInterfaceWrapper) GetSystemSetting

func (siw *ServerInterfaceWrapper) GetSystemSetting(c *gin.Context)

GetSystemSetting operation middleware

func (*ServerInterfaceWrapper) GetTeam

func (siw *ServerInterfaceWrapper) GetTeam(c *gin.Context)

GetTeam operation middleware

func (*ServerInterfaceWrapper) GetTeamMetadata

func (siw *ServerInterfaceWrapper) GetTeamMetadata(c *gin.Context)

GetTeamMetadata operation middleware

func (*ServerInterfaceWrapper) GetTeamNote

func (siw *ServerInterfaceWrapper) GetTeamNote(c *gin.Context)

GetTeamNote operation middleware

func (*ServerInterfaceWrapper) GetThreatAuditTrail

func (siw *ServerInterfaceWrapper) GetThreatAuditTrail(c *gin.Context)

GetThreatAuditTrail operation middleware

func (*ServerInterfaceWrapper) GetThreatMetadata

func (siw *ServerInterfaceWrapper) GetThreatMetadata(c *gin.Context)

GetThreatMetadata operation middleware

func (*ServerInterfaceWrapper) GetThreatMetadataByKey

func (siw *ServerInterfaceWrapper) GetThreatMetadataByKey(c *gin.Context)

GetThreatMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetThreatModel

func (siw *ServerInterfaceWrapper) GetThreatModel(c *gin.Context)

GetThreatModel operation middleware

func (*ServerInterfaceWrapper) GetThreatModelAsset

func (siw *ServerInterfaceWrapper) GetThreatModelAsset(c *gin.Context)

GetThreatModelAsset operation middleware

func (*ServerInterfaceWrapper) GetThreatModelAssetMetadata

func (siw *ServerInterfaceWrapper) GetThreatModelAssetMetadata(c *gin.Context)

GetThreatModelAssetMetadata operation middleware

func (*ServerInterfaceWrapper) GetThreatModelAssetMetadataByKey

func (siw *ServerInterfaceWrapper) GetThreatModelAssetMetadataByKey(c *gin.Context)

GetThreatModelAssetMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetThreatModelAssets

func (siw *ServerInterfaceWrapper) GetThreatModelAssets(c *gin.Context)

GetThreatModelAssets operation middleware

func (*ServerInterfaceWrapper) GetThreatModelAuditTrail

func (siw *ServerInterfaceWrapper) GetThreatModelAuditTrail(c *gin.Context)

GetThreatModelAuditTrail operation middleware

func (*ServerInterfaceWrapper) GetThreatModelDiagram

func (siw *ServerInterfaceWrapper) GetThreatModelDiagram(c *gin.Context)

GetThreatModelDiagram operation middleware

func (*ServerInterfaceWrapper) GetThreatModelDiagrams

func (siw *ServerInterfaceWrapper) GetThreatModelDiagrams(c *gin.Context)

GetThreatModelDiagrams operation middleware

func (*ServerInterfaceWrapper) GetThreatModelDocument

func (siw *ServerInterfaceWrapper) GetThreatModelDocument(c *gin.Context)

GetThreatModelDocument operation middleware

func (*ServerInterfaceWrapper) GetThreatModelDocuments

func (siw *ServerInterfaceWrapper) GetThreatModelDocuments(c *gin.Context)

GetThreatModelDocuments operation middleware

func (*ServerInterfaceWrapper) GetThreatModelMetadata

func (siw *ServerInterfaceWrapper) GetThreatModelMetadata(c *gin.Context)

GetThreatModelMetadata operation middleware

func (*ServerInterfaceWrapper) GetThreatModelMetadataByKey

func (siw *ServerInterfaceWrapper) GetThreatModelMetadataByKey(c *gin.Context)

GetThreatModelMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetThreatModelNote

func (siw *ServerInterfaceWrapper) GetThreatModelNote(c *gin.Context)

GetThreatModelNote operation middleware

func (*ServerInterfaceWrapper) GetThreatModelNotes

func (siw *ServerInterfaceWrapper) GetThreatModelNotes(c *gin.Context)

GetThreatModelNotes operation middleware

func (*ServerInterfaceWrapper) GetThreatModelRepositories

func (siw *ServerInterfaceWrapper) GetThreatModelRepositories(c *gin.Context)

GetThreatModelRepositories operation middleware

func (*ServerInterfaceWrapper) GetThreatModelRepository

func (siw *ServerInterfaceWrapper) GetThreatModelRepository(c *gin.Context)

GetThreatModelRepository operation middleware

func (*ServerInterfaceWrapper) GetThreatModelThreat

func (siw *ServerInterfaceWrapper) GetThreatModelThreat(c *gin.Context)

GetThreatModelThreat operation middleware

func (*ServerInterfaceWrapper) GetThreatModelThreats

func (siw *ServerInterfaceWrapper) GetThreatModelThreats(c *gin.Context)

GetThreatModelThreats operation middleware

func (*ServerInterfaceWrapper) GetTimmyChatSession

func (siw *ServerInterfaceWrapper) GetTimmyChatSession(c *gin.Context)

GetTimmyChatSession operation middleware

func (*ServerInterfaceWrapper) GetTimmyStatus

func (siw *ServerInterfaceWrapper) GetTimmyStatus(c *gin.Context)

GetTimmyStatus operation middleware

func (*ServerInterfaceWrapper) GetTimmyUsage

func (siw *ServerInterfaceWrapper) GetTimmyUsage(c *gin.Context)

GetTimmyUsage operation middleware

func (*ServerInterfaceWrapper) GetTriageSurveyResponse

func (siw *ServerInterfaceWrapper) GetTriageSurveyResponse(c *gin.Context)

GetTriageSurveyResponse operation middleware

func (*ServerInterfaceWrapper) GetTriageSurveyResponseMetadata

func (siw *ServerInterfaceWrapper) GetTriageSurveyResponseMetadata(c *gin.Context)

GetTriageSurveyResponseMetadata operation middleware

func (*ServerInterfaceWrapper) GetTriageSurveyResponseMetadataByKey

func (siw *ServerInterfaceWrapper) GetTriageSurveyResponseMetadataByKey(c *gin.Context)

GetTriageSurveyResponseMetadataByKey operation middleware

func (*ServerInterfaceWrapper) GetTriageSurveyResponseTriageNote

func (siw *ServerInterfaceWrapper) GetTriageSurveyResponseTriageNote(c *gin.Context)

GetTriageSurveyResponseTriageNote operation middleware

func (*ServerInterfaceWrapper) GetUsabilityFeedback

func (siw *ServerInterfaceWrapper) GetUsabilityFeedback(c *gin.Context)

GetUsabilityFeedback operation middleware

func (*ServerInterfaceWrapper) GetUserAPIQuota

func (siw *ServerInterfaceWrapper) GetUserAPIQuota(c *gin.Context)

GetUserAPIQuota operation middleware

func (*ServerInterfaceWrapper) GetWebhookDelivery

func (siw *ServerInterfaceWrapper) GetWebhookDelivery(c *gin.Context)

GetWebhookDelivery operation middleware

func (*ServerInterfaceWrapper) GetWebhookDeliveryStatus

func (siw *ServerInterfaceWrapper) GetWebhookDeliveryStatus(c *gin.Context)

GetWebhookDeliveryStatus operation middleware

func (*ServerInterfaceWrapper) GetWebhookQuota

func (siw *ServerInterfaceWrapper) GetWebhookQuota(c *gin.Context)

GetWebhookQuota operation middleware

func (*ServerInterfaceWrapper) GetWebhookSubscription

func (siw *ServerInterfaceWrapper) GetWebhookSubscription(c *gin.Context)

GetWebhookSubscription operation middleware

func (*ServerInterfaceWrapper) GetWsTicket

func (siw *ServerInterfaceWrapper) GetWsTicket(c *gin.Context)

GetWsTicket operation middleware

func (*ServerInterfaceWrapper) GrantMicrosoftFilePermission

func (siw *ServerInterfaceWrapper) GrantMicrosoftFilePermission(c *gin.Context)

GrantMicrosoftFilePermission operation middleware

func (*ServerInterfaceWrapper) HandleOAuthCallback

func (siw *ServerInterfaceWrapper) HandleOAuthCallback(c *gin.Context)

HandleOAuthCallback operation middleware

func (*ServerInterfaceWrapper) IngestEmbeddings

func (siw *ServerInterfaceWrapper) IngestEmbeddings(c *gin.Context)

IngestEmbeddings operation middleware

func (*ServerInterfaceWrapper) InitiateSAMLLogin

func (siw *ServerInterfaceWrapper) InitiateSAMLLogin(c *gin.Context)

InitiateSAMLLogin operation middleware

func (*ServerInterfaceWrapper) IntrospectToken

func (siw *ServerInterfaceWrapper) IntrospectToken(c *gin.Context)

IntrospectToken operation middleware

func (*ServerInterfaceWrapper) InvokeAddon

func (siw *ServerInterfaceWrapper) InvokeAddon(c *gin.Context)

InvokeAddon operation middleware

func (*ServerInterfaceWrapper) ListAddonInvocationQuotas

func (siw *ServerInterfaceWrapper) ListAddonInvocationQuotas(c *gin.Context)

ListAddonInvocationQuotas operation middleware

func (*ServerInterfaceWrapper) ListAddons

func (siw *ServerInterfaceWrapper) ListAddons(c *gin.Context)

ListAddons operation middleware

func (*ServerInterfaceWrapper) ListAdminGroups

func (siw *ServerInterfaceWrapper) ListAdminGroups(c *gin.Context)

ListAdminGroups operation middleware

func (*ServerInterfaceWrapper) ListAdminSurveys

func (siw *ServerInterfaceWrapper) ListAdminSurveys(c *gin.Context)

ListAdminSurveys operation middleware

func (*ServerInterfaceWrapper) ListAdminThreatModelAuditEntries

func (siw *ServerInterfaceWrapper) ListAdminThreatModelAuditEntries(c *gin.Context)

ListAdminThreatModelAuditEntries operation middleware

func (*ServerInterfaceWrapper) ListAdminUserClientCredentials

func (siw *ServerInterfaceWrapper) ListAdminUserClientCredentials(c *gin.Context)

ListAdminUserClientCredentials operation middleware

func (*ServerInterfaceWrapper) ListAdminUsers

func (siw *ServerInterfaceWrapper) ListAdminUsers(c *gin.Context)

ListAdminUsers operation middleware

func (*ServerInterfaceWrapper) ListContentFeedback

func (siw *ServerInterfaceWrapper) ListContentFeedback(c *gin.Context)

ListContentFeedback operation middleware

func (*ServerInterfaceWrapper) ListCurrentUserClientCredentials

func (siw *ServerInterfaceWrapper) ListCurrentUserClientCredentials(c *gin.Context)

ListCurrentUserClientCredentials operation middleware

func (*ServerInterfaceWrapper) ListGroupMembers

func (siw *ServerInterfaceWrapper) ListGroupMembers(c *gin.Context)

ListGroupMembers operation middleware

func (*ServerInterfaceWrapper) ListIntakeSurveyResponseTriageNotes

func (siw *ServerInterfaceWrapper) ListIntakeSurveyResponseTriageNotes(c *gin.Context)

ListIntakeSurveyResponseTriageNotes operation middleware

func (*ServerInterfaceWrapper) ListIntakeSurveyResponses

func (siw *ServerInterfaceWrapper) ListIntakeSurveyResponses(c *gin.Context)

ListIntakeSurveyResponses operation middleware

func (*ServerInterfaceWrapper) ListIntakeSurveys

func (siw *ServerInterfaceWrapper) ListIntakeSurveys(c *gin.Context)

ListIntakeSurveys operation middleware

func (*ServerInterfaceWrapper) ListMyContentTokens

func (siw *ServerInterfaceWrapper) ListMyContentTokens(c *gin.Context)

ListMyContentTokens operation middleware

func (*ServerInterfaceWrapper) ListMyGroupMembers

func (siw *ServerInterfaceWrapper) ListMyGroupMembers(c *gin.Context)

ListMyGroupMembers operation middleware

func (*ServerInterfaceWrapper) ListMyGroups

func (siw *ServerInterfaceWrapper) ListMyGroups(c *gin.Context)

ListMyGroups operation middleware

func (*ServerInterfaceWrapper) ListMyIdentities

func (siw *ServerInterfaceWrapper) ListMyIdentities(c *gin.Context)

ListMyIdentities operation middleware

func (*ServerInterfaceWrapper) ListProjectNotes

func (siw *ServerInterfaceWrapper) ListProjectNotes(c *gin.Context)

ListProjectNotes operation middleware

func (*ServerInterfaceWrapper) ListProjects

func (siw *ServerInterfaceWrapper) ListProjects(c *gin.Context)

ListProjects operation middleware

func (*ServerInterfaceWrapper) ListSAMLUsers

func (siw *ServerInterfaceWrapper) ListSAMLUsers(c *gin.Context)

ListSAMLUsers operation middleware

func (*ServerInterfaceWrapper) ListSystemAuditEntries

func (siw *ServerInterfaceWrapper) ListSystemAuditEntries(c *gin.Context)

ListSystemAuditEntries operation middleware

func (*ServerInterfaceWrapper) ListSystemSettings

func (siw *ServerInterfaceWrapper) ListSystemSettings(c *gin.Context)

ListSystemSettings operation middleware

func (*ServerInterfaceWrapper) ListTeamNotes

func (siw *ServerInterfaceWrapper) ListTeamNotes(c *gin.Context)

ListTeamNotes operation middleware

func (*ServerInterfaceWrapper) ListTeams

func (siw *ServerInterfaceWrapper) ListTeams(c *gin.Context)

ListTeams operation middleware

func (*ServerInterfaceWrapper) ListThreatModels

func (siw *ServerInterfaceWrapper) ListThreatModels(c *gin.Context)

ListThreatModels operation middleware

func (*ServerInterfaceWrapper) ListTimmyChatMessages

func (siw *ServerInterfaceWrapper) ListTimmyChatMessages(c *gin.Context)

ListTimmyChatMessages operation middleware

func (*ServerInterfaceWrapper) ListTimmyChatSessions

func (siw *ServerInterfaceWrapper) ListTimmyChatSessions(c *gin.Context)

ListTimmyChatSessions operation middleware

func (*ServerInterfaceWrapper) ListTriageSurveyResponseTriageNotes

func (siw *ServerInterfaceWrapper) ListTriageSurveyResponseTriageNotes(c *gin.Context)

ListTriageSurveyResponseTriageNotes operation middleware

func (*ServerInterfaceWrapper) ListTriageSurveyResponses

func (siw *ServerInterfaceWrapper) ListTriageSurveyResponses(c *gin.Context)

ListTriageSurveyResponses operation middleware

func (*ServerInterfaceWrapper) ListUsabilityFeedback

func (siw *ServerInterfaceWrapper) ListUsabilityFeedback(c *gin.Context)

ListUsabilityFeedback operation middleware

func (*ServerInterfaceWrapper) ListUserAPIQuotas

func (siw *ServerInterfaceWrapper) ListUserAPIQuotas(c *gin.Context)

ListUserAPIQuotas operation middleware

func (*ServerInterfaceWrapper) ListWebhookDeliveries

func (siw *ServerInterfaceWrapper) ListWebhookDeliveries(c *gin.Context)

ListWebhookDeliveries operation middleware

func (*ServerInterfaceWrapper) ListWebhookQuotas

func (siw *ServerInterfaceWrapper) ListWebhookQuotas(c *gin.Context)

ListWebhookQuotas operation middleware

func (*ServerInterfaceWrapper) ListWebhookSubscriptions

func (siw *ServerInterfaceWrapper) ListWebhookSubscriptions(c *gin.Context)

ListWebhookSubscriptions operation middleware

func (*ServerInterfaceWrapper) LogoutCurrentUser

func (siw *ServerInterfaceWrapper) LogoutCurrentUser(c *gin.Context)

LogoutCurrentUser operation middleware

func (*ServerInterfaceWrapper) MintPickerToken

func (siw *ServerInterfaceWrapper) MintPickerToken(c *gin.Context)

MintPickerToken operation middleware

func (*ServerInterfaceWrapper) PatchAdminSurvey

func (siw *ServerInterfaceWrapper) PatchAdminSurvey(c *gin.Context)

PatchAdminSurvey operation middleware

func (*ServerInterfaceWrapper) PatchIntakeSurveyResponse

func (siw *ServerInterfaceWrapper) PatchIntakeSurveyResponse(c *gin.Context)

PatchIntakeSurveyResponse operation middleware

func (*ServerInterfaceWrapper) PatchProject

func (siw *ServerInterfaceWrapper) PatchProject(c *gin.Context)

PatchProject operation middleware

func (*ServerInterfaceWrapper) PatchProjectNote

func (siw *ServerInterfaceWrapper) PatchProjectNote(c *gin.Context)

PatchProjectNote operation middleware

func (*ServerInterfaceWrapper) PatchTeam

func (siw *ServerInterfaceWrapper) PatchTeam(c *gin.Context)

PatchTeam operation middleware

func (*ServerInterfaceWrapper) PatchTeamNote

func (siw *ServerInterfaceWrapper) PatchTeamNote(c *gin.Context)

PatchTeamNote operation middleware

func (*ServerInterfaceWrapper) PatchThreatModel

func (siw *ServerInterfaceWrapper) PatchThreatModel(c *gin.Context)

PatchThreatModel operation middleware

func (*ServerInterfaceWrapper) PatchThreatModelAsset

func (siw *ServerInterfaceWrapper) PatchThreatModelAsset(c *gin.Context)

PatchThreatModelAsset operation middleware

func (*ServerInterfaceWrapper) PatchThreatModelDiagram

func (siw *ServerInterfaceWrapper) PatchThreatModelDiagram(c *gin.Context)

PatchThreatModelDiagram operation middleware

func (*ServerInterfaceWrapper) PatchThreatModelDocument

func (siw *ServerInterfaceWrapper) PatchThreatModelDocument(c *gin.Context)

PatchThreatModelDocument operation middleware

func (*ServerInterfaceWrapper) PatchThreatModelNote

func (siw *ServerInterfaceWrapper) PatchThreatModelNote(c *gin.Context)

PatchThreatModelNote operation middleware

func (*ServerInterfaceWrapper) PatchThreatModelRepository

func (siw *ServerInterfaceWrapper) PatchThreatModelRepository(c *gin.Context)

PatchThreatModelRepository operation middleware

func (*ServerInterfaceWrapper) PatchThreatModelThreat

func (siw *ServerInterfaceWrapper) PatchThreatModelThreat(c *gin.Context)

PatchThreatModelThreat operation middleware

func (*ServerInterfaceWrapper) PatchTriageSurveyResponse

func (siw *ServerInterfaceWrapper) PatchTriageSurveyResponse(c *gin.Context)

PatchTriageSurveyResponse operation middleware

func (*ServerInterfaceWrapper) ProcessSAMLLogout

func (siw *ServerInterfaceWrapper) ProcessSAMLLogout(c *gin.Context)

ProcessSAMLLogout operation middleware

func (*ServerInterfaceWrapper) ProcessSAMLLogoutPost

func (siw *ServerInterfaceWrapper) ProcessSAMLLogoutPost(c *gin.Context)

ProcessSAMLLogoutPost operation middleware

func (*ServerInterfaceWrapper) ProcessSAMLResponse

func (siw *ServerInterfaceWrapper) ProcessSAMLResponse(c *gin.Context)

ProcessSAMLResponse operation middleware

func (*ServerInterfaceWrapper) ReencryptSystemSettings

func (siw *ServerInterfaceWrapper) ReencryptSystemSettings(c *gin.Context)

ReencryptSystemSettings operation middleware

func (*ServerInterfaceWrapper) RefreshTimmySources

func (siw *ServerInterfaceWrapper) RefreshTimmySources(c *gin.Context)

RefreshTimmySources operation middleware

func (*ServerInterfaceWrapper) RefreshToken

func (siw *ServerInterfaceWrapper) RefreshToken(c *gin.Context)

RefreshToken operation middleware

func (*ServerInterfaceWrapper) RemoveGroupMember

func (siw *ServerInterfaceWrapper) RemoveGroupMember(c *gin.Context)

RemoveGroupMember operation middleware

func (*ServerInterfaceWrapper) RequestDocumentAccess

func (siw *ServerInterfaceWrapper) RequestDocumentAccess(c *gin.Context)

RequestDocumentAccess operation middleware

func (*ServerInterfaceWrapper) RestoreAsset

func (siw *ServerInterfaceWrapper) RestoreAsset(c *gin.Context)

RestoreAsset operation middleware

func (*ServerInterfaceWrapper) RestoreDiagram

func (siw *ServerInterfaceWrapper) RestoreDiagram(c *gin.Context)

RestoreDiagram operation middleware

func (*ServerInterfaceWrapper) RestoreDocument

func (siw *ServerInterfaceWrapper) RestoreDocument(c *gin.Context)

RestoreDocument operation middleware

func (*ServerInterfaceWrapper) RestoreNote

func (siw *ServerInterfaceWrapper) RestoreNote(c *gin.Context)

RestoreNote operation middleware

func (*ServerInterfaceWrapper) RestoreRepository

func (siw *ServerInterfaceWrapper) RestoreRepository(c *gin.Context)

RestoreRepository operation middleware

func (*ServerInterfaceWrapper) RestoreThreat

func (siw *ServerInterfaceWrapper) RestoreThreat(c *gin.Context)

RestoreThreat operation middleware

func (*ServerInterfaceWrapper) RestoreThreatModel

func (siw *ServerInterfaceWrapper) RestoreThreatModel(c *gin.Context)

RestoreThreatModel operation middleware

func (*ServerInterfaceWrapper) RevokeToken

func (siw *ServerInterfaceWrapper) RevokeToken(c *gin.Context)

RevokeToken operation middleware

func (*ServerInterfaceWrapper) RollbackToVersion

func (siw *ServerInterfaceWrapper) RollbackToVersion(c *gin.Context)

RollbackToVersion operation middleware

func (siw *ServerInterfaceWrapper) StartIdentityLink(c *gin.Context)

StartIdentityLink operation middleware

func (*ServerInterfaceWrapper) StepUpAuthenticate

func (siw *ServerInterfaceWrapper) StepUpAuthenticate(c *gin.Context)

StepUpAuthenticate operation middleware

func (*ServerInterfaceWrapper) TestWebhookSubscription

func (siw *ServerInterfaceWrapper) TestWebhookSubscription(c *gin.Context)

TestWebhookSubscription operation middleware

func (*ServerInterfaceWrapper) TransferAdminUserOwnership

func (siw *ServerInterfaceWrapper) TransferAdminUserOwnership(c *gin.Context)

TransferAdminUserOwnership operation middleware

func (*ServerInterfaceWrapper) TransferCurrentUserOwnership

func (siw *ServerInterfaceWrapper) TransferCurrentUserOwnership(c *gin.Context)

TransferCurrentUserOwnership operation middleware

func (*ServerInterfaceWrapper) UpdateAddonInvocationQuota

func (siw *ServerInterfaceWrapper) UpdateAddonInvocationQuota(c *gin.Context)

UpdateAddonInvocationQuota operation middleware

func (*ServerInterfaceWrapper) UpdateAdminGroup

func (siw *ServerInterfaceWrapper) UpdateAdminGroup(c *gin.Context)

UpdateAdminGroup operation middleware

func (*ServerInterfaceWrapper) UpdateAdminSurvey

func (siw *ServerInterfaceWrapper) UpdateAdminSurvey(c *gin.Context)

UpdateAdminSurvey operation middleware

func (*ServerInterfaceWrapper) UpdateAdminSurveyMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateAdminSurveyMetadataByKey(c *gin.Context)

UpdateAdminSurveyMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateAdminUser

func (siw *ServerInterfaceWrapper) UpdateAdminUser(c *gin.Context)

UpdateAdminUser operation middleware

func (*ServerInterfaceWrapper) UpdateCurrentUserPreferences

func (siw *ServerInterfaceWrapper) UpdateCurrentUserPreferences(c *gin.Context)

UpdateCurrentUserPreferences operation middleware

func (*ServerInterfaceWrapper) UpdateDiagramMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateDiagramMetadataByKey(c *gin.Context)

UpdateDiagramMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateDocumentMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateDocumentMetadataByKey(c *gin.Context)

UpdateDocumentMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateIntakeSurveyResponse

func (siw *ServerInterfaceWrapper) UpdateIntakeSurveyResponse(c *gin.Context)

UpdateIntakeSurveyResponse operation middleware

func (*ServerInterfaceWrapper) UpdateIntakeSurveyResponseMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateIntakeSurveyResponseMetadataByKey(c *gin.Context)

UpdateIntakeSurveyResponseMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateNoteMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateNoteMetadataByKey(c *gin.Context)

UpdateNoteMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateProject

func (siw *ServerInterfaceWrapper) UpdateProject(c *gin.Context)

UpdateProject operation middleware

func (*ServerInterfaceWrapper) UpdateProjectMetadata

func (siw *ServerInterfaceWrapper) UpdateProjectMetadata(c *gin.Context)

UpdateProjectMetadata operation middleware

func (*ServerInterfaceWrapper) UpdateProjectNote

func (siw *ServerInterfaceWrapper) UpdateProjectNote(c *gin.Context)

UpdateProjectNote operation middleware

func (*ServerInterfaceWrapper) UpdateRepositoryMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateRepositoryMetadataByKey(c *gin.Context)

UpdateRepositoryMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateSystemSetting

func (siw *ServerInterfaceWrapper) UpdateSystemSetting(c *gin.Context)

UpdateSystemSetting operation middleware

func (*ServerInterfaceWrapper) UpdateTeam

func (siw *ServerInterfaceWrapper) UpdateTeam(c *gin.Context)

UpdateTeam operation middleware

func (*ServerInterfaceWrapper) UpdateTeamMetadata

func (siw *ServerInterfaceWrapper) UpdateTeamMetadata(c *gin.Context)

UpdateTeamMetadata operation middleware

func (*ServerInterfaceWrapper) UpdateTeamNote

func (siw *ServerInterfaceWrapper) UpdateTeamNote(c *gin.Context)

UpdateTeamNote operation middleware

func (*ServerInterfaceWrapper) UpdateThreatMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateThreatMetadataByKey(c *gin.Context)

UpdateThreatMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModel

func (siw *ServerInterfaceWrapper) UpdateThreatModel(c *gin.Context)

UpdateThreatModel operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelAsset

func (siw *ServerInterfaceWrapper) UpdateThreatModelAsset(c *gin.Context)

UpdateThreatModelAsset operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelAssetMetadata

func (siw *ServerInterfaceWrapper) UpdateThreatModelAssetMetadata(c *gin.Context)

UpdateThreatModelAssetMetadata operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelDiagram

func (siw *ServerInterfaceWrapper) UpdateThreatModelDiagram(c *gin.Context)

UpdateThreatModelDiagram operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelDocument

func (siw *ServerInterfaceWrapper) UpdateThreatModelDocument(c *gin.Context)

UpdateThreatModelDocument operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelMetadataByKey

func (siw *ServerInterfaceWrapper) UpdateThreatModelMetadataByKey(c *gin.Context)

UpdateThreatModelMetadataByKey operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelNote

func (siw *ServerInterfaceWrapper) UpdateThreatModelNote(c *gin.Context)

UpdateThreatModelNote operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelRepository

func (siw *ServerInterfaceWrapper) UpdateThreatModelRepository(c *gin.Context)

UpdateThreatModelRepository operation middleware

func (*ServerInterfaceWrapper) UpdateThreatModelThreat

func (siw *ServerInterfaceWrapper) UpdateThreatModelThreat(c *gin.Context)

UpdateThreatModelThreat operation middleware

func (*ServerInterfaceWrapper) UpdateUserAPIQuota

func (siw *ServerInterfaceWrapper) UpdateUserAPIQuota(c *gin.Context)

UpdateUserAPIQuota operation middleware

func (*ServerInterfaceWrapper) UpdateWebhookDeliveryStatus

func (siw *ServerInterfaceWrapper) UpdateWebhookDeliveryStatus(c *gin.Context)

UpdateWebhookDeliveryStatus operation middleware

func (*ServerInterfaceWrapper) UpdateWebhookQuota

func (siw *ServerInterfaceWrapper) UpdateWebhookQuota(c *gin.Context)

UpdateWebhookQuota operation middleware

type ServiceUnavailable

type ServiceUnavailable = Error

ServiceUnavailable Standard error response format

type SessionId

type SessionId = openapi_types.UUID

SessionId defines model for SessionId.

type SessionProgressCallback

type SessionProgressCallback func(phase, entityType, entityName string, progress int, detail string)

SessionProgressCallback reports progress during session creation phases SEM@9ac60db5b7f349b340ab9963342361d7b81db7e2: callback type reporting phase progress during Timmy session creation (pure)

type SessionState

type SessionState string

SessionState represents the lifecycle state of a collaboration session SEM@6ad68270b3acd88f9906ed851d58631866a8ce01: enumeration of collaborative diagram session lifecycle states (pure)

const (
	// SessionStateActive means the session is active and accepting connections
	SessionStateActive SessionState = "active"
	// SessionStateTerminating means the session is in the process of terminating
	SessionStateTerminating SessionState = "terminating"
	// SessionStateTerminated means the session has been terminated and should be cleaned up
	SessionStateTerminated SessionState = "terminated"
)

type SessionValidator

type SessionValidator struct{}

SessionValidator handles session validation logic SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: helper that validates WebSocket session access and state

func (*SessionValidator) ValidateSessionAccess

func (v *SessionValidator) ValidateSessionAccess(hub *WebSocketHub, userInfo *UserInfo, threatModelID, diagramID string) error

ValidateSessionAccess validates that a user can access a diagram session Uses flexible user identifier matching (email, provider_user_id, or internal_uuid) SEM@489dd32fbe1ec9c985b95318612d6c5434c9f696: validate that the user has permission to collaborate on the diagram session (pure)

func (*SessionValidator) ValidateSessionID

func (v *SessionValidator) ValidateSessionID(session *DiagramSession, providedSessionID string) error

ValidateSessionID validates that the provided session ID matches the actual session SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: validate that a caller-supplied session ID matches the actual session (pure)

func (*SessionValidator) ValidateSessionState

func (v *SessionValidator) ValidateSessionState(session *DiagramSession) error

ValidateSessionState validates the session is in the correct state for connection SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: validate that a diagram session is in the active state (pure)

type SettingError

type SettingError struct {
	Key   string `json:"key"`
	Error string `json:"error"`
}

SettingError represents an error for a specific setting during re-encryption. SEM@b9272d08c168beb55fbc4db127cb1d4eec5f72c1: error value capturing key and message for a failed per-setting operation (pure)

type SettingsService

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

SettingsService provides access to system settings with caching.

Configuration Priority: When a ConfigProvider is set, the service implements a three-tier configuration priority system: environment variables > config file > database.

The ConfigProvider (via GetMigratableSettings) already merges environment variables with config file values (environment takes precedence). When retrieving a setting, if a value exists in the ConfigProvider, it is returned. Otherwise, the database value is used. This allows operators to:

  • Override any setting via environment variables (highest priority)
  • Set defaults in config files (medium priority)
  • Store runtime-configurable values in the database (lowest priority)

The database serves as the persistent store for settings that can be modified at runtime via the admin API, while environment/config values always win. SEM@b9272d08c168beb55fbc4db127cb1d4eec5f72c1: manage system settings with three-tier priority (env > config > DB) and optional encryption (mutates shared state)

func NewSettingsService

func NewSettingsService(gormDB *gorm.DB, redisDB *db.RedisDB) *SettingsService

NewSettingsService creates a new settings service SEM@f25790d896e8e128807a3c9a0a517fcbe6f710fe: build a SettingsService wired to the given DB and optional Redis cache (pure)

func (*SettingsService) Delete

func (s *SettingsService) Delete(ctx context.Context, key string) error

Delete removes a setting SEM@24f7dadfcf515c1af48310c466e75a45e19d6e3b: delete a system setting by key and invalidate its cache entry (reads DB)

func (*SettingsService) Get

Get retrieves a setting by key, checking cache first SEM@290855b441dc47580986878bc40a3cb20d4ea51a: fetch a system setting by key with cache-first lookup and decryption (reads DB)

func (*SettingsService) GetBool

func (s *SettingsService) GetBool(ctx context.Context, key string) (bool, error)

GetBool retrieves a boolean setting value. Priority: environment/config file > database (see SettingsService documentation). SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: fetch and parse a boolean setting applying env/config-file priority over the database (reads DB)

func (*SettingsService) GetInt

func (s *SettingsService) GetInt(ctx context.Context, key string) (int, error)

GetInt retrieves an integer setting value. Priority: environment/config file > database (see SettingsService documentation). SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: fetch and parse an integer setting applying env/config-file priority over the database (reads DB)

func (*SettingsService) GetJSON

func (s *SettingsService) GetJSON(ctx context.Context, key string, target any) error

GetJSON retrieves a JSON setting value and unmarshals it into the target. Priority: environment/config file > database (see SettingsService documentation). SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: fetch a JSON setting and unmarshal it into the target applying env/config-file priority (reads DB)

func (*SettingsService) GetString

func (s *SettingsService) GetString(ctx context.Context, key string) (string, error)

GetString retrieves a string setting value. Priority: environment/config file > database (see SettingsService documentation). SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: fetch a string setting applying env/config-file priority over the database (reads DB)

func (*SettingsService) InvalidateAll

func (s *SettingsService) InvalidateAll(ctx context.Context)

InvalidateAll clears all settings from cache SEM@fe6575f1c15d84b67ee9853a0e59055c1ebe44b6: flush all settings from the active in-memory cache tier (mutates shared state)

func (*SettingsService) List

List retrieves all settings SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: list all system settings ordered by key with decryption applied (reads DB)

func (*SettingsService) ListByPrefix

func (s *SettingsService) ListByPrefix(ctx context.Context, prefix string) ([]models.SystemSetting, error)

ListByPrefix returns all database settings whose key starts with the given prefix. Results are decrypted if an encryptor is configured. SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: list system settings whose key shares a given prefix, decrypting values (reads DB)

func (*SettingsService) ReEncryptAll

func (s *SettingsService) ReEncryptAll(ctx context.Context, modifiedBy *string) (int, []SettingError, error)

ReEncryptAll re-encrypts all settings with the current encryption key. Returns the count of settings re-encrypted, any per-setting errors, and a fatal error if applicable. SEM@5dfa9dcf64aa0662920dbbab3bca200db1b22c73: re-encrypt all stored settings with the current encryption key (reads DB)

func (*SettingsService) SeedDefaults

func (s *SettingsService) SeedDefaults(ctx context.Context) error

SeedDefaults seeds the default settings if they don't exist SEM@ab3b70da0bebdbb7db5fefc97e15036dc3f5c4c5: insert default system settings into the database if they do not already exist (reads DB)

func (*SettingsService) Set

func (s *SettingsService) Set(ctx context.Context, setting *models.SystemSetting) error

Set creates or updates a setting SEM@a3e7b116b059fa4c734b5c77def4c2de21df4dbc: store or update a system setting with type validation, encryption, and cache invalidation (reads DB)

func (*SettingsService) SetConfigProvider

func (s *SettingsService) SetConfigProvider(provider ConfigProvider)

SetConfigProvider sets the config provider for environment/config file priority lookups. When set, GetWithPriority will check config values before database values. SEM@f25790d896e8e128807a3c9a0a517fcbe6f710fe: register the config provider used for env/config-file priority lookups (mutates shared state)

func (*SettingsService) SetEncryptor

func (s *SettingsService) SetEncryptor(enc *crypto.SettingsEncryptor)

SetEncryptor sets the encryptor for at-rest encryption of setting values. When set, values are encrypted before writing to the database and decrypted after reading. SEM@b9272d08c168beb55fbc4db127cb1d4eec5f72c1: register the at-rest encryptor for setting values (mutates shared state)

type SettingsServiceInterface

type SettingsServiceInterface interface {
	Get(ctx context.Context, key string) (*models.SystemSetting, error)
	GetString(ctx context.Context, key string) (string, error)
	GetInt(ctx context.Context, key string) (int, error)
	GetBool(ctx context.Context, key string) (bool, error)
	List(ctx context.Context) ([]models.SystemSetting, error)
	ListByPrefix(ctx context.Context, prefix string) ([]models.SystemSetting, error)
	Set(ctx context.Context, setting *models.SystemSetting) error
	Delete(ctx context.Context, key string) error
	SeedDefaults(ctx context.Context) error
	ReEncryptAll(ctx context.Context, modifiedBy *string) (int, []SettingError, error)
}

SettingsServiceInterface defines the operations needed by handlers on settings. SEM@2ba6ca336dfda2b02702948deea087afc0b1255b: interface for reading, writing, and managing database-stored system settings

type SeverityQueryParam

type SeverityQueryParam = []string

SeverityQueryParam defines model for SeverityQueryParam.

type SkippedSource

type SkippedSource struct {
	// EntityId ID of the skipped entity
	EntityId openapi_types.UUID `json:"entity_id"`

	// Name Name of the skipped entity
	Name string `json:"name"`

	// Reason Why this entity was skipped
	Reason string `json:"reason"`
}

SkippedSource Describes an entity that was skipped during a source-refresh pipeline operation, including the reason it was excluded.

type SlidingWindowRateLimiter

type SlidingWindowRateLimiter struct {
	RedisClient *redis.Client
}

SlidingWindowRateLimiter provides shared sliding window rate limiting using Redis sorted sets. Domain-specific rate limiters embed this struct and add their own key-building and quota logic. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: shared Redis-backed sliding window rate limiter embeddable by domain limiters (mutates shared state)

func (*SlidingWindowRateLimiter) CheckSlidingWindow

func (sw *SlidingWindowRateLimiter) CheckSlidingWindow(ctx context.Context, key string, limit int, windowSeconds int) (bool, int, error)

CheckSlidingWindow implements sliding window rate limiting using Redis sorted sets. Returns allowed (bool), retryAfter (seconds), and error. SEM@914adca66ed5ce0bcfa6a1233361a298648ccf00: enforce a sliding window rate limit and return allowed status with retry-after seconds (mutates shared state)

func (*SlidingWindowRateLimiter) CheckSlidingWindowSimple

func (sw *SlidingWindowRateLimiter) CheckSlidingWindowSimple(ctx context.Context, key string, limit int, windowSeconds int) (bool, error)

CheckSlidingWindowSimple is a simplified variant that only returns allowed/not-allowed without retryAfter. Used by webhook rate limiting where retry-after info is not needed in the check itself. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: check a sliding window rate limit returning only allowed/denied without retry-after (mutates shared state)

func (*SlidingWindowRateLimiter) GetRateLimitInfo

func (sw *SlidingWindowRateLimiter) GetRateLimitInfo(ctx context.Context, key string, limit int, windowSeconds int) (int, int64, error)

GetRateLimitInfo returns current rate limit status for a key. Returns remaining count, resetAt timestamp, and error. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: fetch remaining quota and window reset timestamp for a rate limit key (reads DB)

func (*SlidingWindowRateLimiter) RecordInWindow

func (sw *SlidingWindowRateLimiter) RecordInWindow(ctx context.Context, key string, timestamp int64, ttlSeconds int) error

RecordInWindow records a timestamp in a sliding window without checking limits. SEM@914adca66ed5ce0bcfa6a1233361a298648ccf00: record a timestamped event in a sliding window without enforcing limits (mutates shared state)

type SortByQueryParam

type SortByQueryParam string

SortByQueryParam defines model for SortByQueryParam.

const (
	SortByQueryParamCreatedAt SortByQueryParam = "created_at"
	SortByQueryParamEmail     SortByQueryParam = "email"
	SortByQueryParamLastLogin SortByQueryParam = "last_login"
	SortByQueryParamName      SortByQueryParam = "name"
)

Defines values for SortByQueryParam.

func (SortByQueryParam) Valid

func (e SortByQueryParam) Valid() bool

Valid indicates whether the value is a known member of the SortByQueryParam enum.

type SortOrderQueryParam

type SortOrderQueryParam string

SortOrderQueryParam defines model for SortOrderQueryParam.

const (
	SortOrderQueryParamAsc  SortOrderQueryParam = "asc"
	SortOrderQueryParamDesc SortOrderQueryParam = "desc"
)

Defines values for SortOrderQueryParam.

func (SortOrderQueryParam) Valid

func (e SortOrderQueryParam) Valid() bool

Valid indicates whether the value is a known member of the SortOrderQueryParam enum.

type SortQueryParam

type SortQueryParam = string

SortQueryParam defines model for SortQueryParam.

type SourceSnapshotEntry

type SourceSnapshotEntry struct {
	EntityType string `json:"entity_type"`
	EntityID   string `json:"entity_id"`
	Name       string `json:"name"`
	URI        string `json:"uri,omitempty"`
}

SourceSnapshotEntry represents a single entity included in a Timmy session's source snapshot.

URI is set only for entities whose content lives at an external URL (today: documents). DB-resident entities (notes, assets, threats, repositories) leave it empty so the embedding registry routes them to DirectTextProvider rather than the URI-driven content pipeline. SEM@bd0bc10d5d1f787df91f432d9ae0dd6313a302c6: represents a threat-model entity included in a Timmy session source snapshot (pure)

type StartIdentityLinkParams

type StartIdentityLinkParams struct {
	// Idp The identity provider ID to link
	Idp string `form:"idp" json:"idp"`

	// ClientCallback The URL to redirect to after the provider returns. Must be in the allowlist.
	ClientCallback string `form:"client_callback" json:"client_callback"`
}

StartIdentityLinkParams defines parameters for StartIdentityLink.

type StateQueryParam

type StateQueryParam = string

StateQueryParam defines model for StateQueryParam.

type StatusQueryParam

type StatusQueryParam = []string

StatusQueryParam defines model for StatusQueryParam.

type StatusUpdatedAfterQueryParam

type StatusUpdatedAfterQueryParam = time.Time

StatusUpdatedAfterQueryParam defines model for StatusUpdatedAfterQueryParam.

type StatusUpdatedBeforeQueryParam

type StatusUpdatedBeforeQueryParam = time.Time

StatusUpdatedBeforeQueryParam defines model for StatusUpdatedBeforeQueryParam.

type StepUpAuditAdapter

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

StepUpAuditAdapter adapts a SystemAuditRepository to the auth package's SystemAuditWriter interface, mapping auth.SystemAuditRecord to models.SystemAuditEntry. Used exclusively by /oauth2/step_up (#397) so package auth can write system audit rows without importing package api. SEM@dd66d35bda6952fa6d623976b1adb6177685fe6d: adapter bridging auth.SystemAuditWriter to a SystemAuditRepository (pure)

func NewStepUpAuditAdapter

func NewStepUpAuditAdapter(repo SystemAuditRepository) *StepUpAuditAdapter

NewStepUpAuditAdapter constructs the adapter. SEM@13ccacf4852fae0cb6fc35e8197cb04b2a0df1e9: build a StepUpAuditAdapter wrapping a SystemAuditRepository (pure)

func (*StepUpAuditAdapter) WriteSystemAudit

func (a *StepUpAuditAdapter) WriteSystemAudit(ctx context.Context, rec auth.SystemAuditRecord) error

WriteSystemAudit implements auth.SystemAuditWriter. SEM@87d6f75bc3aecf3edd6c4103567546955c1afadf: convert an auth audit record to a DB model and persist it (writes DB)

type StepUpAuthenticate200JSONResponseBodyResult

type StepUpAuthenticate200JSONResponseBodyResult string

StepUpAuthenticate200JSONResponseBodyResult defines parameters for StepUpAuthenticate.

const (
	StepUpRedirect     StepUpAuthenticate200JSONResponseBodyResult = "step_up_redirect"
	StepUpWeakComplete StepUpAuthenticate200JSONResponseBodyResult = "step_up_weak_complete"
)

Defines values for StepUpAuthenticate200JSONResponseBodyResult.

func (StepUpAuthenticate200JSONResponseBodyResult) Valid

Valid indicates whether the value is a known member of the StepUpAuthenticate200JSONResponseBodyResult enum.

type StepUpAuthenticateParams

type StepUpAuthenticateParams struct {
	// ClientCallback Client callback URL where TMI should redirect after successful OAuth completion with tokens in URL fragment (#access_token=...). If not provided, tokens are returned as JSON response. Per OAuth 2.0 implicit flow spec, tokens are in fragments to prevent logging.
	ClientCallback *ClientCallbackQueryParam `form:"client_callback,omitempty" json:"client_callback,omitempty"`

	// State CSRF protection state parameter. Recommended for security. Will be included in the callback response.
	State *StateQueryParam `form:"state,omitempty" json:"state,omitempty"`

	// CodeChallenge PKCE code challenge (RFC 7636) - Base64url-encoded SHA256 hash of the code_verifier. Must be 43-128 characters using unreserved characters [A-Za-z0-9-._~]. The server associates this with the authorization code for later verification during token exchange.
	CodeChallenge CodeChallengeQueryParam `form:"code_challenge" json:"code_challenge"`

	// CodeChallengeMethod PKCE code challenge method (RFC 7636) - Specifies the transformation applied to the code_verifier. Only "S256" (SHA256) is supported for security. The "plain" method is not supported.
	CodeChallengeMethod StepUpAuthenticateParamsCodeChallengeMethod `form:"code_challenge_method" json:"code_challenge_method"`
}

StepUpAuthenticateParams defines parameters for StepUpAuthenticate.

type StepUpAuthenticateParamsCodeChallengeMethod

type StepUpAuthenticateParamsCodeChallengeMethod string

StepUpAuthenticateParamsCodeChallengeMethod defines parameters for StepUpAuthenticate.

Defines values for StepUpAuthenticateParamsCodeChallengeMethod.

func (StepUpAuthenticateParamsCodeChallengeMethod) Valid

Valid indicates whether the value is a known member of the StepUpAuthenticateParamsCodeChallengeMethod enum.

type StepUpRouteTable

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

StepUpRouteTable answers "does (method, route-template) require a fresh auth_time?" Built once at server boot from the OpenAPI spec; consulted per-request by StepUpMiddleware (#355).

Default policy: any /admin/* operation with a write method (POST/PUT/PATCH/ DELETE) requires step-up. Opt-out via x-tmi-authz-step-up: optional on the operation. Opt-in for any path/method: set x-tmi-authz-step-up: "required" on the operation. SEM@3c2ef72cc84c7ca336332105301ca560fd259567: lookup table mapping route method+path to step-up auth requirement (pure)

func BuildStepUpRouteTable

func BuildStepUpRouteTable(spec *openapi3.T) StepUpRouteTable

BuildStepUpRouteTable walks the OpenAPI spec and constructs the resolution table. Safe to call with a nil spec (returns an empty table).

Two mechanisms register a route:

  1. Opt-in (any path/method): operation carries x-tmi-authz-step-up: "required".
  2. Default (admin write methods): any /admin/* POST/PUT/PATCH/DELETE is required unless opted out via x-tmi-authz-step-up: "optional".

SEM@512260e3fe7e08b889b07b5644777571587d76fb: build step-up route table from OpenAPI spec using opt-in and admin-write defaults (pure)

func (StepUpRouteTable) Required

func (t StepUpRouteTable) Required(method, path string) bool

Required reports whether the given (method, path-template) requires a fresh auth_time per the step-up policy. SEM@3c2ef72cc84c7ca336332105301ca560fd259567: report whether a route requires fresh step-up authentication (pure)

type SubResourceTestFixtures

type SubResourceTestFixtures struct {
	// Test users for authorization
	OwnerUser    string
	WriterUser   string
	ReaderUser   string
	ExternalUser string // User with no access

	// Test threat model
	ThreatModel   ThreatModel
	ThreatModelID string

	// Test threats
	Threat1   Threat
	Threat1ID string
	Threat2   Threat
	Threat2ID string

	// Test documents
	Document1   Document
	Document1ID string
	Document2   Document
	Document2ID string

	// Test repositories
	Repository1   Repository
	Repository1ID string
	Repository2   Repository
	Repository2ID string

	// Test metadata
	ThreatMetadata1     Metadata
	ThreatMetadata2     Metadata
	DocumentMetadata1   Metadata
	DocumentMetadata2   Metadata
	RepositoryMetadata1 Metadata
	RepositoryMetadata2 Metadata
	DiagramMetadata1    Metadata
	DiagramMetadata2    Metadata

	// Test diagram for cell testing
	Diagram   DfdDiagram
	DiagramID string
	Cell1     DfdDiagram_Cells_Item
	Cell1ID   string
	Cell2     DfdDiagram_Cells_Item
	Cell2ID   string

	// Authorization data
	Authorization []Authorization

	// Initialization flag
	Initialized bool
}

SubResourceTestFixtures provides comprehensive test data for sub-resource testing SEM@98c83c6a9092288eead710533517e486c44239b2: data container holding all pre-built entities and authorization data for sub-resource tests (pure)

var SubResourceFixtures SubResourceTestFixtures

type SubjectAuthority

type SubjectAuthority string

SubjectAuthority constrains which kind of authenticated principal can satisfy a route's gate. Default ("any") is the legacy behavior; "invoker" rejects service-account-only tokens (T18, #358) and is paired with the addon-invocation delegation token in api/delegation_token_issuer.go; "service_account" requires an SA token (rare; reserved for SA-internal endpoints). SEM@e2de7c62a484c8859b1f6760addcf1b628ec49bb: enum constraining which authenticated principal type satisfies a route gate (pure)

const (
	SubjectAuthorityAny            SubjectAuthority = ""
	SubjectAuthorityInvoker        SubjectAuthority = "invoker"
	SubjectAuthorityServiceAccount SubjectAuthority = "service_account"
)

type SubscriptionIdQueryParam

type SubscriptionIdQueryParam = openapi_types.UUID

SubscriptionIdQueryParam defines model for SubscriptionIdQueryParam.

type Survey

type Survey struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// CreatedBy Administrator who created the survey
	CreatedBy *User `json:"created_by,omitempty"`

	// Description Description of the survey and its purpose
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the survey (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name of the survey
	Name string `binding:"required" json:"name"`

	// Settings Configuration settings for a survey
	Settings *SurveySettings `json:"settings,omitempty"`

	// Status Survey status: active surveys appear in intake, inactive are hidden but editable, archived are read-only and preserved for historical reference
	Status *string `json:"status,omitempty"`

	// SurveyJson Complete SurveyJS JSON definition. Opaque to the server; validated only for top-level structure (must contain a pages array).
	SurveyJson map[string]interface{} `binding:"required" json:"survey_json"`

	// Version Custom version string (e.g., '2024-Q1', 'v2-pilot')
	Version string `binding:"required" json:"version"`
}

Survey defines model for Survey.

type SurveyAnswerRow

type SurveyAnswerRow struct {
	ID             string
	ResponseID     string
	QuestionName   string
	QuestionType   string
	QuestionTitle  *string
	MapsToTmField  *string
	AnswerValue    json.RawMessage // nil when no answer was provided
	ResponseStatus string
	CreatedAt      time.Time
}

SurveyAnswerRow is the API-layer representation of a stored survey answer. AnswerValue is nil when the respondent did not answer the question. SEM@851a41a40d0b86e1ef600270d09c44cd95ac25d7: API-layer record holding a single stored survey answer with question metadata (pure)

type SurveyAnswerStore

type SurveyAnswerStore interface {
	// ExtractAndSave extracts questions from surveyJSON using ExtractQuestions,
	// pairs each with its answer from the answers map, and atomically replaces
	// all existing answers for responseID with the new set.
	ExtractAndSave(ctx context.Context, responseID string, surveyJSON map[string]any, answers map[string]any, responseStatus string) error

	// GetAnswers returns all answer rows for a response, in insertion order.
	GetAnswers(ctx context.Context, responseID string) ([]SurveyAnswerRow, error)

	// GetFieldMappings returns a map of tmField -> SurveyAnswerRow for all answers
	// whose question has a non-nil MapsToTmField.
	GetFieldMappings(ctx context.Context, responseID string) (map[string]SurveyAnswerRow, error)

	// DeleteByResponseID removes all answer rows for a response.
	DeleteByResponseID(ctx context.Context, responseID string) error
}

SurveyAnswerStore defines operations for persisting extracted survey answers. Answers are fully replaced on every call to ExtractAndSave (atomic delete+insert). SEM@851a41a40d0b86e1ef600270d09c44cd95ac25d7: interface for atomically persisting and fetching extracted survey answers (reads/writes DB)

var GlobalSurveyAnswerStore SurveyAnswerStore

type SurveyBase

type SurveyBase struct {
	// Description Description of the survey and its purpose
	Description *string `json:"description,omitempty"`

	// Name Name of the survey
	Name string `binding:"required" json:"name"`

	// Settings Configuration settings for a survey
	Settings *SurveySettings `json:"settings,omitempty"`

	// Status Survey status: active surveys appear in intake, inactive are hidden but editable, archived are read-only and preserved for historical reference
	Status *string `json:"status,omitempty"`

	// SurveyJson Complete SurveyJS JSON definition. Opaque to the server; validated only for top-level structure (must contain a pages array).
	SurveyJson map[string]interface{} `binding:"required" json:"survey_json"`

	// Version Custom version string (e.g., '2024-Q1', 'v2-pilot')
	Version string `binding:"required" json:"version"`
}

SurveyBase Base schema for Survey with client-writable fields

type SurveyId

type SurveyId = openapi_types.UUID

SurveyId defines model for SurveyId.

type SurveyIdQueryParam

type SurveyIdQueryParam = openapi_types.UUID

SurveyIdQueryParam defines model for SurveyIdQueryParam.

type SurveyInput

type SurveyInput = SurveyBase

SurveyInput Base schema for Survey with client-writable fields

type SurveyListItem

type SurveyListItem struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt time.Time `json:"created_at"`

	// CreatedBy Administrator who created the survey
	CreatedBy *User `json:"created_by,omitempty"`

	// Description Description of the survey
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the survey (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name of the survey
	Name string `json:"name"`

	// Status Survey status
	Status string `json:"status"`

	// Version Version string
	Version string `json:"version"`
}

SurveyListItem Summary of a survey for list responses

type SurveyQuestion

type SurveyQuestion struct {
	Name          string
	Type          string
	Title         *string
	MapsToTmField *string
}

SurveyQuestion represents a leaf question extracted from SurveyJS JSON. SEM@b77f3240790e1d94ed81a805538c9ba9c334b6c3: leaf question extracted from a SurveyJS survey with its field-mapping metadata (pure)

func ExtractQuestions

func ExtractQuestions(surveyJSON map[string]any, logger *slogging.Logger) ([]SurveyQuestion, error)

ExtractQuestions recursively extracts leaf questions from a SurveyJS survey_json object. Returns an error if the JSON structure is invalid or duplicate mapsToTmField values are found. Pass nil for logger to suppress warnings about skipped elements. SEM@b77f3240790e1d94ed81a805538c9ba9c334b6c3: parse all leaf questions from a SurveyJS JSON object, rejecting duplicate field mappings (pure)

type SurveyResponse

type SurveyResponse struct {
	// Answers Question answers keyed by question name. Values can be any JSON type to support all SurveyJS question types including dynamic panels (arrays of objects), matrix questions (objects of objects), and scalar values (strings, numbers, booleans).
	Answers *map[string]interface{} `json:"answers,omitempty"`

	// Authorization List of users and groups with access to this response
	Authorization *[]Authorization `json:"authorization,omitempty"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// CreatedBy User who created the response
	CreatedBy *User `json:"created_by,omitempty"`

	// CreatedThreatModelId ID of threat model created from this response
	CreatedThreatModelId *openapi_types.UUID `json:"created_threat_model_id,omitempty"`

	// Id Unique identifier for the response (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IsConfidential Whether Security Reviewers group was excluded (set at creation, read-only after)
	IsConfidential *bool `json:"is_confidential,omitempty"`

	// LinkedThreatModelId Optional link to existing threat model for re-reviews
	LinkedThreatModelId *openapi_types.UUID `json:"linked_threat_model_id,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Owner User who created the response
	Owner *User `json:"owner,omitempty"`

	// ProjectId Optional reference to the project this survey response belongs to
	ProjectId *openapi_types.UUID `json:"project_id,omitempty"`

	// ReviewedAt When the response was last reviewed
	ReviewedAt *time.Time `json:"reviewed_at,omitempty"`

	// ReviewedBy Security engineer who last reviewed the response
	ReviewedBy *User `json:"reviewed_by,omitempty"`

	// RevisionNotes Notes from security reviewer when returning for revision
	RevisionNotes *string `json:"revision_notes,omitempty"`

	// Status Current status of the survey response in the triage workflow
	Status *string `json:"status,omitempty"`

	// SubmittedAt When the response was submitted for review
	SubmittedAt *time.Time `json:"submitted_at,omitempty"`

	// SurveyId ID of the survey this response is based on
	SurveyId openapi_types.UUID `binding:"required" json:"survey_id"`

	// SurveyJson Snapshot of the survey survey_json at the time this response was created. Used to render historical responses against the correct survey version.
	SurveyJson *map[string]interface{} `json:"survey_json,omitempty"`

	// SurveyVersion Survey version captured at creation time - responses always complete on the original version
	SurveyVersion *string `json:"survey_version,omitempty"`

	// UiState Client-managed UI state for draft resumption (e.g., current page, scroll position). Cleared on submission.
	UiState *map[string]interface{} `json:"ui_state,omitempty"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

SurveyResponse defines model for SurveyResponse.

func RequireSurveyResponseAccess

func RequireSurveyResponseAccess(
	c *gin.Context,
	surveyResponseID SurveyResponseId,
	requiredRole AuthorizationRole,
) (*SurveyResponse, bool)

RequireSurveyResponseAccess centralizes the existence check + access check for survey-response sub-resources. It is the single enforcement point for the four-question authorization decision on /intake/survey_responses/* and /triage/survey_responses/* paths.

On success, it returns the loaded survey response. On any failure (not found, access denied, internal error) it writes the appropriate error to the Gin context and returns (nil, false). Callers must return immediately when the second return is false.

Confidentiality / existence-disclosure rule (T5, #357): To avoid leaking the existence of a survey response that the caller cannot read, both "not found" and "access denied" surface as 404. A leaking 403 would let an attacker probe UUIDs to learn which survey responses exist.

Authorization model: Survey responses have their own per-row ACL stored in `survey_response_access`. The store's HasAccess(...) method evaluates the caller's direct grants AND group memberships against the required role (reader / writer / owner) using the standard role hierarchy (owner > writer > reader). This helper is a thin wrapper that adds the existence check and unifies the response shape so handlers do not duplicate the load + check + 403/404 dance and do not accidentally diverge on the disclosure question. SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: authorize a caller's access to a survey response and return it, emitting 404 on denial to avoid existence disclosure (reads DB)

type SurveyResponseBase

type SurveyResponseBase struct {
	// Answers Question answers keyed by question name. Values can be any JSON type to support all SurveyJS question types including dynamic panels (arrays of objects), matrix questions (objects of objects), and scalar values (strings, numbers, booleans).
	Answers *map[string]interface{} `json:"answers,omitempty"`

	// Authorization List of users and groups with access to this response
	Authorization *[]Authorization `json:"authorization,omitempty"`

	// LinkedThreatModelId Optional link to existing threat model for re-reviews
	LinkedThreatModelId *openapi_types.UUID `json:"linked_threat_model_id,omitempty"`

	// ProjectId Optional reference to the project this survey response belongs to
	ProjectId *openapi_types.UUID `json:"project_id,omitempty"`

	// SurveyId ID of the survey this response is based on
	SurveyId openapi_types.UUID `binding:"required" json:"survey_id"`

	// SurveyVersion Survey version captured at creation time - responses always complete on the original version
	SurveyVersion *string `json:"survey_version,omitempty"`

	// UiState Client-managed UI state for draft resumption (e.g., current page, scroll position). Cleared on submission.
	UiState *map[string]interface{} `json:"ui_state,omitempty"`
}

SurveyResponseBase Base schema for SurveyResponse with client-writable fields

type SurveyResponseCreateRequest

type SurveyResponseCreateRequest struct {
	// Answers Question answers keyed by question name. Values can be any JSON type to support all SurveyJS question types including dynamic panels (arrays of objects), matrix questions (objects of objects), and scalar values (strings, numbers, booleans).
	Answers *map[string]interface{} `json:"answers,omitempty"`

	// Authorization List of users and groups with access to this response
	Authorization *[]Authorization `json:"authorization,omitempty"`

	// IsConfidential If true, Security Reviewers group is NOT auto-added. Can only be set at creation.
	IsConfidential *bool `json:"is_confidential,omitempty"`

	// LinkedThreatModelId Optional link to existing threat model for re-reviews
	LinkedThreatModelId *openapi_types.UUID `json:"linked_threat_model_id,omitempty"`

	// ProjectId Optional reference to the project this survey response belongs to
	ProjectId *openapi_types.UUID `json:"project_id,omitempty"`

	// SurveyId ID of the survey this response is based on
	SurveyId openapi_types.UUID `binding:"required" json:"survey_id"`

	// SurveyVersion Survey version captured at creation time - responses always complete on the original version
	SurveyVersion *string `json:"survey_version,omitempty"`

	// UiState Client-managed UI state for draft resumption (e.g., current page, scroll position). Cleared on submission.
	UiState *map[string]interface{} `json:"ui_state,omitempty"`
}

SurveyResponseCreateRequest defines model for SurveyResponseCreateRequest.

type SurveyResponseFilters

type SurveyResponseFilters struct {
	Status   *string
	SurveyID *uuid.UUID
	OwnerID  *string
}

SurveyResponseFilters defines filter options for listing responses SEM@0bd9c0e0e0c0649294d164b9dc945b801cfd507c: filter parameters for listing survey responses by status, survey, or owner (pure)

type SurveyResponseId

type SurveyResponseId = openapi_types.UUID

SurveyResponseId defines model for SurveyResponseId.

type SurveyResponseInput

type SurveyResponseInput = SurveyResponseBase

SurveyResponseInput Base schema for SurveyResponse with client-writable fields

type SurveyResponseListItem

type SurveyResponseListItem struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt time.Time `json:"created_at"`

	// Id Unique identifier for the response (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IsConfidential Whether this is a secret project (no auto Security Reviewers access)
	IsConfidential *bool `json:"is_confidential,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Owner User who created the response
	Owner *User `json:"owner,omitempty"`

	// Status Current status of the survey response
	Status string `json:"status"`

	// SubmittedAt When the response was submitted
	SubmittedAt *time.Time `json:"submitted_at,omitempty"`

	// SurveyId ID of the survey
	SurveyId openapi_types.UUID `json:"survey_id"`

	// SurveyName Name of the survey
	SurveyName *string `json:"survey_name,omitempty"`

	// SurveyVersion Version of the survey
	SurveyVersion *string `json:"survey_version,omitempty"`
}

SurveyResponseListItem Summary of a survey response for list endpoints

func FilterSurveyResponseListItemsByAccess

func FilterSurveyResponseListItemsByAccess(
	ctx context.Context,
	userInternalUUID string,
	items []SurveyResponseListItem,
	requiredRole AuthorizationRole,
) []SurveyResponseListItem

FilterSurveyResponseListItemsByAccess narrows a list of survey-response list items to only those the caller can read. Used by triage/intake list endpoints where the underlying store query does not enforce per-row ACL (e.g. ListTriageSurveyResponses, which intentionally does not filter by owner).

This is an in-memory filter against the same HasAccess(...) the per-row handlers use, so list and per-row decisions stay in sync. The returned total reflects the filtered count, so pagination metadata never leaks the existence of confidential responses the caller cannot read (matching the list-leak acceptance criterion in #357). SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: filter a list of survey response items to only those the caller can read, without leaking existence of others (reads DB)

type SurveyResponseStatusQueryParam

type SurveyResponseStatusQueryParam = string

SurveyResponseStatusQueryParam defines model for SurveyResponseStatusQueryParam.

type SurveyResponseStore

type SurveyResponseStore interface {
	// CRUD operations
	Create(ctx context.Context, response *SurveyResponse, userInternalUUID string) error
	Get(ctx context.Context, id uuid.UUID) (*SurveyResponse, error)
	Update(ctx context.Context, response *SurveyResponse) error
	Delete(ctx context.Context, id uuid.UUID) error

	// List operations with pagination and filtering
	List(ctx context.Context, limit, offset int, filters *SurveyResponseFilters) ([]SurveyResponseListItem, int, error)

	// List responses for a specific owner
	ListByOwner(ctx context.Context, ownerInternalUUID string, limit, offset int, status *string) ([]SurveyResponseListItem, int, error)

	// State transition
	UpdateStatus(ctx context.Context, id uuid.UUID, newStatus string, reviewerInternalUUID *string, revisionNotes *string) error

	// Authorization operations
	GetAuthorization(ctx context.Context, id uuid.UUID) ([]Authorization, error)
	UpdateAuthorization(ctx context.Context, id uuid.UUID, authorization []Authorization) error

	// Check access
	HasAccess(ctx context.Context, id uuid.UUID, userInternalUUID string, requiredRole AuthorizationRole) (bool, error)

	// SetCreatedThreatModel atomically sets created_threat_model_id and transitions
	// status to review_created. Returns an error if the response is not in
	// ready_for_review status (optimistic concurrency guard).
	SetCreatedThreatModel(ctx context.Context, id uuid.UUID, threatModelID string) error
}

SurveyResponseStore defines the interface for survey response operations SEM@631be7f2c07ebbeba8f94b4c3e8e7e523b41118e: interface defining CRUD, listing, status-transition, and authorization operations for survey responses

var GlobalSurveyResponseStore SurveyResponseStore

type SurveySettings

type SurveySettings struct {
	// AllowThreatModelLinking Whether responses can link to existing threat models for re-reviews
	AllowThreatModelLinking *bool `json:"allow_threat_model_linking,omitempty"`
}

SurveySettings Configuration settings for a survey

type SurveyStatusQueryParam

type SurveyStatusQueryParam = string

SurveyStatusQueryParam defines model for SurveyStatusQueryParam.

type SurveyStore

type SurveyStore interface {
	// CRUD operations
	Create(ctx context.Context, survey *Survey, userInternalUUID string) error
	Get(ctx context.Context, id uuid.UUID) (*Survey, error)
	Update(ctx context.Context, survey *Survey) error
	Delete(ctx context.Context, id uuid.UUID) error

	// ForceDelete removes a survey together with all of its responses and their
	// sub-resources (used by the admin force-delete path).
	ForceDelete(ctx context.Context, id uuid.UUID) error

	// List operations with pagination and filtering
	List(ctx context.Context, limit, offset int, status *string) ([]SurveyListItem, int, error)

	// List active surveys only (for intake endpoints)
	ListActive(ctx context.Context, limit, offset int) ([]SurveyListItem, int, error)

	// Check if survey has responses (for delete validation)
	HasResponses(ctx context.Context, id uuid.UUID) (bool, error)
}

SurveyStore defines the interface for survey operations SEM@0bd9c0e0e0c0649294d164b9dc945b801cfd507c: interface for CRUD and list operations on survey templates (reads/writes DB)

var GlobalSurveyStore SurveyStore

type SyncRequestHandler

type SyncRequestHandler struct{}

SyncRequestHandler handles sync request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: WebSocket handler that dispatches sync_request messages to the diagram session

func (*SyncRequestHandler) HandleMessage

func (h *SyncRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: dispatch a sync_request to the session with panic recovery

func (*SyncRequestHandler) MessageType

func (h *SyncRequestHandler) MessageType() string

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: return the sync_request message type identifier (pure)

type SyncRequestMessage

type SyncRequestMessage struct {
	MessageType  MessageType `json:"message_type"`
	UpdateVector *int64      `json:"update_vector,omitempty"` // Client's current vector, nil means "send everything"
}

SyncRequestMessage is sent by client to request full state if stale SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: client-to-server WebSocket message requesting full diagram state when client is stale (pure)

func (SyncRequestMessage) GetMessageType

func (m SyncRequestMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for SyncRequestMessage (pure)

func (SyncRequestMessage) Validate

func (m SyncRequestMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a SyncRequestMessage has correct type and non-negative update vector if set (pure)

type SyncStatusRequestHandler

type SyncStatusRequestHandler struct{}

SyncStatusRequestHandler handles sync status request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: WebSocket handler that dispatches sync_status_request messages to the diagram session

func (*SyncStatusRequestHandler) HandleMessage

func (h *SyncStatusRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: dispatch a sync_status_request to the session with panic recovery

func (*SyncStatusRequestHandler) MessageType

func (h *SyncStatusRequestHandler) MessageType() string

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: return the sync_status_request message type identifier (pure)

type SyncStatusRequestMessage

type SyncStatusRequestMessage struct {
	MessageType MessageType `json:"message_type"`
}

SyncStatusRequestMessage is sent by client to check server's current update vector SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: client-to-server WebSocket message requesting the server's current update vector (pure)

func (SyncStatusRequestMessage) GetMessageType

func (m SyncStatusRequestMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for SyncStatusRequestMessage (pure)

func (SyncStatusRequestMessage) Validate

func (m SyncStatusRequestMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a SyncStatusRequestMessage has the expected message type (pure)

type SyncStatusResponseMessage

type SyncStatusResponseMessage struct {
	MessageType  MessageType `json:"message_type"`
	UpdateVector int64       `json:"update_vector"`
}

SyncStatusResponseMessage is sent by server with current update vector SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: server-to-client WebSocket response carrying the current diagram update vector (pure)

func (SyncStatusResponseMessage) GetMessageType

func (m SyncStatusResponseMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for SyncStatusResponseMessage (pure)

func (SyncStatusResponseMessage) Validate

func (m SyncStatusResponseMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate a SyncStatusResponseMessage has correct type and non-negative update vector (pure)

type SystemAuditEntry

type SystemAuditEntry struct {
	// Actor Denormalized user information stored with audit entries. Persists after user deletion.
	Actor AuditActor `json:"actor"`

	// ChangeSummary Human-readable change summary.
	ChangeSummary *string `json:"change_summary,omitempty"`

	// CreatedAt When the audited write completed.
	CreatedAt time.Time `json:"created_at"`

	// FieldPath Dotted path of the changed field.
	FieldPath string `json:"field_path"`

	// HttpMethod HTTP method of the audited request.
	HttpMethod string `json:"http_method"`

	// HttpPath Request path of the audited request.
	HttpPath string `json:"http_path"`

	// Id Entry identifier.
	Id openapi_types.UUID `json:"id"`

	// NewValueRedacted New value, redacted at write time.
	NewValueRedacted *string `json:"new_value_redacted,omitempty"`

	// OldValueRedacted Previous value, redacted at write time.
	OldValueRedacted *string `json:"old_value_redacted,omitempty"`
}

SystemAuditEntry An immutable system-level audit record of a successful /admin/* write (T7 evidence). Old/new values are redacted at write time.

type SystemAuditFilter

type SystemAuditFilter struct {
	ActorEmail    *string
	ActorProvider *string
	CreatedAfter  *time.Time
	CreatedBefore *time.Time
	HTTPMethod    *string
	PathPrefix    *string // matched as LIKE '<escaped>%' ESCAPE '\'
	FieldPath     *string
	Limit         int
	Cursor        *auditCursor
}

SystemAuditFilter carries the admin query dimensions for system audit entries (#398). All filter fields are optional and AND-combined. SEM@36f789f9e7fb93d8201a7ff2ce6a132a2a6dce47: carry optional AND-combined filter dimensions for querying system audit entries (pure)

type SystemAuditRepository

type SystemAuditRepository interface {
	Create(ctx context.Context, entry models.SystemAuditEntry) error
	ListByActor(ctx context.Context, actorEmail string, from, to time.Time) ([]models.SystemAuditEntry, error)
	// List returns entries matching the filter, newest first, with bidirectional
	// keyset pagination. Returns (page, total matching the filter, prev cursor,
	// next cursor). Cursors are nil when no further rows exist that direction
	// (#398, #464).
	List(ctx context.Context, f SystemAuditFilter) ([]models.SystemAuditEntry, int, *string, *string, error)
	// Around returns a page of f.Limit entries centered on anchorID (~half newer,
	// ~half older). Returns errAuditAnchorNotFound when the id is unknown (#464).
	Around(ctx context.Context, f SystemAuditFilter, anchorID string) ([]models.SystemAuditEntry, int, *string, *string, error)
	// StreamFiltered keyset-iterates the entire filtered set newest-first in
	// batches of `batch`, invoking fn per batch until exhausted. Ignores
	// f.Limit/f.Cursor. Used by CSV/NDJSON export (#464).
	StreamFiltered(ctx context.Context, f SystemAuditFilter, batch int, fn func([]models.SystemAuditEntry) error) error
	// GetByID returns the entry or nil when not found.
	GetByID(ctx context.Context, id string) (*models.SystemAuditEntry, error)
}

SystemAuditRepository is the data-access surface for system_audit_entries. Read methods are minimal in Part 1 of #355 — the full read API is tracked in #398. Part 1 needs Create (write path) and ListByActor (test verification + lightweight investigator query). SEM@f12e77c453fd57852ba9396c20645e34e8c16784: data-access interface for system audit entries with keyset pagination and streaming

func NewAlertingSystemAuditRepository

func NewAlertingSystemAuditRepository(
	inner SystemAuditRepository,
	emitter auditAlertEmitter,
	operatorName string,
) SystemAuditRepository

NewAlertingSystemAuditRepository wraps inner with an alerting decorator that emits EventSystemAuditAdminWrite after every successful Create. SEM@2f7a2f21d458c7aaf4b361657372e56563f72390: build a SystemAuditRepository decorator that emits admin-write alerts after Create (pure)

func NewSystemAuditRepository

func NewSystemAuditRepository(db *gorm.DB) SystemAuditRepository

NewSystemAuditRepository constructs a GORM-backed SystemAuditRepository. SEM@17032cb417037389f68b10b92286265bafbec4dd: build a GORM-backed SystemAuditRepository from a database connection (pure)

type SystemHealthResult

type SystemHealthResult struct {
	Database ComponentHealthResult
	Redis    ComponentHealthResult
	Overall  ApiInfoStatusCode
}

SystemHealthResult holds health check results for all components SEM@5775fac65ab5239fc263439d133089dda83af787: aggregate health result for all system components with an overall status code (pure)

type SystemNotificationData

type SystemNotificationData struct {
	Severity       string `json:"severity"` // info, warning, error, critical
	Message        string `json:"message"`
	ActionRequired bool   `json:"action_required"`
	ActionURL      string `json:"action_url,omitempty"`
}

SystemNotificationData contains data for system notifications SEM@66b1e1515b82356913c8625edc8616772c3c70d3: payload for system-wide announcements with severity and optional action URL (pure)

type SystemSetting

type SystemSetting struct {
	// Description Human-readable description of the setting
	Description *string `json:"description,omitempty"`

	// Key Unique setting identifier using dot notation (e.g., rate_limit.requests_per_minute)
	Key string `json:"key"`

	// ModifiedAt When the setting was last modified
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// ModifiedBy UUID of the user who last modified the setting
	ModifiedBy *openapi_types.UUID `json:"modified_by,omitempty"`

	// ReadOnly Whether this setting can be modified via the API. True when source is not database.
	ReadOnly *bool `json:"read_only,omitempty"`

	// Source Where the effective value of this setting comes from. Server-managed, not writable.
	Source *SystemSettingSource `json:"source,omitempty"`

	// Type Data type of the setting value
	Type SystemSettingType `json:"type"`

	// Value Setting value as a string (interpreted based on type)
	Value string `json:"value"`
}

SystemSetting A system-wide configuration setting

type SystemSettingReader

type SystemSettingReader interface {
	Read(c *gin.Context, key string) string
}

SystemSettingReader is a narrow interface implemented by the system-settings store; the descriptor table uses it to read the current value before a write. SEM@9145716fc603b05b80fc2f976dec74110f64abcb: narrow interface for reading a system setting value by key before an admin write

type SystemSettingSource

type SystemSettingSource string

SystemSettingSource Where the effective value of this setting comes from. Server-managed, not writable.

const (
	Config      SystemSettingSource = "config"
	Database    SystemSettingSource = "database"
	Environment SystemSettingSource = "environment"
	Vault       SystemSettingSource = "vault"
)

Defines values for SystemSettingSource.

func (SystemSettingSource) Valid

func (e SystemSettingSource) Valid() bool

Valid indicates whether the value is a known member of the SystemSettingSource enum.

type SystemSettingType

type SystemSettingType string

SystemSettingType Data type of the setting value

const (
	SystemSettingTypeBool   SystemSettingType = "bool"
	SystemSettingTypeInt    SystemSettingType = "int"
	SystemSettingTypeJson   SystemSettingType = "json"
	SystemSettingTypeString SystemSettingType = "string"
)

Defines values for SystemSettingType.

func (SystemSettingType) Valid

func (e SystemSettingType) Valid() bool

Valid indicates whether the value is a known member of the SystemSettingType enum.

type SystemSettingUpdate

type SystemSettingUpdate struct {
	// Description Human-readable description of the setting
	Description *string `json:"description,omitempty"`

	// Type Data type of the setting value
	Type SystemSettingUpdateType `json:"type"`

	// Value Setting value as a string (interpreted based on type)
	Value string `json:"value"`
}

SystemSettingUpdate Request body for creating or updating a system setting

type SystemSettingUpdateType

type SystemSettingUpdateType string

SystemSettingUpdateType Data type of the setting value

const (
	Bool   SystemSettingUpdateType = "bool"
	Int    SystemSettingUpdateType = "int"
	Json   SystemSettingUpdateType = "json"
	String SystemSettingUpdateType = "string"
)

Defines values for SystemSettingUpdateType.

func (SystemSettingUpdateType) Valid

func (e SystemSettingUpdateType) Valid() bool

Valid indicates whether the value is a known member of the SystemSettingUpdateType enum.

type TMListItem

type TMListItem struct {
	// Alias Server-assigned monotonically-increasing integer alias, globally unique across all threat models. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// AssetCount Number of assets associated with this threat model
	AssetCount int `json:"asset_count"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt time.Time `json:"created_at"`

	// CreatedBy User who created the threat model
	CreatedBy User `json:"created_by"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of the threat model
	Description *string `json:"description,omitempty"`

	// DiagramCount Number of diagrams associated with this threat model
	DiagramCount int `json:"diagram_count"`

	// DocumentCount Number of documents associated with this threat model
	DocumentCount int `json:"document_count"`

	// Id Unique identifier of the threat model (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IssueUri URL to an issue in an issue tracking system
	IssueUri *string `json:"issue_uri,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt time.Time `json:"modified_at"`

	// Name Name of the threat model
	Name string `json:"name"`

	// NoteCount Number of notes associated with this threat model
	NoteCount int `json:"note_count"`

	// Owner User who owns the threat model
	Owner User `json:"owner"`

	// RepoCount Number of source code repository entries associated with this threat model
	RepoCount int `json:"repo_count"`

	// SecurityReviewer Security reviewer assigned to this threat model. The assigned security reviewer automatically has the owner role on this threat model.
	SecurityReviewer *User `json:"security_reviewer,omitempty"`

	// Status Status of the threat model in the organization's threat modeling or SDLC process. Examples: "not_started", "in_progress", "pending_review", "approved", "closed". Defaults to "not_started" on create.
	Status *string `json:"status,omitempty"`

	// StatusUpdated Timestamp when the status field was last modified (RFC3339). Automatically updated by the server when status changes.
	StatusUpdated *time.Time `json:"status_updated,omitempty"`

	// ThreatCount Number of threats defined in this threat model
	ThreatCount int `json:"threat_count"`

	// ThreatModelFramework The framework used for this threat model
	ThreatModelFramework string `json:"threat_model_framework"`
}

TMListItem Enhanced item for threat model list endpoints with key metadata and counts

type Team

type Team struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// CreatedBy User who created the team
	CreatedBy *User `json:"created_by,omitempty"`

	// Description Team description
	Description *string `json:"description,omitempty"`

	// EmailAddress Team email address
	EmailAddress *openapi_types.Email `json:"email_address,omitempty"`

	// Id Unique identifier for the team (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// Members List of team members with their roles
	Members *[]TeamMember `json:"members,omitempty"`

	// Metadata Optional metadata key-value pairs
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// ModifiedBy User who last modified the team
	ModifiedBy *User `json:"modified_by,omitempty"`

	// Name Team name
	Name string `json:"name"`

	// Notes List of notes associated with the team
	Notes *[]TeamNoteListItem `json:"notes,omitempty"`

	// RelatedTeams Relationships to other teams
	RelatedTeams *[]RelatedTeam `json:"related_teams,omitempty"`

	// ResponsibleParties Responsible parties for this team (in lieu of owner)
	ResponsibleParties *[]ResponsibleParty `json:"responsible_parties,omitempty"`

	// ReviewedAt Last review timestamp (RFC3339)
	ReviewedAt *time.Time `json:"reviewed_at,omitempty"`

	// ReviewedBy User who last reviewed the team
	ReviewedBy *User `json:"reviewed_by,omitempty"`

	// Status Team lifecycle status. Defaults to 'active' if not provided or set to null.
	Status *TeamStatus `json:"status,omitempty"`

	// Uri URL or reference to internal team page
	Uri *string `json:"uri,omitempty"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

Team defines model for Team.

type TeamBase

type TeamBase struct {
	// Description Team description
	Description *string `json:"description,omitempty"`

	// EmailAddress Team email address
	EmailAddress *openapi_types.Email `json:"email_address,omitempty"`

	// Members List of team members with their roles
	Members *[]TeamMember `json:"members,omitempty"`

	// Name Team name
	Name string `json:"name"`

	// RelatedTeams Relationships to other teams
	RelatedTeams *[]RelatedTeam `json:"related_teams,omitempty"`

	// ResponsibleParties Responsible parties for this team (in lieu of owner)
	ResponsibleParties *[]ResponsibleParty `json:"responsible_parties,omitempty"`

	// Status Team lifecycle status. Defaults to 'active' if not provided or set to null.
	Status *TeamStatus `json:"status,omitempty"`

	// Uri URL or reference to internal team page
	Uri *string `json:"uri,omitempty"`
}

TeamBase Client-writable fields for a team

type TeamFilters

type TeamFilters struct {
	Name         *string
	Status       []string
	MemberUserID *string
	RelatedTo    *string
	Relationship *string
	Transitive   *bool
}

TeamFilters defines filtering criteria for listing teams SEM@8c7929da791c778ff88713684c47aa2a10911bba: filtering criteria for listing teams by name, status, member, or relationship (pure)

type TeamInput

type TeamInput = TeamBase

TeamInput Client-writable fields for a team

type TeamListItem

type TeamListItem struct {
	CreatedAt   time.Time          `json:"created_at"`
	Description *string            `json:"description,omitempty"`
	Id          openapi_types.UUID `json:"id"`

	// MemberCount Number of team members
	MemberCount *int       `json:"member_count,omitempty"`
	ModifiedAt  *time.Time `json:"modified_at,omitempty"`
	Name        string     `json:"name"`

	// NoteCount Number of notes associated with this team
	NoteCount *int `json:"note_count,omitempty"`

	// ProjectCount Number of projects associated with this team
	ProjectCount *int `json:"project_count,omitempty"`

	// Status Team lifecycle status. Defaults to 'active' if not provided or set to null.
	Status *TeamStatus `json:"status,omitempty"`
}

TeamListItem Summary of a team for list views

type TeamMember

type TeamMember struct {
	// CustomRole Custom role description when role is 'other'
	CustomRole *string `json:"custom_role,omitempty"`

	// Role Role of a team member or responsible party
	Role *TeamMemberRole `json:"role,omitempty"`

	// User Resolved user details (read-only, populated by server)
	User *User `json:"user,omitempty"`

	// UserId UUID of the team member user
	UserId openapi_types.UUID `json:"user_id"`
}

TeamMember A member of a team with their role

type TeamMemberRole

type TeamMemberRole string

TeamMemberRole Role of a team member or responsible party

const (
	BusinessLeader     TeamMemberRole = "business_leader"
	Engineer           TeamMemberRole = "engineer"
	EngineeringLead    TeamMemberRole = "engineering_lead"
	Other              TeamMemberRole = "other"
	ProductManager     TeamMemberRole = "product_manager"
	SecuritySpecialist TeamMemberRole = "security_specialist"
)

Defines values for TeamMemberRole.

func (TeamMemberRole) Valid

func (e TeamMemberRole) Valid() bool

Valid indicates whether the value is a known member of the TeamMemberRole enum.

type TeamNote

type TeamNote struct {
	// Content Note content in markdown format. Safe inline HTML (tables, SVG, formatting) is allowed and sanitized server-side; dangerous elements (script, iframe, event handlers) are stripped.
	Content string `binding:"required" json:"content"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the team note
	Id *openapi_types.UUID `json:"id,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Note name
	Name string `binding:"required" json:"name"`

	// Sharable Controls note visibility. When true, visible to all team/project members. When false, only visible to admins and security reviewers. Only admins and security reviewers can set this field; regular users who include this field in requests will receive a 403 error. Default: true for regular users, false for admins/security reviewers.
	Sharable *bool `json:"sharable,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

TeamNote defines model for TeamNote.

type TeamNoteId

type TeamNoteId = openapi_types.UUID

TeamNoteId defines model for TeamNoteId.

type TeamNoteInput

type TeamNoteInput = TeamProjectNoteBase

TeamNoteInput Base fields for TeamProjectNote (user-writable only)

type TeamNoteListItem

type TeamNoteListItem struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// Id Unique identifier for the team note
	Id *openapi_types.UUID `json:"id,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Note name
	Name string `json:"name"`

	// Sharable Controls note visibility
	Sharable *bool `json:"sharable,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

TeamNoteListItem Summary information for TeamNote in list responses

type TeamNoteStoreInterface

type TeamNoteStoreInterface interface {
	Create(ctx context.Context, note *TeamNote, teamID string) (*TeamNote, error)
	Get(ctx context.Context, id string) (*TeamNote, error)
	Update(ctx context.Context, id string, note *TeamNote, teamID string) (*TeamNote, error)
	Delete(ctx context.Context, id string) error
	Patch(ctx context.Context, id string, operations []PatchOperation) (*TeamNote, error)
	List(ctx context.Context, teamID string, offset, limit int, includeNonSharable bool) ([]TeamNoteListItem, int, error)
	Count(ctx context.Context, teamID string, includeNonSharable bool) (int, error)
}

TeamNoteStoreInterface defines the store interface for team notes SEM@f860641a78901543e88ebd0a603a69bd4db1d696: CRUD and list contract for persisted team notes (pure)

var GlobalTeamNoteStore TeamNoteStoreInterface

type TeamProjectNoteBase

type TeamProjectNoteBase struct {
	// Content Note content in markdown format. Safe inline HTML (tables, SVG, formatting) is allowed and sanitized server-side; dangerous elements (script, iframe, event handlers) are stripped.
	Content string `binding:"required" json:"content"`

	// Description Description of note purpose or context
	Description *string `json:"description,omitempty"`

	// Name Note name
	Name string `binding:"required" json:"name"`

	// Sharable Controls note visibility. When true, visible to all team/project members. When false, only visible to admins and security reviewers. Only admins and security reviewers can set this field; regular users who include this field in requests will receive a 403 error. Default: true for regular users, false for admins/security reviewers.
	Sharable *bool `json:"sharable,omitempty"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

TeamProjectNoteBase Base fields for TeamProjectNote (user-writable only)

type TeamStatus

type TeamStatus string

TeamStatus Team lifecycle status. Defaults to 'active' if not provided or set to null.

const (
	TeamStatusActive      TeamStatus = "active"
	TeamStatusArchived    TeamStatus = "archived"
	TeamStatusForming     TeamStatus = "forming"
	TeamStatusMerging     TeamStatus = "merging"
	TeamStatusOnHold      TeamStatus = "on_hold"
	TeamStatusSplitting   TeamStatus = "splitting"
	TeamStatusWindingDown TeamStatus = "winding_down"
)

Defines values for TeamStatus.

func (TeamStatus) Valid

func (e TeamStatus) Valid() bool

Valid indicates whether the value is a known member of the TeamStatus enum.

type TeamStoreInterface

type TeamStoreInterface interface {
	Create(ctx context.Context, team *Team, userInternalUUID string) (*Team, error)
	Get(ctx context.Context, id string) (*Team, error)
	Update(ctx context.Context, id string, team *Team, userInternalUUID string) (*Team, error)
	Delete(ctx context.Context, id string) error
	List(ctx context.Context, limit, offset int, filters *TeamFilters, userInternalUUID string, isAdmin bool) ([]TeamListItem, int, error)
	IsMember(ctx context.Context, teamID string, userInternalUUID string) (bool, error)
	HasProjects(ctx context.Context, teamID string) (bool, error)
}

TeamStoreInterface defines the store interface for teams SEM@8c7929da791c778ff88713684c47aa2a10911bba: CRUD and membership query contract for the team store (pure)

var GlobalTeamStore TeamStoreInterface

type TestUserIdentity

type TestUserIdentity struct {
	Email        string
	ProviderID   string
	InternalUUID string
	IdP          string
	Groups       []string
}

TestUserIdentity represents a test user with all identity attributes SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: data container holding all identity attributes for a test user principal (pure)

func (TestUserIdentity) SetContext

func (u TestUserIdentity) SetContext(c *gin.Context)

SetContext sets the user identity in a Gin context SEM@ac74bec7c763b2f6486d3fe0a6731458c37e43c5: store the test user's identity into a Gin request context (mutates shared state)

type TestWebhookSubscriptionJSONRequestBody

type TestWebhookSubscriptionJSONRequestBody = WebhookTestRequest

TestWebhookSubscriptionJSONRequestBody defines body for TestWebhookSubscription for application/json ContentType.

type TextChunker

type TextChunker = extract.TextChunker

Type aliases re-exporting pkg/extract into the api package. The extractor logic was relocated to pkg/extract during Component Platform Plan 2 (#347) so the sandboxed worker can link it without pulling in Gin/GORM. These aliases keep the monolith's many call sites unchanged.

type Threat

type Threat struct {
	// Alias Server-assigned monotonically-increasing integer alias, unique within the parent threat model. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// AssetId Unique identifier of the associated asset (if applicable) (UUID)
	AssetId *openapi_types.UUID `json:"asset_id,omitempty"`

	// AutoGenerated True when the threat was created by an automation/service-account principal. Sticky from creation.
	AutoGenerated *bool `json:"auto_generated,omitempty"`

	// CellId Unique identifier of the associated cell (if applicable) (UUID)
	CellId *openapi_types.UUID `json:"cell_id,omitempty"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Cvss CVSS scoring information for this threat
	Cvss *[]CVSSScore `json:"cvss,omitempty"`

	// CweId CWE (Common Weakness Enumeration) identifiers associated with this threat
	CweId *[]string `json:"cwe_id,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of the threat and risk to the organization
	Description *string `json:"description,omitempty"`

	// DiagramId Unique identifier of the associated diagram (if applicable) (UUID)
	DiagramId *openapi_types.UUID `json:"diagram_id,omitempty"`

	// Id Unique identifier for the threat (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// IssueUri URL to an issue in an issue tracking system for this threat
	IssueUri *string `json:"issue_uri,omitempty"`

	// Metadata Key-value pairs for additional threat metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// Mitigated Whether the threat has been mitigated
	Mitigated *bool `json:"mitigated,omitempty"`

	// Mitigation Recommended or planned mitigation(s) for the threat
	Mitigation *string `json:"mitigation,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name of the threat
	Name string `json:"name"`

	// Priority Priority level for addressing the threat
	Priority *string `json:"priority,omitempty"`

	// Score Numeric score representing the risk or impact of the threat
	Score *float32 `json:"score,omitempty"`

	// Severity Severity level of the threat
	Severity *string `json:"severity,omitempty"`

	// Ssvc SSVC (Stakeholder-Specific Vulnerability Categorization) assessment result. Optional structured decision from CISA/CERT-CC SSVC framework.
	Ssvc *SSVCScore `json:"ssvc,omitempty"`

	// Status Current status of the threat
	Status *string `json:"status,omitempty"`

	// ThreatModelId Unique identifier of the parent threat model (UUID)
	ThreatModelId *openapi_types.UUID `json:"threat_model_id,omitempty"`

	// ThreatType Types or categories of the threat. Supports multiple classifications within the same framework (e.g., ['Spoofing', 'Tampering']). Empty array indicates no types assigned.
	ThreatType []string `json:"threat_type"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

Threat defines model for Threat.

func CreateTestThreatWithMetadata

func CreateTestThreatWithMetadata(threatModelID string, metadata []Metadata) Threat

CreateTestThreatWithMetadata creates a threat with associated metadata for testing SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: build a Threat with attached metadata for use in unit tests (pure)

type ThreatBase

type ThreatBase struct {
	// AssetId Unique identifier of the associated asset (if applicable) (UUID)
	AssetId *openapi_types.UUID `json:"asset_id,omitempty"`

	// CellId Unique identifier of the associated cell (if applicable) (UUID)
	CellId *openapi_types.UUID `json:"cell_id,omitempty"`

	// Cvss CVSS scoring information for this threat
	Cvss *[]CVSSScore `json:"cvss,omitempty"`

	// CweId CWE (Common Weakness Enumeration) identifiers associated with this threat
	CweId *[]string `json:"cwe_id,omitempty"`

	// Description Description of the threat and risk to the organization
	Description *string `json:"description,omitempty"`

	// DiagramId Unique identifier of the associated diagram (if applicable) (UUID)
	DiagramId *openapi_types.UUID `json:"diagram_id,omitempty"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// IssueUri URL to an issue in an issue tracking system for this threat
	IssueUri *string `json:"issue_uri,omitempty"`

	// Metadata Key-value pairs for additional threat metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// Mitigated Whether the threat has been mitigated
	Mitigated *bool `json:"mitigated,omitempty"`

	// Mitigation Recommended or planned mitigation(s) for the threat
	Mitigation *string `json:"mitigation,omitempty"`

	// Name Name of the threat
	Name string `json:"name"`

	// Priority Priority level for addressing the threat
	Priority *string `json:"priority,omitempty"`

	// Score Numeric score representing the risk or impact of the threat
	Score *float32 `json:"score,omitempty"`

	// Severity Severity level of the threat
	Severity *string `json:"severity,omitempty"`

	// Ssvc SSVC (Stakeholder-Specific Vulnerability Categorization) assessment result. Optional structured decision from CISA/CERT-CC SSVC framework.
	Ssvc *SSVCScore `json:"ssvc,omitempty"`

	// Status Current status of the threat
	Status *string `json:"status,omitempty"`

	// ThreatType Types or categories of the threat. Supports multiple classifications within the same framework (e.g., ['Spoofing', 'Tampering']). Empty array indicates no types assigned.
	ThreatType []string `json:"threat_type"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

ThreatBase Base schema for Threat with client-writable fields

type ThreatBulkUpdateItem

type ThreatBulkUpdateItem struct {
	// AssetId Unique identifier of the associated asset (if applicable) (UUID)
	AssetId *openapi_types.UUID `json:"asset_id,omitempty"`

	// CellId Unique identifier of the associated cell (if applicable) (UUID)
	CellId *openapi_types.UUID `json:"cell_id,omitempty"`

	// Cvss CVSS scoring information for this threat
	Cvss *[]CVSSScore `json:"cvss,omitempty"`

	// CweId CWE (Common Weakness Enumeration) identifiers associated with this threat
	CweId *[]string `json:"cwe_id,omitempty"`

	// Description Description of the threat and risk to the organization
	Description *string `json:"description,omitempty"`

	// DiagramId Unique identifier of the associated diagram (if applicable) (UUID)
	DiagramId *openapi_types.UUID `json:"diagram_id,omitempty"`

	// Id Unique identifier of the threat to update (required for bulk updates)
	Id openapi_types.UUID `json:"id"`

	// IncludeInReport Whether this item should be included in generated reports
	IncludeInReport *bool `json:"include_in_report,omitempty"`

	// IssueUri URL to an issue in an issue tracking system for this threat
	IssueUri *string `json:"issue_uri,omitempty"`

	// Metadata Key-value pairs for additional threat metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// Mitigated Whether the threat has been mitigated
	Mitigated *bool `json:"mitigated,omitempty"`

	// Mitigation Recommended or planned mitigation(s) for the threat
	Mitigation *string `json:"mitigation,omitempty"`

	// Name Name of the threat
	Name string `json:"name"`

	// Priority Priority level for addressing the threat
	Priority *string `json:"priority,omitempty"`

	// Score Numeric score representing the risk or impact of the threat
	Score *float32 `json:"score,omitempty"`

	// Severity Severity level of the threat
	Severity *string `json:"severity,omitempty"`

	// Ssvc SSVC (Stakeholder-Specific Vulnerability Categorization) assessment result. Optional structured decision from CISA/CERT-CC SSVC framework.
	Ssvc *SSVCScore `json:"ssvc,omitempty"`

	// Status Current status of the threat
	Status *string `json:"status,omitempty"`

	// ThreatType Types or categories of the threat. Supports multiple classifications within the same framework (e.g., ['Spoofing', 'Tampering']). Empty array indicates no types assigned.
	ThreatType []string `json:"threat_type"`

	// TimmyEnabled Whether the Timmy AI assistant is enabled for this entity
	TimmyEnabled *bool `json:"timmy_enabled,omitempty"`
}

ThreatBulkUpdateItem defines model for ThreatBulkUpdateItem.

type ThreatEntity

type ThreatEntity struct {
	ID          string         `json:"id,omitempty"`
	Name        string         `json:"name" binding:"required"`
	Description *string        `json:"description,omitempty"`
	Metadata    []MetadataItem `json:"metadata,omitempty"`
}

ThreatEntity represents a threat in a threat model (custom name to avoid collision with generated Threat) SEM@386eea01f3b66c35027bf3ca762efbc291419e20: represent a threat within a threat model, avoiding collision with the generated Threat type (pure)

type ThreatFilter

type ThreatFilter struct {
	// Basic filters
	Name        *string
	Description *string
	ThreatType  []string
	Severity    []string
	Priority    []string
	Status      []string
	Mitigated   *bool
	DiagramID   *uuid.UUID
	CellID      *uuid.UUID

	// Score comparison filters
	ScoreGT *float32
	ScoreLT *float32
	ScoreEQ *float32
	ScoreGE *float32
	ScoreLE *float32

	// Date filters
	CreatedAfter   *time.Time
	CreatedBefore  *time.Time
	ModifiedAfter  *time.Time
	ModifiedBefore *time.Time

	// Sorting and pagination
	Sort   *string
	Offset int
	Limit  int
}

ThreatFilter defines filtering criteria for threats SEM@cd9bd2528bd9cff1ec072491f5cbcbe1cb9219ac: filter criteria for threat list queries including scores, dates, and pagination (pure)

type ThreatId

type ThreatId = openapi_types.UUID

ThreatId defines model for ThreatId.

type ThreatIdsQueryParam

type ThreatIdsQueryParam = []openapi_types.UUID

ThreatIdsQueryParam defines model for ThreatIdsQueryParam.

type ThreatInput

type ThreatInput = ThreatBase

ThreatInput Base schema for Threat with client-writable fields

type ThreatModel

type ThreatModel struct {
	// Alias Server-assigned monotonically-increasing integer alias, globally unique across all threat models. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// Assets List of assets associated with the threat model
	Assets *[]ExtendedAsset `json:"assets,omitempty"`

	// Authorization List of users and their roles for this threat model
	Authorization *[]Authorization `json:"authorization"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// CreatedBy User who created the threat model
	CreatedBy *User `json:"created_by,omitempty"`

	// DeletedAt Deletion timestamp (RFC3339). Present only on soft-deleted entities within the tombstone retention period.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	// Description Description of the threat model
	Description *string `json:"description,omitempty"`

	// Diagrams List of diagram objects associated with this threat model
	Diagrams *[]Diagram `json:"diagrams,omitempty"`

	// Documents List of documents related to the threat model
	Documents *[]Document `json:"documents,omitempty"`

	// Id Unique identifier for the threat model (UUID)
	Id *openapi_types.UUID `json:"id,omitempty"`

	// IsConfidential Whether this threat model is confidential (set at creation, read-only after)
	IsConfidential *bool `json:"is_confidential,omitempty"`

	// IssueUri URL to an issue in an issue tracking system for this threat model
	IssueUri *string `json:"issue_uri,omitempty"`

	// Metadata Key-value pairs for additional threat model metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// Name Name of the threat model
	Name string `binding:"required" json:"name"`

	// Notes List of notes associated with the threat model
	Notes *[]Note `json:"notes,omitempty"`

	// Owner User who owns the threat model (can be null for orphaned models)
	Owner User `json:"owner"`

	// ProjectId Optional reference to the project this threat model belongs to
	ProjectId *openapi_types.UUID `json:"project_id,omitempty"`

	// Repositories List of source code repositories related to the threat model
	Repositories *[]Repository `json:"repositories,omitempty"`

	// SecurityReviewer Security reviewer assigned to this threat model. When set, the security reviewer is automatically added to the authorization list with the owner role. The security reviewer's owner role cannot be removed via authorization changes while they remain assigned as security reviewer. To change the security reviewer's authorization, first unassign them as security reviewer.
	SecurityReviewer *User `json:"security_reviewer,omitempty"`

	// Status Status of the threat model in the organization's threat modeling or SDLC process. Examples: "not_started", "in_progress", "pending_review", "approved", "closed". Defaults to "not_started" on create.
	Status *string `json:"status,omitempty"`

	// StatusUpdated Timestamp when the status field was last modified (RFC3339). Automatically updated by the server when status changes.
	StatusUpdated *time.Time `json:"status_updated,omitempty"`

	// ThreatModelFramework The framework used for this threat model
	ThreatModelFramework string `json:"threat_model_framework"`

	// Threats List of threats within the threat model
	Threats *[]Threat `json:"threats,omitempty"`

	// Version Server-managed monotonically-increasing optimistic-locking version. Returned on reads and bumped by every successful PUT/PATCH. Clients echo this back via the If-Match request header (preferred) or the body 'version' field on the next mutation. A mismatch returns 409 Conflict. See issue #385.
	Version *int32 `json:"version,omitempty"`
}

ThreatModel defines model for ThreatModel.

func (*ThreatModel) SetCreatedAt

func (t *ThreatModel) SetCreatedAt(time time.Time)

SetCreatedAt implements WithTimestamps interface SEM@de36efe7c9abdb238cea29efae95937751a21874: set the created_at timestamp on a ThreatModel to implement WithTimestamps (pure)

func (*ThreatModel) SetModifiedAt

func (t *ThreatModel) SetModifiedAt(time time.Time)

SetModifiedAt implements WithTimestamps interface SEM@de36efe7c9abdb238cea29efae95937751a21874: set the modified_at timestamp on a ThreatModel to implement WithTimestamps (pure)

type ThreatModelBase

type ThreatModelBase struct {
	// Alias Server-assigned monotonically-increasing integer alias, globally unique across all threat models. Immutable after creation.
	Alias *int32 `json:"alias,omitempty"`

	// Authorization List of users and their roles for this threat model
	Authorization *[]Authorization `json:"authorization"`

	// Description Description of the threat model
	Description *string `json:"description,omitempty"`

	// IssueUri URL to an issue in an issue tracking system for this threat model
	IssueUri *string `json:"issue_uri,omitempty"`

	// Metadata Key-value pairs for additional threat model metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// Name Name of the threat model
	Name string `binding:"required" json:"name"`

	// Owner User who owns the threat model (can be null for orphaned models)
	Owner User `json:"owner"`

	// ProjectId Optional reference to the project this threat model belongs to
	ProjectId *openapi_types.UUID `json:"project_id,omitempty"`

	// SecurityReviewer Security reviewer assigned to this threat model. When set, the security reviewer is automatically added to the authorization list with the owner role. The security reviewer's owner role cannot be removed via authorization changes while they remain assigned as security reviewer. To change the security reviewer's authorization, first unassign them as security reviewer.
	SecurityReviewer *User `json:"security_reviewer,omitempty"`

	// Status Status of the threat model in the organization's threat modeling or SDLC process. Examples: "not_started", "in_progress", "pending_review", "approved", "closed". Defaults to "not_started" on create.
	Status *string `json:"status,omitempty"`

	// ThreatModelFramework The framework used for this threat model
	ThreatModelFramework string `json:"threat_model_framework"`
}

ThreatModelBase Base schema for ThreatModel with client-writable fields

type ThreatModelDiagramHandler

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

ThreatModelDiagramHandler provides handlers for diagram operations within threat models SEM@314192db3f19e15fbbe44e914b7adf29f1816602: HTTP handler for diagram CRUD and collaboration scoped under a threat model (pure)

func NewThreatModelDiagramHandler

func NewThreatModelDiagramHandler(wsHub *WebSocketHub) *ThreatModelDiagramHandler

NewThreatModelDiagramHandler creates a new handler for diagrams within threat models SEM@314192db3f19e15fbbe44e914b7adf29f1816602: build a ThreatModelDiagramHandler wired to the WebSocket hub (pure)

func (*ThreatModelDiagramHandler) CreateDiagram

func (h *ThreatModelDiagramHandler) CreateDiagram(c *gin.Context, threatModelId string)

CreateDiagram creates a new diagram for a threat model SEM@f24c94ac3b48082482bcf5b8e9642017897fe3b6: create a new diagram under a threat model and return its location (reads DB)

func (*ThreatModelDiagramHandler) CreateDiagramCollaborate

func (h *ThreatModelDiagramHandler) CreateDiagramCollaborate(c *gin.Context, threatModelId, diagramId string)

CreateDiagramCollaborate creates a new collaboration session for a diagram within a threat model SEM@533fc769067d317cc10f227729848688da16fba0: create or retrieve a WebSocket collaboration session for a diagram (reads DB)

func (*ThreatModelDiagramHandler) DeleteDiagram

func (h *ThreatModelDiagramHandler) DeleteDiagram(c *gin.Context, threatModelId, diagramId string)

DeleteDiagram deletes a diagram within a threat model SEM@533fc769067d317cc10f227729848688da16fba0: soft-delete a diagram under a threat model; rejects active collaboration sessions (reads DB)

func (*ThreatModelDiagramHandler) DeleteDiagramCollaborate

func (h *ThreatModelDiagramHandler) DeleteDiagramCollaborate(c *gin.Context, threatModelId, diagramId string)

DeleteDiagramCollaborate leaves a collaboration session for a diagram within a threat model SEM@533fc769067d317cc10f227729848688da16fba0: leave or close a collaboration session; host closes, other participants disconnect (mutates shared state)

func (*ThreatModelDiagramHandler) GetDiagramByID

func (h *ThreatModelDiagramHandler) GetDiagramByID(c *gin.Context, threatModelId, diagramId string)

GetDiagramByID retrieves a specific diagram within a threat model SEM@533fc769067d317cc10f227729848688da16fba0: fetch a single diagram by ID after verifying parent threat model ownership (reads DB)

func (*ThreatModelDiagramHandler) GetDiagramCollaborate

func (h *ThreatModelDiagramHandler) GetDiagramCollaborate(c *gin.Context, threatModelId, diagramId string)

GetDiagramCollaborate gets collaboration session status for a diagram within a threat model SEM@533fc769067d317cc10f227729848688da16fba0: fetch the active collaboration session status for a diagram (reads DB)

func (*ThreatModelDiagramHandler) GetDiagramModel

func (h *ThreatModelDiagramHandler) GetDiagramModel(c *gin.Context, threatModelId, diagramId openapi_types.UUID)

GetDiagramModel retrieves a minimal model representation of a diagram within a threat model. This endpoint is optimized for automated threat modeling tools, returning only essential data without visual styling, layout information, or rendering properties.

Response includes:

  • Threat model context (id, name, description, flattened metadata)
  • Minimal cells (nodes and edges) with:
  • Computed bidirectional parent-child relationships
  • Text labels extracted from attrs and text-box children
  • Flattened metadata from cell.data._metadata
  • Optional dataAssetId references

Authorization: Requires at least RoleReader on the threat model.

Content negotiation (Accept header):

  • application/json (default)
  • application/yaml
  • application/graphml+xml
  • 406 Not Acceptable when the Accept header matches none of these

SEM@29f63eb500c26288d0d3fe23737adf6fd94bdf9c: fetch a diagram model and serialize in the negotiated format (reads DB)

func (*ThreatModelDiagramHandler) GetDiagrams

func (h *ThreatModelDiagramHandler) GetDiagrams(c *gin.Context, threatModelId string)

GetDiagrams returns a list of diagrams for a threat model SEM@56c7ade8aa871465aa5ecb657172ddbf41f9112e: list diagrams for a threat model with pagination (reads DB)

func (*ThreatModelDiagramHandler) PatchDiagram

func (h *ThreatModelDiagramHandler) PatchDiagram(c *gin.Context, threatModelId, diagramId string)

PatchDiagram partially updates a diagram within a threat model SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: apply JSON Patch operations to a diagram with optimistic locking; rejects active sessions (reads DB)

func (*ThreatModelDiagramHandler) UpdateDiagram

func (h *ThreatModelDiagramHandler) UpdateDiagram(c *gin.Context, threatModelId, diagramId string)

UpdateDiagram fully updates a diagram within a threat model SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: fully replace a diagram's content with optimistic locking; rejects active collaboration sessions (reads DB)

type ThreatModelFilters

type ThreatModelFilters struct {
	Owner               *string       // Filter by owner email or display name (partial match)
	Name                *string       // Filter by name (partial match)
	Description         *string       // Filter by description (partial match)
	IssueUri            *string       // Filter by issue_uri (partial match)
	CreatedAfter        *time.Time    // Filter by created_at >= value
	CreatedBefore       *time.Time    // Filter by created_at <= value
	ModifiedAfter       *time.Time    // Filter by modified_at >= value
	ModifiedBefore      *time.Time    // Filter by modified_at <= value
	Status              []string      // Filter by status values (exact match, supports multiple)
	StatusUpdatedAfter  *time.Time    // Filter by status_updated >= value
	StatusUpdatedBefore *time.Time    // Filter by status_updated <= value
	SecurityReviewer    *ParsedFilter // Filter by security reviewer (supports operator syntax: is:null, is:notnull, or partial match)
	IncludeDeleted      bool          // Include soft-deleted (tombstoned) entities
}

ThreatModelFilters defines filtering criteria for listing threat models SEM@cd5f8ed4949685a202f3e973e6cddb10850f0f15: value type holding optional filter criteria for listing threat models (pure)

type ThreatModelHandler

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

ThreatModelHandler provides handlers for threat model operations SEM@5eacb6f5fd0d2a1861dafb4d1fc5a18f97ee8e40: HTTP handler struct for threat model CRUD with WebSocket hub and URI validation

func NewThreatModelHandler

func NewThreatModelHandler(wsHub *WebSocketHub) *ThreatModelHandler

NewThreatModelHandler creates a new threat model handler SEM@8559837d482fde8e2f7e1a9ea5e99d2bb2414141: build a ThreatModelHandler wired to the given WebSocket hub (pure)

func (*ThreatModelHandler) CreateThreatModel

func (h *ThreatModelHandler) CreateThreatModel(c *gin.Context)

CreateThreatModel creates a new threat model SEM@a37a0039279be689bb07be2113fe86024a410a4b: create a threat model owned by the authenticated user with default authorization groups (reads DB)

func (*ThreatModelHandler) DeleteThreatModel

func (h *ThreatModelHandler) DeleteThreatModel(c *gin.Context)

DeleteThreatModel deletes a threat model SEM@533fc769067d317cc10f227729848688da16fba0: soft-delete a threat model, blocking if any diagram has an active collaboration session (reads DB)

func (*ThreatModelHandler) GetThreatModelByID

func (h *ThreatModelHandler) GetThreatModelByID(c *gin.Context)

GetThreatModelByID retrieves a specific threat model SEM@533fc769067d317cc10f227729848688da16fba0: fetch a single threat model by ID for an authorized user (reads DB)

func (*ThreatModelHandler) GetThreatModels

func (h *ThreatModelHandler) GetThreatModels(c *gin.Context)

GetThreatModels returns a list of threat models SEM@17f6e77aac81a016d5aee8d2d0d0f06e671a4a2e: list threat models accessible to the authenticated user with pagination and filters (reads DB)

func (*ThreatModelHandler) PatchThreatModel

func (h *ThreatModelHandler) PatchThreatModel(c *gin.Context)

PatchThreatModel partially updates a threat model SEM@a37a0039279be689bb07be2113fe86024a410a4b: apply JSON Patch operations to a threat model with allowlist and optimistic locking (reads DB)

func (*ThreatModelHandler) SetIssueURIValidator

func (h *ThreatModelHandler) SetIssueURIValidator(v *URIValidator)

SetIssueURIValidator sets the URI validator for issue_uri fields SEM@5eacb6f5fd0d2a1861dafb4d1fc5a18f97ee8e40: register the URI validator used to guard issue_uri fields (mutates shared state)

func (*ThreatModelHandler) UpdateThreatModel

func (h *ThreatModelHandler) UpdateThreatModel(c *gin.Context)

UpdateThreatModel fully updates a threat model SEM@a37a0039279be689bb07be2113fe86024a410a4b: fully replace a threat model's mutable fields, enforcing owner-only auth changes (reads DB)

type ThreatModelId

type ThreatModelId = openapi_types.UUID

ThreatModelId defines model for ThreatModelId.

type ThreatModelIdPathParam

type ThreatModelIdPathParam = openapi_types.UUID

ThreatModelIdPathParam defines model for ThreatModelIdPathParam.

type ThreatModelIdQueryParam

type ThreatModelIdQueryParam = openapi_types.UUID

ThreatModelIdQueryParam defines model for ThreatModelIdQueryParam.

type ThreatModelInput

type ThreatModelInput struct {
	// Authorization List of users and their roles for this threat model
	Authorization *[]Authorization `json:"authorization,omitempty"`

	// Description Description of the threat model and its purpose
	Description *string `json:"description,omitempty"`

	// IsConfidential If true, threat model is marked as confidential. Can only be set at creation.
	IsConfidential *bool `json:"is_confidential,omitempty"`

	// IssueUri URL to an issue in an issue tracking system for this threat model
	IssueUri *string `json:"issue_uri,omitempty"`

	// Metadata Key-value pairs for additional threat model metadata
	Metadata *[]Metadata `json:"metadata,omitempty"`

	// Name Name of the threat model
	Name string `json:"name"`

	// ThreatModelFramework The framework used for this threat model
	ThreatModelFramework *string `json:"threat_model_framework,omitempty"`
}

ThreatModelInput Input schema for creating/updating ThreatModel

type ThreatModelInternal

type ThreatModelInternal struct {
	// Core fields
	Id                   *openapi_types.UUID `json:"id,omitempty"`
	Name                 string              `json:"name"`
	Description          *string             `json:"description,omitempty"`
	Owner                User                `json:"owner"`
	ThreatModelFramework string              `json:"threat_model_framework"`
	CreatedAt            *time.Time          `json:"created_at,omitempty"`
	ModifiedAt           *time.Time          `json:"modified_at,omitempty"`
	CreatedBy            *User               `json:"created_by,omitempty"`
	IssueUri             *string             `json:"issue_uri,omitempty"`

	// Authorization (stored directly since it's small)
	Authorization []Authorization `json:"authorization"`

	// References to related entities (IDs only)
	DiagramIds  []string `json:"diagram_ids,omitempty"`
	ThreatIds   []string `json:"threat_ids,omitempty"`
	DocumentIds []string `json:"document_ids,omitempty"`
	SourceIds   []string `json:"source_ids,omitempty"`
}

ThreatModelInternal is the internal representation used by stores It stores diagram/threat/document IDs instead of full objects for single source of truth SEM@e28c0cfc627a2162c9550e53fb320facb734179e: internal threat model representation storing related entity IDs instead of full objects (pure)

func (*ThreatModelInternal) FromThreatModel

func (tm *ThreatModelInternal) FromThreatModel(external *ThreatModel)

FromThreatModel converts external API model to internal representation SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: populate the internal threat model from an API DTO, extracting related entity IDs (pure)

func (*ThreatModelInternal) ToThreatModel

func (tm *ThreatModelInternal) ToThreatModel() (*ThreatModel, error)

ToThreatModel converts internal representation to external API model This function dynamically loads related entities from their respective stores SEM@d48970168f241f7cb359d0cfdb00f3e26abb59da: convert the internal threat model to the API DTO, loading related diagrams from stores (reads DB)

type ThreatModelNotificationData

type ThreatModelNotificationData struct {
	ThreatModelID   string `json:"threat_model_id"`
	ThreatModelName string `json:"threat_model_name"`
	Action          string `json:"action"` // created, updated, deleted
}

ThreatModelNotificationData contains data for threat model notifications SEM@66b1e1515b82356913c8625edc8616772c3c70d3: payload for threat model lifecycle notifications (pure)

type ThreatModelRequest

type ThreatModelRequest struct {
	Name        string         `json:"name" binding:"required"`
	Description *string        `json:"description,omitempty"`
	DiagramIDs  []string       `json:"diagram_ids,omitempty"`
	Threats     []ThreatEntity `json:"threats,omitempty"`
}

ThreatModelRequest is used for creating and updating threat models SEM@386eea01f3b66c35027bf3ca762efbc291419e20: request DTO for creating or updating a threat model (pure)

type ThreatModelShareData

type ThreatModelShareData struct {
	ThreatModelID   string `json:"threat_model_id"`
	ThreatModelName string `json:"threat_model_name"`
	SharedWithEmail string `json:"shared_with_email"`
	Role            string `json:"role"` // reader, writer, owner
}

ThreatModelShareData contains data for threat model sharing notifications SEM@66b1e1515b82356913c8625edc8616772c3c70d3: payload for threat model sharing notifications including recipient and role (pure)

type ThreatModelStoreInterface

type ThreatModelStoreInterface interface {
	Get(id string) (ThreatModel, error)
	GetIncludingDeleted(id string) (ThreatModel, error)
	GetAuthorization(id string) ([]Authorization, User, error)
	GetAuthorizationIncludingDeleted(id string) ([]Authorization, User, error)
	List(offset, limit int, filter func(ThreatModel) bool) []ThreatModel
	// ListWithCounts returns paginated threat model list items with counts and total count (before pagination)
	ListWithCounts(offset, limit int, filter func(ThreatModel) bool, filters *ThreatModelFilters) ([]TMListItem, int)
	Create(item ThreatModel, idSetter func(ThreatModel, string) ThreatModel) (ThreatModel, error)
	// Update accepts a context.Context so the underlying retry wrapper uses
	// the caller's ctx instead of context.Background(); see #334.
	Update(ctx context.Context, id string, item ThreatModel) error
	Delete(id string) error
	// SoftDelete accepts a context.Context for retry-wrapper cancellability; see #334.
	SoftDelete(ctx context.Context, id string) error
	Restore(id string) error
	HardDelete(id string) error
	Count() int
}

SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: interface for CRUD, soft-delete, list, count, and authorization operations on threat models

var ThreatModelStore ThreatModelStoreInterface

Global store instances (will be initialized in main.go)

type ThreatRepository

type ThreatRepository interface {
	// CRUD operations
	Create(ctx context.Context, threat *Threat) error
	Get(ctx context.Context, id string) (*Threat, error)
	Update(ctx context.Context, threat *Threat) error
	Delete(ctx context.Context, id string) error
	SoftDelete(ctx context.Context, id string) error
	Restore(ctx context.Context, id string) error
	HardDelete(ctx context.Context, id string) error
	GetIncludingDeleted(ctx context.Context, id string) (*Threat, error)

	// List operations with filtering, sorting and pagination
	// Returns: items, total count (before pagination), error
	List(ctx context.Context, threatModelID string, filter ThreatFilter) ([]Threat, int, error)

	// PATCH operations for granular updates
	Patch(ctx context.Context, id string, operations []PatchOperation) (*Threat, error)

	// Bulk operations
	BulkCreate(ctx context.Context, threats []Threat) error
	BulkUpdate(ctx context.Context, threats []Threat) error

	// Cache management
	InvalidateCache(ctx context.Context, id string) error
	WarmCache(ctx context.Context, threatModelID string) error
}

ThreatRepository defines the interface for threat operations with caching support SEM@3e2f91117dc821148cc037a1ea89214f2215cf5e: store interface for threat CRUD, soft-delete, restore, bulk, patch, and cache operations

var GlobalThreatRepository ThreatRepository

type ThreatSubResourceHandler

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

ThreatSubResourceHandler provides handlers for threat sub-resource operations SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: HTTP handler aggregate for threat sub-resource CRUD operations within a threat model

func NewThreatSubResourceHandler

func NewThreatSubResourceHandler(threatStore ThreatRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *ThreatSubResourceHandler

NewThreatSubResourceHandler creates a new threat sub-resource handler SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: build a threat sub-resource handler wired to the store, DB, cache, and invalidator (pure)

func (*ThreatSubResourceHandler) BulkCreateThreats

func (h *ThreatSubResourceHandler) BulkCreateThreats(c *gin.Context)

BulkCreateThreats creates multiple threats in a single request POST /threat_models/{threat_model_id}/threats/bulk SEM@f34985e914fe8d55039296cf4302878c88329818: store up to 50 new threats under a threat model in a single request (mutates shared state)

func (*ThreatSubResourceHandler) BulkDeleteThreats

func (h *ThreatSubResourceHandler) BulkDeleteThreats(c *gin.Context)

BulkDeleteThreats deletes multiple threats DELETE /threat_models/{threat_model_id}/threats/bulk SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: delete up to 20 threats by ID in a single request and return the deleted IDs (mutates shared state)

func (*ThreatSubResourceHandler) BulkPatchThreats

func (h *ThreatSubResourceHandler) BulkPatchThreats(c *gin.Context)

BulkPatchThreats applies JSON patch operations to multiple threats PATCH /threat_models/{threat_model_id}/threats/bulk SEM@f34985e914fe8d55039296cf4302878c88329818: apply JSON patch operations to multiple threats with per-threat authorization checks (mutates shared state)

func (*ThreatSubResourceHandler) BulkUpdateThreats

func (h *ThreatSubResourceHandler) BulkUpdateThreats(c *gin.Context)

BulkUpdateThreats updates multiple threats in a single request PUT /threat_models/{threat_model_id}/threats/bulk SEM@f34985e914fe8d55039296cf4302878c88329818: replace up to 50 existing threats under a threat model in a single request (mutates shared state)

func (*ThreatSubResourceHandler) CreateThreat

func (h *ThreatSubResourceHandler) CreateThreat(c *gin.Context)

CreateThreat creates a new threat in a threat model POST /threat_models/{threat_model_id}/threats SEM@f24c94ac3b48082482bcf5b8e9642017897fe3b6: store a new threat under a threat model, sanitizing inputs and recording an audit entry (mutates shared state)

func (*ThreatSubResourceHandler) DeleteThreat

func (h *ThreatSubResourceHandler) DeleteThreat(c *gin.Context)

DeleteThreat deletes a threat DELETE /threat_models/{threat_model_id}/threats/{threat_id} SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: delete a threat by ID and record a deletion audit entry (mutates shared state)

func (*ThreatSubResourceHandler) GetThreat

func (h *ThreatSubResourceHandler) GetThreat(c *gin.Context)

GetThreat retrieves a specific threat by ID GET /threat_models/{threat_model_id}/threats/{threat_id} SEM@f7d829c2058f4f0be9f76648be2cbcfc3501f485: fetch a single threat by ID for an authenticated user (reads DB)

func (*ThreatSubResourceHandler) GetThreats

func (h *ThreatSubResourceHandler) GetThreats(c *gin.Context)

GetThreats retrieves all threats for a threat model with pagination GET /threat_models/{threat_model_id}/threats SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: list threats for a threat model with pagination, enforcing auth via middleware (reads DB)

func (*ThreatSubResourceHandler) GetThreatsWithFilters

func (h *ThreatSubResourceHandler) GetThreatsWithFilters(c *gin.Context, params GetThreatModelThreatsParams)

GetThreatsWithFilters retrieves all threats for a threat model with advanced filtering GET /threat_models/{threat_model_id}/threats with query parameters SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: list threats for a threat model applying filter, pagination, and sort parameters (reads DB)

func (*ThreatSubResourceHandler) PatchThreat

func (h *ThreatSubResourceHandler) PatchThreat(c *gin.Context)

PatchThreat applies JSON patch operations to a threat PATCH /threat_models/{threat_model_id}/threats/{threat_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: apply JSON patch operations to a threat with authorization and optimistic locking, recording an audit entry (mutates shared state)

func (*ThreatSubResourceHandler) SetIssueURIValidator

func (h *ThreatSubResourceHandler) SetIssueURIValidator(v *URIValidator)

SetIssueURIValidator sets the URI validator for issue_uri fields SEM@5eacb6f5fd0d2a1861dafb4d1fc5a18f97ee8e40: attach a URI validator for SSRF protection on issue_uri fields (mutates shared state)

func (*ThreatSubResourceHandler) UpdateThreat

func (h *ThreatSubResourceHandler) UpdateThreat(c *gin.Context)

UpdateThreat updates an existing threat PUT /threat_models/{threat_model_id}/threats/{threat_id} SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: replace a threat with optimistic locking, sanitize inputs, and record an audit entry (mutates shared state)

type ThreatTypeQueryParam

type ThreatTypeQueryParam = []string

ThreatTypeQueryParam defines model for ThreatTypeQueryParam.

type TicketStore

type TicketStore interface {
	// IssueTicket creates a ticket bound to a user, provider, internal UUID, and session, returning the ticket string.
	IssueTicket(ctx context.Context, userID, provider, internalUUID, sessionID string, ttl time.Duration) (string, error)
	// ValidateTicket validates and consumes a ticket (single-use). Returns the bound userID, provider, internalUUID, and sessionID.
	ValidateTicket(ctx context.Context, ticket string) (userID, provider, internalUUID, sessionID string, err error)
}

TicketStore manages short-lived, single-use WebSocket authentication tickets. SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: interface for issuing and consuming single-use WebSocket authentication tickets (pure)

type TimmyChatMessage

type TimmyChatMessage struct {
	// Content Message content
	Content string `json:"content"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Id Unique identifier for the message
	Id *openapi_types.UUID `json:"id,omitempty"`

	// Role Role of the message sender
	Role TimmyChatMessageRole `json:"role"`

	// Sequence Message sequence number within the session
	Sequence *int `json:"sequence,omitempty"`

	// SessionId Identifier of the parent chat session
	SessionId *openapi_types.UUID `json:"session_id,omitempty"`

	// TokenCount Number of tokens in the message
	TokenCount *int `json:"token_count,omitempty"`
}

TimmyChatMessage A message within a Timmy chat session

type TimmyChatMessageRole

type TimmyChatMessageRole string

TimmyChatMessageRole Role of the message sender

const (
	TimmyChatMessageRoleAssistant TimmyChatMessageRole = "assistant"
	TimmyChatMessageRoleUser      TimmyChatMessageRole = "user"
)

Defines values for TimmyChatMessageRole.

func (TimmyChatMessageRole) Valid

func (e TimmyChatMessageRole) Valid() bool

Valid indicates whether the value is a known member of the TimmyChatMessageRole enum.

type TimmyChatSession

type TimmyChatSession struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// Id Unique identifier for the chat session
	Id *openapi_types.UUID `json:"id,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// SourceSnapshot Snapshot of source entities used for context
	SourceSnapshot *[]struct {
		// EntityId Identifier of the source entity
		EntityId *openapi_types.UUID `json:"entity_id,omitempty"`

		// EntityType Type of the source entity
		EntityType *string `json:"entity_type,omitempty"`
	} `json:"source_snapshot,omitempty"`

	// Status Current status of the chat session
	Status TimmyChatSessionStatus `json:"status"`

	// SystemPromptHash Hash of the system prompt used for this session
	SystemPromptHash *string `json:"system_prompt_hash,omitempty"`

	// ThreatModelId Identifier of the parent threat model
	ThreatModelId *openapi_types.UUID `json:"threat_model_id,omitempty"`

	// Title Optional session title
	Title *string `json:"title,omitempty"`

	// UserId Identifier of the user who created the session
	UserId *openapi_types.UUID `json:"user_id,omitempty"`
}

TimmyChatSession A Timmy AI assistant chat session within a threat model

type TimmyChatSessionStatus

type TimmyChatSessionStatus string

TimmyChatSessionStatus Current status of the chat session

const (
	TimmyChatSessionStatusActive   TimmyChatSessionStatus = "active"
	TimmyChatSessionStatusArchived TimmyChatSessionStatus = "archived"
)

Defines values for TimmyChatSessionStatus.

func (TimmyChatSessionStatus) Valid

func (e TimmyChatSessionStatus) Valid() bool

Valid indicates whether the value is a known member of the TimmyChatSessionStatus enum.

type TimmyConfigProvider

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

TimmyConfigProvider assembles a live config.TimmyConfig from the settings service. Reads honor config-first precedence (env/config file > database), which SettingsServiceInterface.GetString/GetBool/GetInt already implement. SEM@c7c567dc271187337d2712f95c4866c013093ecf: adapter that assembles a live TimmyConfig from the settings service with config-first precedence (pure)

func NewTimmyConfigProvider

func NewTimmyConfigProvider(settings SettingsServiceInterface) *TimmyConfigProvider

NewTimmyConfigProvider constructs a provider over the given settings service. SEM@c7c567dc271187337d2712f95c4866c013093ecf: build a TimmyConfigProvider over the given settings service (pure)

func (*TimmyConfigProvider) Current

Current reads all timmy.* keys and returns an assembled TimmyConfig. It starts from DefaultTimmyConfig so unset numeric knobs keep sane defaults, then overlays any value present in settings. SEM@960dc5fa7f13423b7b5dd06ca76a9f2df67be632: fetch all timmy.* settings and return an assembled TimmyConfig with defaults for unset keys (reads DB)

func (*TimmyConfigProvider) WiringHash

func (p *TimmyConfigProvider) WiringHash(cfg config.TimmyConfig) string

WiringHash returns a stable hash over the fields that, when changed, require rebuilding the LLM/embedding clients. Tuning knobs (top-k, limits, history) are intentionally excluded so changing them does not force a costly client rebuild. The enable flag is also excluded — it is evaluated by the middleware, not the client build. LLMTimeoutSeconds is INCLUDED because NewTimmyLLMService bakes it into the SafeHTTPClient at construction; OperatorSystemPrompt is INCLUDED because it is baked into the base prompt at construction. SEM@cf89687423b4b2d922619ea8e021c2f13cb32481: compute a stable hash over the config fields that require LLM client rebuild when changed (pure)

type TimmyConfigReader

type TimmyConfigReader interface {
	Current(ctx context.Context) config.TimmyConfig
}

TimmyConfigReader is the read surface the middleware needs. *TimmyConfigProvider satisfies it; tests inject a stub. SEM@97d90c492e6b6921c50b9c6e84de6ad5ece1dbb2: interface for reading the current Timmy configuration per request (pure)

type TimmyCore

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

TimmyCore owns the live TimmyRuntime and rebuilds it lazily when the wiring hash changes. Safe for concurrent use. SEM@4f3fae9c4ede6c2d157bdc4671d8fa783e7a2899: thread-safe holder that lazily rebuilds the TimmyRuntime when the wiring config changes (mutates shared state)

func NewTimmyCore

func NewTimmyCore(provider *TimmyConfigProvider, build TimmyRuntimeBuilder) *TimmyCore

NewTimmyCore constructs a core over the given provider and builder. SEM@4f3fae9c4ede6c2d157bdc4671d8fa783e7a2899: build a TimmyCore wired to the given config provider and runtime builder (pure)

func (*TimmyCore) Get

func (c *TimmyCore) Get(ctx context.Context) (*TimmyRuntime, error)

Get returns the live TimmyRuntime, rebuilding it if the wiring config has changed since the last build. A build error is returned to the caller and does NOT poison the cache: the next Get retries. Callers hold the returned pointer for the duration of their request; a concurrent rebuild swaps the holder's pointer but never mutates an in-use runtime.

The config is snapshotted before locking; if the config changes again during a build, the result is still published under the snapshot's hash and will be detected as stale on the next Get. SEM@def63b409c24f2ad196af883736040232f69379e: return the live TimmyRuntime, rebuilding it if the wiring config hash has changed (mutates shared state)

type TimmyEmbeddingStore

type TimmyEmbeddingStore interface {
	ListByThreatModelAndIndexType(ctx context.Context, threatModelID, indexType string) ([]models.TimmyEmbedding, error)
	CreateBatch(ctx context.Context, embeddings []models.TimmyEmbedding) error
	DeleteByEntity(ctx context.Context, threatModelID, entityType, entityID string) (int64, error)
	DeleteByThreatModel(ctx context.Context, threatModelID string) (int64, error)
	DeleteByThreatModelAndIndexType(ctx context.Context, threatModelID, indexType string) (int64, error)

	// ListEntityMetadataByThreatModelAndIndexType returns one EntityEmbeddingMeta
	// per entity in the (threatModelID, indexType) bucket — without loading the
	// vector blobs. Used by prepareVectorIndex to decide which entities need
	// re-embedding due to content, model, or dimension changes.
	ListEntityMetadataByThreatModelAndIndexType(
		ctx context.Context, threatModelID, indexType string,
	) (map[EntityKey]EntityEmbeddingMeta, error)

	// DeleteEntitiesWithStaleEmbeddingMetadata deletes every row in the
	// (threatModelID, indexType) bucket whose embedding_model or embedding_dim
	// disagrees with (currentModel, currentDim). Returns the number of rows
	// deleted; 0 is not an error.
	DeleteEntitiesWithStaleEmbeddingMetadata(
		ctx context.Context, threatModelID, indexType, currentModel string, currentDim int,
	) (int64, error)
}

TimmyEmbeddingStore defines operations for persisting vector embeddings SEM@85c2885c496b7031495d6d6c1aa09ecb6d3d45a2: interface for persisting, fetching, and deleting vector embeddings for threat model entities (reads DB)

var GlobalTimmyEmbeddingStore TimmyEmbeddingStore

GlobalTimmyEmbeddingStore is the global embedding store instance

type TimmyLLMService

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

TimmyLLMService provides LLM chat and embedding capabilities via LangChainGo SEM@91f0b520737c464edc1a86d1115904dac7df3fb9: holds LLM chat model, text and code embedders, and service config (pure)

func NewTimmyLLMService

func NewTimmyLLMService(cfg config.TimmyConfig, validator *URIValidator) (*TimmyLLMService, error)

NewTimmyLLMService creates a new LLM service from configuration. validator MUST be non-nil; in production it is built from the operator's Timmy SSRF allowlist (typically containing the configured LLM/embedding endpoint hosts). SEM@06d5e5b913b744dc0132db2d119ef31db9c989ae: build a TimmyLLMService with SSRF-safe HTTP client, chat model, and text/code embedders from config

func (*TimmyLLMService) EmbedTexts

func (s *TimmyLLMService) EmbedTexts(ctx context.Context, texts []string, indexType string) ([][]float32, error)

EmbedTexts returns embeddings for the given texts using the embedder for the specified index type. SEM@91f0b520737c464edc1a86d1115904dac7df3fb9: convert texts to embedding vectors using the embedder for the given index type

func (*TimmyLLMService) EmbeddingDimension

func (s *TimmyLLMService) EmbeddingDimension(ctx context.Context, indexType string) (int, error)

EmbeddingDimension returns the dimension by embedding a test string for the specified index type. SEM@91f0b520737c464edc1a86d1115904dac7df3fb9: fetch the embedding vector dimension for the given index type via a probe call

func (*TimmyLLMService) GenerateResponse

func (s *TimmyLLMService) GenerateResponse(ctx context.Context, systemPrompt string, userMessage string) (string, error)

GenerateResponse sends a single-turn chat request and returns the full response text. This is a convenience wrapper for non-streaming use cases like query decomposition. SEM@f06df1eae94dd2ca361cfb88f9f58fdc2bbfced6: fetch a single-turn LLM chat completion and return the full response text (pure)

func (*TimmyLLMService) GenerateStreamingResponse

func (s *TimmyLLMService) GenerateStreamingResponse(
	ctx context.Context,
	systemPrompt string,
	messages []llms.MessageContent,
	onToken func(token string),
) (string, int, error)

GenerateStreamingResponse sends a chat request and streams tokens via callback. It returns the full response text, an approximate token count, and any error. SEM@de94ca8de4d9f1541750217c9a701b38bf923214: stream LLM chat completion tokens via callback and return the full response text

func (*TimmyLLMService) GetBasePrompt

func (s *TimmyLLMService) GetBasePrompt() string

GetBasePrompt returns the system prompt (base + operator extension) SEM@ff68770739ff3b106b20c0b32e624202137f857f: return the assembled system prompt including operator extension (pure)

type TimmyMessageStore

type TimmyMessageStore interface {
	Create(ctx context.Context, message *models.TimmyMessage) error
	ListBySession(ctx context.Context, sessionID string, offset, limit int) ([]models.TimmyMessage, int, error)
	GetNextSequence(ctx context.Context, sessionID string) (int, error)
}

TimmyMessageStore defines operations for managing Timmy chat messages SEM@3f30cf32cf8bc373eef534adfb1126a7b2018f76: store and list Timmy chat messages within a session

var GlobalTimmyMessageStore TimmyMessageStore

GlobalTimmyMessageStore is the global message store instance

type TimmyRateLimiter

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

TimmyRateLimiter manages rate limits for Timmy operations SEM@63d2546d6591e57d65783c3032d4412409c2b328: per-user sliding-window message limiter and LLM concurrency limiter for Timmy (mutates shared state)

func NewTimmyRateLimiter

func NewTimmyRateLimiter(limitsFn func() (maxMessages, maxSessions, maxConcurrent int)) *TimmyRateLimiter

NewTimmyRateLimiter creates a rate limiter whose thresholds are read live via limitsFn on each check, so limit changes take effect without rebuilding the limiter (preserving the in-flight sliding-window + concurrency state). SEM@63d2546d6591e57d65783c3032d4412409c2b328: build a Timmy rate limiter with live-readable thresholds and fresh sliding-window state (pure)

func (*TimmyRateLimiter) AcquireLLMSlot

func (rl *TimmyRateLimiter) AcquireLLMSlot() bool

AcquireLLMSlot tries to acquire a concurrent LLM request slot SEM@63d2546d6591e57d65783c3032d4412409c2b328: atomically claim one concurrent LLM request slot, returning false if the cap is reached (mutates shared state)

func (*TimmyRateLimiter) AllowMessage

func (rl *TimmyRateLimiter) AllowMessage(userID string) bool

AllowMessage checks if a user is within their hourly message limit.

limits() is read before taking rl.mu so the (potentially I/O-backed) live config lookup never extends the critical section guarding the per-user sliding-window state. SEM@67b94a899a1542320dc1780972f8e4c60ff217c5: validate that a user is within their hourly message quota and record the attempt (mutates shared state)

func (*TimmyRateLimiter) ReleaseLLMSlot

func (rl *TimmyRateLimiter) ReleaseLLMSlot()

ReleaseLLMSlot releases a concurrent LLM request slot SEM@c47068c629ce2c25efc48aa155d3fa2ba2ab7b57: release a previously acquired LLM concurrency slot (mutates shared state)

type TimmyRuntime

type TimmyRuntime struct {
	SessionManager *TimmySessionManager
	LLMService     *TimmyLLMService
	VectorManager  *VectorIndexManager
}

TimmyRuntime bundles the rebuildable Timmy objects served to a request. It is immutable once built; TimmyCore swaps the whole struct on rebuild. SEM@4f3fae9c4ede6c2d157bdc4671d8fa783e7a2899: immutable bundle of Timmy session manager, LLM service, and vector index served per request

type TimmyRuntimeBuilder

type TimmyRuntimeBuilder func(ctx context.Context, cfg config.TimmyConfig) (*TimmyRuntime, error)

TimmyRuntimeBuilder builds a TimmyRuntime from a resolved config. Injected so tests can substitute a fake builder instead of constructing real LangChainGo clients. SEM@4f3fae9c4ede6c2d157bdc4671d8fa783e7a2899: function type that builds a TimmyRuntime from a resolved Timmy config

type TimmySessionManager

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

TimmySessionManager orchestrates Timmy session and message lifecycle, wiring together LLM, vector index, content providers, and rate limiting SEM@63d2546d6591e57d65783c3032d4412409c2b328: orchestrates Timmy session lifecycle, wiring LLM, vector index, embeddings, and rate limiting (mutates shared state)

func NewTimmySessionManager

func NewTimmySessionManager(
	cfg config.TimmyConfig,
	llm *TimmyLLMService,
	vm *VectorIndexManager,
	registry *EmbeddingSourceRegistry,
	rl *TimmyRateLimiter,
	reranker Reranker,
	decomposer QueryDecomposer,
) *TimmySessionManager

NewTimmySessionManager creates a new session manager with all required dependencies SEM@63d2546d6591e57d65783c3032d4412409c2b328: build a TimmySessionManager with all required LLM, vector, and rate-limit dependencies (pure)

func (*TimmySessionManager) CreateSession

func (sm *TimmySessionManager) CreateSession(
	ctx context.Context,
	userID, threatModelID, title string,
	progress SessionProgressCallback,
) (*models.TimmySession, []SkippedSource, error)

CreateSession creates a new Timmy chat session for a user and threat model. It snapshots timmy-enabled entities, creates the session record, and optionally prepares the vector index (if LLM service is configured). Returns the created session, any skipped sources, and an error. SEM@63d2546d6591e57d65783c3032d4412409c2b328: build a Timmy session: snapshot entities, persist session record, and prepare vector index (reads DB)

func (*TimmySessionManager) HandleMessage

func (sm *TimmySessionManager) HandleMessage(
	ctx context.Context,
	sessionID, userID, userMessage string,
	onToken func(token string),
	onStatus MessageStatusCallback,
) (*models.TimmyMessage, error)

HandleMessage processes a user message: builds context, calls LLM, persists messages. The onToken callback receives streaming tokens as they arrive from the LLM. The onStatus callback (optional, may be nil) receives phase transitions ahead of token streaming so clients can surface "Timmy is …" affordances. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: process a user chat message: build context, stream LLM response, persist messages, record usage (reads DB)

func (*TimmySessionManager) SetLiveConfig

func (sm *TimmySessionManager) SetLiveConfig(read func(ctx context.Context) config.TimmyConfig)

SetLiveConfig wires a live-config reader so tuning knobs (top-k, session caps, conversation history, chunk sizes) are read per request from the database instead of the build-time snapshot. When unset, the session manager falls back to its frozen config (used by unit tests). SEM@63d2546d6591e57d65783c3032d4412409c2b328: wire a per-request live config reader for tuning knobs instead of the build-time snapshot (mutates shared state)

func (*TimmySessionManager) SetStampedConfigProvider

func (sm *TimmySessionManager) SetStampedConfigProvider(p config.StampedConfigProvider)

SetStampedConfigProvider wires the shared-invariant embedding profile into the session manager. Once set, the query path reads the embedding model through the provider so that ingest and query always see the same value. This mirrors the SetSettingsService wiring pattern used elsewhere in the server startup sequence. SEM@534d697cb5ef139c97865f31e32bd7d0b6af458f: wire the shared embedding profile provider so ingest and query use the same model (mutates shared state)

func (*TimmySessionManager) SnapshotSources

func (sm *TimmySessionManager) SnapshotSources(ctx context.Context, threatModelID string) ([]SourceSnapshotEntry, []SkippedSource, error)

SnapshotSources is the public wrapper around snapshotSources for use by the refresh handler. SEM@d6f3b757d6d206d606880902c0c0be607dfc1ee1: public wrapper to collect timmy-enabled source entries for a threat model (reads DB)

type TimmySessionStore

type TimmySessionStore interface {
	Create(ctx context.Context, session *models.TimmySession) error
	Get(ctx context.Context, id string) (*models.TimmySession, error)
	ListByUserAndThreatModel(ctx context.Context, userID, threatModelID string, offset, limit int) ([]models.TimmySession, int, error)
	SoftDelete(ctx context.Context, id string) error
	CountActiveByThreatModel(ctx context.Context, threatModelID string) (int, error)
	// UpdateSnapshot updates the source_snapshot JSON column for a session.
	UpdateSnapshot(ctx context.Context, id string, snapshot models.JSONRaw) error
	// UpdateTitle updates the title column for a session.
	UpdateTitle(ctx context.Context, id, title string) error
}

TimmySessionStore defines operations for managing Timmy chat sessions SEM@31f1e9f6c50875c19da05aa43964a24bc7d7d156: store and retrieve Timmy chat sessions with lifecycle and snapshot operations

var GlobalTimmySessionStore TimmySessionStore

GlobalTimmySessionStore is the global session store instance

type TimmyStatusResponse

type TimmyStatusResponse struct {
	// ActiveSessions Number of active chat sessions
	ActiveSessions int `json:"active_sessions"`

	// EvictionsPressure Number of evictions due to memory pressure
	EvictionsPressure int `json:"evictions_pressure"`

	// EvictionsTotal Total number of index evictions
	EvictionsTotal int `json:"evictions_total"`

	// LoadedIndexes Number of currently loaded indexes
	LoadedIndexes int `json:"loaded_indexes"`

	// MemoryBudgetBytes Total memory budget in bytes
	MemoryBudgetBytes int `json:"memory_budget_bytes"`

	// MemoryUsedBytes Current memory usage in bytes
	MemoryUsedBytes int `json:"memory_used_bytes"`

	// MemoryUtilizationPct Memory utilization percentage
	MemoryUtilizationPct float32 `json:"memory_utilization_pct"`

	// SessionsRejectedTotal Total number of sessions rejected due to resource constraints
	SessionsRejectedTotal int `json:"sessions_rejected_total"`
}

TimmyStatusResponse Timmy AI assistant system status

type TimmyUsageRecord

type TimmyUsageRecord struct {
	// CompletionTokens Number of completion tokens consumed
	CompletionTokens *int `json:"completion_tokens,omitempty"`

	// EmbeddingTokens Number of embedding tokens consumed
	EmbeddingTokens *int `json:"embedding_tokens,omitempty"`

	// MessageCount Number of messages in the period
	MessageCount *int `json:"message_count,omitempty"`

	// PeriodEnd End of the usage period (RFC3339)
	PeriodEnd *time.Time `json:"period_end,omitempty"`

	// PeriodStart Start of the usage period (RFC3339)
	PeriodStart *time.Time `json:"period_start,omitempty"`

	// PromptTokens Number of prompt tokens consumed
	PromptTokens *int `json:"prompt_tokens,omitempty"`

	// SessionId Chat session identifier
	SessionId *openapi_types.UUID `json:"session_id,omitempty"`

	// ThreatModelId Threat model identifier
	ThreatModelId *openapi_types.UUID `json:"threat_model_id,omitempty"`

	// UserId User identifier
	UserId *openapi_types.UUID `json:"user_id,omitempty"`
}

TimmyUsageRecord Usage record for Timmy AI assistant

type TimmyUsageResponse

type TimmyUsageResponse struct {
	// Total Total number of usage records
	Total int                `json:"total"`
	Usage []TimmyUsageRecord `json:"usage"`
}

TimmyUsageResponse Response containing Timmy usage records

type TimmyUsageStore

type TimmyUsageStore interface {
	Record(ctx context.Context, usage *models.TimmyUsage) error
	GetByUser(ctx context.Context, userID string, start, end time.Time) ([]models.TimmyUsage, error)
	GetByThreatModel(ctx context.Context, threatModelID string, start, end time.Time) ([]models.TimmyUsage, error)
	GetAggregated(ctx context.Context, userID, threatModelID string, start, end time.Time) (*UsageAggregation, error)
}

TimmyUsageStore defines operations for recording and querying LLM usage SEM@e5e141caabe74e3ce853b6d7b45827bb1864fb32: store interface for recording and querying LLM usage by user or threat model (pure)

var GlobalTimmyUsageStore TimmyUsageStore

GlobalTimmyUsageStore is the global usage store instance

type TokenIntrospectionRequest

type TokenIntrospectionRequest struct {
	// Token The JWT token to introspect
	Token string `json:"token"`

	// TokenTypeHint Optional hint about the type of token being introspected
	TokenTypeHint *string `json:"token_type_hint,omitempty"`
}

TokenIntrospectionRequest OAuth 2.0 token introspection request per RFC 7662

type TokenRefreshRequest

type TokenRefreshRequest struct {
	// RefreshToken Refresh token. Optional: browser SPA clients may omit it and send an empty body, in which case the server reads the refresh token from the HttpOnly refresh cookie. Non-browser clients should supply it in the body.
	RefreshToken *string `json:"refresh_token,omitempty"`
}

TokenRefreshRequest OAuth 2.0 refresh token request. The refresh token may be supplied either in this body or via the HttpOnly refresh cookie (browser SPA flow); at least one must be present.

type TokenRequest

type TokenRequest struct {
	// ClientId Client identifier (required for client_credentials grant)
	ClientId *string `json:"client_id,omitempty"`

	// ClientSecret Client secret (required for client_credentials grant)
	ClientSecret *string `json:"client_secret,omitempty"`

	// Code Authorization code (required for authorization_code grant)
	Code *string `json:"code,omitempty"`

	// CodeVerifier PKCE code verifier (required for authorization_code grant)
	CodeVerifier *string `json:"code_verifier,omitempty"`

	// GrantType OAuth 2.0 grant type (RFC 6749)
	GrantType TokenRequestGrantType `json:"grant_type"`

	// RedirectUri Redirect URI (required for authorization_code grant)
	RedirectUri *string `json:"redirect_uri,omitempty"`

	// RefreshToken Refresh token (required for refresh_token grant)
	RefreshToken *string `json:"refresh_token,omitempty"`

	// State State parameter for CSRF protection
	State *string `json:"state,omitempty"`
}

TokenRequest OAuth 2.0 token exchange request

type TokenRequestGrantType

type TokenRequestGrantType string

TokenRequestGrantType OAuth 2.0 grant type (RFC 6749)

const (
	TokenRequestGrantTypeAuthorizationCode TokenRequestGrantType = "authorization_code"
	TokenRequestGrantTypeClientCredentials TokenRequestGrantType = "client_credentials"
	TokenRequestGrantTypeRefreshToken      TokenRequestGrantType = "refresh_token"
)

Defines values for TokenRequestGrantType.

func (TokenRequestGrantType) Valid

func (e TokenRequestGrantType) Valid() bool

Valid indicates whether the value is a known member of the TokenRequestGrantType enum.

type TokenRevocationRequest

type TokenRevocationRequest struct {
	// ClientId Client identifier for client credentials authentication (alternative to Bearer token)
	ClientId *string `json:"client_id,omitempty"`

	// ClientSecret Client secret (required if client_id is provided)
	ClientSecret *string `json:"client_secret,omitempty"`

	// Token The token to be revoked (access token or refresh token)
	Token string `json:"token"`

	// TokenTypeHint A hint about the type of the token. If omitted, the server will attempt to determine the token type.
	TokenTypeHint *TokenRevocationRequestTokenTypeHint `json:"token_type_hint,omitempty"`
}

TokenRevocationRequest OAuth 2.0 token revocation request per RFC 7009

type TokenRevocationRequestTokenTypeHint

type TokenRevocationRequestTokenTypeHint string

TokenRevocationRequestTokenTypeHint A hint about the type of the token. If omitted, the server will attempt to determine the token type.

const (
	TokenRevocationRequestTokenTypeHintAccessToken  TokenRevocationRequestTokenTypeHint = "access_token"
	TokenRevocationRequestTokenTypeHintLessThannil  TokenRevocationRequestTokenTypeHint = "<nil>"
	TokenRevocationRequestTokenTypeHintRefreshToken TokenRevocationRequestTokenTypeHint = "refresh_token"
)

Defines values for TokenRevocationRequestTokenTypeHint.

func (TokenRevocationRequestTokenTypeHint) Valid

Valid indicates whether the value is a known member of the TokenRevocationRequestTokenTypeHint enum.

type TooManyRequests

type TooManyRequests = Error

TooManyRequests Standard error response format

type TransferAdminUserOwnershipJSONRequestBody

type TransferAdminUserOwnershipJSONRequestBody = TransferOwnershipRequest

TransferAdminUserOwnershipJSONRequestBody defines body for TransferAdminUserOwnership for application/json ContentType.

type TransferCurrentUserOwnershipJSONRequestBody

type TransferCurrentUserOwnershipJSONRequestBody = TransferOwnershipRequest

TransferCurrentUserOwnershipJSONRequestBody defines body for TransferCurrentUserOwnership for application/json ContentType.

type TransferOwnershipRequest

type TransferOwnershipRequest struct {
	// TargetUserId Internal UUID of the user to receive ownership
	TargetUserId openapi_types.UUID `json:"target_user_id"`
}

TransferOwnershipRequest Request to transfer ownership of all owned threat models and survey responses to another user

type TransferOwnershipResult

type TransferOwnershipResult struct {
	// SurveyResponsesTransferred Survey responses that were transferred
	SurveyResponsesTransferred struct {
		// Count Number of survey responses transferred
		Count int `json:"count"`

		// SurveyResponseIds IDs of the transferred survey responses
		SurveyResponseIds []openapi_types.UUID `json:"survey_response_ids"`
	} `json:"survey_responses_transferred"`

	// ThreatModelsTransferred Threat models that were transferred
	ThreatModelsTransferred struct {
		// Count Number of threat models transferred
		Count int `json:"count"`

		// ThreatModelIds IDs of the transferred threat models
		ThreatModelIds []openapi_types.UUID `json:"threat_model_ids"`
	} `json:"threat_models_transferred"`
}

TransferOwnershipResult Result of an ownership transfer operation

type TriageNote

type TriageNote struct {
	// Content Triage note content in markdown format. Safe inline HTML (tables, SVG, formatting) is allowed and sanitized server-side; dangerous elements (script, iframe, event handlers) are stripped.
	Content string `binding:"required" json:"content"`

	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// CreatedBy User who created this triage note
	CreatedBy *User `json:"created_by,omitempty"`

	// Id Sequential identifier for the triage note within its survey response
	Id *int `json:"id,omitempty"`

	// ModifiedAt Last modification timestamp (RFC3339)
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// ModifiedBy User who last modified this triage note
	ModifiedBy *User `json:"modified_by,omitempty"`

	// Name Triage note name
	Name string `binding:"required" json:"name"`
}

TriageNote defines model for TriageNote.

type TriageNoteBase

type TriageNoteBase struct {
	// Content Triage note content in markdown format. Safe inline HTML (tables, SVG, formatting) is allowed and sanitized server-side; dangerous elements (script, iframe, event handlers) are stripped.
	Content string `binding:"required" json:"content"`

	// Name Triage note name
	Name string `binding:"required" json:"name"`
}

TriageNoteBase Base fields for TriageNote (user-writable only)

type TriageNoteId

type TriageNoteId = int

TriageNoteId defines model for TriageNoteId.

type TriageNoteInput

type TriageNoteInput = TriageNoteBase

TriageNoteInput Base fields for TriageNote (user-writable only)

type TriageNoteListItem

type TriageNoteListItem struct {
	// CreatedAt Creation timestamp (RFC3339)
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// CreatedBy User who created this triage note
	CreatedBy *User `json:"created_by,omitempty"`

	// Id Sequential identifier for the triage note within its survey response
	Id *int `json:"id,omitempty"`

	// Name Triage note name
	Name string `json:"name"`
}

TriageNoteListItem Summary information for TriageNote in list responses

type TriageNoteStore

type TriageNoteStore interface {
	// Create creates a new triage note with an auto-assigned sequential ID
	Create(ctx context.Context, note *TriageNote, surveyResponseID string, creatorInternalUUID string) error
	// Get retrieves a specific triage note by survey response ID and note ID
	Get(ctx context.Context, surveyResponseID string, noteID int) (*TriageNote, error)
	// List returns triage notes for a survey response with pagination
	List(ctx context.Context, surveyResponseID string, offset, limit int) ([]TriageNote, error)
	// Count returns the total number of triage notes for a survey response
	Count(ctx context.Context, surveyResponseID string) (int, error)
}

TriageNoteStore defines the interface for triage note operations. Triage notes are append-only (create + read), so no Update/Delete/Patch methods. SEM@869fcafe6842b187f8cfe8e7cf65ca47021b8418: interface for append-only triage note operations on a survey response (reads DB)

var GlobalTriageNoteStore TriageNoteStore

type TriageNoteSubResourceHandler

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

TriageNoteSubResourceHandler provides handlers for triage note sub-resource operations. Triage notes are append-only: only create and read operations are supported. SEM@869fcafe6842b187f8cfe8e7cf65ca47021b8418: HTTP handler providing read and append-only create operations for triage notes

func NewTriageNoteSubResourceHandler

func NewTriageNoteSubResourceHandler(store TriageNoteStore) *TriageNoteSubResourceHandler

NewTriageNoteSubResourceHandler creates a new triage note sub-resource handler SEM@869fcafe6842b187f8cfe8e7cf65ca47021b8418: build a triage note sub-resource handler backed by the given store (pure)

func (*TriageNoteSubResourceHandler) CreateTriageNote

func (h *TriageNoteSubResourceHandler) CreateTriageNote(c *gin.Context)

CreateTriageNote creates a new triage note in a survey response SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: store a new sanitized triage note under a survey response, enforcing writer access (reads DB)

func (*TriageNoteSubResourceHandler) GetTriageNote

func (h *TriageNoteSubResourceHandler) GetTriageNote(c *gin.Context)

GetTriageNote retrieves a specific triage note by ID SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: fetch a single triage note by ID within a survey response, enforcing reader access (reads DB)

func (*TriageNoteSubResourceHandler) ListTriageNotes

func (h *TriageNoteSubResourceHandler) ListTriageNotes(c *gin.Context)

ListTriageNotes retrieves all triage notes for a survey response with pagination SEM@368e91d91cb110162c64b6ea10d49562a59bf3f0: list triage notes for a survey response with pagination, enforcing reader access (reads DB)

type TypesUUID

type TypesUUID = openapi_types.UUID

TypesUUID is an alias for openapi_types.UUID to make it easier to use

func NewUUID

func NewUUID() TypesUUID

NewUUID generates a new UUID SEM@386eea01f3b66c35027bf3ca762efbc291419e20: generate a new random UUID (pure)

func ParseUUID

func ParseUUID(s string) (TypesUUID, error)

ParseUUID converts a string to a TypesUUID SEM@b68e94b8e6dacc1b4643b872626ca878a7789b60: parse a UUID string and return a typed UUID or an error (pure)

type URIValidator

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

URIValidator validates URIs against an allowlist and SSRF protection rules. It supports exact host matching, wildcard subdomain matching, and configurable URL schemes. When an allowlist is configured, only matching hosts are permitted (and they bypass IP checks). When no allowlist is configured, all hosts are permitted subject to SSRF IP checks. SEM@9918d8cc280289af42fa2ce062596c87c994b704: SSRF-safe URI validator with configurable host allowlist and scheme restrictions (pure)

func NewURIValidator

func NewURIValidator(allowlist []string, schemes []string) *URIValidator

NewURIValidator creates a new URIValidator with the given allowlist and scheme configuration. Allowlist entries may be exact hostnames ("mycompany.com") or wildcard entries ("*.mycompany.com"). Invalid entries are skipped with a warning log. If schemes is nil or empty, defaults to ["https"]. SEM@9918d8cc280289af42fa2ce062596c87c994b704: build a URIValidator from allowlist entries and permitted URL schemes (pure)

func (*URIValidator) Validate

func (v *URIValidator) Validate(rawURL string) error

Validate checks whether the given raw URL is safe to access. It enforces scheme restrictions, allowlist matching, localhost blocking, and SSRF protection against private/internal IP addresses. SEM@e55d63794c48585aafab36880122df63ab8ab1be: validate a URL is safe to fetch, blocking private IPs and localhost (pure)

func (*URIValidator) ValidateReference

func (v *URIValidator) ValidateReference(rawURL string) error

ValidateReference checks whether the given raw URL is well-formed and uses an allowed scheme. It is intended for "reference" URI fields that the server stores but never fetches (e.g. issue_uri on a threat model). DNS resolution and private/loopback/cloud-metadata IP checks are deliberately skipped: without a fetch, there is no SSRF surface, and corporate trackers commonly resolve to RFC 1918 addresses.

When an allowlist is configured, the host must still match it. When no allowlist is configured, any host with an allowed scheme is accepted. SEM@f34985e914fe8d55039296cf4302878c88329818: validate a reference URI for scheme and allowlist without SSRF IP checks (pure)

type URLPatternMatcher

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

URLPatternMatcher maps URIs to provider names. Always active — even for disabled providers — to enable clear 422 errors. SEM@d98d9d1c0d122ade355ea522b49b132e523ebf52: maps URL patterns to content provider identifiers (pure)

func NewURLPatternMatcher

func NewURLPatternMatcher() *URLPatternMatcher

NewURLPatternMatcher creates a matcher with all known provider patterns. SEM@8b53645247cdf13cbfc2a73ad553fde880a9c3bd: build a URLPatternMatcher with all supported content providers registered (pure)

func (*URLPatternMatcher) Identify

func (m *URLPatternMatcher) Identify(uri string) string

Identify returns the provider name for a URI, or "" if unrecognized. SEM@a2db6d159e7859f682bdd332f9a3bfb0b222b7af: map a URL to its canonical content provider name (pure)

func (*URLPatternMatcher) IsKnownProvider

func (m *URLPatternMatcher) IsKnownProvider(name string) bool

IsKnownProvider returns true if the provider name is recognized. SEM@d98d9d1c0d122ade355ea522b49b132e523ebf52: validate that a provider name is registered in the matcher (pure)

type Unauthorized

type Unauthorized = Error

Unauthorized Standard error response format

type UndoRequestHandler

type UndoRequestHandler struct{}

UndoRequestHandler handles undo request messages SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: WebSocket handler that dispatches undo_request messages to the diagram session

func (*UndoRequestHandler) HandleMessage

func (h *UndoRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: dispatch an undo_request to the session with panic recovery

func (*UndoRequestHandler) MessageType

func (h *UndoRequestHandler) MessageType() string

SEM@d791c9a859555ac908a93f4bd6d49574103f13b9: return the undo_request message type identifier (pure)

type UndoRequestMessage

type UndoRequestMessage struct {
	MessageType    MessageType `json:"message_type"`
	InitiatingUser User        `json:"initiating_user"`
}

SEM@6b83881f440de9677d8274560c98c1baeb79d8c0: WebSocket message struct carrying the initiating user for an undo request (pure)

func (UndoRequestMessage) GetMessageType

func (m UndoRequestMessage) GetMessageType() MessageType

SEM@79bd6821708dbab17a998153f9a0d9ae26399bb5: return the message type discriminator for an undo request message (pure)

func (UndoRequestMessage) Validate

func (m UndoRequestMessage) Validate() error

SEM@892d57cddcb45ff8d7f653d68c1077422974e7b4: validate an undo request message; reject if type or user identity is missing (pure)

type UnsupportedMediaType

type UnsupportedMediaType = Error

UnsupportedMediaType Standard error response format

type UpdateAddonInvocationQuotaJSONRequestBody

type UpdateAddonInvocationQuotaJSONRequestBody = AddonQuotaUpdate

UpdateAddonInvocationQuotaJSONRequestBody defines body for UpdateAddonInvocationQuota for application/json ContentType.

type UpdateAdminGroupJSONRequestBody

type UpdateAdminGroupJSONRequestBody = UpdateAdminGroupRequest

UpdateAdminGroupJSONRequestBody defines body for UpdateAdminGroup for application/json ContentType.

type UpdateAdminGroupRequest

type UpdateAdminGroupRequest struct {
	// Description Updated group description
	Description *string `json:"description,omitempty"`

	// Name Updated human-readable group name
	Name *string `json:"name,omitempty"`
}

UpdateAdminGroupRequest Request body for updating group metadata

type UpdateAdminSurveyJSONRequestBody

type UpdateAdminSurveyJSONRequestBody = SurveyInput

UpdateAdminSurveyJSONRequestBody defines body for UpdateAdminSurvey for application/json ContentType.

type UpdateAdminSurveyMetadataByKeyJSONRequestBody

type UpdateAdminSurveyMetadataByKeyJSONRequestBody = Metadata

UpdateAdminSurveyMetadataByKeyJSONRequestBody defines body for UpdateAdminSurveyMetadataByKey for application/json ContentType.

type UpdateAdminUserJSONRequestBody

type UpdateAdminUserJSONRequestBody = UpdateAdminUserRequest

UpdateAdminUserJSONRequestBody defines body for UpdateAdminUser for application/json ContentType.

type UpdateAdminUserRequest

type UpdateAdminUserRequest struct {
	// Email Updated email address
	Email *openapi_types.Email `json:"email,omitempty"`

	// EmailVerified Updated email verification status
	EmailVerified *bool `json:"email_verified,omitempty"`

	// Name Updated display name
	Name *string `json:"name,omitempty"`
}

UpdateAdminUserRequest Request body for updating user metadata

type UpdateCurrentUserPreferencesJSONRequestBody

type UpdateCurrentUserPreferencesJSONRequestBody = UserPreferences

UpdateCurrentUserPreferencesJSONRequestBody defines body for UpdateCurrentUserPreferences for application/json ContentType.

type UpdateDiagramMetadataByKeyJSONBody

type UpdateDiagramMetadataByKeyJSONBody struct {
	// Value Metadata value
	Value string `json:"value"`
}

UpdateDiagramMetadataByKeyJSONBody defines parameters for UpdateDiagramMetadataByKey.

type UpdateDiagramMetadataByKeyJSONRequestBody

type UpdateDiagramMetadataByKeyJSONRequestBody UpdateDiagramMetadataByKeyJSONBody

UpdateDiagramMetadataByKeyJSONRequestBody defines body for UpdateDiagramMetadataByKey for application/json ContentType.

type UpdateDiagramResult

type UpdateDiagramResult struct {
	UpdatedDiagram    DfdDiagram
	PreviousVector    int64
	NewVector         int64
	VectorIncremented bool
}

UpdateDiagramResult contains the result of a centralized diagram update SEM@46c5960fcabe5dcd3f7014239dc4a8ed43579299: result of a centralized diagram update carrying the updated diagram and version vector change (pure)

type UpdateDocumentMetadataByKeyJSONBody

type UpdateDocumentMetadataByKeyJSONBody struct {
	// Value New value for the metadata entry
	Value string `json:"value"`
}

UpdateDocumentMetadataByKeyJSONBody defines parameters for UpdateDocumentMetadataByKey.

type UpdateDocumentMetadataByKeyJSONRequestBody

type UpdateDocumentMetadataByKeyJSONRequestBody UpdateDocumentMetadataByKeyJSONBody

UpdateDocumentMetadataByKeyJSONRequestBody defines body for UpdateDocumentMetadataByKey for application/json ContentType.

type UpdateIntakeSurveyResponseJSONRequestBody

type UpdateIntakeSurveyResponseJSONRequestBody = SurveyResponseInput

UpdateIntakeSurveyResponseJSONRequestBody defines body for UpdateIntakeSurveyResponse for application/json ContentType.

type UpdateIntakeSurveyResponseMetadataByKeyJSONRequestBody

type UpdateIntakeSurveyResponseMetadataByKeyJSONRequestBody = Metadata

UpdateIntakeSurveyResponseMetadataByKeyJSONRequestBody defines body for UpdateIntakeSurveyResponseMetadataByKey for application/json ContentType.

type UpdateIntakeSurveyResponseParams

type UpdateIntakeSurveyResponseParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateIntakeSurveyResponseParams defines parameters for UpdateIntakeSurveyResponse.

type UpdateNoteMetadataByKeyJSONBody

type UpdateNoteMetadataByKeyJSONBody struct {
	// Value New value for the metadata entry
	Value string `json:"value"`
}

UpdateNoteMetadataByKeyJSONBody defines parameters for UpdateNoteMetadataByKey.

type UpdateNoteMetadataByKeyJSONRequestBody

type UpdateNoteMetadataByKeyJSONRequestBody UpdateNoteMetadataByKeyJSONBody

UpdateNoteMetadataByKeyJSONRequestBody defines body for UpdateNoteMetadataByKey for application/json ContentType.

type UpdateProjectJSONRequestBody

type UpdateProjectJSONRequestBody = ProjectInput

UpdateProjectJSONRequestBody defines body for UpdateProject for application/json ContentType.

type UpdateProjectMetadataJSONRequestBody

type UpdateProjectMetadataJSONRequestBody = Metadata

UpdateProjectMetadataJSONRequestBody defines body for UpdateProjectMetadata for application/json ContentType.

type UpdateProjectNoteJSONRequestBody

type UpdateProjectNoteJSONRequestBody = ProjectNoteInput

UpdateProjectNoteJSONRequestBody defines body for UpdateProjectNote for application/json ContentType.

type UpdateProjectParams

type UpdateProjectParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateProjectParams defines parameters for UpdateProject.

type UpdateRepositoryMetadataByKeyJSONBody

type UpdateRepositoryMetadataByKeyJSONBody struct {
	// Value New value for the metadata entry
	Value string `json:"value"`
}

UpdateRepositoryMetadataByKeyJSONBody defines parameters for UpdateRepositoryMetadataByKey.

type UpdateRepositoryMetadataByKeyJSONRequestBody

type UpdateRepositoryMetadataByKeyJSONRequestBody UpdateRepositoryMetadataByKeyJSONBody

UpdateRepositoryMetadataByKeyJSONRequestBody defines body for UpdateRepositoryMetadataByKey for application/json ContentType.

type UpdateSystemSettingJSONRequestBody

type UpdateSystemSettingJSONRequestBody = SystemSettingUpdate

UpdateSystemSettingJSONRequestBody defines body for UpdateSystemSetting for application/json ContentType.

type UpdateTeamJSONRequestBody

type UpdateTeamJSONRequestBody = TeamInput

UpdateTeamJSONRequestBody defines body for UpdateTeam for application/json ContentType.

type UpdateTeamMetadataJSONRequestBody

type UpdateTeamMetadataJSONRequestBody = Metadata

UpdateTeamMetadataJSONRequestBody defines body for UpdateTeamMetadata for application/json ContentType.

type UpdateTeamNoteJSONRequestBody

type UpdateTeamNoteJSONRequestBody = TeamNoteInput

UpdateTeamNoteJSONRequestBody defines body for UpdateTeamNote for application/json ContentType.

type UpdateTeamParams

type UpdateTeamParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateTeamParams defines parameters for UpdateTeam.

type UpdateThreatMetadataByKeyJSONBody

type UpdateThreatMetadataByKeyJSONBody struct {
	// Value New value for the metadata entry
	Value string `json:"value"`
}

UpdateThreatMetadataByKeyJSONBody defines parameters for UpdateThreatMetadataByKey.

type UpdateThreatMetadataByKeyJSONRequestBody

type UpdateThreatMetadataByKeyJSONRequestBody UpdateThreatMetadataByKeyJSONBody

UpdateThreatMetadataByKeyJSONRequestBody defines body for UpdateThreatMetadataByKey for application/json ContentType.

type UpdateThreatModelAssetJSONRequestBody

type UpdateThreatModelAssetJSONRequestBody = AssetInput

UpdateThreatModelAssetJSONRequestBody defines body for UpdateThreatModelAsset for application/json ContentType.

type UpdateThreatModelAssetMetadataJSONRequestBody

type UpdateThreatModelAssetMetadataJSONRequestBody = Metadata

UpdateThreatModelAssetMetadataJSONRequestBody defines body for UpdateThreatModelAssetMetadata for application/json ContentType.

type UpdateThreatModelAssetParams

type UpdateThreatModelAssetParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateThreatModelAssetParams defines parameters for UpdateThreatModelAsset.

type UpdateThreatModelDiagramJSONRequestBody

type UpdateThreatModelDiagramJSONRequestBody = DfdDiagramInput

UpdateThreatModelDiagramJSONRequestBody defines body for UpdateThreatModelDiagram for application/json ContentType.

type UpdateThreatModelDiagramParams

type UpdateThreatModelDiagramParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateThreatModelDiagramParams defines parameters for UpdateThreatModelDiagram.

type UpdateThreatModelDocumentJSONRequestBody

type UpdateThreatModelDocumentJSONRequestBody = DocumentInput

UpdateThreatModelDocumentJSONRequestBody defines body for UpdateThreatModelDocument for application/json ContentType.

type UpdateThreatModelDocumentParams

type UpdateThreatModelDocumentParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateThreatModelDocumentParams defines parameters for UpdateThreatModelDocument.

type UpdateThreatModelJSONRequestBody

type UpdateThreatModelJSONRequestBody = ThreatModelInput

UpdateThreatModelJSONRequestBody defines body for UpdateThreatModel for application/json ContentType.

type UpdateThreatModelMetadataByKeyJSONBody

type UpdateThreatModelMetadataByKeyJSONBody struct {
	// Value New value for the metadata entry
	Value string `json:"value"`
}

UpdateThreatModelMetadataByKeyJSONBody defines parameters for UpdateThreatModelMetadataByKey.

type UpdateThreatModelMetadataByKeyJSONRequestBody

type UpdateThreatModelMetadataByKeyJSONRequestBody UpdateThreatModelMetadataByKeyJSONBody

UpdateThreatModelMetadataByKeyJSONRequestBody defines body for UpdateThreatModelMetadataByKey for application/json ContentType.

type UpdateThreatModelNoteJSONRequestBody

type UpdateThreatModelNoteJSONRequestBody = NoteInput

UpdateThreatModelNoteJSONRequestBody defines body for UpdateThreatModelNote for application/json ContentType.

type UpdateThreatModelParams

type UpdateThreatModelParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateThreatModelParams defines parameters for UpdateThreatModel.

type UpdateThreatModelRepositoryJSONRequestBody

type UpdateThreatModelRepositoryJSONRequestBody = RepositoryInput

UpdateThreatModelRepositoryJSONRequestBody defines body for UpdateThreatModelRepository for application/json ContentType.

type UpdateThreatModelThreatJSONRequestBody

type UpdateThreatModelThreatJSONRequestBody = ThreatInput

UpdateThreatModelThreatJSONRequestBody defines body for UpdateThreatModelThreat for application/json ContentType.

type UpdateThreatModelThreatParams

type UpdateThreatModelThreatParams struct {
	// IfMatch Optimistic-locking precondition. Pass the integer version returned by the previous read (or as the body 'version' field on the previous write). On version mismatch the server returns 409 Conflict. In a future release this header will be required and missing values will return 428 Precondition Required.
	IfMatch *IfMatchHeader `json:"If-Match,omitempty"`
}

UpdateThreatModelThreatParams defines parameters for UpdateThreatModelThreat.

type UpdateUserAPIQuotaJSONRequestBody

type UpdateUserAPIQuotaJSONRequestBody = UserQuotaUpdate

UpdateUserAPIQuotaJSONRequestBody defines body for UpdateUserAPIQuota for application/json ContentType.

type UpdateWebhookDeliveryStatusJSONRequestBody

type UpdateWebhookDeliveryStatusJSONRequestBody = UpdateWebhookDeliveryStatusRequest

UpdateWebhookDeliveryStatusJSONRequestBody defines body for UpdateWebhookDeliveryStatus for application/json ContentType.

type UpdateWebhookDeliveryStatusParams

type UpdateWebhookDeliveryStatusParams struct {
	// XWebhookSignature HMAC-SHA256 signature (format: sha256={hex_signature})
	XWebhookSignature XWebhookSignatureHeaderParam `json:"X-Webhook-Signature"`
}

UpdateWebhookDeliveryStatusParams defines parameters for UpdateWebhookDeliveryStatus.

type UpdateWebhookDeliveryStatusRequest

type UpdateWebhookDeliveryStatusRequest struct {
	// Status New delivery status
	Status UpdateWebhookDeliveryStatusRequestStatus `json:"status"`

	// StatusMessage Human-readable status description
	StatusMessage *string `json:"status_message,omitempty"`

	// StatusPercent Progress percentage (0-100)
	StatusPercent *int `json:"status_percent,omitempty"`
}

UpdateWebhookDeliveryStatusRequest Request to update the status of a webhook delivery

type UpdateWebhookDeliveryStatusRequestStatus

type UpdateWebhookDeliveryStatusRequestStatus string

UpdateWebhookDeliveryStatusRequestStatus New delivery status

const (
	UpdateWebhookDeliveryStatusRequestStatusCompleted  UpdateWebhookDeliveryStatusRequestStatus = "completed"
	UpdateWebhookDeliveryStatusRequestStatusFailed     UpdateWebhookDeliveryStatusRequestStatus = "failed"
	UpdateWebhookDeliveryStatusRequestStatusInProgress UpdateWebhookDeliveryStatusRequestStatus = "in_progress"
)

Defines values for UpdateWebhookDeliveryStatusRequestStatus.

func (UpdateWebhookDeliveryStatusRequestStatus) Valid

Valid indicates whether the value is a known member of the UpdateWebhookDeliveryStatusRequestStatus enum.

type UpdateWebhookDeliveryStatusResponse

type UpdateWebhookDeliveryStatusResponse struct {
	Id              openapi_types.UUID                        `json:"id"`
	Status          UpdateWebhookDeliveryStatusResponseStatus `json:"status"`
	StatusPercent   int                                       `json:"status_percent"`
	StatusUpdatedAt time.Time                                 `json:"status_updated_at"`
}

UpdateWebhookDeliveryStatusResponse Response confirming webhook delivery status update

type UpdateWebhookDeliveryStatusResponseStatus

type UpdateWebhookDeliveryStatusResponseStatus string

UpdateWebhookDeliveryStatusResponseStatus defines model for UpdateWebhookDeliveryStatusResponse.Status.

const (
	UpdateWebhookDeliveryStatusResponseStatusDelivered  UpdateWebhookDeliveryStatusResponseStatus = "delivered"
	UpdateWebhookDeliveryStatusResponseStatusFailed     UpdateWebhookDeliveryStatusResponseStatus = "failed"
	UpdateWebhookDeliveryStatusResponseStatusInProgress UpdateWebhookDeliveryStatusResponseStatus = "in_progress"
	UpdateWebhookDeliveryStatusResponseStatusPending    UpdateWebhookDeliveryStatusResponseStatus = "pending"
)

Defines values for UpdateWebhookDeliveryStatusResponseStatus.

func (UpdateWebhookDeliveryStatusResponseStatus) Valid

Valid indicates whether the value is a known member of the UpdateWebhookDeliveryStatusResponseStatus enum.

type UpdateWebhookQuotaJSONRequestBody

type UpdateWebhookQuotaJSONRequestBody = WebhookQuotaUpdate

UpdateWebhookQuotaJSONRequestBody defines body for UpdateWebhookQuota for application/json ContentType.

type UsabilityFeedback

type UsabilityFeedback struct {
	// ClientBuild Short commit hash of the client build
	ClientBuild *string `json:"client_build,omitempty"`

	// ClientId Identifier of the client emitting the feedback (e.g., 'tmi-ux')
	ClientId string `json:"client_id"`

	// ClientVersion Semver version string of the client
	ClientVersion *string `json:"client_version,omitempty"`

	// CreatedAt Server-assigned timestamp
	CreatedAt time.Time `json:"created_at"`

	// CreatedBy Internal UUID of the submitting user
	CreatedBy openapi_types.UUID `json:"created_by"`

	// Id Server-assigned identifier
	Id openapi_types.UUID `json:"id"`

	// Screenshot Optional viewport screenshot captured by the client at submission time. Data URL form (e.g. `data:image/jpeg;base64,...`). Used as support context.
	Screenshot *string `json:"screenshot,omitempty"`

	// Sentiment User sentiment
	Sentiment UsabilityFeedbackSentiment `json:"sentiment"`

	// Surface Logical UI-surface identifier (developer-supplied tag for analytics)
	Surface string `json:"surface"`

	// UserAgent Browser User-Agent header value (when applicable)
	UserAgent *string `json:"user_agent,omitempty"`

	// UserAgentData Optional NavigatorUAData payload (≤ 4 KB serialized)
	UserAgentData *map[string]interface{} `json:"user_agent_data,omitempty"`

	// Verbatim Optional free-text comment from the user
	Verbatim *string `json:"verbatim,omitempty"`

	// Viewport Viewport dimensions, e.g. '1280x1024'
	Viewport *string `json:"viewport,omitempty"`
}

UsabilityFeedback defines model for UsabilityFeedback.

type UsabilityFeedbackHandler

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

UsabilityFeedbackHandler bundles the three endpoints for /usability_feedback*. SEM@72f2ef0deaad62ae1c2054ae42a059a253d123b7: handle HTTP endpoints for the usability feedback resource (reads DB)

func NewUsabilityFeedbackHandler

func NewUsabilityFeedbackHandler(repo UsabilityFeedbackRepository) *UsabilityFeedbackHandler

NewUsabilityFeedbackHandler constructs the handler. SEM@72f2ef0deaad62ae1c2054ae42a059a253d123b7: build a UsabilityFeedbackHandler wired to a given repository (pure)

func (*UsabilityFeedbackHandler) Create

func (h *UsabilityFeedbackHandler) Create(c *gin.Context)

Create handles POST /usability_feedback. SEM@72f2ef0deaad62ae1c2054ae42a059a253d123b7: store a new usability feedback record for the authenticated user (reads DB)

func (*UsabilityFeedbackHandler) Get

Get handles GET /usability_feedback/{id}. SEM@72f2ef0deaad62ae1c2054ae42a059a253d123b7: fetch a single usability feedback record by UUID (reads DB)

func (*UsabilityFeedbackHandler) List

func (h *UsabilityFeedbackHandler) List(c *gin.Context)

List handles GET /usability_feedback with filters and pagination. SEM@72f2ef0deaad62ae1c2054ae42a059a253d123b7: list paginated usability feedback records with optional filters (reads DB)

type UsabilityFeedbackInput

type UsabilityFeedbackInput struct {
	// ClientBuild Short commit hash of the client build
	ClientBuild *string `json:"client_build,omitempty"`

	// ClientId Identifier of the client emitting the feedback (e.g., 'tmi-ux')
	ClientId string `json:"client_id"`

	// ClientVersion Semver version string of the client
	ClientVersion *string `json:"client_version,omitempty"`

	// Screenshot Optional viewport screenshot captured by the client at submission time. Data URL form (e.g. `data:image/jpeg;base64,...`). Used as support context.
	Screenshot *string `json:"screenshot,omitempty"`

	// Sentiment User sentiment
	Sentiment UsabilityFeedbackInputSentiment `json:"sentiment"`

	// Surface Logical UI-surface identifier (developer-supplied tag for analytics)
	Surface string `json:"surface"`

	// UserAgent Browser User-Agent header value (when applicable)
	UserAgent *string `json:"user_agent,omitempty"`

	// UserAgentData Optional NavigatorUAData payload (≤ 4 KB serialized)
	UserAgentData *map[string]interface{} `json:"user_agent_data,omitempty"`

	// Verbatim Optional free-text comment from the user
	Verbatim *string `json:"verbatim,omitempty"`

	// Viewport Viewport dimensions, e.g. '1280x1024'
	Viewport *string `json:"viewport,omitempty"`
}

UsabilityFeedbackInput defines model for UsabilityFeedbackInput.

type UsabilityFeedbackInputSentiment

type UsabilityFeedbackInputSentiment string

UsabilityFeedbackInputSentiment User sentiment

const (
	UsabilityFeedbackInputSentimentDown UsabilityFeedbackInputSentiment = "down"
	UsabilityFeedbackInputSentimentUp   UsabilityFeedbackInputSentiment = "up"
)

Defines values for UsabilityFeedbackInputSentiment.

func (UsabilityFeedbackInputSentiment) Valid

Valid indicates whether the value is a known member of the UsabilityFeedbackInputSentiment enum.

type UsabilityFeedbackListFilter

type UsabilityFeedbackListFilter struct {
	Sentiment     string // "up", "down", or "" for any
	ClientID      string
	Surface       string
	CreatedAfter  time.Time // zero value = no lower bound
	CreatedBefore time.Time // zero value = no upper bound
}

UsabilityFeedbackListFilter controls UsabilityFeedbackRepository.List. Zero/empty fields are ignored (no filter applied). SEM@c02756463276ea096f49221b581d44cd5b21ea12: filter criteria for listing usability feedback by sentiment, surface, or date range (pure)

type UsabilityFeedbackRepository

type UsabilityFeedbackRepository interface {
	Create(ctx context.Context, fb *models.UsabilityFeedback) error
	Get(ctx context.Context, id string) (*models.UsabilityFeedback, error)
	List(ctx context.Context, filter UsabilityFeedbackListFilter, offset, limit int) ([]models.UsabilityFeedback, error)
	Count(ctx context.Context, filter UsabilityFeedbackListFilter) (int64, error)
}

UsabilityFeedbackRepository defines persistence for usability_feedback rows. SEM@c02756463276ea096f49221b581d44cd5b21ea12: interface for persisting and querying usability feedback records (reads DB)

var GlobalUsabilityFeedbackRepository UsabilityFeedbackRepository

Feedback repository globals

type UsabilityFeedbackSentiment

type UsabilityFeedbackSentiment string

UsabilityFeedbackSentiment User sentiment

const (
	UsabilityFeedbackSentimentDown UsabilityFeedbackSentiment = "down"
	UsabilityFeedbackSentimentUp   UsabilityFeedbackSentiment = "up"
)

Defines values for UsabilityFeedbackSentiment.

func (UsabilityFeedbackSentiment) Valid

func (e UsabilityFeedbackSentiment) Valid() bool

Valid indicates whether the value is a known member of the UsabilityFeedbackSentiment enum.

type UsageAggregation

type UsageAggregation struct {
	TotalMessages         int `json:"total_messages"`
	TotalPromptTokens     int `json:"total_prompt_tokens"`
	TotalCompletionTokens int `json:"total_completion_tokens"`
	TotalEmbeddingTokens  int `json:"total_embedding_tokens"`
	SessionCount          int `json:"session_count"`
}

UsageAggregation holds aggregated usage totals across multiple records SEM@e5e141caabe74e3ce853b6d7b45827bb1864fb32: aggregated LLM token and session usage totals across multiple records (pure)

type UsedInAuthorizationsQueryParam

type UsedInAuthorizationsQueryParam = bool

UsedInAuthorizationsQueryParam defines model for UsedInAuthorizationsQueryParam.

type User

type User struct {
	// DisplayName User full name for display
	DisplayName string `json:"display_name"`

	// Email User email address (required)
	Email openapi_types.Email `json:"email"`

	// PrincipalType Always "user" for User objects
	PrincipalType UserPrincipalType `json:"principal_type"`

	// Provider Identity provider name (e.g., "google", "github", "microsoft", "tmi"). Use "tmi" for TMI built-in groups.
	Provider string `json:"provider"`

	// ProviderId Provider-assigned identifier. For users: provider_user_id (e.g., email or OAuth sub). For groups: group_name.
	ProviderId string `json:"provider_id"`
}

User defines model for User.

type UserAPIQuota

type UserAPIQuota struct {
	// CreatedAt Creation timestamp
	CreatedAt time.Time `json:"created_at"`

	// MaxRequestsPerHour Maximum API requests per hour (optional)
	MaxRequestsPerHour *int `json:"max_requests_per_hour,omitempty"`

	// MaxRequestsPerMinute Maximum API requests per minute
	MaxRequestsPerMinute int `json:"max_requests_per_minute"`

	// ModifiedAt Last modification timestamp
	ModifiedAt time.Time `json:"modified_at"`

	// UserId User ID
	UserId openapi_types.UUID `json:"user_id"`
}

UserAPIQuota API rate limit and quota configuration for a user

func (*UserAPIQuota) SetCreatedAt

func (q *UserAPIQuota) SetCreatedAt(t time.Time)

SetCreatedAt implements WithTimestamps for UserAPIQuota SEM@922d880b24abd3da8955ba05fd9038f3ec43e512: set the created_at timestamp on a UserAPIQuota to implement WithTimestamps (pure)

func (*UserAPIQuota) SetModifiedAt

func (q *UserAPIQuota) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps for UserAPIQuota SEM@922d880b24abd3da8955ba05fd9038f3ec43e512: set the modified_at timestamp on a UserAPIQuota to implement WithTimestamps (pure)

type UserAPIQuotaStoreInterface

type UserAPIQuotaStoreInterface interface {
	Get(ctx context.Context, userID string) (UserAPIQuota, error)
	GetOrDefault(ctx context.Context, userID string) UserAPIQuota
	List(ctx context.Context, offset, limit int) ([]UserAPIQuota, error)
	Count(ctx context.Context) (int, error)
	Create(ctx context.Context, item UserAPIQuota) (UserAPIQuota, error)
	Update(ctx context.Context, userID string, item UserAPIQuota) error
	Delete(ctx context.Context, userID string) error
	Upsert(ctx context.Context, item UserAPIQuota) (UserAPIQuota, error)
}

UserAPIQuotaStoreInterface defines operations for user API quotas. All methods accept a context.Context so the underlying GORM transaction retry wrapper can use the caller-supplied context for cancellation instead of falling back to context.Background(). SEM@f02caa14cf5cd68c437a2bddba77d5f8f0d17f8c: define CRUD and upsert operations for per-user API quota records (reads DB)

var GlobalUserAPIQuotaStore UserAPIQuotaStoreInterface

Global user API quota store instance

type UserActivityData

type UserActivityData struct {
	UserEmail string `json:"user_email"`
	UserName  string `json:"user_name,omitempty"`
}

UserActivityData contains data for user activity notifications SEM@66b1e1515b82356913c8625edc8616772c3c70d3: payload for user join/leave activity notifications (pure)

type UserDeletionHandler

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

UserDeletionHandler handles user self-deletion operations SEM@bd740ab90ce24a669adc1fa8b8153efbd33bac10: HTTP handler struct for the two-step user self-deletion flow

func NewUserDeletionHandler

func NewUserDeletionHandler(authService *auth.Service) *UserDeletionHandler

NewUserDeletionHandler creates a new user deletion handler SEM@bd740ab90ce24a669adc1fa8b8153efbd33bac10: build a UserDeletionHandler wired to the given auth service (pure)

func (*UserDeletionHandler) DeleteUserAccount

func (h *UserDeletionHandler) DeleteUserAccount(c *gin.Context)

DeleteUserAccount handles the two-step user deletion process Step 1: No challenge parameter -> Generate and return challenge Step 2: With challenge parameter -> Validate and delete user SEM@c85b80a7fe0b19a3e43a1c6f9dc121ba2ccd093c: handle the two-step user self-deletion: issue a challenge or validate one and delete the account

type UserFilter

type UserFilter struct {
	Provider        string
	Email           string // Case-insensitive ILIKE %email%
	Name            string // Case-insensitive ILIKE %name%
	CreatedAfter    *time.Time
	CreatedBefore   *time.Time
	LastLoginAfter  *time.Time
	LastLoginBefore *time.Time
	Automation      *bool
	Limit           int
	Offset          int
	SortBy          string // created_at, last_login, email, name
	SortOrder       string // asc, desc
}

UserFilter defines filtering options for user queries SEM@24dcbaf59ea6bfe4e66c3f1fbc4863c809cfdc0e: filter and pagination criteria for listing users by provider, email, name, or date range (pure)

type UserGroupMembership

type UserGroupMembership struct {
	// GroupName Group name (e.g. administrators, security-reviewers)
	GroupName string `json:"group_name"`

	// InternalUuid Group internal UUID
	InternalUuid openapi_types.UUID `json:"internal_uuid"`

	// Name Display name for the group
	Name *string `json:"name,omitempty"`
}

UserGroupMembership TMI-managed group that a user belongs to

type UserIdPathParam

type UserIdPathParam = openapi_types.UUID

UserIdPathParam defines model for UserIdPathParam.

type UserInfo

type UserInfo struct {
	UserID       string
	UserName     string
	UserEmail    string
	UserProvider string
	InternalUUID string
	// TokenExpiry is the absolute expiration time of the JWT that
	// authenticated the request, captured from the "tokenExp" gin
	// context value populated by the JWT middleware. Zero when the
	// caller is not JWT-authenticated (e.g., test fixtures).
	TokenExpiry time.Time
}

UserInfo represents extracted user information SEM@a9626140ff4ccb3bf8ae4b474024684bd7063b72: value object holding authenticated user identity and JWT expiry for a WebSocket session

type UserInfoExtractor

type UserInfoExtractor struct{}

UserInfoExtractor handles extracting user information from the request context SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: helper that extracts authenticated user identity fields from a Gin request context

func (*UserInfoExtractor) ExtractUserInfo

func (u *UserInfoExtractor) ExtractUserInfo(c *gin.Context) (*UserInfo, error)

ExtractUserInfo extracts user information from the gin context SEM@a9626140ff4ccb3bf8ae4b474024684bd7063b72: extract and validate user identity fields from the Gin context, returning an error if the user ID is absent (pure)

type UserPreferences

type UserPreferences map[string]map[string]interface{}

UserPreferences User preferences organized by client application. Keys are client identifiers (1-64 chars, alphanumeric + underscore/hyphen), values are preference objects. Maximum 20 clients, 1KB total size.

type UserPrincipalType

type UserPrincipalType string

UserPrincipalType Always "user" for User objects

const (
	UserPrincipalTypeUser UserPrincipalType = "user"
)

Defines values for UserPrincipalType.

func (UserPrincipalType) Valid

func (e UserPrincipalType) Valid() bool

Valid indicates whether the value is a known member of the UserPrincipalType enum.

type UserQuotaUpdate

type UserQuotaUpdate struct {
	// MaxRequestsPerHour Maximum API requests per hour (optional)
	MaxRequestsPerHour *int `json:"max_requests_per_hour,omitempty"`

	// MaxRequestsPerMinute Maximum API requests per minute
	MaxRequestsPerMinute int `json:"max_requests_per_minute"`
}

UserQuotaUpdate Configuration update for user API quotas

type UserResolver

type UserResolver interface {
	GetUserByID(ctx context.Context, id string) (auth.User, error)
	GetUserByProviderID(ctx context.Context, provider, providerUserID string) (auth.User, error)
	GetUserByProviderAndEmail(ctx context.Context, provider, email string) (auth.User, error)
	GetUserByEmail(ctx context.Context, email string) (auth.User, error)
	GetUserByAnyProviderID(ctx context.Context, providerUserID string) (auth.User, error)
}

UserResolver provides user lookup capabilities for identity resolution. Implemented by auth.Service. SEM@c189a53ba583916876378527997b8c11ab450f46: interface for looking up a user by UUID, provider ID, provider+email, or email (reads DB)

type UserStore

type UserStore interface {
	// List returns users with optional filtering and pagination
	List(ctx context.Context, filter UserFilter) ([]AdminUser, error)

	// Get retrieves a user by internal UUID
	Get(ctx context.Context, internalUUID uuid.UUID) (*AdminUser, error)

	// GetByProviderAndID retrieves a user by provider and provider_user_id
	GetByProviderAndID(ctx context.Context, provider string, providerUserID string) (*AdminUser, error)

	// Update updates user metadata (email, name, email_verified)
	Update(ctx context.Context, user AdminUser) error

	// Delete deletes a user by internal UUID.
	// Returns deletion statistics.
	Delete(ctx context.Context, internalUUID uuid.UUID) (*DeletionStats, error)

	// Count returns total count of users matching the filter
	Count(ctx context.Context, filter UserFilter) (int, error)

	// EnrichUsers adds related data to users (admin status, groups, threat model counts)
	EnrichUsers(ctx context.Context, users []AdminUser) ([]AdminUser, error)
}

UserStore defines the interface for user storage operations SEM@aaa9664f0ee44fef65807ddde317d73afdfcf8eb: store interface for listing, fetching, updating, and deleting user accounts (reads DB)

var GlobalUserStore UserStore

GlobalUserStore is the global singleton for user storage

type UserWithAdminStatus

type UserWithAdminStatus struct {
	// DisplayName User full name for display
	DisplayName string `json:"display_name"`

	// Email User email address (required)
	Email openapi_types.Email `json:"email"`

	// Groups TMI-managed groups that the user belongs to (direct membership only, excludes the implicit everyone pseudo-group)
	Groups []UserGroupMembership `json:"groups"`

	// IsAdmin Whether the user has administrator privileges (computed dynamically based on Administrators group membership)
	IsAdmin bool `json:"is_admin"`

	// IsSecurityReviewer Whether the user is a security reviewer (computed dynamically based on Security Reviewers group membership)
	IsSecurityReviewer bool `json:"is_security_reviewer"`

	// PrincipalType Always "user" for User objects
	PrincipalType UserWithAdminStatusPrincipalType `json:"principal_type"`

	// Provider Identity provider name (e.g., "google", "github", "microsoft", "tmi"). Use "tmi" for TMI built-in groups.
	Provider string `json:"provider"`

	// ProviderId Provider-assigned identifier. For users: provider_user_id (e.g., email or OAuth sub). For groups: group_name.
	ProviderId string `json:"provider_id"`
}

UserWithAdminStatus defines model for UserWithAdminStatus.

type UserWithAdminStatusPrincipalType

type UserWithAdminStatusPrincipalType string

UserWithAdminStatusPrincipalType Always "user" for User objects

const (
	UserWithAdminStatusPrincipalTypeUser UserWithAdminStatusPrincipalType = "user"
)

Defines values for UserWithAdminStatusPrincipalType.

func (UserWithAdminStatusPrincipalType) Valid

Valid indicates whether the value is a known member of the UserWithAdminStatusPrincipalType enum.

type ValidatedMetadataRequest

type ValidatedMetadataRequest struct {
	Key   string `json:"key" binding:"required" maxlength:"100"`
	Value string `json:"value" binding:"required" maxlength:"1000"`
}

Enhanced Metadata Request Structs (for migration example) SEM@4fa1d37f07fd36467dea01526b97410523474271: request struct for a metadata key-value pair with required binding and length constraints

type ValidationConfig

type ValidationConfig struct {
	// ProhibitedFields lists fields that cannot be set for this operation
	ProhibitedFields []string
	// CustomValidators are additional validation functions to run
	CustomValidators []ValidatorFunc
	// AllowOwnerField permits the owner field (for PUT operations)
	AllowOwnerField bool
	// Operation type for context-specific error messages
	Operation string
}

ValidationConfig defines validation rules for an endpoint SEM@63189587a90229342bc1d25023ec7a515412fb4f: configuration of prohibited fields, custom validators, and operation context for request validation

func GetValidationConfig

func GetValidationConfig(endpoint string) (ValidationConfig, bool)

GetValidationConfig returns the validation config for an endpoint SEM@63189587a90229342bc1d25023ec7a515412fb4f: fetch the validation config for a named API endpoint (pure)

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

ValidationError represents a validation error SEM@386eea01f3b66c35027bf3ca762efbc291419e20: represent a field-level validation failure with field name and message (pure)

type ValidationResult

type ValidationResult struct {
	Valid  bool
	Errors []string
}

ValidationResult provides validation outcome details SEM@63189587a90229342bc1d25023ec7a515412fb4f: outcome of a struct validation run with a validity flag and list of error messages

func ValidateStruct

func ValidateStruct(s any, config ValidationConfig) ValidationResult

ValidateStruct performs validation on any struct and returns detailed results SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: run custom validators and required-field checks on a struct and return aggregated validation results (pure)

type ValidatorFunc

type ValidatorFunc func(any) error

ValidatorFunc is a function that validates a parsed request SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: function type for a custom per-struct validation rule

var ValidateAuthorizationEntriesFunc ValidatorFunc = ValidateAuthorizationEntriesFromStruct

ValidateAuthorizationEntriesFunc validates authorization array

var ValidateDiagramTypeFunc ValidatorFunc = ValidateDiagramType

ValidateDiagramTypeFunc validates diagram type field

var ValidateUUIDFieldsFunc ValidatorFunc = ValidateUUIDFieldsFromStruct

ValidateUUIDFieldsFunc validates UUID format for ID fields

type VectorIndex

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

VectorIndex is an in-memory vector index using brute-force cosine similarity. This is adequate for threat-model scale (hundreds of vectors). SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: in-memory vector index supporting cosine-similarity search with concurrent access (mutates shared state)

func NewVectorIndex

func NewVectorIndex(dimension int) *VectorIndex

NewVectorIndex creates a new vector index for vectors of the given dimension SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: build an empty vector index for the specified embedding dimension (pure)

func (*VectorIndex) Add

func (vi *VectorIndex) Add(id string, vector []float32, chunkText string)

Add inserts a vector into the index SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: store a vector and its chunk text in the index (mutates shared state)

func (*VectorIndex) Count

func (vi *VectorIndex) Count() int

Count returns the number of vectors in the index SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: return the number of vectors currently stored in the index (pure)

func (*VectorIndex) Delete

func (vi *VectorIndex) Delete(id string)

Delete removes a vector by ID SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: remove a vector entry by ID from the index (mutates shared state)

func (*VectorIndex) MemorySize

func (vi *VectorIndex) MemorySize() int64

MemorySize estimates the memory used by this index in bytes SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: estimate total memory consumed by all vectors and chunk text in the index in bytes (pure)

func (*VectorIndex) Search

func (vi *VectorIndex) Search(query []float32, topK int) []VectorSearchResult

Search returns the top-K most similar vectors to the query SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: return the top-K most similar vectors to a query using cosine similarity (pure)

type VectorIndexManager

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

VectorIndexManager manages in-memory vector indexes per threat model SEM@def63b409c24f2ad196af883736040232f69379e: manages memory-budgeted in-memory vector indexes per threat model with LRU eviction (mutates shared state)

func NewVectorIndexManager

func NewVectorIndexManager(embeddingStore TimmyEmbeddingStore, maxMemoryMB int, inactivityTimeoutSeconds int) *VectorIndexManager

NewVectorIndexManager creates a new manager with the given memory budget SEM@def63b409c24f2ad196af883736040232f69379e: build a VectorIndexManager with a memory budget and start the background eviction loop (mutates shared state)

func (*VectorIndexManager) GetOrLoadIndex

func (m *VectorIndexManager) GetOrLoadIndex(
	ctx context.Context,
	threatModelID, indexType, expectedModel string,
	dimension int,
) (*VectorIndex, error)

GetOrLoadIndex returns the index for a threat model and index type, loading from DB if needed. expectedModel + dimension are the active embedding model and dimension; if any loaded row disagrees, *ErrEmbeddingModelMismatch is returned and the caller is responsible for cleanup. SEM@ebf201816c3638ec74fc8483a2a649af3ccddfc9: fetch a threat model's vector index from memory or load from DB, rejecting stale embeddings (reads DB)

func (*VectorIndexManager) GetStatus

func (m *VectorIndexManager) GetStatus() map[string]any

GetStatus returns current memory and index status for the admin endpoint SEM@93f3b413fc45194106e4b8c0a3c1705ca53fa822: aggregate memory usage and per-index metrics for the admin status endpoint (pure)

func (*VectorIndexManager) InvalidateIndex

func (m *VectorIndexManager) InvalidateIndex(threatModelID, indexType string)

InvalidateIndex removes the in-memory index for the given threat model and index type, but only if there are no active sessions. If active sessions exist, it logs and skips. SEM@93f3b413fc45194106e4b8c0a3c1705ca53fa822: remove a vector index from memory if no sessions are active (mutates shared state)

func (*VectorIndexManager) IsStopped

func (m *VectorIndexManager) IsStopped() bool

IsStopped reports whether Stop has been called on this manager. It does not indicate that the eviction goroutine has fully exited, only that it has been signalled to stop. SEM@def63b409c24f2ad196af883736040232f69379e: report whether Stop has been called on this manager (pure)

func (*VectorIndexManager) ReleaseIndex

func (m *VectorIndexManager) ReleaseIndex(threatModelID, indexType string)

ReleaseIndex decrements the active session count for the given threat model and index type SEM@93f3b413fc45194106e4b8c0a3c1705ca53fa822: decrement the active session count for a vector index (mutates shared state)

func (*VectorIndexManager) Stop

func (m *VectorIndexManager) Stop()

Stop terminates the background eviction goroutine. It is safe to call once; subsequent calls are no-ops. Call this when discarding a VectorIndexManager (e.g. when the Timmy runtime is rebuilt) to avoid leaking the eviction goroutine and its ticker. SEM@def63b409c24f2ad196af883736040232f69379e: signal the background eviction goroutine to terminate; safe to call multiple times (mutates shared state)

type VectorSearchResult

type VectorSearchResult struct {
	ID         string
	ChunkText  string
	Similarity float32
}

VectorSearchResult represents a search result with similarity score SEM@83f445fe5f41f248da5bfb60c60326e7d7c65d0a: result from a vector similarity search, pairing chunk text with its relevance score (pure)

type Version

type Version struct {
	Major      int    `json:"major"`
	Minor      int    `json:"minor"`
	Patch      int    `json:"patch"`
	PreRelease string `json:"pre_release,omitempty"`
	GitCommit  string `json:"git_commit,omitempty"`
	BuildDate  string `json:"build_date,omitempty"`
	APIVersion string `json:"api_version"`
}

Version contains versioning information for the API SEM@6acba406c94a7bc4caaf713a960fd4f28bb3e6a7: structured type holding semantic version, pre-release, commit, build date, and API version (pure)

func GetVersion

func GetVersion() Version

GetVersion returns the current application version SEM@6acba406c94a7bc4caaf713a960fd4f28bb3e6a7: build and return the current application version from build-time variables (pure)

type VersionedStore

type VersionedStore interface {
	CheckAndBumpVersion(ctx context.Context, id string, expected int) (int, error)
}

VersionedStore is the minimal interface a Gorm-backed store implements to participate in optimistic locking. Each entity store calls into the central CheckAndBumpVersion helper; this interface exists primarily to type-assert the package-level store globals (which are typed as broader interfaces) at the handler boundary without introducing circular references. SEM@3253a9999eeaddc59fa7469d4f7d7fe80d59c6ca: interface for stores that support atomic version check-and-bump for optimistic locking (pure)

type WWWAuthenticateError

type WWWAuthenticateError string

WWWAuthenticateError represents error types per RFC 6750 section 3.1 SEM@c9dfddf1e0b3e1f0e3423564ea4d4a997e4fdc45: string type enumerating RFC 6750 WWW-Authenticate error codes (pure)

const (
	// WWWAuthInvalidRequest indicates the request is malformed or missing parameters
	WWWAuthInvalidRequest WWWAuthenticateError = wwwauth.ErrInvalidRequest
	// WWWAuthInvalidToken indicates the token is expired, revoked, or malformed
	WWWAuthInvalidToken WWWAuthenticateError = wwwauth.ErrInvalidToken
	// WWWAuthInsufficientScope indicates the request requires higher privileges
	WWWAuthInsufficientScope WWWAuthenticateError = wwwauth.ErrInsufficientScope
)

type WarmingPriority

type WarmingPriority int

WarmingPriority defines priority levels for cache warming SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: enumerate priority levels for cache warming requests (pure)

const (
	// PriorityHigh for critical data that must be cached
	PriorityHigh WarmingPriority = iota
	// PriorityMedium for important but not critical data
	PriorityMedium
	// PriorityLow for nice-to-have cached data
	PriorityLow
)

type WarmingRequest

type WarmingRequest struct {
	EntityType    string
	EntityID      string
	ThreatModelID string
	Priority      WarmingPriority
	Strategy      WarmingStrategy
	TTLOverride   *time.Duration
	ForceRefresh  bool
}

WarmingRequest represents a request to warm specific cache data SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: specify which entity to warm, at what priority and strategy (pure)

type WarmingStats

type WarmingStats struct {
	TotalWarmed       int
	ThreatsWarmed     int
	DocumentsWarmed   int
	SourcesWarmed     int
	MetadataWarmed    int
	AuthDataWarmed    int
	WarmingDuration   time.Duration
	ErrorsEncountered int
	LastWarmingTime   time.Time
}

WarmingStats tracks cache warming performance SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: aggregate counts and timing for a cache warming run (pure)

type WarmingStrategy

type WarmingStrategy int

WarmingStrategy defines different cache warming approaches SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: enumerate cache warming trigger strategies: on-access, proactive, or on-demand (pure)

const (
	// WarmOnAccess warms cache when data is first accessed
	WarmOnAccess WarmingStrategy = iota
	// WarmProactively warms cache on a schedule
	WarmProactively
	// WarmOnDemand warms cache only when explicitly requested
	WarmOnDemand
)

type WebSocketClient

type WebSocketClient struct {
	// Hub reference
	Hub *WebSocketHub
	// Diagram session reference
	Session *DiagramSession
	// The websocket connection
	Conn *websocket.Conn
	// User ID from JWT 'sub' claim (immutable identifier)
	UserID string
	// User display name from JWT 'name' claim
	UserName string
	// User email from JWT 'email' claim
	UserEmail string
	// User identity provider from JWT 'idp' claim
	UserProvider string
	// Internal UUID from users table (system-assigned)
	InternalUUID string
	// Buffered channel of outbound messages
	Send chan []byte
	// Last activity timestamp
	LastActivity time.Time

	// JWTExpiry is the absolute expiration time of the JWT that authenticated
	// the upgrade. The WritePump heartbeat compares this to the current time
	// each ping cycle and closes the socket once the token has expired,
	// preventing a long-lived session from outliving its credential (T20).
	// Zero means "no expiry check" (e.g., service-account or test connections).
	JWTExpiry time.Time
	// contains filtered or unexported fields
}

WebSocketClient represents a connected client SEM@a9626140ff4ccb3bf8ae4b474024684bd7063b72: connected WebSocket participant holding user identity, connection, and outbound message channel

func (*WebSocketClient) ReadPump

func (c *WebSocketClient) ReadPump()

ReadPump pumps messages from WebSocket to hub SEM@ed2b33cfd26b4cfc2ced06af67d1734a3218e38e: receive inbound WebSocket messages from a client and dispatch them for processing (mutates shared state)

func (*WebSocketClient) WritePump

func (c *WebSocketClient) WritePump()

WritePump pumps messages from hub to WebSocket SEM@d056a3ea026249d40d05ab6af7f092a043f72c7a: deliver outbound messages and pings to a WebSocket client; close on JWT expiry or revoked access (mutates shared state)

type WebSocketConnectionManager

type WebSocketConnectionManager struct{}

WebSocketConnectionManager handles WebSocket connection setup and error handling SEM@90b176688ca38f0b04e4e70a233b332f1c28218e: helper that manages WebSocket connection lifecycle, errors, and client registration

func (*WebSocketConnectionManager) RegisterClientWithTimeout

func (m *WebSocketConnectionManager) RegisterClientWithTimeout(session *DiagramSession, client *WebSocketClient, timeoutDuration time.Duration) error

RegisterClientWithTimeout registers a client with the session with a timeout to prevent blocking SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: register a WebSocket client with a session, returning an error if registration times out

func (*WebSocketConnectionManager) SendCloseAndClose

func (m *WebSocketConnectionManager) SendCloseAndClose(conn *websocket.Conn, closeCode int, closeText string)

SendCloseAndClose sends a close message to the WebSocket connection and closes it SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: send a WebSocket close frame with a code and reason then close the connection

func (*WebSocketConnectionManager) SendErrorAndClose

func (m *WebSocketConnectionManager) SendErrorAndClose(conn *websocket.Conn, errorCode, errorMessage string)

SendErrorAndClose sends an error message to the WebSocket connection and closes it SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: send a structured error message to a WebSocket connection then close it

type WebSocketHub

type WebSocketHub struct {
	// Registered connections by diagram ID
	Diagrams map[string]*DiagramSession

	// WebSocket logging configuration
	LoggingConfig slogging.WebSocketLoggingConfig
	// Inactivity timeout duration
	InactivityTimeout time.Duration
	// contains filtered or unexported fields
}

WebSocketHub maintains active connections and broadcasts messages SEM@46c5960fcabe5dcd3f7014239dc4a8ed43579299: central registry managing active diagram collaboration sessions and their WebSocket connections

func NewWebSocketHub

func NewWebSocketHub(loggingConfig slogging.WebSocketLoggingConfig, inactivityTimeout time.Duration) *WebSocketHub

NewWebSocketHub creates a new WebSocket hub SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: build a WebSocket hub with the given logging config and inactivity timeout (pure)

func NewWebSocketHubForTests

func NewWebSocketHubForTests() *WebSocketHub

NewWebSocketHubForTests creates a WebSocket hub with default test configuration SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: build a WebSocket hub with test-safe defaults and short inactivity timeout (pure)

func (*WebSocketHub) CleanupAllSessions

func (h *WebSocketHub) CleanupAllSessions()

CleanupAllSessions removes all active sessions (used at server startup) SEM@121da1d17d5493726e31faef8eeb0102f384e8d0: terminate all active collaboration sessions, used at server startup (mutates shared state)

func (*WebSocketHub) CleanupEmptySessions

func (h *WebSocketHub) CleanupEmptySessions()

CleanupEmptySessions performs immediate cleanup of empty sessions SEM@0c5cc661671b64da65ba64a68f6515095be0454b: delete sessions with no connected clients immediately (mutates shared state)

func (*WebSocketHub) CleanupInactiveSessions

func (h *WebSocketHub) CleanupInactiveSessions()

CleanupInactiveSessions removes sessions that are inactive or empty with grace period SEM@0c5cc661671b64da65ba64a68f6515095be0454b: delete terminated, empty, or timed-out sessions and close their connections (mutates shared state)

func (*WebSocketHub) CloseSession

func (h *WebSocketHub) CloseSession(diagramID string)

CloseSession closes a session and removes it SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: terminate a collaboration session immediately and disconnect all clients (mutates shared state)

func (*WebSocketHub) CountSessionParticipants

func (h *WebSocketHub) CountSessionParticipants(diagramID string) int

CountSessionParticipants returns the number of currently-registered clients on the session for the given diagram, or 0 if no session exists yet. SEM@a9626140ff4ccb3bf8ae4b474024684bd7063b72: count clients currently in a diagram WebSocket session (reads shared state)

func (*WebSocketHub) CountUserConnections

func (h *WebSocketHub) CountUserConnections(userID string) int

CountUserConnections returns the number of clients on this hub whose UserID matches the argument. Excluding the empty string is intentional — anonymous / pre-auth slots must not collapse into a single bucket. SEM@a9626140ff4ccb3bf8ae4b474024684bd7063b72: count active WebSocket connections for a given user across all hub sessions (reads shared state)

func (*WebSocketHub) CreateSession

func (h *WebSocketHub) CreateSession(diagramID string, threatModelID string, hostUser ResolvedUser) (*DiagramSession, error)

CreateSession creates a new collaboration session if none exists, returns error if one already exists SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: create and start a new collaboration session for a diagram; error if one already exists (mutates shared state)

func (*WebSocketHub) FindSessionByID

func (h *WebSocketHub) FindSessionByID(sessionID string) *DiagramSession

FindSessionByID finds a collaboration session by its session ID. SEM@e9c06824054dff110125e003301c169f002e9392: search all diagram sessions to find one matching the given session ID (reads shared state)

func (*WebSocketHub) GetActiveSessions

func (h *WebSocketHub) GetActiveSessions() []CollaborationSession

GetActiveSessions returns all active collaboration sessions SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: list all active collaboration sessions with participants and metadata (reads DB)

func (*WebSocketHub) GetActiveSessionsForUser

func (h *WebSocketHub) GetActiveSessionsForUser(c *gin.Context, user ResolvedUser) []CollaborationSession

GetActiveSessionsForUser returns all active collaboration sessions that the specified user has access to SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: list active collaboration sessions the given user has at least reader access to (reads DB)

func (*WebSocketHub) GetOrCreateSession

func (h *WebSocketHub) GetOrCreateSession(diagramID string, threatModelID string, hostUser ResolvedUser) *DiagramSession

GetOrCreateSession returns an existing session or creates a new one SEM@ab27b1c7ef336f1860c29d6f19f34f84adfc5b02: return an existing diagram collaboration session or create a new one if absent (mutates shared state)

func (*WebSocketHub) GetSession

func (h *WebSocketHub) GetSession(diagramID string) *DiagramSession

GetSession returns an existing session or nil if none exists SEM@a4a68f06d4cc47fec791b1d05abbfe61a3b94af7: return the collaboration session for a diagram, or nil if none exists (reads shared state)

func (*WebSocketHub) HandleWS

func (h *WebSocketHub) HandleWS(c *gin.Context)

HandleWS handles WebSocket connections SEM@a9626140ff4ccb3bf8ae4b474024684bd7063b72: handle an incoming WebSocket connection request, authorize, upgrade, and register the client (mutates shared state)

func (*WebSocketHub) HasActiveSession

func (h *WebSocketHub) HasActiveSession(diagramID string) bool

HasActiveSession checks if there is an active collaboration session for a diagram SEM@8559837d482fde8e2f7e1a9ea5e99d2bb2414141: report whether a diagram has an active (non-terminating) collaboration session (reads shared state)

func (*WebSocketHub) JoinSession

func (h *WebSocketHub) JoinSession(diagramID string, userID string) (*DiagramSession, error)

JoinSession joins an existing collaboration session, returns error if none exists SEM@a4a68f06d4cc47fec791b1d05abbfe61a3b94af7: register a user into an existing diagram collaboration session; error if none exists (mutates shared state)

func (*WebSocketHub) StartCleanupTimer

func (h *WebSocketHub) StartCleanupTimer(ctx context.Context)

StartCleanupTimer starts a periodic cleanup timer SEM@0d66846bab368d2a0b035f9750caa0c4eb1cb0ff: run periodic inactive-session cleanup until the context is cancelled (mutates shared state)

func (*WebSocketHub) UpdateDiagram

func (h *WebSocketHub) UpdateDiagram(diagramID string, updateFunc func(DfdDiagram) (DfdDiagram, bool, error), updateSource string, excludeUserID string) (*UpdateDiagramResult, error)

UpdateDiagram provides centralized diagram updates with version control and WebSocket notification This function: 1. Handles all diagram modifications (cells, metadata, properties) 2. Auto-increments update_vector when cells[] changes or when explicitly requested 3. Notifies WebSocket sessions when updates come from REST API 4. Serves as single source of truth for all diagram modifications 5. Provides thread-safe updates with proper locking SEM@c79f3cd129aecd7cd6562b875b7f02232594d3d1: apply an update function to a diagram with version control, persistence, audit, and WebSocket notification (mutates shared state)

func (*WebSocketHub) UpdateDiagramCells

func (h *WebSocketHub) UpdateDiagramCells(diagramID string, newCells []DfdDiagram_Cells_Item, updateSource string, excludeUserID string) (*UpdateDiagramResult, error)

UpdateDiagramCells provides centralized diagram cell updates (convenience wrapper) SEM@be6cc4edcc9140493267132a7d584481845e0dfe: replace a diagram's cell list and increment the update vector (mutates shared state)

type WebhookChallengeWorker

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

WebhookChallengeWorker handles webhook subscription verification challenges. All outbound requests go through SafeHTTPClient (DNS-pinned, SSRF-checked). SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: background worker that sends challenge requests to pending webhook subscriptions

func NewWebhookChallengeWorker

func NewWebhookChallengeWorker(validator *URIValidator) *WebhookChallengeWorker

NewWebhookChallengeWorker creates a new challenge verification worker. The validator controls the SSRF blocklist and URL schemes used for outbound calls. SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: build a WebhookChallengeWorker with a safe HTTP client and a 30-second polling interval (pure)

func (*WebhookChallengeWorker) Start

func (bw *WebhookChallengeWorker) Start(ctx context.Context) error

Start begins the worker's processing loop. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: start the background worker processing loop in a goroutine (mutates shared state)

func (*WebhookChallengeWorker) Stop

func (bw *WebhookChallengeWorker) Stop()

Stop gracefully stops the worker. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: gracefully stop the background worker by signaling the stop channel (mutates shared state)

type WebhookCleanupWorker

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

WebhookCleanupWorker handles cleanup of old deliveries, idle subscriptions, and broken subscriptions SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: background worker that periodically purges stale webhook subscriptions and deliveries

func NewWebhookCleanupWorker

func NewWebhookCleanupWorker() *WebhookCleanupWorker

NewWebhookCleanupWorker creates a new cleanup worker SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: build a WebhookCleanupWorker configured for hourly cleanup runs

func (*WebhookCleanupWorker) Start

func (bw *WebhookCleanupWorker) Start(ctx context.Context) error

Start begins the worker's processing loop. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: start the background worker processing loop in a goroutine (mutates shared state)

func (*WebhookCleanupWorker) Stop

func (bw *WebhookCleanupWorker) Stop()

Stop gracefully stops the worker. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: gracefully stop the background worker by signaling the stop channel (mutates shared state)

type WebhookDelivery

type WebhookDelivery struct {
	// AddonId Add-on ID (for addon invocations only)
	AddonId *openapi_types.UUID `json:"addon_id,omitempty"`

	// Attempts Number of delivery attempts
	Attempts int `json:"attempts"`

	// CreatedAt Creation timestamp
	CreatedAt time.Time `json:"created_at"`

	// DeliveredAt Successful delivery timestamp
	DeliveredAt *time.Time `json:"delivered_at,omitempty"`

	// EventType Webhook event type following {resource}.{action} pattern. CRUD events are emitted for resource lifecycle changes (created, updated, deleted). The addon.invoked event is emitted when an add-on is invoked.
	EventType WebhookEventType `json:"event_type"`

	// Id Unique identifier (UUIDv7)
	Id openapi_types.UUID `json:"id"`

	// InvokedBy User who invoked the add-on (for addon invocations only)
	InvokedBy *User `json:"invoked_by,omitempty"`

	// LastActivityAt Last status update or delivery attempt
	LastActivityAt *time.Time `json:"last_activity_at,omitempty"`

	// LastError Last error message
	LastError *string `json:"last_error,omitempty"`

	// NextRetryAt Next retry timestamp
	NextRetryAt *time.Time `json:"next_retry_at,omitempty"`

	// Payload Event payload (JSON)
	Payload *map[string]interface{} `json:"payload,omitempty"`

	// Status Delivery status
	Status WebhookDeliveryStatus `json:"status"`

	// StatusMessage Human-readable status description
	StatusMessage *string `json:"status_message,omitempty"`

	// StatusPercent Progress percentage
	StatusPercent *int `json:"status_percent,omitempty"`

	// SubscriptionId Subscription that triggered this delivery
	SubscriptionId openapi_types.UUID `json:"subscription_id"`
}

WebhookDelivery Record of a webhook delivery attempt including status and response

type WebhookDeliveryData

type WebhookDeliveryData struct {
	AddonID  *uuid.UUID       `json:"addon_id,omitempty"`
	UserData *json.RawMessage `json:"user_data,omitempty"`
}

WebhookDeliveryData contains addon-specific fields within the unified payload data. SEM@ca61a567c4babc9270ee913396aaa4fb530505a3: addon-specific fields embedded within a webhook delivery payload

type WebhookDeliveryPayload

type WebhookDeliveryPayload struct {
	EventType     string          `json:"event_type"`
	ThreatModelID uuid.UUID       `json:"threat_model_id"`
	Timestamp     time.Time       `json:"timestamp"`
	ObjectType    string          `json:"object_type,omitempty"`
	ObjectID      *uuid.UUID      `json:"object_id,omitempty"`
	Data          json.RawMessage `json:"data"`
}

WebhookDeliveryPayload represents the unified payload sent to webhook endpoints. Used for all webhook deliveries (resource-change events and addon invocations). SEM@ca61a567c4babc9270ee913396aaa4fb530505a3: unified webhook event payload sent to subscriber endpoints for all delivery types

type WebhookDeliveryRecord

type WebhookDeliveryRecord struct {
	ID             uuid.UUID  `json:"id"`
	SubscriptionID uuid.UUID  `json:"subscription_id"`
	EventType      string     `json:"event_type"`
	Payload        string     `json:"payload"`
	Status         string     `json:"status"`         // pending, in_progress, delivered, failed
	StatusPercent  int        `json:"status_percent"` // 0-100 progress indicator
	StatusMessage  string     `json:"status_message"` // human-readable status description
	Attempts       int        `json:"attempts"`       // number of delivery attempts so far
	NextRetryAt    *time.Time `json:"next_retry_at,omitempty"`
	LastError      string     `json:"last_error,omitempty"`
	CreatedAt      time.Time  `json:"created_at"`
	DeliveredAt    *time.Time `json:"delivered_at,omitempty"`
	LastActivityAt time.Time  `json:"last_activity_at"`

	// Addon-specific fields (only populated for addon.invoked events)
	AddonID        *uuid.UUID `json:"addon_id,omitempty"`
	InvokedByUUID  *uuid.UUID `json:"invoked_by_uuid,omitempty"`
	InvokedByEmail string     `json:"invoked_by_email,omitempty"`
	InvokedByName  string     `json:"invoked_by_name,omitempty"`
}

WebhookDeliveryRecord is the unified delivery record used for both resource-change events and addon invocations, backed by Redis. SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: Redis-backed delivery record for resource-change events and addon invocations (pure)

type WebhookDeliveryRedisStore

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

WebhookDeliveryRedisStore implements WebhookDeliveryRedisStoreInterface using Redis SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: Redis implementation of WebhookDeliveryRedisStoreInterface (pure)

func NewWebhookDeliveryRedisStore

func NewWebhookDeliveryRedisStore(redisDB *db.RedisDB) *WebhookDeliveryRedisStore

NewWebhookDeliveryRedisStore creates a new Redis-backed webhook delivery store SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: build a WebhookDeliveryRedisStore from a Redis connection (pure)

func (*WebhookDeliveryRedisStore) CountActiveByAddon

func (s *WebhookDeliveryRedisStore) CountActiveByAddon(ctx context.Context, addonID uuid.UUID) (int, error)

CountActiveByAddon returns the count of pending/in_progress delivery records associated with the supplied add-on. Counts are computed by scanning the full delivery keyspace, so the result is correct regardless of the number of in-flight deliveries. SEM@1f7fa52ef92fb87a8cf91a548761c53324b4c630: count pending or in-progress delivery records for a specific addon (reads DB)

func (*WebhookDeliveryRedisStore) Create

Create creates a new delivery record in Redis SEM@a37a0039279be689bb07be2113fe86024a410a4b: store a new webhook delivery record in Redis with TTL and default status (writes DB)

func (*WebhookDeliveryRedisStore) Delete

Delete removes a delivery record from Redis SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: delete a webhook delivery record from Redis by ID (writes DB)

func (*WebhookDeliveryRedisStore) Get

Get retrieves a delivery record by ID SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: fetch a webhook delivery record from Redis by ID (reads DB)

func (*WebhookDeliveryRedisStore) ListAll

func (s *WebhookDeliveryRedisStore) ListAll(ctx context.Context, limit, offset int) ([]WebhookDeliveryRecord, int, error)

ListAll returns all delivery records with pagination. Returns the paginated records, total count of all records, and any error. SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: list all webhook delivery records with pagination (reads DB)

func (*WebhookDeliveryRedisStore) ListBySubscription

func (s *WebhookDeliveryRedisStore) ListBySubscription(ctx context.Context, subscriptionID uuid.UUID, limit, offset int) ([]WebhookDeliveryRecord, int, error)

ListBySubscription returns delivery records for a specific subscription with pagination. Returns the paginated records, total count of matching records, and any error. SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: list paginated delivery records for a specific webhook subscription (reads DB)

func (*WebhookDeliveryRedisStore) ListPending

func (s *WebhookDeliveryRedisStore) ListPending(ctx context.Context, limit int) ([]WebhookDeliveryRecord, error)

ListPending returns delivery records that are pending and ready for delivery. A record is ready when its status is "pending" and either NextRetryAt is nil (first attempt) or NextRetryAt <= now (retry time has arrived). SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: list pending delivery records that are ready for first or retry delivery (reads DB)

func (*WebhookDeliveryRedisStore) ListReadyForRetry

func (s *WebhookDeliveryRedisStore) ListReadyForRetry(ctx context.Context) ([]WebhookDeliveryRecord, error)

ListReadyForRetry returns delivery records that are pending, have been attempted before, and are due for another retry (NextRetryAt != nil AND NextRetryAt <= now AND Attempts > 0). SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: list pending delivery records with prior attempts whose retry time has arrived (reads DB)

func (*WebhookDeliveryRedisStore) ListStale

ListStale returns in_progress delivery records with no activity within the given timeout. SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: list in-progress delivery records with no activity within a given timeout (reads DB)

func (*WebhookDeliveryRedisStore) Update

Update updates an existing delivery record in Redis SEM@a37a0039279be689bb07be2113fe86024a410a4b: replace a webhook delivery record in Redis, refreshing its TTL and activity timestamp (writes DB)

func (*WebhookDeliveryRedisStore) UpdateRetry

func (s *WebhookDeliveryRedisStore) UpdateRetry(ctx context.Context, id uuid.UUID, attempts int, nextRetryAt *time.Time, lastError string) error

UpdateRetry updates retry-related fields after a failed delivery attempt SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: update retry attempt count, next retry time, and last error on a delivery record (writes DB)

func (*WebhookDeliveryRedisStore) UpdateStatus

func (s *WebhookDeliveryRedisStore) UpdateStatus(ctx context.Context, id uuid.UUID, status string, deliveredAt *time.Time) error

UpdateStatus updates the status (and optional delivered-at timestamp) of a delivery record SEM@cd3dd48b5b6403e9553ba59af4c3b004de35f6fa: update the status and optional delivered-at timestamp of a delivery record (writes DB)

type WebhookDeliveryRedisStoreInterface

type WebhookDeliveryRedisStoreInterface interface {
	// Create creates a new delivery record
	Create(ctx context.Context, record *WebhookDeliveryRecord) error
	// Get retrieves a delivery record by ID
	Get(ctx context.Context, id uuid.UUID) (*WebhookDeliveryRecord, error)
	// Update updates an existing delivery record
	Update(ctx context.Context, record *WebhookDeliveryRecord) error
	// UpdateStatus updates only the status and optional delivered-at timestamp
	UpdateStatus(ctx context.Context, id uuid.UUID, status string, deliveredAt *time.Time) error
	// UpdateRetry updates retry-related fields after a failed attempt
	UpdateRetry(ctx context.Context, id uuid.UUID, attempts int, nextRetryAt *time.Time, lastError string) error
	// Delete removes a delivery record
	Delete(ctx context.Context, id uuid.UUID) error
	// ListPending returns delivery records that are pending and ready for delivery
	ListPending(ctx context.Context, limit int) ([]WebhookDeliveryRecord, error)
	// ListReadyForRetry returns delivery records that have been retried and are due for another attempt
	ListReadyForRetry(ctx context.Context) ([]WebhookDeliveryRecord, error)
	// ListStale returns in_progress records with no activity within the given timeout
	ListStale(ctx context.Context, timeout time.Duration) ([]WebhookDeliveryRecord, error)
	// ListBySubscription returns delivery records for a specific subscription with pagination
	ListBySubscription(ctx context.Context, subscriptionID uuid.UUID, limit, offset int) ([]WebhookDeliveryRecord, int, error)
	// ListAll returns all delivery records with pagination
	ListAll(ctx context.Context, limit, offset int) ([]WebhookDeliveryRecord, int, error)
	// CountActiveByAddon counts pending/in_progress delivery records for an
	// add-on without paginating. Returns the full count regardless of size.
	CountActiveByAddon(ctx context.Context, addonID uuid.UUID) (int, error)
}

WebhookDeliveryRedisStoreInterface defines all operations for the unified webhook delivery store SEM@1f7fa52ef92fb87a8cf91a548761c53324b4c630: CRUD and query contract for the Redis-backed webhook delivery store (pure)

var GlobalWebhookDeliveryRedisStore WebhookDeliveryRedisStoreInterface

GlobalWebhookDeliveryRedisStore is the global singleton for the unified webhook delivery store

type WebhookDeliveryStatus

type WebhookDeliveryStatus string

WebhookDeliveryStatus Delivery status

const (
	WebhookDeliveryStatusDelivered  WebhookDeliveryStatus = "delivered"
	WebhookDeliveryStatusFailed     WebhookDeliveryStatus = "failed"
	WebhookDeliveryStatusInProgress WebhookDeliveryStatus = "in_progress"
	WebhookDeliveryStatusPending    WebhookDeliveryStatus = "pending"
)

Defines values for WebhookDeliveryStatus.

func (WebhookDeliveryStatus) Valid

func (e WebhookDeliveryStatus) Valid() bool

Valid indicates whether the value is a known member of the WebhookDeliveryStatus enum.

type WebhookDeliveryWorker

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

WebhookDeliveryWorker handles delivery of webhook events to subscribed endpoints. All outbound requests go through SafeHTTPClient which pins the validated IP at dial time, defending against DNS rebinding between subscription validation and per-delivery dispatch. SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: background worker that dispatches pending webhook deliveries via SSRF-safe HTTP

func NewWebhookDeliveryWorker

func NewWebhookDeliveryWorker(validator *URIValidator) *WebhookDeliveryWorker

NewWebhookDeliveryWorker creates a new delivery worker. The validator controls the SSRF blocklist and URL schemes used for outbound calls. SEM@9bf8890e7d4a04bdbb3f0e80fb295392276e3a5d: build a WebhookDeliveryWorker with circuit breaker and SSRF-safe HTTP client

func (*WebhookDeliveryWorker) Start

func (bw *WebhookDeliveryWorker) Start(ctx context.Context) error

Start begins the worker's processing loop. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: start the background worker processing loop in a goroutine (mutates shared state)

func (*WebhookDeliveryWorker) Stop

func (bw *WebhookDeliveryWorker) Stop()

Stop gracefully stops the worker. SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: gracefully stop the background worker by signaling the stop channel (mutates shared state)

type WebhookEventConsumer

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

WebhookEventConsumer consumes events from Redis Streams and creates webhook deliveries SEM@00eb592b65c7f67e499ac7e598f6742cd1f5d2a5: Redis Streams consumer that routes domain events to webhook delivery records

func NewWebhookEventConsumer

func NewWebhookEventConsumer(redisClient *redis.Client, streamKey, groupName, consumerID string) *WebhookEventConsumer

NewWebhookEventConsumer creates a new event consumer SEM@00eb592b65c7f67e499ac7e598f6742cd1f5d2a5: build a WebhookEventConsumer for a specific Redis stream and consumer group

func (*WebhookEventConsumer) Start

func (c *WebhookEventConsumer) Start(ctx context.Context) error

Start begins consuming events from the Redis Stream SEM@00eb592b65c7f67e499ac7e598f6742cd1f5d2a5: create the consumer group if absent and start the event-consumption goroutine

func (*WebhookEventConsumer) Stop

func (c *WebhookEventConsumer) Stop()

Stop gracefully stops the consumer SEM@00eb592b65c7f67e499ac7e598f6742cd1f5d2a5: signal the consume loop to exit and mark the consumer as stopped

type WebhookEventType

type WebhookEventType string

WebhookEventType Webhook event type following {resource}.{action} pattern. CRUD events are emitted for resource lifecycle changes (created, updated, deleted). The addon.invoked event is emitted when an add-on is invoked.

const (
	WebhookEventTypeAddonInvoked                WebhookEventType = "addon.invoked"
	WebhookEventTypeAssetCreated                WebhookEventType = "asset.created"
	WebhookEventTypeAssetDeleted                WebhookEventType = "asset.deleted"
	WebhookEventTypeAssetUpdated                WebhookEventType = "asset.updated"
	WebhookEventTypeDiagramCreated              WebhookEventType = "diagram.created"
	WebhookEventTypeDiagramDeleted              WebhookEventType = "diagram.deleted"
	WebhookEventTypeDiagramUpdated              WebhookEventType = "diagram.updated"
	WebhookEventTypeDocumentCreated             WebhookEventType = "document.created"
	WebhookEventTypeDocumentDeleted             WebhookEventType = "document.deleted"
	WebhookEventTypeDocumentExtractionCompleted WebhookEventType = "document.extraction_completed"
	WebhookEventTypeDocumentExtractionFailed    WebhookEventType = "document.extraction_failed"
	WebhookEventTypeDocumentUpdated             WebhookEventType = "document.updated"
	WebhookEventTypeMetadataCreated             WebhookEventType = "metadata.created"
	WebhookEventTypeMetadataDeleted             WebhookEventType = "metadata.deleted"
	WebhookEventTypeMetadataUpdated             WebhookEventType = "metadata.updated"
	WebhookEventTypeNoteCreated                 WebhookEventType = "note.created"
	WebhookEventTypeNoteDeleted                 WebhookEventType = "note.deleted"
	WebhookEventTypeNoteUpdated                 WebhookEventType = "note.updated"
	WebhookEventTypeRepositoryCreated           WebhookEventType = "repository.created"
	WebhookEventTypeRepositoryDeleted           WebhookEventType = "repository.deleted"
	WebhookEventTypeRepositoryUpdated           WebhookEventType = "repository.updated"
	WebhookEventTypeSurveyCreated               WebhookEventType = "survey.created"
	WebhookEventTypeSurveyDeleted               WebhookEventType = "survey.deleted"
	WebhookEventTypeSurveyResponseCreated       WebhookEventType = "survey_response.created"
	WebhookEventTypeSurveyResponseDeleted       WebhookEventType = "survey_response.deleted"
	WebhookEventTypeSurveyResponseUpdated       WebhookEventType = "survey_response.updated"
	WebhookEventTypeSurveyUpdated               WebhookEventType = "survey.updated"
	WebhookEventTypeSystemAuditAdminWrite       WebhookEventType = "system_audit.admin_write"
	WebhookEventTypeThreatCreated               WebhookEventType = "threat.created"
	WebhookEventTypeThreatDeleted               WebhookEventType = "threat.deleted"
	WebhookEventTypeThreatModelCreated          WebhookEventType = "threat_model.created"
	WebhookEventTypeThreatModelDeleted          WebhookEventType = "threat_model.deleted"
	WebhookEventTypeThreatModelUpdated          WebhookEventType = "threat_model.updated"
	WebhookEventTypeThreatUpdated               WebhookEventType = "threat.updated"
)

Defines values for WebhookEventType.

func (WebhookEventType) Valid

func (e WebhookEventType) Valid() bool

Valid indicates whether the value is a known member of the WebhookEventType enum.

type WebhookId

type WebhookId = openapi_types.UUID

WebhookId defines model for WebhookId.

type WebhookQuota

type WebhookQuota struct {
	// CreatedAt Timestamp when the quota was created
	CreatedAt *time.Time `json:"created_at,omitempty"`

	// MaxEventsPerMinute Maximum webhook events per minute
	MaxEventsPerMinute int `json:"max_events_per_minute"`

	// MaxSubscriptionRequestsPerDay Maximum subscription requests per day
	MaxSubscriptionRequestsPerDay int `json:"max_subscription_requests_per_day"`

	// MaxSubscriptionRequestsPerMinute Maximum subscription requests per minute
	MaxSubscriptionRequestsPerMinute int `json:"max_subscription_requests_per_minute"`

	// MaxSubscriptions Maximum number of webhook subscriptions
	MaxSubscriptions int `json:"max_subscriptions"`

	// ModifiedAt Timestamp when the quota was last modified
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// OwnerId Owner ID
	OwnerId openapi_types.UUID `json:"owner_id"`
}

WebhookQuota Webhook subscription quota configuration for a user

type WebhookQuotaStoreInterface

type WebhookQuotaStoreInterface interface {
	Get(ctx context.Context, ownerID string) (DBWebhookQuota, error)
	GetOrDefault(ctx context.Context, ownerID string) DBWebhookQuota
	List(ctx context.Context, offset, limit int) ([]DBWebhookQuota, error)
	Count(ctx context.Context) (int, error)
	Create(ctx context.Context, item DBWebhookQuota) (DBWebhookQuota, error)
	Update(ctx context.Context, ownerID string, item DBWebhookQuota) error
	Delete(ctx context.Context, ownerID string) error
}

WebhookQuotaStoreInterface defines operations for webhook quotas. See WebhookSubscriptionStoreInterface for ctx threading rationale. SEM@a19a29138f4caaab0d2efe0d5b6f54106b447672: store contract for CRUD on per-owner webhook quota records (reads DB)

var GlobalWebhookQuotaStore WebhookQuotaStoreInterface

type WebhookQuotaUpdate

type WebhookQuotaUpdate struct {
	// MaxEventsPerMinute Maximum webhook events per minute
	MaxEventsPerMinute int `json:"max_events_per_minute"`

	// MaxSubscriptionRequestsPerDay Maximum subscription requests per day
	MaxSubscriptionRequestsPerDay int `json:"max_subscription_requests_per_day"`

	// MaxSubscriptionRequestsPerMinute Maximum subscription requests per minute
	MaxSubscriptionRequestsPerMinute int `json:"max_subscription_requests_per_minute"`

	// MaxSubscriptions Maximum webhook subscriptions
	MaxSubscriptions int `json:"max_subscriptions"`
}

WebhookQuotaUpdate Configuration update for webhook subscription quotas

type WebhookRateLimiter

type WebhookRateLimiter struct {
	SlidingWindowRateLimiter
}

WebhookRateLimiter implements rate limiting for webhook operations using Redis SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: Redis-backed rate limiter for webhook subscription and event publication quotas

func NewWebhookRateLimiter

func NewWebhookRateLimiter(redisClient *redis.Client) *WebhookRateLimiter

NewWebhookRateLimiter creates a new rate limiter SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: build a webhook rate limiter backed by the given Redis client (pure)

func (*WebhookRateLimiter) CheckEventPublicationLimit

func (r *WebhookRateLimiter) CheckEventPublicationLimit(ctx context.Context, ownerID string) error

CheckEventPublicationLimit checks rate limit for event publications SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: validate the per-minute event publication rate limit for an owner (reads DB)

func (*WebhookRateLimiter) CheckSubscriptionLimit

func (r *WebhookRateLimiter) CheckSubscriptionLimit(ctx context.Context, ownerID string) error

CheckSubscriptionLimit checks if owner can create a new subscription SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: validate that an owner has not exceeded their maximum subscription count (reads DB)

func (*WebhookRateLimiter) CheckSubscriptionRequestLimit

func (r *WebhookRateLimiter) CheckSubscriptionRequestLimit(ctx context.Context, ownerID string) error

CheckSubscriptionRequestLimit checks rate limit for subscription creation requests SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: validate per-minute and per-day subscription creation rate limits for an owner (reads DB)

func (*WebhookRateLimiter) GetSubscriptionRateLimitInfo

func (r *WebhookRateLimiter) GetSubscriptionRateLimitInfo(ctx context.Context, ownerID string) (limit int, remaining int, resetAt int64, err error)

GetSubscriptionRateLimitInfo returns current subscription request rate limit status SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: fetch current subscription rate limit, remaining capacity, and reset time for an owner (reads DB)

func (*WebhookRateLimiter) RecordEventPublication

func (r *WebhookRateLimiter) RecordEventPublication(ctx context.Context, ownerID string) error

RecordEventPublication records an event publication for rate limiting SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: record an event publication in the per-minute Redis sliding window (reads DB)

func (*WebhookRateLimiter) RecordSubscriptionRequest

func (r *WebhookRateLimiter) RecordSubscriptionRequest(ctx context.Context, ownerID string) error

RecordSubscriptionRequest records a subscription creation request for rate limiting SEM@ea4348bffa66284d10fa60dbe3b7ea079942bab0: record a subscription creation attempt in the per-minute and per-day Redis windows (reads DB)

type WebhookSubscription

type WebhookSubscription struct {
	// ChallengesSent Number of verification challenges sent
	ChallengesSent *int `json:"challenges_sent,omitempty"`

	// CreatedAt Creation timestamp
	CreatedAt time.Time `json:"created_at"`

	// Events List of event types to subscribe to. See WebhookEventType for available events.
	Events []WebhookEventType `json:"events"`

	// Id Unique identifier
	Id openapi_types.UUID `json:"id"`

	// LastSuccessfulUse Last successful delivery timestamp
	LastSuccessfulUse *time.Time `json:"last_successful_use,omitempty"`

	// ModifiedAt Last modification timestamp
	ModifiedAt time.Time `json:"modified_at"`

	// Name Descriptive name
	Name string `json:"name"`

	// OwnerId Owner user ID
	OwnerId openapi_types.UUID `json:"owner_id"`

	// PublicationFailures Count of consecutive failed deliveries
	PublicationFailures *int `json:"publication_failures,omitempty"`

	// Secret HMAC secret for signing payloads (not returned in GET responses)
	Secret *string `json:"secret,omitempty"`

	// Status Subscription status
	Status WebhookSubscriptionStatus `json:"status"`

	// ThreatModelId Optional threat model filter (null means all threat models)
	ThreatModelId *openapi_types.UUID `json:"threat_model_id,omitempty"`

	// Url Webhook endpoint URL (must be HTTPS)
	Url string `json:"url"`
}

WebhookSubscription Webhook subscription configuration for event notifications

type WebhookSubscriptionInput

type WebhookSubscriptionInput struct {
	// Events List of event types to subscribe to
	Events []string `json:"events"`

	// Name Descriptive name for the subscription
	Name string `json:"name"`

	// Secret Optional HMAC secret for signing payloads (auto-generated if not provided)
	Secret *string `json:"secret,omitempty"`

	// ThreatModelId Optional threat model filter
	ThreatModelId *openapi_types.UUID `json:"threat_model_id,omitempty"`

	// Url Webhook endpoint URL (must be HTTPS)
	Url string `json:"url"`
}

WebhookSubscriptionInput Input schema for creating or updating a webhook subscription

type WebhookSubscriptionStatus

type WebhookSubscriptionStatus string

WebhookSubscriptionStatus Subscription status

const (
	WebhookSubscriptionStatusActive              WebhookSubscriptionStatus = "active"
	WebhookSubscriptionStatusPendingDelete       WebhookSubscriptionStatus = "pending_delete"
	WebhookSubscriptionStatusPendingVerification WebhookSubscriptionStatus = "pending_verification"
)

Defines values for WebhookSubscriptionStatus.

func (WebhookSubscriptionStatus) Valid

func (e WebhookSubscriptionStatus) Valid() bool

Valid indicates whether the value is a known member of the WebhookSubscriptionStatus enum.

type WebhookSubscriptionStoreInterface

type WebhookSubscriptionStoreInterface interface {
	Get(ctx context.Context, id string) (DBWebhookSubscription, error)
	List(ctx context.Context, offset, limit int, filter func(DBWebhookSubscription) bool) []DBWebhookSubscription
	ListByOwner(ctx context.Context, ownerID string, offset, limit int) ([]DBWebhookSubscription, error)
	ListByThreatModel(ctx context.Context, threatModelID string, offset, limit int) ([]DBWebhookSubscription, error)
	ListActiveByOwner(ctx context.Context, ownerID string) ([]DBWebhookSubscription, error)
	ListActiveByEventType(ctx context.Context, eventType string) ([]DBWebhookSubscription, error)
	ListPendingVerification(ctx context.Context) ([]DBWebhookSubscription, error)
	ListPendingDelete(ctx context.Context) ([]DBWebhookSubscription, error)
	ListIdle(ctx context.Context, daysIdle int) ([]DBWebhookSubscription, error)
	ListBroken(ctx context.Context, minFailures int, daysSinceSuccess int) ([]DBWebhookSubscription, error)
	Create(ctx context.Context, item DBWebhookSubscription, idSetter func(DBWebhookSubscription, string) DBWebhookSubscription) (DBWebhookSubscription, error)
	Update(ctx context.Context, id string, item DBWebhookSubscription) error
	UpdateStatus(ctx context.Context, id string, status string) error
	UpdateChallenge(ctx context.Context, id string, challenge string, challengesSent int) error
	UpdatePublicationStats(ctx context.Context, id string, success bool) error
	IncrementTimeouts(ctx context.Context, id string) error
	ResetTimeouts(ctx context.Context, id string) error
	Delete(ctx context.Context, id string) error
	Count(ctx context.Context) int
	CountByOwner(ctx context.Context, ownerID string) (int, error)
}

WebhookSubscriptionStoreInterface defines operations for webhook subscriptions. All methods accept a context.Context so the underlying GORM transaction retry wrapper can use the caller-supplied context for cancellation instead of falling back to context.Background(). This makes Oracle ORA-08177/ORA-00060 retry chains cancellable when the originating HTTP request is cancelled. SEM@c13f85301f7c723dfb20f687cb8fddc4ed77e703: store contract for CRUD and lifecycle queries on webhook subscriptions (reads DB)

var GlobalWebhookSubscriptionStore WebhookSubscriptionStoreInterface

Global webhook store instances

type WebhookTestRequest

type WebhookTestRequest struct {
	// EventType Webhook event type following {resource}.{action} pattern
	EventType *WebhookTestRequestEventType `json:"event_type,omitempty"`
}

WebhookTestRequest Request to test a webhook subscription with a sample event

type WebhookTestRequestEventType

type WebhookTestRequestEventType string

WebhookTestRequestEventType Webhook event type following {resource}.{action} pattern

const (
	WebhookTestRequestEventTypeAssetCreated                WebhookTestRequestEventType = "asset.created"
	WebhookTestRequestEventTypeAssetDeleted                WebhookTestRequestEventType = "asset.deleted"
	WebhookTestRequestEventTypeAssetUpdated                WebhookTestRequestEventType = "asset.updated"
	WebhookTestRequestEventTypeDiagramCreated              WebhookTestRequestEventType = "diagram.created"
	WebhookTestRequestEventTypeDiagramDeleted              WebhookTestRequestEventType = "diagram.deleted"
	WebhookTestRequestEventTypeDiagramUpdated              WebhookTestRequestEventType = "diagram.updated"
	WebhookTestRequestEventTypeDocumentCreated             WebhookTestRequestEventType = "document.created"
	WebhookTestRequestEventTypeDocumentDeleted             WebhookTestRequestEventType = "document.deleted"
	WebhookTestRequestEventTypeDocumentExtractionCompleted WebhookTestRequestEventType = "document.extraction_completed"
	WebhookTestRequestEventTypeDocumentExtractionFailed    WebhookTestRequestEventType = "document.extraction_failed"
	WebhookTestRequestEventTypeDocumentUpdated             WebhookTestRequestEventType = "document.updated"
	WebhookTestRequestEventTypeMetadataCreated             WebhookTestRequestEventType = "metadata.created"
	WebhookTestRequestEventTypeMetadataDeleted             WebhookTestRequestEventType = "metadata.deleted"
	WebhookTestRequestEventTypeMetadataUpdated             WebhookTestRequestEventType = "metadata.updated"
	WebhookTestRequestEventTypeNoteCreated                 WebhookTestRequestEventType = "note.created"
	WebhookTestRequestEventTypeNoteDeleted                 WebhookTestRequestEventType = "note.deleted"
	WebhookTestRequestEventTypeNoteUpdated                 WebhookTestRequestEventType = "note.updated"
	WebhookTestRequestEventTypeRepositoryCreated           WebhookTestRequestEventType = "repository.created"
	WebhookTestRequestEventTypeRepositoryDeleted           WebhookTestRequestEventType = "repository.deleted"
	WebhookTestRequestEventTypeRepositoryUpdated           WebhookTestRequestEventType = "repository.updated"
	WebhookTestRequestEventTypeSystemAuditAdminWrite       WebhookTestRequestEventType = "system_audit.admin_write"
	WebhookTestRequestEventTypeThreatCreated               WebhookTestRequestEventType = "threat.created"
	WebhookTestRequestEventTypeThreatDeleted               WebhookTestRequestEventType = "threat.deleted"
	WebhookTestRequestEventTypeThreatModelCreated          WebhookTestRequestEventType = "threat_model.created"
	WebhookTestRequestEventTypeThreatModelDeleted          WebhookTestRequestEventType = "threat_model.deleted"
	WebhookTestRequestEventTypeThreatModelUpdated          WebhookTestRequestEventType = "threat_model.updated"
	WebhookTestRequestEventTypeThreatUpdated               WebhookTestRequestEventType = "threat.updated"
)

Defines values for WebhookTestRequestEventType.

func (WebhookTestRequestEventType) Valid

Valid indicates whether the value is a known member of the WebhookTestRequestEventType enum.

type WebhookTestResponse

type WebhookTestResponse struct {
	// DeliveryId Test delivery ID
	DeliveryId openapi_types.UUID `json:"delivery_id"`

	// Message Result message
	Message *string `json:"message,omitempty"`

	// Status Test result status
	Status string `json:"status"`
}

WebhookTestResponse Response from a webhook test including delivery status

type WebhookUrlDenyListEntry

type WebhookUrlDenyListEntry struct {
	Id          uuid.UUID `json:"id"`
	Pattern     string    `json:"pattern"`
	PatternType string    `json:"pattern_type"` // glob, regex
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"created_at"`
}

WebhookUrlDenyListEntry represents a URL pattern to block SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: DB model for a URL pattern that blocks webhook registrations

type WebhookUrlDenyListStoreInterface

type WebhookUrlDenyListStoreInterface interface {
	List(ctx context.Context) ([]WebhookUrlDenyListEntry, error)
	Create(ctx context.Context, item WebhookUrlDenyListEntry) (WebhookUrlDenyListEntry, error)
	Delete(ctx context.Context, id string) error
}

WebhookUrlDenyListStoreInterface defines operations for URL deny list. See WebhookSubscriptionStoreInterface for ctx threading rationale. SEM@a19a29138f4caaab0d2efe0d5b6f54106b447672: store contract for listing, creating, and deleting webhook URL deny list entries (reads DB)

var GlobalWebhookUrlDenyListStore WebhookUrlDenyListStoreInterface

type WebhookUrlValidator

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

WebhookUrlValidator validates webhook URLs against security rules SEM@baf9ecb79a22da23c9922e1df63b14cb07d01523: validator for webhook URLs enforcing scheme, DNS hostname, and deny-list rules

func NewWebhookUrlValidator

func NewWebhookUrlValidator(denyListStore WebhookUrlDenyListStoreInterface) *WebhookUrlValidator

NewWebhookUrlValidator creates a new URL validator SEM@9ea792b9df3b1ab947a5ab9a404a0fbccd779d21: build a webhook URL validator that requires HTTPS only

func NewWebhookUrlValidatorWithHTTP

func NewWebhookUrlValidatorWithHTTP(denyListStore WebhookUrlDenyListStoreInterface, allowHTTP bool) *WebhookUrlValidator

NewWebhookUrlValidatorWithHTTP creates a new URL validator that optionally allows HTTP URLs SEM@baf9ecb79a22da23c9922e1df63b14cb07d01523: build a webhook URL validator with configurable HTTP/HTTPS scheme allowance

func (*WebhookUrlValidator) ValidateWebhookURL

func (v *WebhookUrlValidator) ValidateWebhookURL(ctx context.Context, rawURL string) error

ValidateWebhookURL validates a webhook URL according to security requirements SEM@a3e8f5e791cb2d0db34a3485d770fb2aa7cdaaf5: validate a webhook URL for scheme, DNS hostname, and deny-list compliance (reads DB)

type WithTimestamps

type WithTimestamps interface {
	SetCreatedAt(time.Time)
	SetModifiedAt(time.Time)
}

WithTimestamps is a mixin interface for entities with timestamps SEM@386eea01f3b66c35027bf3ca762efbc291419e20: mixin interface for entities that expose created_at and modified_at timestamp setters (pure)

type WsTicketResponse

type WsTicketResponse struct {
	// Ticket Short-lived, single-use authentication ticket for WebSocket connection
	Ticket string `json:"ticket"`
}

WsTicketResponse Response containing a short-lived, single-use authentication ticket for WebSocket connection

type XWebhookSignatureHeaderParam

type XWebhookSignatureHeaderParam = string

XWebhookSignatureHeaderParam defines model for X-Webhook-SignatureHeaderParam.

Source Files

Directories

Path Synopsis
Package models - hooks.go contains GORM lifecycle hooks for validation.
Package models - hooks.go contains GORM lifecycle hooks for validation.
Package notifications provides database notification services that work across different database backends (PostgreSQL and Oracle).
Package notifications provides database notification services that work across different database backends (PostgreSQL and Oracle).
platform
v1alpha1
Package v1alpha1 contains the TMIComponent custom resource API for the TMI Component Platform.
Package v1alpha1 contains the TMIComponent custom resource API for the TMI Component Platform.
Package seed provides database seeding for required initial data.
Package seed provides database seeding for required initial data.
Package validation provides cross-database validation for TMI models.
Package validation provides cross-database validation for TMI models.

Jump to

Keyboard shortcuts

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