api

package
v1.21.30 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 100 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 contracts for the optimistic-locking write path (T14 / #385, same-transaction fix #594).

A versioned entity store implements UpdateWithVersion(ctx, ..., expected int) alongside its plain Update. UpdateWithVersion opens one retryable transaction and, as its first statement, calls the central CheckAndBumpVersion helper on the tx handle before issuing the content UPDATE — so the CAS and the write it guards commit or roll back together. A concurrent writer either blocks on the CAS's row lock until the first transaction commits (then sees a version mismatch), or loses the CAS outright; it can never observe a stale version and interleave its content write with the winner's, which was possible before #594.

Handlers cannot call UpdateWithVersion through a common interface because each entity's Update method has its own parameter and result shape, so this file declares one narrow interface per entity. Handlers type-assert the package-level store globals (typed as broader interfaces) against the matching interface here to reach UpdateWithVersion without introducing circular references.

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 (
	// MaxBulkThreats caps POST/PUT /threat_models/{id}/threats/bulk.
	MaxBulkThreats = 20
	// MaxBulkThreatPatches caps the `patches` array of PATCH
	// /threat_models/{id}/threats/bulk (schema BulkPatchRequest).
	MaxBulkThreatPatches = 20
	// MaxBulkThreatDeletes caps the `threat_ids` query parameter of DELETE
	// /threat_models/{id}/threats/bulk (parameter ThreatIdsQueryParam).
	MaxBulkThreatDeletes = 20
	// MaxBulkDocuments caps POST/PUT /threat_models/{id}/documents/bulk.
	MaxBulkDocuments = 20
	// MaxBulkRepositories caps POST/PUT /threat_models/{id}/repositories/bulk.
	MaxBulkRepositories = 20
	// MaxBulkAssets caps POST/PUT /threat_models/{id}/assets/bulk.
	MaxBulkAssets = 50
)

Bulk-operation size limits.

Every value here mirrors a `maxItems` declared on the corresponding request body (or query parameter) in api-schema/tmi-openapi.json. The spec is the source of truth; these constants exist only so a handler that is reached without the OpenAPI validation middleware still refuses an oversized batch.

Keeping the two in step matters in both directions. A handler limit that is *looser* than the spec is dead code, because the middleware rejects the request first. A handler limit that is *stricter* silently rejects requests the published contract says are valid -- which is what the flat metadata cap of 20 was doing to the six resources whose spec allows 100.

If you change a `maxItems` in the spec, change the matching constant here.

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"
	DeliveryStatusCancelled  = "cancelled" // #913: set by DELETE /webhook-deliveries/{id}; terminal
)

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 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 VersionWildcard = -1

VersionWildcard is the sentinel expected-version value meaning "match any current version" — the CAS bump in CheckAndBumpVersion applies unconditionally. It is negative so it can never collide with a real version (all other call sites enforce n >= 0).

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)

	// ErrContentTokenInvalidKey guards Upsert's read-back (see below): an
	// empty UserID or ProviderID reaching that point indicates a caller bug,
	// not a legitimate token, so it fails closed rather than risking a
	// mismatched read-back (#705).
	ErrContentTokenInvalidKey = fmt.Errorf("content token: %w", dberrors.ErrConstraint)
)

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 = "21"
	// Patch version number
	VersionPatch = "30"
	// 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 ErrContentOAuthStateUnavailable = fmt.Errorf("content oauth state store unavailable: %w", dberrors.ErrTransient)

ErrContentOAuthStateUnavailable is returned when the Redis state store cannot be reached or rejects the operation. It wraps dberrors.ErrTransient so handlers map it to 503 through StoreErrorToRequestError (#1119).

View Source
var ErrEncryptionNotEnabled = errors.New("encryption is not enabled")

ErrEncryptionNotEnabled is returned by ReEncryptAll when no settings encryptor is configured. Handlers distinguish it from a database failure (#845): the former is a 409 precondition, the latter is 503/500.

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 ErrTooManyUnreadableSettings = errors.New("too many unreadable settings")

ErrTooManyUnreadableSettings is returned by ReEncryptAll when it stops at the maxUnreadableSettings cap. It is an operator-fixable data condition (409), not a database failure.

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

func AcceptLanguageMiddleware

func AcceptLanguageMiddleware() gin.HandlerFunc

AcceptLanguageMiddleware handles Accept-Language headers gracefully

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

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.

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.

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.

func AdministratorMiddleware

func AdministratorMiddleware() gin.HandlerFunc

AdministratorMiddleware creates a middleware that requires the user to be an administrator

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.

func ApplyDiff

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

ApplyDiff applies a JSON Merge Patch (RFC 7396) to a state, producing a new state.

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

func AssertAuthDataEqual

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

AssertAuthDataEqual compares two AuthorizationData structs for equality

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).

func AssertDocumentEqual

func AssertDocumentEqual(d1, d2 Document) bool

AssertDocumentEqual compares two documents for testing equality

func AssertHSTSHeader

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

AssertHSTSHeader verifies that HSTS header is present and correctly configured

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

func AssertMetadataEqual

func AssertMetadataEqual(m1, m2 Metadata) bool

AssertMetadataEqual compares two metadata items for testing equality

func AssertRateLimitHeaders

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

AssertRateLimitHeaders verifies rate limit headers are present with expected values

func AssertRepositoryEqual

func AssertRepositoryEqual(r1, r2 Repository) bool

AssertRepositoryEqual compares two repositories for testing equality

func AssertSecurityHeaders

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

AssertSecurityHeaders verifies that all expected security headers are present

func AssertThreatEqual

func AssertThreatEqual(t1, t2 Threat) bool

AssertThreatEqual compares two threats for testing equality

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.

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).

func AuthFlowRateLimitMiddleware

func AuthFlowRateLimitMiddleware(server *Server) gin.HandlerFunc

AuthFlowRateLimitMiddleware creates middleware for multi-scope auth flow rate limiting (Tier 2)

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.

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.

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.

func BodySizeLimitMiddleware

func BodySizeLimitMiddleware() gin.HandlerFunc

BodySizeLimitMiddleware enforces bodySizeLimits before any middleware reads the body: a declared Content-Length over the limit is rejected with 413 without reading; otherwise the body is read with a hard cap into memory (413 when exceeded, 400 on any other read failure) and replaced with the buffered copy, so later middleware never sees a half-read body.

func BoundaryValueValidationMiddleware

func BoundaryValueValidationMiddleware() gin.HandlerFunc

BoundaryValueValidationMiddleware enhances validation of boundary values in JSON

func BroadcastCollaborationStarted

func BroadcastCollaborationStarted(userID, diagramID, diagramName string, tm ThreatModel, sessionID string)

BroadcastCollaborationStarted notifies clients that can read the threat model about a new collaboration session

func BroadcastSystemAnnouncement

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

BroadcastSystemAnnouncement sends a system-wide announcement

func BroadcastThreatModelCreated

func BroadcastThreatModelCreated(userID string, tm ThreatModel)

BroadcastThreatModelCreated notifies connected clients that can read the threat model that it was created

func BroadcastThreatModelDeleted

func BroadcastThreatModelDeleted(userID string, tm ThreatModel)

BroadcastThreatModelDeleted notifies connected clients that can read the threat model that it was deleted

func BroadcastThreatModelUpdated

func BroadcastThreatModelUpdated(userID string, tm ThreatModel)

BroadcastThreatModelUpdated notifies connected clients that can read the threat model that it was updated

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.

func CancelWebhookDelivery

func CancelWebhookDelivery(c *gin.Context)

CancelWebhookDelivery marks a non-terminal delivery as cancelled (#913). JWT only: admin, subscription owner, addon invoker, or the addon-linked credential.

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.

If expected is VersionWildcard (the caller sent "If-Match: *", RFC 7232's "match any current representation"), the bump is unconditional: the WHERE clause carries only the id, and the new version is read back with a SELECT since UpdateColumn does not return the updated row's value on either PostgreSQL or Oracle. A clause.Returning cannot substitute for the read-back here: gorm-oracle only builds `RETURNING ... INTO` when stmt.Schema is non-nil, and this call uses Table() with no model, so Schema is nil and a Returning clause would be silently ignored (verified against gorm-oracle's Dialector.UpdateFromRewrite).

Errors:

  • dberrors.ErrNotFound if the row with id does not exist.
  • ErrVersionMismatch if the row exists but version != expected. Under VersionWildcard this is also returned (instead of a bare classified error) when the bump committed but the read-back could not confirm the resulting version — see the wildcard branch below for why.
  • other GORM errors are returned wrapped via dberrors.Classify.

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).

The CAS runs as the first statement inside the same transaction as the entity's content UPDATE (#594, fixed): each versioned store's UpdateWithVersion method opens one retryable transaction and calls this function on the tx handle before writing content, so the version bump genuinely guards the write. Concurrent writers race on the CAS's row lock: the first UPDATE to reach the row holds it until commit, so a second writer's CAS blocks behind it rather than racing free. The blocked writer then sees version != expected once the first transaction commits and gets ErrVersionMismatch — it cannot observe a stale version and proceed to interleave its content write with the winner's.

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).

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.

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.

func CheckOwnershipChanges

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

CheckOwnershipChanges analyzes patch operations to determine if owner or authorization fields are being modified

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.

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.

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.

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.

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.

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.

func CleanupTestFixtures

func CleanupTestFixtures(ctx context.Context) error

CleanupTestFixtures removes all test data from stores

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.

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.

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.

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.

func ContentTypeValidationMiddleware

func ContentTypeValidationMiddleware() gin.HandlerFunc

ContentTypeValidationMiddleware validates Content-Type header and rejects unsupported types

func ContextTimeout

func ContextTimeout(timeout time.Duration) gin.HandlerFunc

ContextTimeout adds a timeout to the request context

func ContextWithIncludeDeleted

func ContextWithIncludeDeleted(ctx context.Context) context.Context

ContextWithIncludeDeleted returns a context with include_deleted set

func CreateAddon

func CreateAddon(c *gin.Context)

CreateAddon creates a new add-on (admin only)

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

func CreateTestGinContextWithBody

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

CreateTestGinContextWithBody creates a Gin context with a request body

func CurrentTime

func CurrentTime() time.Time

CurrentTime returns current time in UTC

func CustomRecoveryMiddleware

func CustomRecoveryMiddleware() gin.HandlerFunc

CustomRecoveryMiddleware returns a Gin middleware that recovers from panics and returns appropriate error responses without exposing sensitive information

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)),
}

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.

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{})

func DeleteAddon

func DeleteAddon(c *gin.Context)

DeleteAddon deletes an add-on (admin only)

func DetailedRequestLoggingMiddleware

func DetailedRequestLoggingMiddleware() gin.HandlerFunc

DetailedRequestLoggingMiddleware logs request details at each stage

func DiagramMiddleware

func DiagramMiddleware() gin.HandlerFunc

DiagramMiddleware creates middleware for diagram authorization

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.

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.

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.

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.

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).

func EnrichAuthorizationList

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

EnrichAuthorizationList enriches all authorization entries in a list

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.

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.

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

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

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

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

func FindProhibitedPatchPath added in v1.21.15

func FindProhibitedPatchPath(operations []PatchOperation, prohibited []string) (string, bool)

FindProhibitedPatchPath returns the first prohibited path (or sub-path of one) that any operation reads or writes, and whether one was found. It checks the "from" source of move and copy as well as the target: move removes its source, and copy would expose a prohibited field (owner, is_confidential, ...) through a field the caller may read.

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"

func GetAddon

func GetAddon(c *gin.Context)

GetAddon retrieves a single add-on by ID

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

func GetDialectName

func GetDialectName(db *gorm.DB) string

GetDialectName is a convenience function to get the dialect name from a GORM DB instance.

func GetFieldErrorMessage

func GetFieldErrorMessage(field, operation string) string

GetFieldErrorMessage is the global function to get error messages

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.

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)

func GetProjectTeamID

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

GetProjectTeamID retrieves the team_id for a given project.

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

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

func GetTestUsers

func GetTestUsers() map[string]string

GetTestUsers returns a map of test users with their roles

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.

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)

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

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

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)

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})"

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

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

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

func GetVersionString

func GetVersionString() string

GetVersionString returns the version as a formatted string

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).

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

func HSTSMiddleware

func HSTSMiddleware(tlsEnabled bool) gin.HandlerFunc

HSTSMiddleware adds Strict-Transport-Security header when TLS is enabled

func HandleRequestError

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

HandleRequestError sends an appropriate HTTP error response

func HandleRestoreAsset

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

RestoreAsset restores a soft-deleted asset.

func HandleRestoreDiagram

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

RestoreDiagram restores a soft-deleted diagram.

func HandleRestoreDocument

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

RestoreDocument restores a soft-deleted document.

func HandleRestoreNote

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

RestoreNote restores a soft-deleted note.

func HandleRestoreRepository

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

RestoreRepository restores a soft-deleted repository.

func HandleRestoreThreat

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

RestoreThreat restores a soft-deleted threat.

func HandleRestoreThreatModel

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

HandleRestoreThreatModel restores a soft-deleted threat model and all its children.

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.

func IPRateLimitMiddleware

func IPRateLimitMiddleware(server *Server) gin.HandlerFunc

IPRateLimitMiddleware creates middleware for IP-based rate limiting (Tier 1 - public discovery)

func InitNotificationHub

func InitNotificationHub()

InitNotificationHub initializes the global notification hub

func InitSubResourceTestFixtures

func InitSubResourceTestFixtures()

InitSubResourceTestFixtures initializes comprehensive test fixtures for sub-resource testing

func InitTestFixtures

func InitTestFixtures()

InitTestFixtures initializes test data in stores

func InitializeEventEmitter

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

InitializeEventEmitter initializes the global event emitter

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

func InitializeMockStores

func InitializeMockStores()

InitializeMockStores creates simple mock stores for unit tests

func InitializeQuotaCache

func InitializeQuotaCache(ttl time.Duration)

InitializeQuotaCache initializes the global quota cache

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

func InvokeAddon

func InvokeAddon(c *gin.Context)

InvokeAddon invokes an add-on (authenticated users). Creates a WebhookDeliveryRecord and emits an addon.invoked event.

func IsConfidentialProjectReviewersGroup

func IsConfidentialProjectReviewersGroup(auth Authorization) bool

IsConfidentialProjectReviewersGroup checks if an authorization entry represents the Confidential Project Reviewers group

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.

func IsEffectiveAdministratorByUUID

func IsEffectiveAdministratorByUUID(ctx context.Context, memberStore GroupMemberRepository, userInternalUUID string) (bool, error)

IsEffectiveAdministratorByUUID reports whether a user is an administrator through direct membership or through any TMI-managed group they belong to. It needs no request context or IdP group list, so it is the check to use when the user is not the caller (credential owners, automation accounts). Errors are returned, never swallowed: callers gating a privilege on this answer must fail closed (#856, T18).

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.

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.

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.

func IsIPv4

func IsIPv4(hostname string) bool

IsIPv4 checks if a string is an IPv4 address

func IsIPv6

func IsIPv6(hostname string) bool

IsIPv6 checks if a string is an IPv6 address

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.

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

func IsSecurityReviewersGroup

func IsSecurityReviewersGroup(auth Authorization) bool

IsSecurityReviewersGroup checks if an authorization entry represents the Security Reviewers group

func IsServiceAccountRequest

func IsServiceAccountRequest(c *gin.Context) bool

IsServiceAccountRequest returns true if the current request is from a service account

func IsTMIAutomationGroup

func IsTMIAutomationGroup(auth Authorization) bool

IsTMIAutomationGroup checks if an authorization entry represents the TMI Automation group

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.

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).

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.

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

func ListAddons

func ListAddons(c *gin.Context)

ListAddons retrieves add-ons with pagination

func ListMyWebhookDeliveries

func ListMyWebhookDeliveries(c *gin.Context, params ListMyWebhookDeliveriesParams)

ListMyWebhookDeliveries lists the deliveries the JWT caller may see (#913): everything for admins; otherwise the same rule as verifyDeliveryJWTAccess.

func LogRequest

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

LogRequest logs debug information about the request

func MapOptimisticLockError

func MapOptimisticLockError(err error, notFoundMsg string) error

MapOptimisticLockError converts a store-layer error from a versioned write into the appropriate HTTP RequestError for the optimistic-locking contract. notFoundMsg is the entity-specific 404 message ("Project not found"), so a versioned write does not regress to a generic one (#777). Returns nil when err is not a versioning error, so callers fall through to their existing error mapping.

func MarshalAsyncMessage

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

Helper function to marshal AsyncMessage to JSON

func MarshalAuditEntryResponse

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

MarshalAuditEntryResponse is a helper to serialize an AuditEntryResponse to JSON.

func MaxBulkMetadataFor

func MaxBulkMetadataFor(entityType string) int

MaxBulkMetadataFor returns the bulk metadata cap for an entity type. An unregistered entity type falls back to the more restrictive value rather than the more permissive one, so a new handler that forgets to add itself here is merely stricter than the spec instead of unbounded.

func MethodNotAllowedHandler

func MethodNotAllowedHandler() gin.HandlerFunc

MethodNotAllowedHandler returns 405 for unsupported HTTP methods

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.

func MigrateLegacyThreatValues

func MigrateLegacyThreatValues(ctx context.Context, db *gorm.DB) (int64, error)

MigrateLegacyThreatValues rewrites stored legacy severity, priority and status values to canonical form and returns the number of values changed. Idempotent: keys and values of each map are disjoint, so a second run matches nothing. Keys are emitted in sorted order so the SQL text is stable.

Runs in one explicit READ COMMITTED transaction: a bare Exec would inherit whatever isolation the pooled Oracle session last had, and a full-scan UPDATE under a leftover SERIALIZABLE raises ORA-08177 instead of restarting (#906). The LOWER() predicates cannot use the column indexes; the caller is expected to drop this once every environment has been migrated (#926).

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.

func NewExtractedTextNoteDumper

func NewExtractedTextNoteDumper(notes NoteRepository, documents DocumentRepository) *extractedTextNoteDumper

NewExtractedTextNoteDumper builds a dumper. notes/documents must be non-nil.

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.

func NewReadCloser

func NewReadCloser(b []byte) *readCloser

func NewStampedConfigProvider

func NewStampedConfigProvider(settings settingsReader) config.StampedConfigProvider

NewStampedConfigProvider builds a config.StampedConfigProvider that reads through the given settings reader (normally *SettingsService).

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)

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

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"

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).

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).

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.

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.

func OpenAPIErrorHandler

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

OpenAPIErrorHandler converts OpenAPI validation errors to TMI's error format

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.

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.

func ParseIfMatchHeader

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

ParseIfMatchHeader extracts the expected 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"), a quoted integer (`If-Match: "5"`), or the "*" wildcard, which RFC 7232 defines as matching any current representation — we map it to VersionWildcard so the write proceeds unconditionally.

func ParseRequestBody

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

ParseRequestBody parses JSON request body into the specified type

func ParseUUIDOrNil

func ParseUUIDOrNil(s string) uuid.UUID

ParseUUIDOrNil parses a UUID string, returning a nil UUID on error

func PatchAddon

func PatchAddon(c *gin.Context)

PatchAddon partially updates an add-on (admin only)

func PathParameterValidationMiddleware

func PathParameterValidationMiddleware() gin.HandlerFunc

PathParameterValidationMiddleware validates all path parameters for common issues

func PathToRawSpec

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

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

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

func RangeFilterValidationMiddleware added in v1.20.0

func RangeFilterValidationMiddleware() gin.HandlerFunc

RangeFilterValidationMiddleware rejects GET list requests whose range filters describe an empty range (lower bound above upper bound, or equal when either bound is exclusive) with 400 invalid_input. It is the single enforcement point for all range query pairs (#1051).

func RateLimitMiddleware

func RateLimitMiddleware(server *Server) gin.HandlerFunc

RateLimitMiddleware creates a middleware that enforces API rate limiting

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.

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.

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.

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.

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

func RequireIfMatch

func RequireIfMatch() bool

RequireIfMatch reports whether missing If-Match should hard-fail with 428.

func ResetSubResourceStores

func ResetSubResourceStores()

ResetSubResourceStores clears all sub-resource stores for testing

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().

func ResolveOptimisticLock

func ResolveOptimisticLock(c *gin.Context, bodyVersion *int) (expected int, present bool, err error)

ResolveOptimisticLock implements the handler-side "what version does this write expect" step, decoupled from any store access:

  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).

Callers that get (expected, true, nil) pass expected straight to the store's UpdateWithVersion method, which runs the CAS inside the same transaction as the content write (#594). Callers that get (0, false, nil) call the store's plain Update instead.

func RespondWithBadRequest

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

RespondWithBadRequest sends a 400 Bad Request error response

func RespondWithError

func RespondWithError(c *gin.Context, statusCode int, errorCode errcode.Code, 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.

func RouteMatchingMiddleware

func RouteMatchingMiddleware() gin.HandlerFunc

RouteMatchingMiddleware logs which routes are being matched

func RunMiddlewareTestCases

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

RunMiddlewareTestCases executes a slice of test cases against a middleware

func SAMLProviderOnlyMiddleware

func SAMLProviderOnlyMiddleware() gin.HandlerFunc

SAMLProviderOnlyMiddleware ensures the provider is a SAML provider (not OAuth)

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.

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() currently marshals the value as given, because oapi-codegen v2.7.1 assigns the discriminator in From<Variant>/Merge<Variant> only when the discriminator mapping has exactly one entry per oneOf member (union.tmpl). Here cells.items has 2 members and 6 mapping entries, so nothing is assigned. Collapsing Node's five shape entries to one would make the union qualify and hardcode a single shape into every node. This helper is the required guard: it marshals the node directly and stores the raw bytes via UnmarshalJSON.

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

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.

func SameProviderMiddleware

func SameProviderMiddleware() gin.HandlerFunc

SameProviderMiddleware ensures the authenticated user is from the same provider as specified in the path

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.

func SanitizeMarkdownContent

func SanitizeMarkdownContent(content string) string

SanitizeMarkdownContent strips dangerous HTML from a markdown string while leaving all non-markup text byte-for-byte intact (#992).

Markdown is not HTML, so the source is tokenized and only tag-like tokens are run through the bluemonday allowlist; text tokens are copied verbatim rather than re-serialized, which would entity-encode quotes, apostrophes and ampersands. Content of script/style and similar elements is dropped, as bluemonday does. Stripping a tag can splice neighbouring text into a new tag (e.g. "<<script>script>"), so the pass repeats until stable; if it does not settle, fall back to bluemonday's fully escaped output.

Each pass also neutralizes markdown link, image and reference-definition destinations whose scheme is not http, https or mailto (#1013); see markdown_link_destinations.go.

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.

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.

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.

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".

func SecurityHeaders

func SecurityHeaders() gin.HandlerFunc

SecurityHeaders middleware adds security headers to all responses

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.

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.

func SetFullUserContext

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

SetFullUserContext sets complete user authentication context including groups and IdP

func SetGlobalAuthServiceForEvents

func SetGlobalAuthServiceForEvents(authService AuthService)

SetGlobalAuthServiceForEvents sets the global auth service for event owner lookups

func SetGlobalDelegationTokenIssuer

func SetGlobalDelegationTokenIssuer(issuer DelegationTokenIssuer)

SetGlobalDelegationTokenIssuer sets the global delegation-token issuer. Safe to call once at startup from cmd/server/main.go.

func SetRequireIfMatch

func SetRequireIfMatch(v bool)

SetRequireIfMatch updates the optimistic-locking enforcement flag. Called once during server initialization from the loaded config.

func SetTeamAuthDB

func SetTeamAuthDB(db *gorm.DB)

SetTeamAuthDB sets the GORM database handle for team authorization.

func SetUserContext

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

SetUserContext sets authentication context on a Gin context

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)

func SetupOpenAPIValidation

func SetupOpenAPIValidation() (gin.HandlerFunc, error)

SetupOpenAPIValidation creates and returns OpenAPI validation middleware

func SetupStoresWithFixtures

func SetupStoresWithFixtures(ctx context.Context) error

SetupStoresWithFixtures initializes stores with test fixtures

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.).

func SourceAddonIDFromContext

func SourceAddonIDFromContext(ctx context.Context) string

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".

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.

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.

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).

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).

func TeamExists

func TeamExists(ctx context.Context, teamID string) (bool, error)

TeamExists reports whether a team row exists.

Authorization alone cannot answer this: both IsTeamMemberOrAdmin and IsProjectTeamMemberOrAdmin return true for an administrator before ever looking the parent up, so an admin listing a sub-resource of a nonexistent team got 200 with an empty list while a regular user got 404 for the same URL (#609). Callers check existence first so both answers agree.

func ThreatModelMiddleware

func ThreatModelMiddleware() gin.HandlerFunc

ThreatModelMiddleware creates middleware for threat model authorization

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.

func TombstoneRetentionDays

func TombstoneRetentionDays() int

TombstoneRetentionDays returns the configured tombstone retention in days (TOMBSTONE_RETENTION_DAYS, default 30). See AuditRetentionDays.

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

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.

func UUIDValidationMiddleware

func UUIDValidationMiddleware() gin.HandlerFunc

UUIDValidationMiddleware validates UUID path parameters

func UnicodeNormalizationMiddleware

func UnicodeNormalizationMiddleware() gin.HandlerFunc

UnicodeNormalizationMiddleware normalizes Unicode in request bodies and rejects problematic characters

func UpdateTimestamps

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

UpdateTimestamps updates the timestamps on an entity

func UpdateWebhookDeliveryStatus

func UpdateWebhookDeliveryStatus(c *gin.Context)

UpdateWebhookDeliveryStatus updates the status of a webhook delivery (HMAC authenticated).

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.

func ValidateAddonDescription

func ValidateAddonDescription(description string) error

ValidateAddonDescription validates the add-on description for XSS and length

func ValidateAddonName

func ValidateAddonName(name string) error

ValidateAddonName validates the add-on name for XSS and length

func ValidateAddonParameters

func ValidateAddonParameters(params []AddonParameter) error

ValidateAddonParameters validates parameter definitions at addon creation time

func ValidateAndParseRequest

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

ValidateAndParseRequest provides unified request validation and parsing

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

func ValidateAuthorizationEntriesFromStruct

func ValidateAuthorizationEntriesFromStruct(data any) error

ValidateAuthorizationEntriesFromStruct is the public wrapper for the validator

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

func ValidateAuthorizationWithPseudoGroups

func ValidateAuthorizationWithPseudoGroups(authList []Authorization) error

ValidateAuthorizationWithPseudoGroups validates authorization entries and applies pseudo-group specific rules

func ValidateDiagramType

func ValidateDiagramType(data any) error

ValidateDiagramType validates diagram type field

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.

func ValidateEmailFields

func ValidateEmailFields(data any) error

ValidateEmailFields validates email format in struct fields

func ValidateIcon

func ValidateIcon(icon string) error

ValidateIcon validates an icon string against Material Symbols or FontAwesome formats

func ValidateInvocationData

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

ValidateInvocationData validates invocation data against declared addon parameters

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.

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.

func ValidateMetadataKey

func ValidateMetadataKey(data any) error

ValidateMetadataKey validates metadata key format against validation.MetadataKeyPattern

func ValidateNoDuplicateEntries

func ValidateNoDuplicateEntries(data any) error

ValidateNoDuplicateEntries validates that slice fields don't contain duplicates

func ValidateNoHTMLInjection

func ValidateNoHTMLInjection(data any) error

ValidateNoHTMLInjection prevents HTML/script injection in text fields. Uses the unified CheckHTMLInjection checker for consistent pattern coverage.

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.

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

func ValidateObjects

func ValidateObjects(objects []string) error

ValidateObjects validates that all object types are in the TMI taxonomy

func ValidatePatchAuthorization

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

ValidatePatchAuthorization validates that the user has permission to perform the patch operations

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

func ValidateQuotaValue

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

ValidateQuotaValue validates that a quota value is within acceptable bounds

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.

func ValidateResourceAccess

func ValidateResourceAccess(requiredRole Role) gin.HandlerFunc

ValidateResourceAccess is a Gin middleware-compatible function for authorization checks

func ValidateRoleFields

func ValidateRoleFields(data any) error

ValidateRoleFields validates role format in struct fields

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

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.

func ValidateSettingSemantics added in v1.21.15

func ValidateSettingSemantics(key, value string, productionMode bool) error

ValidateSettingSemantics applies the per-key semantic validator for key, if any; keys without a validator pass. Exported so writers that bypass SettingsService.Set (cmd/dbtool) enforce the same rules (#1108).

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

func ValidateStringLengths

func ValidateStringLengths(data any) error

ValidateStringLengths validates string field lengths based on struct tags

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

func ValidateSubResourceAccessOwner

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

ValidateSubResourceAccessOwner creates middleware for owner-only sub-resource access

func ValidateSubResourceAccessReader

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

ValidateSubResourceAccessReader creates middleware for read-only sub-resource access

func ValidateSubResourceAccessWriter

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

ValidateSubResourceAccessWriter creates middleware for write sub-resource access

func ValidateSurveyResponseStatusTransition

func ValidateSurveyResponseStatusTransition(newStatus string, revisionNotes *string) error

ValidateSurveyResponseStatusTransition checks a status transition is well-formed before any write: the target must be a known status, and needs_revision requires revision_notes. Callers that also perform a CAS-guarded content write (PatchIntakeSurveyResponse, #594) run this BEFORE that write so a malformed status transition fails without committing anything, rather than surfacing as a 409 after the write that preceded it already committed.

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.

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

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.

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.

func ValidateURLFields

func ValidateURLFields(data any) error

ValidateURLFields validates URL format in struct fields

func ValidateUUID

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

ValidateUUID validates that a string is a valid UUID format

func ValidateUUIDFieldsFromStruct

func ValidateUUIDFieldsFromStruct(data any) error

Enhanced UUID validation with better error messages

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.

func ValidateUserIdentity

func ValidateUserIdentity(u User) error

ValidateUserIdentity validates that a User struct contains at least one valid identifier

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.

func VersionRetentionDays

func VersionRetentionDays() int

VersionRetentionDays returns the configured version-snapshot retention in days (VERSION_RETENTION_DAYS, default 90). See AuditRetentionDays.

func WithSourceAddonID

func WithSourceAddonID(ctx context.Context, addonID string) context.Context

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.

Types

type APIRateLimiter

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

APIRateLimiter implements rate limiting for general API operations using Redis

func NewAPIRateLimiter

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

NewAPIRateLimiter creates a new API rate limiter

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

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

type APIReranker

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

APIReranker calls an HTTP reranker endpoint compatible with Cohere/Jina/vLLM.

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).

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.

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.

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).

type AccessPoller

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

AccessPoller periodically checks documents with "pending_access" status.

func NewAccessPoller

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

NewAccessPoller creates a new background access poller.

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.

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.

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.

func (*AccessPoller) Start

func (p *AccessPoller) Start()

Start begins the background polling loop.

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).

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.

type AccessRequester

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

AccessRequester programmatically requests access to a URI (e.g., share request email).

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.

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.

func NewAccessTrackerWithDebounce

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

NewAccessTrackerWithDebounce creates an AccessTracker with a custom debounce duration (for testing).

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.

func (*AccessTracker) Reset

func (at *AccessTracker) Reset()

Reset clears the debounce map. Used in tests.

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.

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

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

func NewAddonInvocationQuotaDatabaseStore

func NewAddonInvocationQuotaDatabaseStore(db *sql.DB) *AddonInvocationQuotaDatabaseStore

NewAddonInvocationQuotaDatabaseStore creates a new database-backed quota store

func (*AddonInvocationQuotaDatabaseStore) Count

Count returns the total number of addon invocation quotas

func (*AddonInvocationQuotaDatabaseStore) Delete

Delete removes quota for a user (reverts to defaults)

func (*AddonInvocationQuotaDatabaseStore) Get

Get retrieves quota for a user, returns error if not found

func (*AddonInvocationQuotaDatabaseStore) GetOrDefault

GetOrDefault retrieves quota for a user, or returns defaults if not set

func (*AddonInvocationQuotaDatabaseStore) List

List retrieves all addon invocation quotas with pagination

func (*AddonInvocationQuotaDatabaseStore) Set

Set creates or updates quota for a user

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

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

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

func (*AddonRateLimiter) CheckActiveInvocationLimit

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

CheckActiveInvocationLimit checks if user has reached their concurrent invocation limit

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

func (*AddonRateLimiter) RecordInvocation

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

RecordInvocation records a new invocation in the sliding window

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)

	// Update writes the mutable fields of an existing add-on, identified by
	// addon.ID. Returns ErrAddonNotFound when no such add-on exists.
	Update(ctx context.Context, addon *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

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

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.

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"`

	// IsBuiltin True only for server-seeded built-in groups; false for admin-created groups (which also use provider "tmi")
	IsBuiltin *bool `json:"is_builtin,omitempty"`

	// 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 AdminUserIdentitiesResponse

type AdminUserIdentitiesResponse struct {
	// Linked Linked sign-in identities; the primary identity is not deletable and does not appear here
	Linked  *[]LinkedIdentity `json:"linked,omitempty"`
	Primary struct {
		// Email Email on the user record
		Email string `json:"email"`

		// Name Display name on the user record
		Name string `json:"name"`

		// Provider Identity provider of the primary sign-in identity
		Provider string `json:"provider"`
	} `json:"primary"`
}

AdminUserIdentitiesResponse A user's primary sign-in identity plus any linked identities, as seen by an administrator

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).

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

func NewApiInfoHandler

func NewApiInfoHandler(server *Server) *ApiInfoHandler

NewApiInfoHandler creates a new handler for API info

func (*ApiInfoHandler) GetApiInfo

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

GetApiInfo returns service, API, and operator information

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 AssetBulkUpdateItem

type AssetBulkUpdateItem 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"`

	// Id Unique identifier of the asset 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"`

	// 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 AssetBulkUpdateItemType `binding:"required" json:"type"`
}

AssetBulkUpdateItem defines model for AssetBulkUpdateItem.

type AssetBulkUpdateItemType

type AssetBulkUpdateItemType string

AssetBulkUpdateItemType Type of asset

const (
	AssetBulkUpdateItemTypeData           AssetBulkUpdateItemType = "data"
	AssetBulkUpdateItemTypeHardware       AssetBulkUpdateItemType = "hardware"
	AssetBulkUpdateItemTypeInfrastructure AssetBulkUpdateItemType = "infrastructure"
	AssetBulkUpdateItemTypePersonnel      AssetBulkUpdateItemType = "personnel"
	AssetBulkUpdateItemTypeService        AssetBulkUpdateItemType = "service"
	AssetBulkUpdateItemTypeSoftware       AssetBulkUpdateItemType = "software"
)

Defines values for AssetBulkUpdateItemType.

func (AssetBulkUpdateItemType) Valid

func (e AssetBulkUpdateItemType) Valid() bool

Valid indicates whether the value is a known member of the AssetBulkUpdateItemType 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

var GlobalAssetRepository AssetRepository

type AssetSubResourceHandler

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

AssetSubResourceHandler provides handlers for asset sub-resource operations

func NewAssetSubResourceHandler

func NewAssetSubResourceHandler(assetStore AssetRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *AssetSubResourceHandler

NewAssetSubResourceHandler creates a new asset sub-resource handler

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

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

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

func (*AssetSubResourceHandler) DeleteAsset

func (h *AssetSubResourceHandler) DeleteAsset(c *gin.Context)

DeleteAsset deletes an asset DELETE /threat_models/{threat_model_id}/assets/{asset_id}

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}

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

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}

func (*AssetSubResourceHandler) UpdateAsset

func (h *AssetSubResourceHandler) UpdateAsset(c *gin.Context)

UpdateAsset updates an existing asset PUT /threat_models/{threat_model_id}/assets/{asset_id}

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

func ParseAsyncMessage

func ParseAsyncMessage(data []byte) (AsyncMessage, error)

Message Parser utility to parse incoming WebSocket messages

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

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

func ExtractAuditContext

func ExtractAuditContext(c *gin.Context) *AuditContext

ExtractAuditContext extracts actor information from the Gin context

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.

var GlobalAuditDebouncer *AuditDebouncer

func NewAuditDebouncer

func NewAuditDebouncer(auditService AuditServiceInterface) *AuditDebouncer

NewAuditDebouncer creates a new debouncer with the given audit service.

func (*AuditDebouncer) FlushAll

func (d *AuditDebouncer) FlushAll()

FlushAll flushes all pending audit entries immediately. Should be called during server shutdown or WebSocket session end.

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.

func (*AuditDebouncer) PendingCount

func (d *AuditDebouncer) PendingCount() int

PendingCount returns the number of pending (un-flushed) audit entries. Useful for testing.

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).

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.

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.

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.

func NewAuditHandler

func NewAuditHandler(auditService AuditServiceInterface) *AuditHandler

NewAuditHandler creates a new audit handler.

func (*AuditHandler) GetAssetAuditTrail

func (h *AuditHandler) GetAssetAuditTrail(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, params GetAssetAuditTrailParams)

GetAssetAuditTrail lists audit entries for a specific asset.

func (*AuditHandler) GetAuditEntry

func (h *AuditHandler) GetAuditEntry(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

GetAuditEntry returns a single audit entry.

func (*AuditHandler) GetDiagramAuditTrail

func (h *AuditHandler) GetDiagramAuditTrail(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, params GetDiagramAuditTrailParams)

GetDiagramAuditTrail lists audit entries for a specific diagram.

func (*AuditHandler) GetDocumentAuditTrail

func (h *AuditHandler) GetDocumentAuditTrail(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, params GetDocumentAuditTrailParams)

GetDocumentAuditTrail lists audit entries for a specific document.

func (*AuditHandler) GetNoteAuditTrail

func (h *AuditHandler) GetNoteAuditTrail(c *gin.Context, threatModelId ThreatModelId, noteId NoteId, params GetNoteAuditTrailParams)

GetNoteAuditTrail lists audit entries for a specific note.

func (*AuditHandler) GetRepositoryAuditTrail

func (h *AuditHandler) GetRepositoryAuditTrail(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, params GetRepositoryAuditTrailParams)

GetRepositoryAuditTrail lists audit entries for a specific repository.

func (*AuditHandler) GetThreatAuditTrail

func (h *AuditHandler) GetThreatAuditTrail(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, params GetThreatAuditTrailParams)

GetThreatAuditTrail lists audit entries for a specific threat.

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.

func (*AuditHandler) RollbackToVersion

func (h *AuditHandler) RollbackToVersion(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

RollbackToVersion restores an entity to a previous version.

type AuditLogger

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

AuditLogger provides standardized audit logging for admin operations

func NewAuditLogger

func NewAuditLogger() *AuditLogger

NewAuditLogger creates a new audit logger

func (*AuditLogger) LogAction

func (a *AuditLogger) LogAction(ctx *AuditContext, action string, details map[string]any)

LogAction logs an audit event with standardized format

func (*AuditLogger) LogCreate

func (a *AuditLogger) LogCreate(ctx *AuditContext, entityType string, entityID string, details map[string]any)

LogCreate logs an entity creation event

func (*AuditLogger) LogDelete

func (a *AuditLogger) LogDelete(ctx *AuditContext, entityType string, entityID string, details map[string]any)

LogDelete logs an entity deletion event

func (*AuditLogger) LogGroupMemberAdded

func (a *AuditLogger) LogGroupMemberAdded(ctx *AuditContext, groupUUID string, userUUID string, userEmail string)

LogGroupMemberAdded logs a group member addition event

func (*AuditLogger) LogGroupMemberRemoved

func (a *AuditLogger) LogGroupMemberRemoved(ctx *AuditContext, groupUUID string, userUUID string)

LogGroupMemberRemoved logs a group member removal event

func (*AuditLogger) LogUpdate

func (a *AuditLogger) LogUpdate(ctx *AuditContext, entityType string, entityID string, changes []string)

LogUpdate logs an entity update event

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

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.

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.

func NewAuditPruner

func NewAuditPruner(auditService AuditServiceInterface) *AuditPruner

NewAuditPruner creates a new pruner for the given audit service.

func (*AuditPruner) Start

func (p *AuditPruner) Start()

Start begins the background pruning goroutine.

func (*AuditPruner) Stop

func (p *AuditPruner) Stop()

Stop gracefully stops the pruning goroutine.

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.

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

func NewAuthFlowRateLimiter

func NewAuthFlowRateLimiter(redisClient *redis.Client) *AuthFlowRateLimiter

NewAuthFlowRateLimiter creates a new auth flow rate limiter

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).

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

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.

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

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

func NewAuthServiceAdapter

func NewAuthServiceAdapter(handlers *auth.Handlers) *AuthServiceAdapter

NewAuthServiceAdapter creates a new adapter for auth handlers

func (*AuthServiceAdapter) Authorize

func (a *AuthServiceAdapter) Authorize(c *gin.Context)

Authorize delegates to auth handlers

func (*AuthServiceAdapter) Callback

func (a *AuthServiceAdapter) Callback(c *gin.Context)

Callback delegates to auth handlers

func (*AuthServiceAdapter) Exchange

func (a *AuthServiceAdapter) Exchange(c *gin.Context)

Exchange delegates to auth handlers

func (*AuthServiceAdapter) GetJWKS

func (a *AuthServiceAdapter) GetJWKS(c *gin.Context)

GetJWKS delegates to auth handlers

func (*AuthServiceAdapter) GetOAuthAuthorizationServerMetadata

func (a *AuthServiceAdapter) GetOAuthAuthorizationServerMetadata(c *gin.Context)

GetOAuthAuthorizationServerMetadata delegates to auth handlers

func (*AuthServiceAdapter) GetOAuthProtectedResourceMetadata

func (a *AuthServiceAdapter) GetOAuthProtectedResourceMetadata(c *gin.Context)

GetOAuthProtectedResourceMetadata delegates to auth handlers

func (*AuthServiceAdapter) GetOpenIDConfiguration

func (a *AuthServiceAdapter) GetOpenIDConfiguration(c *gin.Context)

GetOpenIDConfiguration delegates to auth handlers

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

func (*AuthServiceAdapter) GetProviders

func (a *AuthServiceAdapter) GetProviders(c *gin.Context)

GetProviders delegates to auth handlers

func (*AuthServiceAdapter) GetSAMLMetadata

func (a *AuthServiceAdapter) GetSAMLMetadata(c *gin.Context, providerID string)

GetSAMLMetadata delegates to auth handlers for SAML metadata

func (*AuthServiceAdapter) GetSAMLProviders

func (a *AuthServiceAdapter) GetSAMLProviders(c *gin.Context)

GetSAMLProviders delegates to auth handlers

func (*AuthServiceAdapter) GetService

func (a *AuthServiceAdapter) GetService() *auth.Service

GetService returns the underlying auth service for advanced operations

func (*AuthServiceAdapter) InitiateSAMLLogin

func (a *AuthServiceAdapter) InitiateSAMLLogin(c *gin.Context, providerID string, clientCallback *string)

InitiateSAMLLogin delegates to auth handlers to start SAML authentication

func (*AuthServiceAdapter) IntrospectToken

func (a *AuthServiceAdapter) IntrospectToken(c *gin.Context)

IntrospectToken delegates to auth handlers

func (*AuthServiceAdapter) IsValidProvider

func (a *AuthServiceAdapter) IsValidProvider(idp string) bool

IsValidProvider checks if the given provider ID is configured and enabled

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).

func (*AuthServiceAdapter) Logout

func (a *AuthServiceAdapter) Logout(c *gin.Context)

Logout delegates to auth handlers (deprecated - use RevokeToken or MeLogout)

func (*AuthServiceAdapter) Me

func (a *AuthServiceAdapter) Me(c *gin.Context)

Me delegates to auth handlers, with fallback user lookup if needed

func (*AuthServiceAdapter) MeLogout

func (a *AuthServiceAdapter) MeLogout(c *gin.Context)

MeLogout delegates to auth handlers for self-logout

func (*AuthServiceAdapter) ProcessSAMLLogout

func (a *AuthServiceAdapter) ProcessSAMLLogout(c *gin.Context, providerID string, samlRequest string)

ProcessSAMLLogout delegates to auth handlers for SAML logout

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

func (*AuthServiceAdapter) Refresh

func (a *AuthServiceAdapter) Refresh(c *gin.Context)

Refresh delegates to auth handlers

func (*AuthServiceAdapter) RevokeToken

func (a *AuthServiceAdapter) RevokeToken(c *gin.Context)

RevokeToken delegates to auth handlers for RFC 7009 token revocation

func (*AuthServiceAdapter) StepUp

func (a *AuthServiceAdapter) StepUp(c *gin.Context)

StepUp delegates to auth.Handlers.StepUp (#397).

func (*AuthServiceAdapter) Token

func (a *AuthServiceAdapter) Token(c *gin.Context)

Token delegates to auth handlers (supports all grant types and content types)

type AuthServiceGetter

type AuthServiceGetter interface {
	GetService() *auth.Service
}

AuthServiceGetter defines an interface for getting the auth service

type AuthTestHelper

type AuthTestHelper struct {
	DB               *sql.DB
	Cache            *CacheService
	CacheInvalidator *CacheInvalidator
	TestContext      context.Context
}

AuthTestHelper provides utilities for testing authorization functionality with caching

func NewAuthTestHelper

func NewAuthTestHelper(db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *AuthTestHelper

NewAuthTestHelper creates a new authorization test helper

func (*AuthTestHelper) CleanupTestAuth

func (h *AuthTestHelper) CleanupTestAuth(t *testing.T, threatModelIDs []string)

CleanupTestAuth cleans up test authorization data

func (*AuthTestHelper) CreateTestGinContext

func (h *AuthTestHelper) CreateTestGinContext(userEmail string, threatModelID string) (*gin.Context, *httptest.ResponseRecorder)

CreateTestGinContext creates a Gin context for testing with authentication

func (*AuthTestHelper) SetupTestAuthorizationData

func (h *AuthTestHelper) SetupTestAuthorizationData() []AuthTestScenario

SetupTestAuthorizationData creates test authorization data for various scenarios

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

func (*AuthTestHelper) TestCacheInvalidation

func (h *AuthTestHelper) TestCacheInvalidation(t *testing.T, threatModelID string)

TestCacheInvalidation tests that cache is properly invalidated when authorization changes

func (*AuthTestHelper) TestCheckSubResourceAccess

func (h *AuthTestHelper) TestCheckSubResourceAccess(t *testing.T, scenarios []AuthTestScenario)

TestCheckSubResourceAccess tests the CheckSubResourceAccess function with caching

func (*AuthTestHelper) TestGetInheritedAuthData

func (h *AuthTestHelper) TestGetInheritedAuthData(t *testing.T, scenarios []AuthTestScenario)

TestGetInheritedAuthData tests the GetInheritedAuthData function with various scenarios

func (*AuthTestHelper) TestValidateSubResourceAccess

func (h *AuthTestHelper) TestValidateSubResourceAccess(t *testing.T, scenarios []AuthTestScenario)

TestValidateSubResourceAccess tests the middleware function

func (*AuthTestHelper) VerifyAuthorizationInheritance

func (h *AuthTestHelper) VerifyAuthorizationInheritance(t *testing.T, threatModelID, subResourceID string)

VerifyAuthorizationInheritance verifies that sub-resource authorization inherits from 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

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

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

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.

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.

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.

func ExtractOwnershipChangesFromOperations

func ExtractOwnershipChangesFromOperations(operations []PatchOperation) (newOwner string, newAuth []Authorization, hasOwnerChange, hasAuthChange bool)

ExtractOwnershipChangesFromOperations extracts owner and authorization changes from patch operations

func NormalizePseudoGroupAuthorization

func NormalizePseudoGroupAuthorization(auth Authorization) Authorization

NormalizePseudoGroupAuthorization ensures pseudo-group authorization entries have the correct Provider value (BuiltInProvider for cross-provider pseudo-groups)

func NormalizePseudoGroupAuthorizationList

func NormalizePseudoGroupAuthorizationList(authList []Authorization) []Authorization

NormalizePseudoGroupAuthorizationList applies normalization to a list of authorization entries

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.

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)

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.

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

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

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

func GetTestAuthorizationData

func GetTestAuthorizationData(scenario string) *AuthorizationData

GetTestAuthorizationData returns test authorization data for a specific scenario

type AuthorizationDeniedMessage

type AuthorizationDeniedMessage struct {
	MessageType         MessageType `json:"message_type"`
	OriginalOperationID string      `json:"original_operation_id"`
	Reason              string      `json:"reason"`
}

func (AuthorizationDeniedMessage) GetMessageType

func (m AuthorizationDeniedMessage) GetMessageType() MessageType

func (AuthorizationDeniedMessage) Validate

func (m AuthorizationDeniedMessage) Validate() error

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 redirects after successful authentication. For OAuth (authorization code with PKCE) the redirect carries the authorization code and state in the query string (?code=...&state=...); the client exchanges the code for tokens at POST /oauth2/token, which returns a JSON body and, when cookie delivery is enabled, also sets HttpOnly token cookies. OAuth never delivers tokens in the URL fragment. SAML login instead redirects with the tokens in the URL fragment (#access_token=...).
	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 forwarded to the provider (login_hint), so the provider knows which account to authenticate. For the TMI provider this selects the test identity: either a username (alice) or its address form (alice@tmi.local); other providers receive it as an email address or username, per their own login_hint semantics. Valid characters: letters, digits, periods, underscores, percent signs, plus signs, at 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.

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.

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}).

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.

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.

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.

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).

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.

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.

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.

func (*BaseContentOAuthProvider) ID

ID returns the provider identifier.

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.

func (*BaseContentOAuthProvider) RequiredScopes

func (p *BaseContentOAuthProvider) RequiredScopes() []string

RequiredScopes returns the scopes required by this provider.

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.

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.

type BuiltInGroup

type BuiltInGroup struct {
	Name string
	UUID uuid.UUID
}

BuiltInGroup represents a well-known TMI group used as an authorization fixture.

type BuiltInQueryParam

type BuiltInQueryParam = bool

BuiltInQueryParam defines model for BuiltInQueryParam.

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 = []DocumentInput

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 = []RepositoryInput

BulkCreateThreatModelRepositoriesJSONBody defines parameters for BulkCreateThreatModelRepositories.

type BulkCreateThreatModelRepositoriesJSONRequestBody

type BulkCreateThreatModelRepositoriesJSONRequestBody = BulkCreateThreatModelRepositoriesJSONBody

BulkCreateThreatModelRepositoriesJSONRequestBody defines body for BulkCreateThreatModelRepositories for application/json ContentType.

type BulkCreateThreatModelThreatsJSONBody

type BulkCreateThreatModelThreatsJSONBody = []ThreatInput

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 = []AssetBulkUpdateItem

BulkUpsertThreatModelAssetsJSONBody defines parameters for BulkUpsertThreatModelAssets.

type BulkUpsertThreatModelAssetsJSONRequestBody

type BulkUpsertThreatModelAssetsJSONRequestBody = BulkUpsertThreatModelAssetsJSONBody

BulkUpsertThreatModelAssetsJSONRequestBody defines body for BulkUpsertThreatModelAssets for application/json ContentType.

type BulkUpsertThreatModelDocumentsJSONBody

type BulkUpsertThreatModelDocumentsJSONBody = []DocumentBulkUpdateItem

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 = []RepositoryBulkUpdateItem

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

func NewCacheInvalidator

func NewCacheInvalidator(redis *db.RedisDB, cache *CacheService) *CacheInvalidator

NewCacheInvalidator creates a new cache invalidator

func (*CacheInvalidator) BulkInvalidate

func (ci *CacheInvalidator) BulkInvalidate(ctx context.Context, events []InvalidationEvent) error

BulkInvalidate handles bulk cache invalidation for multiple entities

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

func (*CacheInvalidator) InvalidateAllRelatedCaches

func (ci *CacheInvalidator) InvalidateAllRelatedCaches(ctx context.Context, threatModelID string) error

InvalidateAllRelatedCaches performs comprehensive cache invalidation for a threat model

func (*CacheInvalidator) InvalidatePermissionRelatedCaches

func (ci *CacheInvalidator) InvalidatePermissionRelatedCaches(ctx context.Context, threatModelID string) error

InvalidatePermissionRelatedCaches invalidates caches when permissions change

func (*CacheInvalidator) InvalidateSubResourceChange

func (ci *CacheInvalidator) InvalidateSubResourceChange(ctx context.Context, event InvalidationEvent) error

InvalidateSubResourceChange handles cache invalidation when a sub-resource changes

type CacheService

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

CacheService provides caching functionality for sub-resources

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

func (*CacheService) CacheAsset

func (cs *CacheService) CacheAsset(ctx context.Context, asset *Asset) error

CacheAsset caches an asset

func (*CacheService) CacheAuthData

func (cs *CacheService) CacheAuthData(ctx context.Context, threatModelID string, authData AuthorizationData) error

CacheAuthData caches authorization data for a threat model

func (*CacheService) CacheDocument

func (cs *CacheService) CacheDocument(ctx context.Context, document *Document) error

CacheDocument caches a document

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

func (*CacheService) CacheMetadata

func (cs *CacheService) CacheMetadata(ctx context.Context, entityType, entityID string, metadata []Metadata) error

CacheMetadata caches metadata collection for an entity

func (*CacheService) CacheMiddlewareAuth

func (cs *CacheService) CacheMiddlewareAuth(ctx context.Context, threatModelID string, data MiddlewareAuthData) error

CacheMiddlewareAuth caches lightweight auth data for middleware

func (*CacheService) CacheNote

func (cs *CacheService) CacheNote(ctx context.Context, note *Note) error

CacheNote caches a note

func (*CacheService) CacheRepository

func (cs *CacheService) CacheRepository(ctx context.Context, repository *Repository) error

CacheRepository caches a repository code entry

func (*CacheService) CacheThreat

func (cs *CacheService) CacheThreat(ctx context.Context, threat *Threat) error

CacheThreat caches an individual threat with write-through strategy

func (*CacheService) CacheThreatModelResponse

func (cs *CacheService) CacheThreatModelResponse(ctx context.Context, id string, tm *ThreatModel) error

CacheThreatModelResponse caches a full threat model API response

func (*CacheService) GetCachedAsset

func (cs *CacheService) GetCachedAsset(ctx context.Context, assetID string) (*Asset, error)

GetCachedAsset retrieves a cached asset

func (*CacheService) GetCachedAuthData

func (cs *CacheService) GetCachedAuthData(ctx context.Context, threatModelID string) (*AuthorizationData, error)

GetCachedAuthData retrieves cached authorization data

func (*CacheService) GetCachedDocument

func (cs *CacheService) GetCachedDocument(ctx context.Context, documentID string) (*Document, error)

GetCachedDocument retrieves a cached document

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

func (*CacheService) GetCachedMetadata

func (cs *CacheService) GetCachedMetadata(ctx context.Context, entityType, entityID string) ([]Metadata, error)

GetCachedMetadata retrieves cached metadata for an entity

func (*CacheService) GetCachedMiddlewareAuth

func (cs *CacheService) GetCachedMiddlewareAuth(ctx context.Context, threatModelID string) (*MiddlewareAuthData, error)

GetCachedMiddlewareAuth retrieves cached middleware auth data

func (*CacheService) GetCachedNote

func (cs *CacheService) GetCachedNote(ctx context.Context, noteID string) (*Note, error)

GetCachedNote retrieves a cached note

func (*CacheService) GetCachedRepository

func (cs *CacheService) GetCachedRepository(ctx context.Context, repositoryID string) (*Repository, error)

GetCachedRepository retrieves a cached repository code entry

func (*CacheService) GetCachedThreat

func (cs *CacheService) GetCachedThreat(ctx context.Context, threatID string) (*Threat, error)

GetCachedThreat retrieves a cached threat

func (*CacheService) GetCachedThreatModelResponse

func (cs *CacheService) GetCachedThreatModelResponse(ctx context.Context, id string) (*ThreatModel, error)

GetCachedThreatModelResponse retrieves a cached threat model response

func (*CacheService) InvalidateAuthData

func (cs *CacheService) InvalidateAuthData(ctx context.Context, threatModelID string) error

InvalidateAuthData removes authorization data cache

func (*CacheService) InvalidateEntity

func (cs *CacheService) InvalidateEntity(ctx context.Context, entityType, entityID string) error

InvalidateEntity removes an entity from cache

func (*CacheService) InvalidateMetadata

func (cs *CacheService) InvalidateMetadata(ctx context.Context, entityType, entityID string) error

InvalidateMetadata removes metadata cache for an entity

func (*CacheService) InvalidateMiddlewareAuth

func (cs *CacheService) InvalidateMiddlewareAuth(ctx context.Context, threatModelID string) error

InvalidateMiddlewareAuth invalidates middleware auth cache for a threat model

func (*CacheService) InvalidateThreatModelResponse

func (cs *CacheService) InvalidateThreatModelResponse(ctx context.Context, id string) error

InvalidateThreatModelResponse invalidates the response cache for a threat model

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

func NewCacheTestHelper

func NewCacheTestHelper(cache *CacheService, invalidator *CacheInvalidator, redisClient *db.RedisDB) *CacheTestHelper

NewCacheTestHelper creates a new cache test helper

func (*CacheTestHelper) CacheTestDocument

func (h *CacheTestHelper) CacheTestDocument(t *testing.T, document *Document)

CacheTestDocument caches a document for testing

func (*CacheTestHelper) CacheTestRepository

func (h *CacheTestHelper) CacheTestRepository(t *testing.T, repository *Repository)

CacheTestRepository caches a repository for testing

func (*CacheTestHelper) CacheTestThreat

func (h *CacheTestHelper) CacheTestThreat(t *testing.T, threat *Threat)

CacheTestThreat caches a threat for testing

func (*CacheTestHelper) ClearAllTestCache

func (h *CacheTestHelper) ClearAllTestCache(t *testing.T)

ClearAllTestCache clears all test cache data

func (*CacheTestHelper) ClearDocumentCache

func (h *CacheTestHelper) ClearDocumentCache(t *testing.T, documentID string)

ClearDocumentCache clears document cache for testing

func (*CacheTestHelper) ClearRepositoryCache

func (h *CacheTestHelper) ClearRepositoryCache(t *testing.T, repositoryID string)

ClearRepositoryCache clears repository cache for testing

func (*CacheTestHelper) ClearThreatCache

func (h *CacheTestHelper) ClearThreatCache(t *testing.T, threatID string)

ClearThreatCache clears threat cache for testing

func (*CacheTestHelper) GetCacheStats

func (h *CacheTestHelper) GetCacheStats(t *testing.T) map[string]any

GetCacheStats returns cache statistics for testing

func (*CacheTestHelper) SetupTestCache

func (h *CacheTestHelper) SetupTestCache(t *testing.T)

SetupTestCache initializes cache with test data

func (*CacheTestHelper) TestCacheAuthOperations

func (h *CacheTestHelper) TestCacheAuthOperations(t *testing.T, threatModelID string)

TestCacheAuthOperations tests caching operations for authorization data

func (*CacheTestHelper) TestCacheConsistency

func (h *CacheTestHelper) TestCacheConsistency(t *testing.T, threatModelID string)

TestCacheConsistency tests cache consistency across operations

func (*CacheTestHelper) TestCacheDocumentOperations

func (h *CacheTestHelper) TestCacheDocumentOperations(t *testing.T, scenarios []CacheTestScenario)

TestCacheDocumentOperations tests caching operations for documents

func (*CacheTestHelper) TestCacheInvalidationStrategies

func (h *CacheTestHelper) TestCacheInvalidationStrategies(t *testing.T, threatModelID string)

TestCacheInvalidationStrategies tests different invalidation strategies

func (*CacheTestHelper) TestCacheMetadataOperations

func (h *CacheTestHelper) TestCacheMetadataOperations(t *testing.T, entityType, entityID string)

TestCacheMetadataOperations tests caching operations for metadata

func (*CacheTestHelper) TestCacheRepositoryOperations

func (h *CacheTestHelper) TestCacheRepositoryOperations(t *testing.T, scenarios []CacheTestScenario)

TestCacheRepositoryOperations tests caching operations for repositories

func (*CacheTestHelper) TestCacheTTLBehavior

func (h *CacheTestHelper) TestCacheTTLBehavior(t *testing.T, scenarios []CacheTestScenario)

TestCacheTTLBehavior tests TTL behavior for cached items

func (*CacheTestHelper) TestCacheThreatOperations

func (h *CacheTestHelper) TestCacheThreatOperations(t *testing.T, scenarios []CacheTestScenario)

TestCacheThreatOperations tests caching operations for threats

func (*CacheTestHelper) VerifyCacheMetrics

func (h *CacheTestHelper) VerifyCacheMetrics(t *testing.T, expectedHitRatio float64)

VerifyCacheMetrics verifies cache performance metrics

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

func SetupCacheTestScenarios

func SetupCacheTestScenarios() []CacheTestScenario

SetupCacheTestScenarios returns common cache test scenarios

type CacheWarmer

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

CacheWarmer handles proactive cache warming for frequently accessed data

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

func (*CacheWarmer) DisableWarming

func (cw *CacheWarmer) DisableWarming()

DisableWarming disables cache warming

func (*CacheWarmer) EnableWarming

func (cw *CacheWarmer) EnableWarming()

EnableWarming enables cache warming

func (*CacheWarmer) GetWarmingStats

func (cw *CacheWarmer) GetWarmingStats() WarmingStats

GetWarmingStats returns current warming statistics

func (*CacheWarmer) IsWarmingEnabled

func (cw *CacheWarmer) IsWarmingEnabled() bool

IsWarmingEnabled returns whether cache warming is enabled

func (*CacheWarmer) SetWarmingInterval

func (cw *CacheWarmer) SetWarmingInterval(interval time.Duration)

SetWarmingInterval configures the proactive warming interval

func (*CacheWarmer) StartProactiveWarming

func (cw *CacheWarmer) StartProactiveWarming(ctx context.Context) error

StartProactiveWarming starts the proactive cache warming process

func (*CacheWarmer) StopProactiveWarming

func (cw *CacheWarmer) StopProactiveWarming()

StopProactiveWarming stops the proactive cache warming process

func (*CacheWarmer) WarmFrequentlyAccessedData

func (cw *CacheWarmer) WarmFrequentlyAccessedData(ctx context.Context) error

WarmFrequentlyAccessedData warms cache with frequently accessed data

func (*CacheWarmer) WarmOnDemandRequest

func (cw *CacheWarmer) WarmOnDemandRequest(ctx context.Context, request WarmingRequest) error

WarmOnDemandRequest handles on-demand cache warming requests

func (*CacheWarmer) WarmThreatModelData

func (cw *CacheWarmer) WarmThreatModelData(ctx context.Context, threatModelID string) error

WarmThreatModelData warms cache with all data for a specific threat model

type CellData added in v1.19.0

type CellData 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:"-"`
}

CellData Flexible data storage compatible with X6, with reserved metadata namespace

func (CellData) Get added in v1.19.0

func (a CellData) Get(fieldName string) (value interface{}, found bool)

Getter for additional properties for CellData. Returns the specified element and whether it was found

func (CellData) MarshalJSON added in v1.19.0

func (a CellData) MarshalJSON() ([]byte, error)

Override default JSON handling for CellData to handle AdditionalProperties

func (*CellData) Set added in v1.19.0

func (a *CellData) Set(fieldName string, value interface{})

Setter for additional properties for CellData

func (*CellData) UnmarshalJSON added in v1.19.0

func (a *CellData) UnmarshalJSON(b []byte) error

Override default JSON handling for CellData to handle AdditionalProperties

type CellId added in v1.19.0

type CellId = openapi_types.UUID

CellId Unique identifier of the cell (UUID)

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)

func (CellOperation) Validate

func (op CellOperation) Validate() error

type CellOperationProcessor

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

CellOperationProcessor processes cell operations with validation and conflict detection

func NewCellOperationProcessor

func NewCellOperationProcessor(store DiagramStoreInterface) *CellOperationProcessor

NewCellOperationProcessor creates a new cell operation processor

func (*CellOperationProcessor) ProcessCellOperations

func (cop *CellOperationProcessor) ProcessCellOperations(diagramID string, operation CellPatchOperation) (*OperationValidationResult, error)

ProcessCellOperations processes a batch of cell operations with full validation

type CellPatchOperation

type CellPatchOperation struct {
	Type  string          `json:"type"`
	Cells []CellOperation `json:"cells"`
}

CellPatchOperation mirrors REST PATCH operations for cells with batch support

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

func (CellPatchOperation) Validate

func (op CellPatchOperation) Validate() error

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"`
}

func (ChangePresenterMessage) GetMessageType

func (m ChangePresenterMessage) GetMessageType() MessageType

func (ChangePresenterMessage) Validate

func (m ChangePresenterMessage) Validate() error

type ChangePresenterRequest

type ChangePresenterRequest struct {
	MessageType  MessageType `json:"message_type"`
	NewPresenter User        `json:"new_presenter"`
}

ChangePresenterRequest is sent by client to change presenter

func (ChangePresenterRequest) GetMessageType

func (m ChangePresenterRequest) GetMessageType() MessageType

func (ChangePresenterRequest) Validate

func (m ChangePresenterRequest) Validate() error

type ChangePresenterRequestHandler

type ChangePresenterRequestHandler struct{}

ChangePresenterRequestHandler handles change presenter request messages

func (*ChangePresenterRequestHandler) HandleMessage

func (h *ChangePresenterRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*ChangePresenterRequestHandler) MessageType

func (h *ChangePresenterRequestHandler) MessageType() string

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"`

		// TimmyEnabled Whether Timmy (AI chat) is enabled and fully configured on this server
		TimmyEnabled *bool `json:"timmy_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 {
	// AddonId Addon this credential is linked to, if any. Events caused by writes made with this credential's tokens are not delivered to that addon's own webhook subscription. Only set on direct_write credentials.
	AddonId *openapi_types.UUID `json:"addon_id,omitempty"`

	// 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"`

	// DirectWrite When true, tokens minted from this credential may write threat-model sub-resources (notes, threats, diagrams, metadata, ...) that are otherwise reserved for interactive users; the owner's roles still apply. Never true for credentials owned by an administrator.
	DirectWrite *bool `json:"direct_write,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"`
	DirectWrite bool       `json:"direct_write"`
	AddonID     string     `json:"addon_id,omitempty"`
	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)

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

var GlobalClientCredentialQuotaStore ClientCredentialQuotaStore

GlobalClientCredentialQuotaStore is the global singleton for client credential quota

type ClientCredentialResponse

type ClientCredentialResponse struct {
	// AddonId Addon this credential is linked to for self-delivery suppression, if any (see ClientCredentialInfo.addon_id).
	AddonId *openapi_types.UUID `json:"addon_id,omitempty"`

	// 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"`

	// DirectWrite Whether direct_write was enabled for this credential (see ClientCredentialInfo.direct_write).
	DirectWrite *bool `json:"direct_write,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

func NewClientCredentialService

func NewClientCredentialService(authService *auth.Service) *ClientCredentialService

NewClientCredentialService creates a new client credential service

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)

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)

func (*ClientCredentialService) Delete

func (s *ClientCredentialService) Delete(ctx context.Context, credID uuid.UUID, ownerUUID uuid.UUID) error

Delete permanently deletes a client credential

func (*ClientCredentialService) List

List retrieves all client credentials for the specified owner (without secrets)

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

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

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 Users authorized to take part in the session: the threat model owner and each user in its authorization list, each with their session permission, plus any connected user not otherwise listed. This is not the set of currently connected users. Group authorization entries are not expanded. For users who are not currently connected, last_activity is the session last-activity time. For users who are not connected, permissions come from the threat model authorization role (owner and writer map to writer, reader to reader); roles elevated through group membership are not reflected.
	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

func NewValidatorRegistry

func NewValidatorRegistry() *CommonValidatorRegistry

NewValidatorRegistry creates a new validator registry with common validators

func (*CommonValidatorRegistry) Get

Get retrieves a validator by name

func (*CommonValidatorRegistry) GetValidators

func (r *CommonValidatorRegistry) GetValidators(names []string) []ValidatorFunc

GetValidators returns multiple validators by names

func (*CommonValidatorRegistry) Register

func (r *CommonValidatorRegistry) Register(name string, validator ValidatorFunc)

Register adds a validator to the registry

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

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

func (ComponentHealthResult) ToAPIComponentHealth

func (r ComponentHealthResult) ToAPIComponentHealth() *ComponentHealth

ToAPIComponentHealth converts a ComponentHealthResult to the API ComponentHealth type

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.

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.

type ConfigProvider

type ConfigProvider interface {
	GetMigratableSettings() []MigratableSetting
}

ConfigProvider provides access to migratable settings from configuration

type ConfigProviderAdapter

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

ConfigProviderAdapter adapts config.Config to implement the ConfigProvider interface

func NewConfigProviderAdapter

func NewConfigProviderAdapter(cfg *config.Config) *ConfigProviderAdapter

NewConfigProviderAdapter creates a new ConfigProviderAdapter

func (*ConfigProviderAdapter) GetMigratableSettings

func (a *ConfigProviderAdapter) GetMigratableSettings() []MigratableSetting

GetMigratableSettings returns migratable settings from the config

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.

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).

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).

func (*ConfluenceContentOAuthProvider) ExchangeCode

func (p *ConfluenceContentOAuthProvider) ExchangeCode(ctx context.Context, code, pkceVerifier, redirectURI string) (*ContentOAuthTokenResponse, error)

ExchangeCode delegates to 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.

func (*ConfluenceContentOAuthProvider) ID

ID returns the wrapped provider's id (always "confluence" in practice; the registry chooses this implementation by id).

func (*ConfluenceContentOAuthProvider) Refresh

Refresh delegates to 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.

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.

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.

func NewContentFeedbackHandler

func NewContentFeedbackHandler(repo ContentFeedbackRepository, db *gorm.DB) *ContentFeedbackHandler

NewContentFeedbackHandler constructs the handler.

func (*ContentFeedbackHandler) Create

func (h *ContentFeedbackHandler) Create(c *gin.Context)

Create handles POST /threat_models/{threat_model_id}/feedback.

func (*ContentFeedbackHandler) Get

func (h *ContentFeedbackHandler) Get(c *gin.Context)

Get handles GET /threat_models/{threat_model_id}/feedback/{feedback_id}.

func (*ContentFeedbackHandler) List

func (h *ContentFeedbackHandler) List(c *gin.Context)

List handles GET /threat_models/{threat_model_id}/feedback.

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.

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.

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").

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.

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.

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.

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}.

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.

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).

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.

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.

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.

type ContentOAuthProviderRegistry

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

ContentOAuthProviderRegistry is a thread-safe registry mapping provider id to a ContentOAuthProvider instance.

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.

func NewContentOAuthProviderRegistry

func NewContentOAuthProviderRegistry() *ContentOAuthProviderRegistry

NewContentOAuthProviderRegistry creates a new, empty ContentOAuthProviderRegistry.

func (*ContentOAuthProviderRegistry) Get

Get returns the provider with the given id, and whether it was found. It is safe to call concurrently.

func (*ContentOAuthProviderRegistry) IDs

IDs returns a snapshot of the registered provider ids. The order of the returned slice is not guaranteed.

func (*ContentOAuthProviderRegistry) Register

Register adds or replaces the provider in the registry. It is safe to call concurrently.

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.

type ContentOAuthStateStore

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

ContentOAuthStateStore stores short-lived OAuth state nonces in Redis.

func NewContentOAuthStateStore

func NewContentOAuthStateStore(rdb redis.UniversalClient) *ContentOAuthStateStore

NewContentOAuthStateStore creates a new ContentOAuthStateStore backed by the given Redis client.

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.

func (*ContentOAuthStateStore) Put

Put stores the payload under a freshly generated nonce and returns the nonce. The entry expires after ttl.

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.

func (*ContentOAuthTokenResponse) ExpiresAt

func (r *ContentOAuthTokenResponse) ExpiresAt() *time.Time

ExpiresAt returns the computed absolute expiry time, or nil if ExpiresIn is zero.

type ContentPipeline

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

ContentPipeline orchestrates Source -> Extractor for URI-based content.

func NewContentPipeline

func NewContentPipeline(
	sources *ContentSourceRegistry,
	extractors *ContentExtractorRegistry,
	matcher *URLPatternMatcher,
) *ContentPipeline

NewContentPipeline creates a new pipeline.

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.

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.

func (*ContentPipeline) Extract

func (p *ContentPipeline) Extract(ctx context.Context, uri string) (ExtractedContent, error)

Extract fetches bytes from the appropriate source and extracts text.

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.

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.

func (*ContentPipeline) Matcher

func (p *ContentPipeline) Matcher() *URLPatternMatcher

Matcher returns the pipeline's URL pattern matcher.

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.

func (*ContentPipeline) Sources

func (p *ContentPipeline) Sources() *ContentSourceRegistry

Sources returns the pipeline's source registry.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

type ContentSourceRegistry

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

ContentSourceRegistry manages content sources in priority order.

func NewContentSourceRegistry

func NewContentSourceRegistry() *ContentSourceRegistry

NewContentSourceRegistry creates a new registry.

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.

func (*ContentSourceRegistry) FindSourceByName

func (r *ContentSourceRegistry) FindSourceByName(name string) (ContentSource, bool)

FindSourceByName returns the source with the given name, if registered.

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.

func (*ContentSourceRegistry) Names

func (r *ContentSourceRegistry) Names() []string

Names returns the names of all registered sources.

func (*ContentSourceRegistry) Register

func (r *ContentSourceRegistry) Register(source ContentSource)

Register adds a source to the registry (tried in registration order).

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.

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.

func NewContentTokenEncryptor

func NewContentTokenEncryptor(hexKey string) (*ContentTokenEncryptor, error)

NewContentTokenEncryptor constructs an encryptor from a hex-encoded 32-byte key.

func (*ContentTokenEncryptor) Decrypt

func (e *ContentTokenEncryptor) Decrypt(nonceAndCiphertext []byte) ([]byte, error)

Decrypt parses nonce || ciphertext and returns the plaintext.

func (*ContentTokenEncryptor) Encrypt

func (e *ContentTokenEncryptor) Encrypt(plaintext []byte) ([]byte, error)

Encrypt returns nonce || ciphertext.

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).

func NewContentTokenLinkedChecker

func NewContentTokenLinkedChecker(tokens ContentTokenRepository) *ContentTokenLinkedChecker

NewContentTokenLinkedChecker constructs a LinkedProviderChecker backed by the given ContentTokenRepository.

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.

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.

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

func NewContextBuilder

func NewContextBuilder() *ContextBuilder

NewContextBuilder creates a new ContextBuilder

func (*ContextBuilder) BuildFullContext

func (cb *ContextBuilder) BuildFullContext(basePrompt, tier1, tier2 string) string

BuildFullContext assembles the complete system prompt with context

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.

func (*ContextBuilder) BuildTier2Context

func (cb *ContextBuilder) BuildTier2Context(index *VectorIndex, queryVector []float32, topK int) string

BuildTier2Context performs vector search and formats results with source attribution

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.

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 {
	// AddonId Optional addon to link this credential to (only valid with direct_write=true; 400 otherwise, or if the addon does not exist). Events caused by writes made with tokens from this credential are not delivered to the linked addon's own webhook subscription, matching the suppression applied to delegation-token write-backs. Not a foreign key: deleting the addon leaves the credential intact and simply stops the suppression.
	AddonId *openapi_types.UUID `json:"addon_id,omitempty"`

	// Description Optional description of the credential's purpose
	Description *string `json:"description,omitempty"`

	// DirectWrite Opt in to direct writes for this automation account: tokens from this credential may modify threat-model sub-resources, authorized by the automation user's roles. Omitting the field is the same as false. Rejected with 400 when the automation user is a member of the Administrators group.
	DirectWrite *bool `json:"direct_write,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 {
	// AddonId Optional addon to link this credential to (only valid with direct_write=true; 400 otherwise, or if the addon does not exist). Events caused by writes made with tokens from this credential are not delivered to the linked addon's own webhook subscription, matching the suppression applied to delegation-token write-backs. Not a foreign key: deleting the addon leaves the credential intact and simply stops the suppression.
	AddonId *openapi_types.UUID `json:"addon_id,omitempty"`

	// DirectWrite Opt in to direct writes for the initial client credential: tokens from it may modify threat-model sub-resources, authorized by the automation user's roles. Omitting the field is the same as false.
	DirectWrite *bool `json:"direct_write,omitempty"`

	// 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"`
	DirectWrite bool       `json:"direct_write,omitempty"`
	AddonID     string     `json:"addon_id,omitempty"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
}

CreateClientCredentialRequest contains parameters for creating a new client credential

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"`
	DirectWrite  bool       `json:"direct_write"`
	AddonID      string     `json:"addon_id,omitempty"`
	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

type CreateContentFeedbackJSONRequestBody

type CreateContentFeedbackJSONRequestBody = ContentFeedbackInput

CreateContentFeedbackJSONRequestBody defines body for CreateContentFeedback for application/json ContentType.

type CreateCurrentUserClientCredentialJSONBody

type CreateCurrentUserClientCredentialJSONBody struct {
	// AddonId Optional addon to link this credential to (only valid with direct_write=true; 400 otherwise, or if the addon does not exist). Events caused by writes made with tokens from this credential are not delivered to the linked addon's own webhook subscription, matching the suppression applied to delegation-token write-backs. Not a foreign key: deleting the addon leaves the credential intact and simply stops the suppression.
	AddonId *openapi_types.UUID `json:"addon_id,omitempty"`

	// Description Optional description of the credential's purpose
	Description *string `json:"description,omitempty"`

	// DirectWrite Opt in to direct writes: tokens from this credential may modify threat-model sub-resources, authorized by your normal roles. Omitting the field is the same as false. Rejected with 400 when the owner is a member of the Administrators group.
	DirectWrite *bool `json:"direct_write,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

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

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

func (*DBWebhookQuota) SetCreatedAt

func (w *DBWebhookQuota) SetCreatedAt(t time.Time)

SetCreatedAt implements WithTimestamps for DBWebhookQuota

func (*DBWebhookQuota) SetModifiedAt

func (w *DBWebhookQuota) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps for DBWebhookQuota

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, inactive, 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

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).

func (*DBWebhookSubscription) SetCreatedAt

func (w *DBWebhookSubscription) SetCreatedAt(t time.Time)

SetCreatedAt implements WithTimestamps

func (*DBWebhookSubscription) SetModifiedAt

func (w *DBWebhookSubscription) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps

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.

func NewDLQProducer

func NewDLQProducer(conn *worker.Conn) *DLQProducer

NewDLQProducer constructs a DLQProducer bound to the monolith's NATS conn.

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.

func (*DLQProducer) Stop

func (p *DLQProducer) Stop()

Stop cancels the producer's context. Safe to call when Start was never run.

type DatabaseClientCredentialQuotaStore

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

DatabaseClientCredentialQuotaStore implements ClientCredentialQuotaStore using auth service and global quota store

func NewDatabaseClientCredentialQuotaStore

func NewDatabaseClientCredentialQuotaStore(authService *auth.Service, defaultQuota int, globalStore UserAPIQuotaStoreInterface) *DatabaseClientCredentialQuotaStore

NewDatabaseClientCredentialQuotaStore creates a new client credential quota store

func (*DatabaseClientCredentialQuotaStore) CheckClientCredentialQuota

func (s *DatabaseClientCredentialQuotaStore) CheckClientCredentialQuota(ctx context.Context, userUUID uuid.UUID) error

CheckClientCredentialQuota verifies if a user can create a new credential

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

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

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.

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.

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.

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).

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/...

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.

func (*DelegatedConfluenceSource) Name

Name returns the provider id "confluence".

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).

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.

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.

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).

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.

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.

func (*DelegatedGoogleWorkspaceSource) Name

Name returns the provider id "google_workspace".

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.

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.

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.

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).

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.

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.

func (*DelegatedMicrosoftSource) Name

func (s *DelegatedMicrosoftSource) Name() string

Name returns the provider id "microsoft".

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.

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.

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).

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.

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.

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.

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

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 the diagram 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 Data Flow Diagram with cells, edges, and visual styling for JointJS rendering

func (*DfdDiagram) SetCreatedAt

func (d *DfdDiagram) SetCreatedAt(t time.Time)

SetCreatedAt implements WithTimestamps interface for DfdDiagram

func (*DfdDiagram) SetModifiedAt

func (d *DfdDiagram) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps interface for DfdDiagram

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 the diagram 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 Input schema for creating or updating a Data Flow Diagram

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)

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)

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 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

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

func (DiagramOperationEvent) GetMessageType

func (m DiagramOperationEvent) GetMessageType() MessageType

func (DiagramOperationEvent) Validate

func (m DiagramOperationEvent) Validate() error

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

func (DiagramOperationMessage) GetMessageType

func (m DiagramOperationMessage) GetMessageType() MessageType

func (DiagramOperationMessage) Validate

func (m DiagramOperationMessage) Validate() error

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

func (DiagramOperationRequest) GetMessageType

func (m DiagramOperationRequest) GetMessageType() MessageType

func (DiagramOperationRequest) Validate

func (m DiagramOperationRequest) Validate() error

type DiagramOperationRequestHandler

type DiagramOperationRequestHandler struct{}

DiagramOperationRequestHandler handles diagram operation request messages

func (*DiagramOperationRequestHandler) HandleMessage

func (h *DiagramOperationRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

HandleMessage processes diagram operation request messages

func (*DiagramOperationRequestHandler) MessageType

func (h *DiagramOperationRequestHandler) MessageType() string

MessageType returns the message type this handler processes

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

func (*DiagramSession) GetHistoryEntry

func (s *DiagramSession) GetHistoryEntry(sequenceNumber uint64) (*HistoryEntry, bool)

GetHistoryEntry retrieves a specific history entry by sequence number

func (*DiagramSession) GetHistoryStats

func (s *DiagramSession) GetHistoryStats() map[string]any

GetHistoryStats returns statistics about the operation history

func (*DiagramSession) GetRecentOperations

func (s *DiagramSession) GetRecentOperations(count int) []*HistoryEntry

GetRecentOperations returns the most recent N operations

func (*DiagramSession) ProcessMessage

func (s *DiagramSession) ProcessMessage(client *WebSocketClient, message []byte)

ProcessMessage handles enhanced message types for collaborative editing

func (*DiagramSession) Run

func (s *DiagramSession) Run()

Run processes messages for a diagram session

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

func (DiagramStateMessage) GetMessageType

func (m DiagramStateMessage) GetMessageType() MessageType

func (DiagramStateMessage) Validate

func (m DiagramStateMessage) Validate() error

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
}
var DiagramStore DiagramStoreInterface

type DirectTextProvider

type DirectTextProvider struct{}

DirectTextProvider extracts text from DB-resident entities (notes, assets, threats, repositories)

func NewDirectTextProvider

func NewDirectTextProvider() *DirectTextProvider

NewDirectTextProvider creates a new DirectTextProvider

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

func (*DirectTextProvider) Extract

Extract fetches and returns plain text content from the entity

func (*DirectTextProvider) Name

func (p *DirectTextProvider) Name() string

Name returns the provider name for logging

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

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 DocumentBulkUpdateItem

type DocumentBulkUpdateItem struct {
	// Description Description of document purpose or content
	Description *string `json:"description,omitempty"`

	// Id Unique identifier of the document 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"`

	// 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"`
}

DocumentBulkUpdateItem defines model for DocumentBulkUpdateItem.

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

var GlobalDocumentRepository DocumentRepository

type DocumentSubResourceHandler

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

DocumentSubResourceHandler provides handlers for document sub-resource operations

func NewDocumentSubResourceHandler

func NewDocumentSubResourceHandler(documentStore DocumentRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *DocumentSubResourceHandler

NewDocumentSubResourceHandler creates a new document sub-resource handler

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

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

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

func (*DocumentSubResourceHandler) DeleteDocument

func (h *DocumentSubResourceHandler) DeleteDocument(c *gin.Context)

DeleteDocument deletes a document DELETE /threat_models/{threat_model_id}/documents/{document_id}

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}

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

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}

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.

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).

func (*DocumentSubResourceHandler) SetContentPipeline

func (h *DocumentSubResourceHandler) SetContentPipeline(p *ContentPipeline)

SetContentPipeline sets the content pipeline for content source detection and access validation

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.

func (*DocumentSubResourceHandler) SetDocumentURIValidator

func (h *DocumentSubResourceHandler) SetDocumentURIValidator(v *URIValidator)

SetDocumentURIValidator sets the URI validator for document uri fields

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.

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.

func (*DocumentSubResourceHandler) UpdateDocument

func (h *DocumentSubResourceHandler) UpdateDocument(c *gin.Context)

UpdateDocument updates an existing document PUT /threat_models/{threat_model_id}/documents/{document_id}

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 *CellData `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 CellId `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 Diagram edge representing a data flow connection between nodes

Fully compatible with X6 Edge objects and supports X6 routing algorithms (manhattan, orth, one_side, metro, er), connector styles (normal, rounded, smooth, jumpover), custom markup, tools, and convenience properties (label, style) for easier integration.

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 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.

func NewEmbeddingCleaner

func NewEmbeddingCleaner(
	embeddingStore TimmyEmbeddingStore,
	db *gorm.DB,
	interval time.Duration,
	activeIdleDays int,
	closedIdleDays int,
) *EmbeddingCleaner

NewEmbeddingCleaner creates a new embedding cleaner.

func (*EmbeddingCleaner) CleanOnce

func (ec *EmbeddingCleaner) CleanOnce() int64

CleanOnce runs a single cleanup cycle. Returns total embeddings deleted.

func (*EmbeddingCleaner) Start

func (ec *EmbeddingCleaner) Start()

Start begins the background cleanup loop.

func (*EmbeddingCleaner) Stop

func (ec *EmbeddingCleaner) Stop()

Stop signals the cleaner to stop.

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

type EmbeddingSourceRegistry

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

EmbeddingSourceRegistry manages embedding sources in priority order

func NewEmbeddingSourceRegistry

func NewEmbeddingSourceRegistry() *EmbeddingSourceRegistry

NewEmbeddingSourceRegistry creates a new registry

func (*EmbeddingSourceRegistry) Extract

Extract finds the first provider that can handle the entity and extracts its content

func (*EmbeddingSourceRegistry) Register

func (r *EmbeddingSourceRegistry) Register(provider EmbeddingSource)

Register adds a provider to the registry (providers are tried in registration order)

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)

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).

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).

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

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.

func (*ErrEmbeddingModelMismatch) Error

func (e *ErrEmbeddingModelMismatch) Error() string

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 Machine-readable REST error code. One of: invalid_input (400, a body, field, header or query value fails validation); invalid_id (400, a path or query identifier is malformed); invalid_patch (400, a JSON Patch document is malformed or cannot be applied); unauthorized (401, missing, expired or invalid credentials); insufficient_user_authentication (401, step-up authentication required, RFC 9470); forbidden (403, authenticated but not permitted); not_found (404, resource does not exist or is hidden by authorization); method_not_allowed (405); not_acceptable (406); conflict (409, duplicate, in use, or wrong lifecycle state); gone (410, permanently removed); version_mismatch (409, If-Match does not match the current version); payload_too_large (413); unsupported_media_type (415); unprocessable_entity (422, well-formed request that cannot be processed in the current state); if_match_required (428, If-Match header missing); rate_limit_exceeded (429, transient limit, honor Retry-After); quota_exceeded (403 or 429, hard cap reached, retrying does not help); server_error (500); not_implemented (501); service_unavailable (503, a dependency is unavailable, retry later); feature_not_available (404) and content_token_provider_not_configured (422) are legacy domain codes kept at top level because clients branch on them; they are also present in details.code and will move to details.code only in a future breaking change. A domain-specific reason a client can act on is in details.code.
	Error ErrorError `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

type ErrorError added in v1.21.0

type ErrorError string

ErrorError Machine-readable REST error code. One of: invalid_input (400, a body, field, header or query value fails validation); invalid_id (400, a path or query identifier is malformed); invalid_patch (400, a JSON Patch document is malformed or cannot be applied); unauthorized (401, missing, expired or invalid credentials); insufficient_user_authentication (401, step-up authentication required, RFC 9470); forbidden (403, authenticated but not permitted); not_found (404, resource does not exist or is hidden by authorization); method_not_allowed (405); not_acceptable (406); conflict (409, duplicate, in use, or wrong lifecycle state); gone (410, permanently removed); version_mismatch (409, If-Match does not match the current version); payload_too_large (413); unsupported_media_type (415); unprocessable_entity (422, well-formed request that cannot be processed in the current state); if_match_required (428, If-Match header missing); rate_limit_exceeded (429, transient limit, honor Retry-After); quota_exceeded (403 or 429, hard cap reached, retrying does not help); server_error (500); not_implemented (501); service_unavailable (503, a dependency is unavailable, retry later); feature_not_available (404) and content_token_provider_not_configured (422) are legacy domain codes kept at top level because clients branch on them; they are also present in details.code and will move to details.code only in a future breaking change. A domain-specific reason a client can act on is in details.code.

const (
	ErrorErrorConflict                          ErrorError = "conflict"
	ErrorErrorContentTokenProviderNotConfigured ErrorError = "content_token_provider_not_configured"
	ErrorErrorFeatureNotAvailable               ErrorError = "feature_not_available"
	ErrorErrorForbidden                         ErrorError = "forbidden"
	ErrorErrorGone                              ErrorError = "gone"
	ErrorErrorIfMatchRequired                   ErrorError = "if_match_required"
	ErrorErrorInsufficientUserAuthentication    ErrorError = "insufficient_user_authentication"
	ErrorErrorInvalidId                         ErrorError = "invalid_id"
	ErrorErrorInvalidInput                      ErrorError = "invalid_input"
	ErrorErrorInvalidPatch                      ErrorError = "invalid_patch"
	ErrorErrorMethodNotAllowed                  ErrorError = "method_not_allowed"
	ErrorErrorNotAcceptable                     ErrorError = "not_acceptable"
	ErrorErrorNotFound                          ErrorError = "not_found"
	ErrorErrorNotImplemented                    ErrorError = "not_implemented"
	ErrorErrorPayloadTooLarge                   ErrorError = "payload_too_large"
	ErrorErrorQuotaExceeded                     ErrorError = "quota_exceeded"
	ErrorErrorRateLimitExceeded                 ErrorError = "rate_limit_exceeded"
	ErrorErrorServerError                       ErrorError = "server_error"
	ErrorErrorServiceUnavailable                ErrorError = "service_unavailable"
	ErrorErrorUnauthorized                      ErrorError = "unauthorized"
	ErrorErrorUnprocessableEntity               ErrorError = "unprocessable_entity"
	ErrorErrorUnsupportedMediaType              ErrorError = "unsupported_media_type"
	ErrorErrorVersionMismatch                   ErrorError = "version_mismatch"
)

Defines values for ErrorError.

func (ErrorError) Valid added in v1.21.0

func (e ErrorError) Valid() bool

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

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

func (ErrorMessage) GetMessageType

func (m ErrorMessage) GetMessageType() MessageType

func (ErrorMessage) Validate

func (m ErrorMessage) Validate() error

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

var GlobalEventEmitter *EventEmitter

Global event emitter instance

func NewEventEmitter

func NewEventEmitter(redisClient *redis.Client, streamKey string) *EventEmitter

NewEventEmitter creates a new event emitter

func (*EventEmitter) EmitEvent

func (e *EventEmitter) EmitEvent(ctx context.Context, payload EventPayload) error

EmitEvent emits an event to Redis Stream with deduplication

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"`
	// SourceAddonID is set when the request that caused the event acted under
	// an addon delegation token (#876). The webhook consumer uses it to skip
	// delivering the event back to that addon's own subscription.
	SourceAddonID string `json:"source_addon_id,omitempty"`
}

EventPayload represents the structure of an event emitted to Redis

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). maxLength is deliberately generous: Microsoft Entra v2.0 codes routinely exceed 700 characters and can pass 2000 with additional scopes/claims. A 512 limit silently broke Microsoft sign-in with a 400 from request validation before the handler ran (Google codes are ~100 chars, so only Microsoft was affected). Do not tighten without checking real Entra code lengths.
	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 (
	Data           ExtendedAssetType = "data"
	Hardware       ExtendedAssetType = "hardware"
	Infrastructure ExtendedAssetType = "infrastructure"
	Personnel      ExtendedAssetType = "personnel"
	Service        ExtendedAssetType = "service"
	Software       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.

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.

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.

func NewExtractionJobStore

func NewExtractionJobStore(db *gorm.DB) *ExtractionJobStore

NewExtractionJobStore constructs the store.

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).

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.

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.

type ExtractionPublisher

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

ExtractionPublisher submits 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.

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.

type ExtractionRequest

type ExtractionRequest struct {
	DocumentID  string
	ContentType string
	Bytes       []byte
}

ExtractionRequest is one document's extraction submission.

type FieldErrorRegistry

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

FieldErrorRegistry provides contextual error messages for prohibited fields

func (*FieldErrorRegistry) GetMessage

func (r *FieldErrorRegistry) GetMessage(field, operation string) string

GetFieldErrorMessage returns a contextual error message for a prohibited field

type FilterOperator

type FilterOperator int

FilterOperator represents the type of filter operation to apply.

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.

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)

func (*GenericMetadataHandler) BulkCreate

func (h *GenericMetadataHandler) BulkCreate(c *gin.Context)

BulkCreate creates multiple metadata entries in a single request.

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.

func (*GenericMetadataHandler) BulkUpsert

func (h *GenericMetadataHandler) BulkUpsert(c *gin.Context)

BulkUpsert updates or creates multiple metadata entries in a single request.

func (*GenericMetadataHandler) Create

func (h *GenericMetadataHandler) Create(c *gin.Context)

Create creates a new metadata entry.

func (*GenericMetadataHandler) Delete

func (h *GenericMetadataHandler) Delete(c *gin.Context)

Delete deletes a metadata entry.

func (*GenericMetadataHandler) GetByKey

func (h *GenericMetadataHandler) GetByKey(c *gin.Context)

GetByKey retrieves a specific metadata entry by key.

func (*GenericMetadataHandler) List

func (h *GenericMetadataHandler) List(c *gin.Context)

List retrieves all metadata for an entity.

func (*GenericMetadataHandler) Update

func (h *GenericMetadataHandler) Update(c *gin.Context)

Update updates an existing metadata entry.

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. If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp. If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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. Must be less than `score_lt` and `score_le` when supplied (equal is also rejected when either bound is exclusive); an empty range is rejected with 400 `invalid_input`.
	ScoreGt *ScoreGtQueryParam `form:"score_gt,omitempty" json:"score_gt,omitempty"`

	// ScoreLt Filter threats with score less than this value. Must be greater than `score_gt` and `score_ge` when supplied; an empty range is rejected with 400 `invalid_input`.
	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. Must not be greater than `score_le` and must be less than `score_lt` when supplied; an empty range is rejected with 400 `invalid_input`.
	ScoreGe *ScoreGeQueryParam `form:"score_ge,omitempty" json:"score_ge,omitempty"`

	// ScoreLe Filter threats with score less than or equal to this value. Must be greater than `score_gt` and not less than `score_ge` when supplied; an empty range is rejected with 400 `invalid_input`.
	ScoreLe *ScoreLeQueryParam `form:"score_le,omitempty" json:"score_le,omitempty"`

	// CreatedAfter Filter results created after this timestamp (ISO 8601). If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601). If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601). If `modified_before` is also supplied and the resulting range is empty (this value is later than `modified_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601). If `modified_after` is also supplied and the resulting range is empty (this value is later than `modified_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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.

func NewGoogleDriveSource

func NewGoogleDriveSource(credentialsFile string, serviceAccountEmail string) (*GoogleDriveSource, error)

NewGoogleDriveSource creates a new GoogleDriveSource from a credentials JSON 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.

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.

func (*GoogleDriveSource) Name

func (s *GoogleDriveSource) Name() string

Name returns the source name.

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.

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.

type GormAddonInvocationQuotaStore

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

GormAddonInvocationQuotaStore implements AddonInvocationQuotaStore using GORM

func NewGormAddonInvocationQuotaStore

func NewGormAddonInvocationQuotaStore(db *gorm.DB) *GormAddonInvocationQuotaStore

NewGormAddonInvocationQuotaStore creates a new GORM-backed quota store

func (*GormAddonInvocationQuotaStore) Count

Count returns the total number of addon invocation quotas

func (*GormAddonInvocationQuotaStore) Delete

func (s *GormAddonInvocationQuotaStore) Delete(ctx context.Context, ownerID uuid.UUID) error

Delete removes quota for a user (reverts to defaults)

func (*GormAddonInvocationQuotaStore) Get

Get retrieves quota for a user, returns error if not found

func (*GormAddonInvocationQuotaStore) GetOrDefault

GetOrDefault retrieves quota for a user, or returns defaults if not set

func (*GormAddonInvocationQuotaStore) List

func (s *GormAddonInvocationQuotaStore) List(ctx context.Context, offset, limit int) ([]*AddonInvocationQuota, error)

List retrieves all addon invocation quotas with pagination

func (*GormAddonInvocationQuotaStore) Set

Set creates or updates quota for a user using GORM's OnConflict clause, then reads the row back so the returned timestamps reflect what is actually stored rather than a client-side stamp (#706)

type GormAddonStore

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

GormAddonStore implements AddonStore using GORM

func NewGormAddonStore

func NewGormAddonStore(db *gorm.DB) *GormAddonStore

NewGormAddonStore creates a new GORM-backed add-on store

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

func (*GormAddonStore) Create

func (s *GormAddonStore) Create(ctx context.Context, addon *Addon) error

Create creates a new add-on

func (*GormAddonStore) Delete

func (s *GormAddonStore) Delete(ctx context.Context, id uuid.UUID) error

Delete removes an add-on by ID

func (*GormAddonStore) DeleteByWebhookID

func (s *GormAddonStore) DeleteByWebhookID(ctx context.Context, webhookID uuid.UUID) (int, error)

DeleteByWebhookID deletes all add-ons associated with a webhook

func (*GormAddonStore) Get

func (s *GormAddonStore) Get(ctx context.Context, id uuid.UUID) (*Addon, error)

Get retrieves an add-on by ID

func (*GormAddonStore) GetByWebhookID

func (s *GormAddonStore) GetByWebhookID(ctx context.Context, webhookID uuid.UUID) ([]Addon, error)

GetByWebhookID retrieves all add-ons associated with a webhook

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

func (*GormAddonStore) Update

func (s *GormAddonStore) Update(ctx context.Context, addon *Addon) error

Update writes the mutable fields of an existing add-on

type GormAssetRepository

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

GormAssetRepository implements AssetRepository with GORM for database persistence and Redis caching

func NewGormAssetRepository

func NewGormAssetRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormAssetRepository

NewGormAssetRepository creates a new GORM-backed asset repository with caching

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

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

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

func (*GormAssetRepository) Delete

func (s *GormAssetRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes an asset by setting deleted_at

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

func (*GormAssetRepository) GetIncludingDeleted

func (s *GormAssetRepository) GetIncludingDeleted(ctx context.Context, id string) (*Asset, error)

func (*GormAssetRepository) HardDelete

func (s *GormAssetRepository) HardDelete(ctx context.Context, id string) error

func (*GormAssetRepository) InvalidateCache

func (s *GormAssetRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache invalidates the cache for a specific asset

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

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

func (*GormAssetRepository) PatchWithVersion

func (s *GormAssetRepository) PatchWithVersion(ctx context.Context, id string, operations []PatchOperation, expectedVersion int) (*Asset, int, error)

PatchWithVersion applies JSON patch operations to an asset guarded by a same-transaction optimistic-lock CAS (#594).

func (*GormAssetRepository) Restore

func (s *GormAssetRepository) Restore(ctx context.Context, id string) error

func (*GormAssetRepository) SoftDelete

func (s *GormAssetRepository) SoftDelete(ctx context.Context, id string) error

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

func (*GormAssetRepository) UpdateWithVersion

func (s *GormAssetRepository) UpdateWithVersion(ctx context.Context, asset *Asset, threatModelID string, expectedVersion int) (int, error)

UpdateWithVersion updates an asset guarded by a same-transaction optimistic-lock CAS (#594).

func (*GormAssetRepository) WarmCache

func (s *GormAssetRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache pre-loads assets for a threat model into the cache

type GormAuditService

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

GormAuditService implements AuditServiceInterface using GORM.

func NewGormAuditService

func NewGormAuditService(db *gorm.DB) *GormAuditService

NewGormAuditService creates a new GormAuditService with configuration from environment.

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.

func (*GormAuditService) GetAuditEntry

func (s *GormAuditService) GetAuditEntry(ctx context.Context, entryID string) (*AuditEntryResponse, error)

GetAuditEntry retrieves a single audit entry by ID.

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.

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.

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).

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).

func (*GormAuditService) PruneAuditEntries

func (s *GormAuditService) PruneAuditEntries(ctx context.Context) (int, error)

PruneAuditEntries removes audit entries older than the configured retention period.

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.

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.

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.

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.

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.

type GormContentFeedbackRepository

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

GormContentFeedbackRepository implements ContentFeedbackRepository with GORM.

func NewGormContentFeedbackRepository

func NewGormContentFeedbackRepository(db *gorm.DB) *GormContentFeedbackRepository

NewGormContentFeedbackRepository constructs a repository.

func (*GormContentFeedbackRepository) Count

Count returns the row count for a threat model and filter.

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).

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.

func (*GormContentFeedbackRepository) Get

Get returns a feedback row by ID, or NotFound if absent.

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.

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.

func NewGormContentTokenRepository

func NewGormContentTokenRepository(db *gorm.DB, enc *ContentTokenEncryptor) *GormContentTokenRepository

NewGormContentTokenRepository creates a new GORM-backed content-token repository.

func (*GormContentTokenRepository) Delete

Delete removes the token with the given ID.

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.

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.

func (*GormContentTokenRepository) ListByUser

func (r *GormContentTokenRepository) ListByUser(ctx context.Context, userID string) ([]ContentToken, error)

ListByUser returns all tokens for the given user ID.

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.

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.

func (*GormContentTokenRepository) Upsert

Upsert creates or updates the token for the (UserID, ProviderID) pair using ON CONFLICT DO UPDATE so the operation is idempotent.

type GormDiagramStore

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

GormDiagramStore handles diagram database operations using GORM

func NewGormDiagramStore

func NewGormDiagramStore(database *gorm.DB) *GormDiagramStore

NewGormDiagramStore creates a new diagram GORM store

func (*GormDiagramStore) Count

func (s *GormDiagramStore) Count() int

Count returns the total number of diagrams using GORM

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)

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

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.

func (*GormDiagramStore) Get

func (s *GormDiagramStore) Get(id string) (DfdDiagram, error)

Get retrieves a diagram by ID using GORM

func (*GormDiagramStore) GetBatch

func (s *GormDiagramStore) GetBatch(ids []string) ([]DfdDiagram, error)

GetBatch retrieves multiple diagrams by ID in a single query.

func (*GormDiagramStore) GetIncludingDeleted

func (s *GormDiagramStore) GetIncludingDeleted(id string) (DfdDiagram, error)

GetIncludingDeleted retrieves a diagram by ID without filtering on deleted_at

func (*GormDiagramStore) GetThreatModelID

func (s *GormDiagramStore) GetThreatModelID(diagramID string) (string, error)

GetThreatModelID returns the threat model ID for a given diagram

func (*GormDiagramStore) HardDelete

func (s *GormDiagramStore) HardDelete(id string) error

HardDelete permanently removes a diagram (original Delete behavior with FK cleanup)

func (*GormDiagramStore) List

func (s *GormDiagramStore) List(offset, limit int, filter func(DfdDiagram) bool) []DfdDiagram

List returns all diagrams (not used in current implementation)

func (*GormDiagramStore) Restore

func (s *GormDiagramStore) Restore(id string) error

Restore clears deleted_at on a diagram

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

func (*GormDiagramStore) Update

func (s *GormDiagramStore) Update(ctx context.Context, id string, item DfdDiagram) error

Update modifies an existing diagram using GORM

func (*GormDiagramStore) UpdateWithVersion

func (s *GormDiagramStore) UpdateWithVersion(ctx context.Context, id string, item DfdDiagram, expectedVersion int) (int, error)

UpdateWithVersion updates a diagram guarded by a same-transaction optimistic-lock CAS (#594).

type GormDocumentRepository

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

GormDocumentRepository implements DocumentStore using GORM

func NewGormDocumentRepository

func NewGormDocumentRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormDocumentRepository

NewGormDocumentRepository creates a new GORM-backed document store with optional caching

func (*GormDocumentRepository) BulkCreate

func (s *GormDocumentRepository) BulkCreate(ctx context.Context, documents []Document, threatModelID string) error

BulkCreate creates multiple documents in a single transaction

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.

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

func (*GormDocumentRepository) Create

func (s *GormDocumentRepository) Create(ctx context.Context, document *Document, threatModelID string) error

Create creates a new document

func (*GormDocumentRepository) Delete

func (s *GormDocumentRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes a document by setting deleted_at

func (*GormDocumentRepository) Get

Get retrieves a document by ID

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.

func (*GormDocumentRepository) GetIncludingDeleted

func (s *GormDocumentRepository) GetIncludingDeleted(ctx context.Context, id string) (*Document, error)

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.

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.

func (*GormDocumentRepository) HardDelete

func (s *GormDocumentRepository) HardDelete(ctx context.Context, id string) error

func (*GormDocumentRepository) InvalidateCache

func (s *GormDocumentRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes document-related cache entries

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

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.

func (*GormDocumentRepository) Patch

func (s *GormDocumentRepository) Patch(ctx context.Context, id string, operations []PatchOperation) (*Document, error)

Patch applies JSON patch operations to a document

func (*GormDocumentRepository) PatchWithVersion

func (s *GormDocumentRepository) PatchWithVersion(ctx context.Context, id string, operations []PatchOperation, expectedVersion int) (*Document, int, error)

PatchWithVersion applies JSON patch operations to a document guarded by a same-transaction optimistic-lock CAS (#594).

func (*GormDocumentRepository) Restore

func (s *GormDocumentRepository) Restore(ctx context.Context, id string) error

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.

func (*GormDocumentRepository) SoftDelete

func (s *GormDocumentRepository) SoftDelete(ctx context.Context, id string) error

func (*GormDocumentRepository) Update

func (s *GormDocumentRepository) Update(ctx context.Context, document *Document, threatModelID string) error

Update updates an existing document

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.

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.

func (*GormDocumentRepository) UpdateWithVersion

func (s *GormDocumentRepository) UpdateWithVersion(ctx context.Context, document *Document, threatModelID string, expectedVersion int) (int, error)

UpdateWithVersion updates a document guarded by a same-transaction optimistic-lock CAS (#594).

func (*GormDocumentRepository) WarmCache

func (s *GormDocumentRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads documents for a threat model into cache

type GormGroupMemberRepository

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

GormGroupMemberRepository implements GroupMemberRepository using GORM

func NewGormGroupMemberRepository

func NewGormGroupMemberRepository(db *gorm.DB) *GormGroupMemberRepository

NewGormGroupMemberRepository creates a new GORM-backed group member repository

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)

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

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

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).

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)

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).

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

func (*GormGroupMemberRepository) ListMembers

ListMembers returns all members of a group with pagination

func (*GormGroupMemberRepository) RemoveGroupMember

func (r *GormGroupMemberRepository) RemoveGroupMember(ctx context.Context, groupInternalUUID, memberGroupInternalUUID uuid.UUID) error

RemoveGroupMember removes a group from membership in another group

func (*GormGroupMemberRepository) RemoveMember

func (r *GormGroupMemberRepository) RemoveMember(ctx context.Context, groupInternalUUID, userInternalUUID uuid.UUID) error

RemoveMember removes a user from a group

type GormGroupRepository

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

GormGroupRepository implements GroupRepository using GORM for cross-database support

func NewGormGroupRepository

func NewGormGroupRepository(db *gorm.DB) *GormGroupRepository

NewGormGroupRepository creates a new GORM-backed group repository

func (*GormGroupRepository) Count

func (r *GormGroupRepository) Count(ctx context.Context, filter GroupFilter) (int, error)

Count returns total count of groups matching the filter

func (*GormGroupRepository) Create

func (r *GormGroupRepository) Create(ctx context.Context, group Group) error

Create creates a new group (primarily for provider-independent groups)

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)

func (*GormGroupRepository) Get

func (r *GormGroupRepository) Get(ctx context.Context, internalUUID uuid.UUID) (*Group, error)

Get retrieves a group by internal UUID

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

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)

func (*GormGroupRepository) List

func (r *GormGroupRepository) List(ctx context.Context, filter GroupFilter) ([]Group, error)

List returns groups with optional filtering and pagination

func (*GormGroupRepository) Update

func (r *GormGroupRepository) Update(ctx context.Context, group Group) error

Update updates group metadata (name, description)

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.

type GormMetadataRepository

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

GormMetadataRepository implements MetadataRepository using GORM.

No mutex: earlier versions serialized every metadata write in the process behind a sync.RWMutex, which protected nothing (GORM connections are concurrency-safe and the transactions below already provide atomicity) while turning every bulk write into a process-wide bottleneck. In a multi-replica deployment concurrent writers are in different processes anyway, so the mutex bought no additional safety there either (#666).

func NewGormMetadataRepository

func NewGormMetadataRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormMetadataRepository

NewGormMetadataRepository creates a new GORM-backed metadata repository

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

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 statement

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.

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.

func (*GormMetadataRepository) Create

func (r *GormMetadataRepository) Create(ctx context.Context, entityType, entityID string, metadata *Metadata) error

Create creates a new metadata entry

func (*GormMetadataRepository) Delete

func (r *GormMetadataRepository) Delete(ctx context.Context, entityType, entityID, key string) error

Delete removes a metadata entry

func (*GormMetadataRepository) Get

func (r *GormMetadataRepository) Get(ctx context.Context, entityType, entityID, key string) (*Metadata, error)

Get retrieves a specific metadata entry by key

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

func (*GormMetadataRepository) InvalidateCache

func (r *GormMetadataRepository) InvalidateCache(ctx context.Context, entityType, entityID string) error

InvalidateCache removes metadata-related cache entries

func (*GormMetadataRepository) List

func (r *GormMetadataRepository) List(ctx context.Context, entityType, entityID string) ([]Metadata, error)

List retrieves all metadata for an entity

func (*GormMetadataRepository) ListKeys

func (r *GormMetadataRepository) ListKeys(ctx context.Context, entityType, entityID string) ([]string, error)

ListKeys retrieves all metadata keys for an entity

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

func (*GormMetadataRepository) Update

func (r *GormMetadataRepository) Update(ctx context.Context, entityType, entityID string, metadata *Metadata) error

Update updates an existing metadata entry

func (*GormMetadataRepository) WarmCache

func (r *GormMetadataRepository) WarmCache(ctx context.Context, entityType, entityID string) error

WarmCache preloads metadata for an entity into cache

type GormNoteRepository

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

GormNoteRepository implements NoteStore using GORM

func NewGormNoteRepository

func NewGormNoteRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormNoteRepository

NewGormNoteRepository creates a new GORM-backed note store with optional caching

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

func (*GormNoteRepository) Create

func (s *GormNoteRepository) Create(ctx context.Context, note *Note, threatModelID string) error

Create creates a new note

func (*GormNoteRepository) Delete

func (s *GormNoteRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes a note by setting deleted_at

func (*GormNoteRepository) Get

func (s *GormNoteRepository) Get(ctx context.Context, id string) (*Note, error)

Get retrieves a note by ID

func (*GormNoteRepository) GetIncludingDeleted

func (s *GormNoteRepository) GetIncludingDeleted(ctx context.Context, id string) (*Note, error)

func (*GormNoteRepository) HardDelete

func (s *GormNoteRepository) HardDelete(ctx context.Context, id string) error

func (*GormNoteRepository) InvalidateCache

func (s *GormNoteRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes note-related cache entries

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

func (*GormNoteRepository) Patch

func (s *GormNoteRepository) Patch(ctx context.Context, id string, operations []PatchOperation, check func(before, after *Note) error) (*Note, error)

Patch applies JSON patch operations to a note, runs check on the result, and persists it.

func (*GormNoteRepository) Restore

func (s *GormNoteRepository) Restore(ctx context.Context, id string) error

func (*GormNoteRepository) SoftDelete

func (s *GormNoteRepository) SoftDelete(ctx context.Context, id string) error

func (*GormNoteRepository) Update

func (s *GormNoteRepository) Update(ctx context.Context, note *Note, threatModelID string) error

Update updates an existing note

func (*GormNoteRepository) WarmCache

func (s *GormNoteRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads notes for a threat model into cache

type GormProjectNoteStore

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

GormProjectNoteStore implements ProjectNoteStoreInterface using GORM

func NewGormProjectNoteStore

func NewGormProjectNoteStore(db *gorm.DB) *GormProjectNoteStore

NewGormProjectNoteStore creates a new GORM-backed project note store

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

func (*GormProjectNoteStore) Create

func (s *GormProjectNoteStore) Create(ctx context.Context, note *ProjectNote, projectID string) (*ProjectNote, error)

Create creates a new project note

func (*GormProjectNoteStore) Delete

func (s *GormProjectNoteStore) Delete(ctx context.Context, id string) error

Delete deletes a project note

func (*GormProjectNoteStore) Get

Get retrieves a project note by ID

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

func (*GormProjectNoteStore) Patch

func (s *GormProjectNoteStore) Patch(ctx context.Context, id string, operations []PatchOperation, check func(before, after *ProjectNote) error) (*ProjectNote, error)

Patch applies JSON Patch operations to a project note, runs check on the result, and persists it.

func (*GormProjectNoteStore) Update

func (s *GormProjectNoteStore) Update(ctx context.Context, id string, note *ProjectNote, projectID string) (*ProjectNote, error)

Update replaces a project note

type GormProjectStore

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

GormProjectStore implements ProjectStoreInterface using GORM

func NewGormProjectStore

func NewGormProjectStore(db *gorm.DB) *GormProjectStore

NewGormProjectStore creates a new GORM-backed project store

func (*GormProjectStore) Create

func (s *GormProjectStore) Create(ctx context.Context, project *Project, userInternalUUID string) (*Project, error)

Create creates a new project

func (*GormProjectStore) Delete

func (s *GormProjectStore) Delete(ctx context.Context, id string) error

Delete removes a project by ID

func (*GormProjectStore) Get

func (s *GormProjectStore) Get(ctx context.Context, id string) (*Project, error)

Get retrieves a project by ID

func (*GormProjectStore) GetTeamID

func (s *GormProjectStore) GetTeamID(ctx context.Context, projectID string) (string, error)

GetTeamID returns the team_id for a given project

func (*GormProjectStore) HasThreatModels

func (s *GormProjectStore) HasThreatModels(ctx context.Context, projectID string) (bool, error)

HasThreatModels checks if a project has any associated threat models

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

func (*GormProjectStore) Update

func (s *GormProjectStore) Update(ctx context.Context, id string, project *Project, userInternalUUID string) (*Project, error)

Update updates an existing project

func (*GormProjectStore) UpdateWithVersion

func (s *GormProjectStore) UpdateWithVersion(ctx context.Context, id string, project *Project, userInternalUUID string, expectedVersion int) (*Project, int, error)

UpdateWithVersion updates a project guarded by a same-transaction optimistic-lock CAS (#594).

type GormRepositoryRepository

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

GormRepositoryRepository implements RepositoryStore using GORM

func NewGormRepositoryRepository

func NewGormRepositoryRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormRepositoryRepository

NewGormRepositoryRepository creates a new GORM-backed repository store with optional caching

func (*GormRepositoryRepository) BulkCreate

func (s *GormRepositoryRepository) BulkCreate(ctx context.Context, repositories []Repository, threatModelID string) error

BulkCreate creates multiple repositories in a single transaction

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

func (*GormRepositoryRepository) Create

func (s *GormRepositoryRepository) Create(ctx context.Context, repository *Repository, threatModelID string) error

Create creates a new repository

func (*GormRepositoryRepository) Delete

Delete soft-deletes a repository by setting deleted_at

func (*GormRepositoryRepository) Get

Get retrieves a repository by ID

func (*GormRepositoryRepository) GetIncludingDeleted

func (s *GormRepositoryRepository) GetIncludingDeleted(ctx context.Context, id string) (*Repository, error)

func (*GormRepositoryRepository) HardDelete

func (s *GormRepositoryRepository) HardDelete(ctx context.Context, id string) error

func (*GormRepositoryRepository) InvalidateCache

func (s *GormRepositoryRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes repository-related cache entries

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

func (*GormRepositoryRepository) Patch

func (s *GormRepositoryRepository) Patch(ctx context.Context, id string, operations []PatchOperation) (*Repository, error)

Patch applies JSON patch operations to a repository

func (*GormRepositoryRepository) Restore

func (s *GormRepositoryRepository) Restore(ctx context.Context, id string) error

func (*GormRepositoryRepository) SoftDelete

func (s *GormRepositoryRepository) SoftDelete(ctx context.Context, id string) error

func (*GormRepositoryRepository) Update

func (s *GormRepositoryRepository) Update(ctx context.Context, repository *Repository, threatModelID string) error

Update updates an existing repository

func (*GormRepositoryRepository) WarmCache

func (s *GormRepositoryRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads repositories for a threat model into cache

type GormSurveyAnswerStore

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

GormSurveyAnswerStore implements SurveyAnswerStore backed by a GORM database.

func NewGormSurveyAnswerStore

func NewGormSurveyAnswerStore(db *gorm.DB) *GormSurveyAnswerStore

NewGormSurveyAnswerStore creates a new GORM-backed SurveyAnswerStore.

func (*GormSurveyAnswerStore) DeleteByResponseID

func (s *GormSurveyAnswerStore) DeleteByResponseID(ctx context.Context, responseID string) error

DeleteByResponseID implements SurveyAnswerStore.

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.

func (*GormSurveyAnswerStore) GetAnswers

func (s *GormSurveyAnswerStore) GetAnswers(ctx context.Context, responseID string) ([]SurveyAnswerRow, error)

GetAnswers implements SurveyAnswerStore.

func (*GormSurveyAnswerStore) GetFieldMappings

func (s *GormSurveyAnswerStore) GetFieldMappings(ctx context.Context, responseID string) (map[string]SurveyAnswerRow, error)

GetFieldMappings implements SurveyAnswerStore.

type GormSurveyResponseStore

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

GormSurveyResponseStore implements SurveyResponseStore using GORM

func NewGormSurveyResponseStore

func NewGormSurveyResponseStore(db *gorm.DB) *GormSurveyResponseStore

NewGormSurveyResponseStore creates a new GORM-backed survey response store

func (*GormSurveyResponseStore) Create

func (s *GormSurveyResponseStore) Create(ctx context.Context, response *SurveyResponse, userInternalUUID string) error

Create creates a new survey response

func (*GormSurveyResponseStore) Delete

Delete removes a survey response by ID

func (*GormSurveyResponseStore) Get

Get retrieves a survey response by ID

func (*GormSurveyResponseStore) GetAuthorization

func (s *GormSurveyResponseStore) GetAuthorization(ctx context.Context, id uuid.UUID) ([]Authorization, error)

GetAuthorization retrieves authorization entries for a response

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

func (*GormSurveyResponseStore) List

List retrieves survey responses with pagination and optional filters

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.

func (*GormSurveyResponseStore) Update

func (s *GormSurveyResponseStore) Update(ctx context.Context, response *SurveyResponse) error

Update updates an existing survey response

func (*GormSurveyResponseStore) UpdateAuthorization

func (s *GormSurveyResponseStore) UpdateAuthorization(ctx context.Context, id uuid.UUID, authorization []Authorization) error

UpdateAuthorization updates authorization entries for a response

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

func (*GormSurveyResponseStore) UpdateWithVersion

func (s *GormSurveyResponseStore) UpdateWithVersion(ctx context.Context, response *SurveyResponse, expectedVersion int) (int, error)

UpdateWithVersion updates a survey response guarded by a same-transaction optimistic-lock CAS (#594).

type GormSurveyStore

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

GormSurveyStore implements SurveyStore using GORM

func NewGormSurveyStore

func NewGormSurveyStore(db *gorm.DB) *GormSurveyStore

NewGormSurveyStore creates a new GORM-backed survey store

func (*GormSurveyStore) Create

func (s *GormSurveyStore) Create(ctx context.Context, survey *Survey, userInternalUUID string) error

Create creates a new survey

func (*GormSurveyStore) Delete

func (s *GormSurveyStore) Delete(ctx context.Context, id uuid.UUID) error

Delete removes a survey by ID

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

func (*GormSurveyStore) HasResponses

func (s *GormSurveyStore) HasResponses(ctx context.Context, id uuid.UUID) (bool, error)

HasResponses checks if a survey has any associated responses

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

func (*GormSurveyStore) ListActive

func (s *GormSurveyStore) ListActive(ctx context.Context, limit, offset int) ([]SurveyListItem, int, error)

ListActive retrieves only active surveys (for intake endpoints)

func (*GormSurveyStore) Update

func (s *GormSurveyStore) Update(ctx context.Context, survey *Survey) error

Update updates an existing survey

type GormTeamNoteStore

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

GormTeamNoteStore implements TeamNoteStoreInterface using GORM

func NewGormTeamNoteStore

func NewGormTeamNoteStore(db *gorm.DB) *GormTeamNoteStore

NewGormTeamNoteStore creates a new GORM-backed team note store

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

func (*GormTeamNoteStore) Create

func (s *GormTeamNoteStore) Create(ctx context.Context, note *TeamNote, teamID string) (*TeamNote, error)

Create creates a new team note

func (*GormTeamNoteStore) Delete

func (s *GormTeamNoteStore) Delete(ctx context.Context, id string) error

Delete deletes a team note

func (*GormTeamNoteStore) Get

func (s *GormTeamNoteStore) Get(ctx context.Context, id string) (*TeamNote, error)

Get retrieves a team note by ID

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

func (*GormTeamNoteStore) Patch

func (s *GormTeamNoteStore) Patch(ctx context.Context, id string, operations []PatchOperation, check func(before, after *TeamNote) error) (*TeamNote, error)

Patch applies JSON Patch operations to a team note, runs check on the result, and persists it.

func (*GormTeamNoteStore) Update

func (s *GormTeamNoteStore) Update(ctx context.Context, id string, note *TeamNote, teamID string) (*TeamNote, error)

Update replaces a team note

type GormTeamStore

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

GormTeamStore implements TeamStoreInterface using GORM for database persistence

func NewGormTeamStore

func NewGormTeamStore(db *gorm.DB) *GormTeamStore

NewGormTeamStore creates a new GORM-backed team store

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

func (*GormTeamStore) Delete

func (s *GormTeamStore) Delete(ctx context.Context, id string) error

Delete removes a team and all associated data

func (*GormTeamStore) Get

func (s *GormTeamStore) Get(ctx context.Context, id string) (*Team, error)

Get retrieves a team by ID with all associated data

func (*GormTeamStore) HasProjects

func (s *GormTeamStore) HasProjects(ctx context.Context, teamID string) (bool, error)

HasProjects checks if a team has any associated projects

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

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

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

func (*GormTeamStore) UpdateWithVersion

func (s *GormTeamStore) UpdateWithVersion(ctx context.Context, id string, team *Team, userInternalUUID string, expectedVersion int) (*Team, int, error)

UpdateWithVersion updates a team guarded by a same-transaction optimistic-lock CAS (#594).

type GormThreatModelStore

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

GormThreatModelStore handles threat model database operations using GORM

func NewGormThreatModelStore

func NewGormThreatModelStore(database *gorm.DB) *GormThreatModelStore

NewGormThreatModelStore creates a new threat model GORM store

func (*GormThreatModelStore) Count

func (s *GormThreatModelStore) Count() int

Count returns the total number of threat models using GORM

func (*GormThreatModelStore) Create

Create adds a new threat model using GORM

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.

func (*GormThreatModelStore) Get

Get retrieves a threat model by ID using GORM

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.

func (*GormThreatModelStore) GetAuthorizationIncludingDeleted

func (s *GormThreatModelStore) GetAuthorizationIncludingDeleted(id string) ([]Authorization, User, error)

GetAuthorizationIncludingDeleted loads authorization for a potentially soft-deleted threat model.

func (*GormThreatModelStore) GetDB

func (s *GormThreatModelStore) GetDB() *gorm.DB

GetDB returns the underlying GORM database connection

func (*GormThreatModelStore) GetIncludingDeleted

func (s *GormThreatModelStore) GetIncludingDeleted(id string) (ThreatModel, error)

GetIncludingDeleted retrieves a threat model by ID without filtering on deleted_at

func (*GormThreatModelStore) HardDelete

func (s *GormThreatModelStore) HardDelete(id string) error

HardDelete permanently removes a threat model and all its children (the original Delete behavior)

func (*GormThreatModelStore) ListWithCounts

func (s *GormThreatModelStore) ListWithCounts(offset, limit int, filter func(ThreatModel) bool, filters *ThreatModelFilters) ([]TMListItem, int, error)

func (*GormThreatModelStore) Restore

func (s *GormThreatModelStore) Restore(id string) error

Restore clears deleted_at on a threat model and all its children

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

func (*GormThreatModelStore) Update

func (s *GormThreatModelStore) Update(ctx context.Context, id string, item ThreatModel) error

Update modifies an existing threat model using GORM

func (*GormThreatModelStore) UpdateWithVersion

func (s *GormThreatModelStore) UpdateWithVersion(ctx context.Context, id string, item ThreatModel, expectedVersion int) (int, error)

UpdateWithVersion updates a threat model guarded by a same-transaction optimistic-lock CAS (#594).

type GormThreatRepository

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

GormThreatRepository implements ThreatStore with GORM for database persistence and Redis caching

func NewGormThreatRepository

func NewGormThreatRepository(db *gorm.DB, cache *CacheService, invalidator *CacheInvalidator) *GormThreatRepository

NewGormThreatRepository creates a new GORM-backed threat repository with caching

func (*GormThreatRepository) BulkCreate

func (s *GormThreatRepository) BulkCreate(ctx context.Context, threats []Threat) error

BulkCreate creates multiple threats in a single transaction using GORM

func (*GormThreatRepository) BulkSoftDelete

func (s *GormThreatRepository) BulkSoftDelete(ctx context.Context, threatModelID string, ids []string) error

BulkSoftDelete soft-deletes every id in a single transaction, scoped to the threat model that owns them.

Two properties matter here and neither is optional:

  • Scoping. The predicate includes threat_model_id, so an id belonging to a different threat model simply does not match. Authorization is granted against the {threat_model_id} path segment, so without this a caller with writer access to one threat model could delete threats out of another. (Compare the check at api/audit_handlers.go:127.)

  • Atomicity. One UPDATE, one commit. A per-id loop would commit each delete separately, so an abort partway through would leave the batch applied to an arbitrary prefix -- and because the surviving rows no longer satisfy "deleted_at IS NULL", retrying the same request would then fail forever with 404. On Oracle a mid-batch abort is routine: ORA-08177 under the SERIALIZABLE isolation these transactions request, ORA-00060, and the connection drops ADB raises while autoscaling.

func (*GormThreatRepository) BulkUpdate

func (s *GormThreatRepository) BulkUpdate(ctx context.Context, threats []Threat) error

BulkUpdate updates multiple threats in a single transaction using GORM

func (*GormThreatRepository) Create

func (s *GormThreatRepository) Create(ctx context.Context, threat *Threat) error

Create creates a new threat with write-through caching using GORM

func (*GormThreatRepository) Delete

func (s *GormThreatRepository) Delete(ctx context.Context, id string) error

Delete soft-deletes a threat by setting deleted_at

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

func (*GormThreatRepository) GetIncludingDeleted

func (s *GormThreatRepository) GetIncludingDeleted(ctx context.Context, id string) (*Threat, error)

func (*GormThreatRepository) HardDelete

func (s *GormThreatRepository) HardDelete(ctx context.Context, id string) error

func (*GormThreatRepository) InvalidateCache

func (s *GormThreatRepository) InvalidateCache(ctx context.Context, id string) error

InvalidateCache removes threat-related cache entries

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

func (*GormThreatRepository) Patch

func (s *GormThreatRepository) Patch(ctx context.Context, threatModelID string, id string, operations []PatchOperation) (*Threat, error)

Patch applies JSON patch operations to a threat using GORM, scoped to the parent threat model so a bulk-patch caller supplying only a child id cannot load and overwrite a threat belonging to a different threat model

func (*GormThreatRepository) PatchWithVersion

func (s *GormThreatRepository) PatchWithVersion(ctx context.Context, threatModelID string, id string, operations []PatchOperation, expectedVersion int) (*Threat, int, error)

PatchWithVersion applies JSON patch operations to a threat guarded by a same-transaction optimistic-lock CAS (#594).

func (*GormThreatRepository) Restore

func (s *GormThreatRepository) Restore(ctx context.Context, id string) error

func (*GormThreatRepository) SoftDelete

func (s *GormThreatRepository) SoftDelete(ctx context.Context, id string) error

func (*GormThreatRepository) Update

func (s *GormThreatRepository) Update(ctx context.Context, threat *Threat) error

Update updates an existing threat with write-through caching using GORM

func (*GormThreatRepository) UpdateWithVersion

func (s *GormThreatRepository) UpdateWithVersion(ctx context.Context, threat *Threat, expectedVersion int) (int, error)

UpdateWithVersion updates a threat guarded by a same-transaction optimistic-lock CAS (#594).

func (*GormThreatRepository) WarmCache

func (s *GormThreatRepository) WarmCache(ctx context.Context, threatModelID string) error

WarmCache preloads threats for a threat model into cache

type GormTimmyEmbeddingStore

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

GormTimmyEmbeddingStore implements TimmyEmbeddingStore using GORM

func NewGormTimmyEmbeddingStore

func NewGormTimmyEmbeddingStore(db *gorm.DB) *GormTimmyEmbeddingStore

NewGormTimmyEmbeddingStore creates a new GORM-backed embedding store

func (*GormTimmyEmbeddingStore) CreateBatch

func (s *GormTimmyEmbeddingStore) CreateBatch(ctx context.Context, embeddings []models.TimmyEmbedding) error

CreateBatch creates a batch of embeddings

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

func (*GormTimmyEmbeddingStore) DeleteByThreatModel

func (s *GormTimmyEmbeddingStore) DeleteByThreatModel(ctx context.Context, threatModelID string) (int64, error)

DeleteByThreatModel deletes all embeddings for a threat model

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

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.

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

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.

type GormTimmyMessageStore

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

GormTimmyMessageStore implements TimmyMessageStore using GORM

func NewGormTimmyMessageStore

func NewGormTimmyMessageStore(db *gorm.DB) *GormTimmyMessageStore

NewGormTimmyMessageStore creates a new GORM-backed message store

func (*GormTimmyMessageStore) Create

func (s *GormTimmyMessageStore) Create(ctx context.Context, message *models.TimmyMessage) error

Create persists a new message

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)

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

type GormTimmySessionStore

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

GormTimmySessionStore implements TimmySessionStore using GORM

func NewGormTimmySessionStore

func NewGormTimmySessionStore(db *gorm.DB) *GormTimmySessionStore

NewGormTimmySessionStore creates a new GORM-backed session store

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

func (*GormTimmySessionStore) Create

func (s *GormTimmySessionStore) Create(ctx context.Context, session *models.TimmySession) error

Create persists a new session

func (*GormTimmySessionStore) Get

Get retrieves a session by ID, excluding soft-deleted sessions

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

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

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.

func (*GormTimmySessionStore) UpdateTitle

func (s *GormTimmySessionStore) UpdateTitle(ctx context.Context, id, title string) error

UpdateTitle updates the title column for a session.

type GormTimmyUsageStore

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

GormTimmyUsageStore implements TimmyUsageStore using GORM

func NewGormTimmyUsageStore

func NewGormTimmyUsageStore(db *gorm.DB) *GormTimmyUsageStore

NewGormTimmyUsageStore creates a new GORM-backed usage store

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

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

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

func (*GormTimmyUsageStore) Record

func (s *GormTimmyUsageStore) Record(ctx context.Context, usage *models.TimmyUsage) error

Record persists a new usage record

type GormTriageNoteStore

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

GormTriageNoteStore implements TriageNoteStore using GORM

func NewGormTriageNoteStore

func NewGormTriageNoteStore(db *gorm.DB) *GormTriageNoteStore

NewGormTriageNoteStore creates a new 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

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

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

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

type GormUsabilityFeedbackRepository

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

GormUsabilityFeedbackRepository implements UsabilityFeedbackRepository with GORM.

func NewGormUsabilityFeedbackRepository

func NewGormUsabilityFeedbackRepository(db *gorm.DB) *GormUsabilityFeedbackRepository

NewGormUsabilityFeedbackRepository constructs a repository.

func (*GormUsabilityFeedbackRepository) Count

Count returns the row count for the filter.

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).

func (*GormUsabilityFeedbackRepository) Get

Get returns a feedback row by ID, or NotFound if absent.

func (*GormUsabilityFeedbackRepository) List

List returns feedback rows matching the filter, paginated.

type GormUserAPIQuotaStore

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

GormUserAPIQuotaStore implements UserAPIQuotaStoreInterface using GORM

func NewGormUserAPIQuotaStore

func NewGormUserAPIQuotaStore(db *gorm.DB) *GormUserAPIQuotaStore

NewGormUserAPIQuotaStore creates a new GORM-backed user API quota store

func (*GormUserAPIQuotaStore) Count

func (s *GormUserAPIQuotaStore) Count(ctx context.Context) (int, error)

Count returns the total number of user API quotas

func (*GormUserAPIQuotaStore) Create

Create creates a new user API quota

func (*GormUserAPIQuotaStore) Delete

func (s *GormUserAPIQuotaStore) Delete(ctx context.Context, userID string) error

Delete deletes a user API quota

func (*GormUserAPIQuotaStore) Get

Get retrieves a user API quota by user ID

func (*GormUserAPIQuotaStore) GetOrDefault

func (s *GormUserAPIQuotaStore) GetOrDefault(ctx context.Context, userID string) UserAPIQuota

GetOrDefault retrieves a quota or returns default values

func (*GormUserAPIQuotaStore) List

func (s *GormUserAPIQuotaStore) List(ctx context.Context, offset, limit int) ([]UserAPIQuota, error)

List retrieves all user API quotas with pagination

func (*GormUserAPIQuotaStore) Update

func (s *GormUserAPIQuotaStore) Update(ctx context.Context, userID string, item UserAPIQuota) error

Update updates an existing user API quota

func (*GormUserAPIQuotaStore) Upsert

Upsert creates or updates a user API quota using GORM's OnConflict clause, then reads the row back so the returned timestamps reflect what is actually stored rather than a client-side stamp (#706) This is cross-database compatible via GORM's dialect abstraction

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.

func NewGormUserGroupsFetcher

func NewGormUserGroupsFetcher(memberStore GroupMemberRepository) *GormUserGroupsFetcher

NewGormUserGroupsFetcher creates a new user groups fetcher.

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.

type GormUserStore

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

GormUserStore implements UserStore using GORM for cross-database support

func NewGormUserStore

func NewGormUserStore(db *gorm.DB, authService *auth.Service) *GormUserStore

NewGormUserStore creates a new GORM-backed user store

func (*GormUserStore) Count

func (s *GormUserStore) Count(ctx context.Context, filter UserFilter) (int, error)

Count returns total count of users matching the filter

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.

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)

func (*GormUserStore) Get

func (s *GormUserStore) Get(ctx context.Context, internalUUID openapi_types.UUID) (*AdminUser, error)

Get retrieves a user by internal UUID

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

func (*GormUserStore) List

func (s *GormUserStore) List(ctx context.Context, filter UserFilter) ([]AdminUser, error)

List returns users with optional filtering and pagination

func (*GormUserStore) Update

func (s *GormUserStore) Update(ctx context.Context, user AdminUser) error

Update updates user metadata (email, name, email_verified)

type GormWebhookQuotaStore

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

GormWebhookQuotaStore implements WebhookQuotaStoreInterface using GORM

func NewGormWebhookQuotaStore

func NewGormWebhookQuotaStore(db *gorm.DB) *GormWebhookQuotaStore

NewGormWebhookQuotaStore creates a new GORM-backed webhook quota store

func (*GormWebhookQuotaStore) Count

func (s *GormWebhookQuotaStore) Count(ctx context.Context) (int, error)

Count returns the total number of webhook quotas using GORM

func (*GormWebhookQuotaStore) Create

Create creates a new webhook quota using GORM

func (*GormWebhookQuotaStore) Delete

func (s *GormWebhookQuotaStore) Delete(ctx context.Context, ownerID string) error

Delete deletes a webhook quota using GORM

func (*GormWebhookQuotaStore) Get

Get retrieves a webhook quota by owner ID using GORM

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.

func (*GormWebhookQuotaStore) List

func (s *GormWebhookQuotaStore) List(ctx context.Context, offset, limit int) ([]DBWebhookQuota, error)

List retrieves all webhook quotas with pagination using GORM

func (*GormWebhookQuotaStore) Update

func (s *GormWebhookQuotaStore) Update(ctx context.Context, ownerID string, item DBWebhookQuota) error

Update updates an existing webhook quota using GORM

type GormWebhookSubscriptionStore

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

GormWebhookSubscriptionStore implements WebhookSubscriptionStoreInterface using GORM

func NewGormWebhookSubscriptionStore

func NewGormWebhookSubscriptionStore(db *gorm.DB) *GormWebhookSubscriptionStore

NewGormWebhookSubscriptionStore creates a new GORM-backed webhook subscription store

func (*GormWebhookSubscriptionStore) Count

Count returns the total number of webhook subscriptions using GORM

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

func (*GormWebhookSubscriptionStore) Create

Create creates a new webhook subscription using GORM

func (*GormWebhookSubscriptionStore) Delete

Delete deletes a webhook subscription using GORM

func (*GormWebhookSubscriptionStore) Get

Get retrieves a webhook subscription by ID using GORM

func (*GormWebhookSubscriptionStore) IncrementTimeouts

func (s *GormWebhookSubscriptionStore) IncrementTimeouts(ctx context.Context, id string) error

IncrementTimeouts increments the timeout count using GORM

func (*GormWebhookSubscriptionStore) List

List retrieves webhook subscriptions with pagination and filtering using GORM

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.

func (*GormWebhookSubscriptionStore) ListActiveByOwner

func (s *GormWebhookSubscriptionStore) ListActiveByOwner(ctx context.Context, ownerID string) ([]DBWebhookSubscription, error)

ListActiveByOwner retrieves active subscriptions for an owner using GORM

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

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

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

func (*GormWebhookSubscriptionStore) ListIdle

ListIdle retrieves subscriptions that have been idle for a certain number of days using GORM

func (*GormWebhookSubscriptionStore) ListPendingDelete

ListPendingDelete retrieves subscriptions pending deletion using GORM

func (*GormWebhookSubscriptionStore) ListPendingVerification

func (s *GormWebhookSubscriptionStore) ListPendingVerification(ctx context.Context) ([]DBWebhookSubscription, error)

ListPendingVerification retrieves subscriptions pending verification using GORM

func (*GormWebhookSubscriptionStore) ResetTimeouts

func (s *GormWebhookSubscriptionStore) ResetTimeouts(ctx context.Context, id string) error

ResetTimeouts resets the timeout count using GORM

func (*GormWebhookSubscriptionStore) Update

Update updates an existing webhook subscription using GORM. Callers may pass an explicit field list to narrow the write, so a caller that did not touch the verification state does not clobber a concurrent challenge-worker update.

func (*GormWebhookSubscriptionStore) UpdateChallenge

func (s *GormWebhookSubscriptionStore) UpdateChallenge(ctx context.Context, id string, challenge string, challengesSent int) error

UpdateChallenge updates challenge-related fields using GORM

func (*GormWebhookSubscriptionStore) UpdatePublicationStats

func (s *GormWebhookSubscriptionStore) UpdatePublicationStats(ctx context.Context, id string, success bool) error

UpdatePublicationStats updates publication statistics using GORM

func (*GormWebhookSubscriptionStore) UpdateStatus

func (s *GormWebhookSubscriptionStore) UpdateStatus(ctx context.Context, id string, status string) error

UpdateStatus updates only the status field using GORM

type GormWebhookUrlDenyListStore

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

GormWebhookUrlDenyListStore implements WebhookUrlDenyListStoreInterface using GORM

func NewGormWebhookUrlDenyListStore

func NewGormWebhookUrlDenyListStore(db *gorm.DB) *GormWebhookUrlDenyListStore

NewGormWebhookUrlDenyListStore creates a new GORM-backed store

func (*GormWebhookUrlDenyListStore) Create

Create creates a new deny list entry using GORM

func (*GormWebhookUrlDenyListStore) Delete

Delete deletes a deny list entry using GORM

func (*GormWebhookUrlDenyListStore) List

List retrieves all deny list entries using GORM

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"`
}

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"`
}

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"`
}

type GraphMLEdge

type GraphMLEdge struct {
	ID     string      `xml:"id,attr"`
	Source string      `xml:"source,attr"`
	Target string      `xml:"target,attr"`
	Data   []GraphData `xml:"data"`
}

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"`
}

type GraphMLNode

type GraphMLNode struct {
	ID   string      `xml:"id,attr"`
	Data []GraphData `xml:"data"`
}

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
	// IsBuiltin is derived from the UUID allowlist (validation.IsBuiltInGroup), not persisted.
	// No omitempty: false is meaningful (distinguishes admin-created groups sharing provider "tmi").
	IsBuiltin bool `json:"is_builtin"`
}

Group represents a group in the system

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.

func NewGroupBasedAdminChecker

func NewGroupBasedAdminChecker(db *gorm.DB, memberStore GroupMemberRepository) *GroupBasedAdminChecker

NewGroupBasedAdminChecker creates a new admin checker backed by the Administrators group.

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.

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.

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.

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

type GroupFilter

type GroupFilter struct {
	Provider             string
	GroupName            string // Case-insensitive ILIKE %name%
	UsedInAuthorizations *bool
	BuiltIn              *bool // Filter by validation.IsBuiltInGroup(internal_uuid) membership
	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

type GroupIdPathParam

type GroupIdPathParam = openapi_types.UUID

GroupIdPathParam defines model for GroupIdPathParam.

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

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).

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.

func NewGroupMembershipEnricher

func NewGroupMembershipEnricher(memberStore GroupMemberRepository, db *gorm.DB) *GroupMembershipEnricher

NewGroupMembershipEnricher creates a new enricher for JWT claims.

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.

func (*GroupMembershipEnricher) IsAdministrator

func (e *GroupMembershipEnricher) IsAdministrator(ctx context.Context, userInternalUUID string) (bool, error)

IsAdministrator reports whether the user is an administrator directly or via a nested TMI-managed group, independent of any IdP group list (#856).

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.

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.

func NewHTTPEmbeddingSource

func NewHTTPEmbeddingSource(ssrfValidator *URIValidator) *HTTPEmbeddingSource

NewHTTPEmbeddingSource creates a new HTTPEmbeddingSource with the given SSRF validator.

func (*HTTPEmbeddingSource) CanHandle

CanHandle returns true for entity references with an http:// or https:// URI.

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.

func (*HTTPEmbeddingSource) Name

func (p *HTTPEmbeddingSource) Name() string

Name returns the provider name for logging.

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.

func NewHTTPSource

func NewHTTPSource(ssrfValidator *URIValidator) *HTTPSource

NewHTTPSource creates a new HTTPSource with the given SSRF validator.

func (*HTTPSource) CanHandle

func (s *HTTPSource) CanHandle(_ context.Context, uri string) bool

CanHandle returns true for URIs with an http:// or https:// scheme.

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.

func (*HTTPSource) Name

func (s *HTTPSource) Name() string

Name returns the source name.

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

func NewHealthChecker

func NewHealthChecker(timeout time.Duration) *HealthChecker

NewHealthChecker creates a new health checker with the specified timeout

func (*HealthChecker) CheckHealth

func (h *HealthChecker) CheckHealth(ctx context.Context) SystemHealthResult

CheckHealth performs health checks on all system components

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

type HistoryOperationMessage

type HistoryOperationMessage struct {
	MessageType   MessageType `json:"message_type"`
	OperationType string      `json:"operation_type"`
	Message       string      `json:"message"`
}

func (HistoryOperationMessage) GetMessageType

func (m HistoryOperationMessage) GetMessageType() MessageType

func (HistoryOperationMessage) Validate

func (m HistoryOperationMessage) Validate() error

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.

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

func NewIPRateLimiter

func NewIPRateLimiter(redisClient *redis.Client) *IPRateLimiter

NewIPRateLimiter creates a new IP-based rate limiter

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

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

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 = string

IfMatchHeader defines model for IfMatchHeader.

type InMemoryTicketStore

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

InMemoryTicketStore implements TicketStore using in-memory storage.

func NewInMemoryTicketStore

func NewInMemoryTicketStore() *InMemoryTicketStore

NewInMemoryTicketStore creates a new in-memory ticket store.

func (*InMemoryTicketStore) Close

func (s *InMemoryTicketStore) Close()

Close stops the cleanup goroutine.

func (*InMemoryTicketStore) IssueTicket

func (s *InMemoryTicketStore) IssueTicket(_ context.Context, claims TicketClaims, ttl time.Duration) (string, error)

IssueTicket creates a cryptographically random ticket bound to the given claims.

func (*InMemoryTicketStore) ValidateTicket

func (s *InMemoryTicketStore) ValidateTicket(_ context.Context, ticket string) (TicketClaims, error)

ValidateTicket validates and consumes a ticket. It is single-use: the ticket is deleted on first access.

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 redirects after successful authentication. For OAuth (authorization code with PKCE) the redirect carries the authorization code and state in the query string (?code=...&state=...); the client exchanges the code for tokens at POST /oauth2/token, which returns a JSON body and, when cookie delivery is enabled, also sets HttpOnly token cookies. OAuth never delivers tokens in the URL fragment. SAML login instead redirects with the tokens in the URL fragment (#access_token=...).
	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.

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.

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 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

type InvalidationStrategy

type InvalidationStrategy int

InvalidationStrategy defines different cache invalidation approaches

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.

func NewJSONEmbeddingSource

func NewJSONEmbeddingSource() *JSONEmbeddingSource

NewJSONEmbeddingSource creates a new JSONEmbeddingSource.

func (*JSONEmbeddingSource) CanHandle

CanHandle returns true when the entity is a diagram with no external URI.

func (*JSONEmbeddingSource) Extract

Extract reads the diagram from DiagramStore and converts its cells to human-readable text.

func (*JSONEmbeddingSource) Name

func (p *JSONEmbeddingSource) Name() string

Name returns the provider name for logging.

type JsonPatchDocument

type JsonPatchDocument = []struct {
	// From JSON Pointer (RFC 6901) to the source location. Required for move and copy operations, ignored otherwise; must start with "/".
	From *string `json:"from,omitempty"`

	// Op Patch operation type
	Op JsonPatchDocumentOp `json:"op"`

	// Path JSON Pointer (RFC 6901) to the target; must start with "/" (the document root "" is not allowed)
	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.

func NewLLMQueryDecomposer

func NewLLMQueryDecomposer(llm DecomposerLLM) *LLMQueryDecomposer

NewLLMQueryDecomposer creates a new LLMQueryDecomposer backed by the given LLM.

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.

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.

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 {
	// Defaults Server default quota values applied when a user has no quota row
	Defaults struct {
		// MaxActiveInvocations Default max active invocations limit
		MaxActiveInvocations int `json:"max_active_invocations"`

		// MaxInvocationsPerHour Default max invocations-per-hour limit
		MaxInvocationsPerHour int `json:"max_invocations_per_hour"`
	} `json:"defaults"`

	// 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"`

	// BuiltIn Filter groups by built-in (server-seeded) status
	BuiltIn *BuiltInQueryParam `form:"built_in,omitempty" json:"built_in,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). If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601). If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601). If `modified_before` is also supplied and the resulting range is empty (this value is later than `modified_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601). If `modified_after` is also supplied and the resulting range is empty (this value is later than `modified_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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. If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp. If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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. If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp. If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedBefore *CreatedBeforeQueryParam `form:"created_before,omitempty" json:"created_before,omitempty"`

	// LastLoginAfter Filter users who logged in after this timestamp (RFC3339). If `last_login_before` is also supplied and the resulting range is empty (this value is later than `last_login_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	LastLoginAfter *LastLoginAfterQueryParam `form:"last_login_after,omitempty" json:"last_login_after,omitempty"`

	// LastLoginBefore Filter users who logged in before this timestamp (RFC3339). If `last_login_after` is also supplied and the resulting range is empty (this value is later than `last_login_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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). Valid values: draft, submitted, needs_revision, ready_for_review, review_created.
	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). If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601). If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601). If `modified_before` is also supplied and the resulting range is empty (this value is later than `modified_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601). If `modified_after` is also supplied and the resulting range is empty (this value is later than `modified_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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). If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601). If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601). If `modified_before` is also supplied and the resulting range is empty (this value is later than `modified_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601). If `modified_after` is also supplied and the resulting range is empty (this value is later than `modified_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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 ListMyWebhookDeliveriesParams

type ListMyWebhookDeliveriesParams struct {
	// 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"`
}

ListMyWebhookDeliveriesParams defines parameters for ListMyWebhookDeliveries.

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 ListSAMLUsersParams

type ListSAMLUsersParams struct {
	// Email Filter by email (case-insensitive substring match)
	Email *EmailQueryParam `form:"email,omitempty" json:"email,omitempty"`

	// Limit Maximum number of users to return.
	Limit *int `form:"limit,omitempty" json:"limit,omitempty"`

	// Offset Number of users to skip before starting to return results.
	Offset *int `form:"offset,omitempty" json:"offset,omitempty"`
}

ListSAMLUsersParams defines parameters for ListSAMLUsers.

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. If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfterQueryParam `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only records created before this RFC 3339 timestamp. If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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). If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601). If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601). If `modified_before` is also supplied and the resulting range is empty (this value is later than `modified_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601). If `modified_after` is also supplied and the resulting range is empty (this value is later than `modified_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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). If `status_updated_before` is also supplied and the resulting range is empty (this value is later than `status_updated_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	StatusUpdatedAfter *StatusUpdatedAfterQueryParam `form:"status_updated_after,omitempty" json:"status_updated_after,omitempty"`

	// StatusUpdatedBefore Filter threat models where status was updated before this timestamp (RFC3339). If `status_updated_after` is also supplied and the resulting range is empty (this value is later than `status_updated_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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). Valid values: draft, submitted, needs_revision, ready_for_review, review_created.
	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 survey responses by their is_confidential flag, intersected with the caller's reviewer scope
	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). If `created_before` is also supplied and the resulting range is empty (this value is later than `created_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedAfter *CreatedAfter `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Filter results created before this timestamp (ISO 8601). If `created_after` is also supplied and the resulting range is empty (this value is later than `created_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	CreatedBefore *CreatedBefore `form:"created_before,omitempty" json:"created_before,omitempty"`

	// ModifiedAfter Filter results modified after this timestamp (ISO 8601). If `modified_before` is also supplied and the resulting range is empty (this value is later than `modified_before`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	ModifiedAfter *ModifiedAfter `form:"modified_after,omitempty" json:"modified_after,omitempty"`

	// ModifiedBefore Filter results modified before this timestamp (ISO 8601). If `modified_after` is also supplied and the resulting range is empty (this value is later than `modified_after`, or equal to it when either bound is exclusive), the request is rejected with 400 `invalid_input`.
	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 Return only feedback created at or after this RFC 3339 timestamp. If `created_before` is also supplied and the range is empty (this value is not earlier than `created_before`), the request is rejected with 400 `invalid_input`.
	CreatedAfter *time.Time `form:"created_after,omitempty" json:"created_after,omitempty"`

	// CreatedBefore Return only feedback created before this RFC 3339 timestamp (exclusive). If `created_after` is also supplied and the range is empty (`created_after` is not earlier than this value), the request is rejected with 400 `invalid_input`.
	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 {
	// Defaults Server default quota values applied when a user has no quota row
	Defaults struct {
		// MaxRequestsPerHour Default requests-per-hour limit
		MaxRequestsPerHour int `json:"max_requests_per_hour"`

		// MaxRequestsPerMinute Default requests-per-minute limit
		MaxRequestsPerMinute int `json:"max_requests_per_minute"`
	} `json:"defaults"`

	// 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 {
	// Defaults Server default quota values applied when a user has no quota row
	Defaults struct {
		// MaxEventsPerMinute Default max events-per-minute limit
		MaxEventsPerMinute int `json:"max_events_per_minute"`

		// MaxSubscriptionRequestsPerDay Default max subscription requests-per-day limit
		MaxSubscriptionRequestsPerDay int `json:"max_subscription_requests_per_day"`

		// MaxSubscriptionRequestsPerMinute Default max subscription requests-per-minute limit
		MaxSubscriptionRequestsPerMinute int `json:"max_subscription_requests_per_minute"`

		// MaxSubscriptions Default max subscriptions limit
		MaxSubscriptions int `json:"max_subscriptions"`
	} `json:"defaults"`

	// 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.

func NewLivePipelineEmbeddingSource

func NewLivePipelineEmbeddingSource(holder *ContentSourceHolder) *LivePipelineEmbeddingSource

NewLivePipelineEmbeddingSource creates an embedding source that resolves its pipeline from holder.Get on each call.

func (*LivePipelineEmbeddingSource) CanHandle

CanHandle returns true for entity references with a URI.

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.

func (*LivePipelineEmbeddingSource) Name

Name returns the adapter name.

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

type LogLevel

type LogLevel int

LogLevel represents logging verbosity

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

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.

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.

type MessageHandler

type MessageHandler interface {
	HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error
	MessageType() string
}

MessageHandler defines the interface for handling WebSocket messages

type MessageRouter

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

MessageRouter handles routing of WebSocket messages to appropriate handlers

func NewMessageRouter

func NewMessageRouter() *MessageRouter

NewMessageRouter creates a new message router with default handlers

func (*MessageRouter) RegisterHandler

func (r *MessageRouter) RegisterHandler(handler MessageHandler)

RegisterHandler registers a message handler for a specific message type

func (*MessageRouter) RouteMessage

func (r *MessageRouter) RouteMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

RouteMessage routes a message to the appropriate handler

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.

type MessageType

type MessageType string

MessageType represents the type of WebSocket message

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.

func (*MetadataConflictError) Error

func (e *MetadataConflictError) Error() string

Error implements the error interface.

func (*MetadataConflictError) Unwrap

func (e *MetadataConflictError) Unwrap() error

Unwrap returns ErrMetadataKeyExists so that errors.Is and errors.As work against the sentinel.

type MetadataItem

type MetadataItem struct {
	Key   string `json:"key" binding:"required"`
	Value string `json:"value" binding:"required"`
}

MetadataItem represents a metadata key-value pair

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.

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.

func NewMicrosoftContentOAuthProvider

func NewMicrosoftContentOAuthProvider(base *BaseContentOAuthProvider) *MicrosoftContentOAuthProvider

NewMicrosoftContentOAuthProvider wraps base for the Microsoft provider id.

func (*MicrosoftContentOAuthProvider) AuthorizationURL

func (p *MicrosoftContentOAuthProvider) AuthorizationURL(state, pkceChallenge, redirectURI string) string

AuthorizationURL delegates to the base provider.

func (*MicrosoftContentOAuthProvider) ExchangeCode

func (p *MicrosoftContentOAuthProvider) ExchangeCode(ctx context.Context, code, pkceVerifier, redirectURI string) (*ContentOAuthTokenResponse, error)

ExchangeCode delegates to the base provider.

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.

func (*MicrosoftContentOAuthProvider) ID

ID returns "microsoft".

func (*MicrosoftContentOAuthProvider) Refresh

Refresh delegates to the base provider.

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.

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.

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

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).

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.

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.

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

type MiddlewareTestHelper

type MiddlewareTestHelper struct {
	Router *gin.Engine
}

MiddlewareTestHelper provides utilities for testing middleware functions

func NewMiddlewareTestHelper

func NewMiddlewareTestHelper() *MiddlewareTestHelper

NewMiddlewareTestHelper creates a new middleware test helper with a clean router

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

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

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"
	// Explicit reports whether an operator actually supplied this value (env
	// var set, or key written in the YAML file) rather than it being the
	// struct default. The settings service uses it to decide whether a
	// database value may apply — see getConfigSetting (#415).
	Explicit bool
	// Class carries the setting's classification; Category distinguishes
	// bootstrap settings (never database-backed) from operational ones.
	Class config.ConfigClass
}

MigratableSetting represents a setting that can be migrated from config to 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
}

func (*MockDiagramStore) Count

func (m *MockDiagramStore) Count() int

func (*MockDiagramStore) Create

func (m *MockDiagramStore) Create(item DfdDiagram, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)

func (*MockDiagramStore) CreateWithThreatModel

func (m *MockDiagramStore) CreateWithThreatModel(item DfdDiagram, threatModelID string, idSetter func(DfdDiagram, string) DfdDiagram) (DfdDiagram, error)

func (*MockDiagramStore) Delete

func (m *MockDiagramStore) Delete(id string) error

func (*MockDiagramStore) Get

func (m *MockDiagramStore) Get(id string) (DfdDiagram, error)

func (*MockDiagramStore) GetBatch

func (m *MockDiagramStore) GetBatch(ids []string) ([]DfdDiagram, error)

func (*MockDiagramStore) GetIncludingDeleted

func (m *MockDiagramStore) GetIncludingDeleted(id string) (DfdDiagram, error)

func (*MockDiagramStore) GetThreatModelID

func (m *MockDiagramStore) GetThreatModelID(diagramID string) (string, error)

func (*MockDiagramStore) HardDelete

func (m *MockDiagramStore) HardDelete(id string) error

func (*MockDiagramStore) List

func (m *MockDiagramStore) List(offset, limit int, filter func(DfdDiagram) bool) []DfdDiagram

func (*MockDiagramStore) Restore

func (m *MockDiagramStore) Restore(id string) error

func (*MockDiagramStore) SoftDelete

func (m *MockDiagramStore) SoftDelete(_ context.Context, id string) error

func (*MockDiagramStore) Update

func (m *MockDiagramStore) Update(_ context.Context, id string, item DfdDiagram) error

type MockThreatModelStore

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

Simple mock stores for unit tests

func (*MockThreatModelStore) Count

func (m *MockThreatModelStore) Count() int

func (*MockThreatModelStore) Create

func (*MockThreatModelStore) Delete

func (m *MockThreatModelStore) Delete(id string) error

func (*MockThreatModelStore) Get

func (*MockThreatModelStore) GetAuthorization

func (m *MockThreatModelStore) GetAuthorization(id string) ([]Authorization, User, error)

func (*MockThreatModelStore) GetAuthorizationIncludingDeleted

func (m *MockThreatModelStore) GetAuthorizationIncludingDeleted(id string) ([]Authorization, User, error)

func (*MockThreatModelStore) GetIncludingDeleted

func (m *MockThreatModelStore) GetIncludingDeleted(id string) (ThreatModel, error)

func (*MockThreatModelStore) HardDelete

func (m *MockThreatModelStore) HardDelete(id string) error

func (*MockThreatModelStore) ListWithCounts

func (m *MockThreatModelStore) ListWithCounts(offset, limit int, filter func(ThreatModel) bool, filters *ThreatModelFilters) ([]TMListItem, int, error)

func (*MockThreatModelStore) Restore

func (m *MockThreatModelStore) Restore(id string) error

func (*MockThreatModelStore) SoftDelete

func (m *MockThreatModelStore) SoftDelete(_ context.Context, id string) error

func (*MockThreatModelStore) Update

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 *CellData `json:"data,omitempty"`

	// Height Height in pixels (flat format)
	Height *float32 `json:"height,omitempty"`

	// Id Unique identifier of the cell (UUID)
	Id CellId `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 Diagram node representing a process, data store, external entity, or trust boundary

Supports both X6 position/size object format and flat x/y/width/height format. Input accepts either format. Output always uses flat format (x, y, width, height).

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.

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.

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 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 applies operations to the stored note, then calls check (when
	// non-nil) with the stored and patched notes before persisting; check may
	// rewrite the patched note, and an error from it aborts the patch.
	Patch(ctx context.Context, id string, operations []PatchOperation, check func(before, after *Note) error) (*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

var GlobalNoteRepository NoteRepository

type NoteSubResourceHandler

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

NoteSubResourceHandler provides handlers for note sub-resource operations

func NewNoteSubResourceHandler

func NewNoteSubResourceHandler(noteStore NoteRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *NoteSubResourceHandler

NewNoteSubResourceHandler creates a new note sub-resource handler

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

func (*NoteSubResourceHandler) DeleteNote

func (h *NoteSubResourceHandler) DeleteNote(c *gin.Context)

DeleteNote deletes a note DELETE /threat_models/{threat_model_id}/notes/{note_id}

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}

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

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}

func (*NoteSubResourceHandler) UpdateNote

func (h *NoteSubResourceHandler) UpdateNote(c *gin.Context)

UpdateNote updates an existing note PUT /threat_models/{threat_model_id}/notes/{note_id}

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

	// Identity and group claims used to authorize delivery of threat model scoped events
	User   ResolvedUser
	Groups []string

	// Hub reference
	Hub *NotificationHub

	// Connection metadata
	ConnectedAt time.Time
}

NotificationClient represents a client connected to the notification hub

type NotificationHub

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

NotificationHub manages all notification WebSocket connections

func GetNotificationHub

func GetNotificationHub() *NotificationHub

GetNotificationHub returns the global notification hub instance

func NewNotificationHub

func NewNotificationHub() *NotificationHub

NewNotificationHub creates a new notification hub

func (*NotificationHub) BroadcastCollaborationEvent

func (h *NotificationHub) BroadcastCollaborationEvent(eventType NotificationMessageType, userID, diagramID, diagramName string, tm ThreatModel, sessionID string)

BroadcastCollaborationEvent broadcasts a collaboration event to clients with read access to the threat model

func (*NotificationHub) BroadcastSystemNotification

func (h *NotificationHub) BroadcastSystemNotification(severity, message string, actionRequired bool, actionURL string)

BroadcastSystemNotification broadcasts a system notification to all connected clients

func (*NotificationHub) BroadcastThreatModelEvent

func (h *NotificationHub) BroadcastThreatModelEvent(eventType NotificationMessageType, userID string, tm ThreatModel, action string)

BroadcastThreatModelEvent broadcasts a threat model event to clients with read access to it

func (*NotificationHub) GetConnectedUsers

func (h *NotificationHub) GetConnectedUsers() []string

GetConnectedUsers returns a list of currently connected user IDs

func (*NotificationHub) GetConnectionCount

func (h *NotificationHub) GetConnectionCount() int

GetConnectionCount returns the total number of active connections

func (*NotificationHub) Run

func (h *NotificationHub) Run()

Run starts the notification hub

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
	// contains filtered or unexported fields
}

NotificationMessage is the base structure for all notification messages

type NotificationMessageType

type NotificationMessageType string

NotificationMessageType represents the type of notification message

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

type OAuthConflict added in v1.21.0

type OAuthConflict = OAuthError

OAuthConflict Error response for OAuth, SAML and discovery routes

type OAuthError added in v1.21.0

type OAuthError 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 for OAuth, SAML and discovery routes: the RFC 6749, 7009 and 9470 codes, the documented TMI extensions (identity_mismatch, account_conflict, email_not_verified, provider_unreachable, provider_response_invalid, invalid_provider), and the transport codes that route-agnostic middleware can emit (unauthorized, not_found, method_not_allowed, not_acceptable, payload_too_large, unsupported_media_type, rate_limit_exceeded, server_error). SAML routes also use the TMI extension codes saml_error, saml_not_enabled, saml_unavailable, saml_provider_not_found, saml_metadata_error, saml_init_error, saml_invalid_logout_request and saml_logout_error.
	Error OAuthErrorError `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"`
}

OAuthError Error response for OAuth, SAML and discovery routes

type OAuthErrorError added in v1.21.0

type OAuthErrorError string

OAuthErrorError Error code for OAuth, SAML and discovery routes: the RFC 6749, 7009 and 9470 codes, the documented TMI extensions (identity_mismatch, account_conflict, email_not_verified, provider_unreachable, provider_response_invalid, invalid_provider), and the transport codes that route-agnostic middleware can emit (unauthorized, not_found, method_not_allowed, not_acceptable, payload_too_large, unsupported_media_type, rate_limit_exceeded, server_error). SAML routes also use the TMI extension codes saml_error, saml_not_enabled, saml_unavailable, saml_provider_not_found, saml_metadata_error, saml_init_error, saml_invalid_logout_request and saml_logout_error.

const (
	OAuthErrorErrorAccessDenied                   OAuthErrorError = "access_denied"
	OAuthErrorErrorAccountConflict                OAuthErrorError = "account_conflict"
	OAuthErrorErrorEmailNotVerified               OAuthErrorError = "email_not_verified"
	OAuthErrorErrorIdentityMismatch               OAuthErrorError = "identity_mismatch"
	OAuthErrorErrorInsufficientUserAuthentication OAuthErrorError = "insufficient_user_authentication"
	OAuthErrorErrorInvalidClient                  OAuthErrorError = "invalid_client"
	OAuthErrorErrorInvalidGrant                   OAuthErrorError = "invalid_grant"
	OAuthErrorErrorInvalidProvider                OAuthErrorError = "invalid_provider"
	OAuthErrorErrorInvalidRequest                 OAuthErrorError = "invalid_request"
	OAuthErrorErrorInvalidScope                   OAuthErrorError = "invalid_scope"
	OAuthErrorErrorMethodNotAllowed               OAuthErrorError = "method_not_allowed"
	OAuthErrorErrorNotAcceptable                  OAuthErrorError = "not_acceptable"
	OAuthErrorErrorNotFound                       OAuthErrorError = "not_found"
	OAuthErrorErrorPayloadTooLarge                OAuthErrorError = "payload_too_large"
	OAuthErrorErrorProviderResponseInvalid        OAuthErrorError = "provider_response_invalid"
	OAuthErrorErrorProviderUnreachable            OAuthErrorError = "provider_unreachable"
	OAuthErrorErrorRateLimitExceeded              OAuthErrorError = "rate_limit_exceeded"
	OAuthErrorErrorSamlError                      OAuthErrorError = "saml_error"
	OAuthErrorErrorSamlInitError                  OAuthErrorError = "saml_init_error"
	OAuthErrorErrorSamlInvalidLogoutRequest       OAuthErrorError = "saml_invalid_logout_request"
	OAuthErrorErrorSamlLogoutError                OAuthErrorError = "saml_logout_error"
	OAuthErrorErrorSamlMetadataError              OAuthErrorError = "saml_metadata_error"
	OAuthErrorErrorSamlNotEnabled                 OAuthErrorError = "saml_not_enabled"
	OAuthErrorErrorSamlProviderNotFound           OAuthErrorError = "saml_provider_not_found"
	OAuthErrorErrorSamlUnavailable                OAuthErrorError = "saml_unavailable"
	OAuthErrorErrorServerError                    OAuthErrorError = "server_error"
	OAuthErrorErrorTemporarilyUnavailable         OAuthErrorError = "temporarily_unavailable"
	OAuthErrorErrorUnauthorized                   OAuthErrorError = "unauthorized"
	OAuthErrorErrorUnauthorizedClient             OAuthErrorError = "unauthorized_client"
	OAuthErrorErrorUnsupportedGrantType           OAuthErrorError = "unsupported_grant_type"
	OAuthErrorErrorUnsupportedMediaType           OAuthErrorError = "unsupported_media_type"
	OAuthErrorErrorUnsupportedResponseType        OAuthErrorError = "unsupported_response_type"
	OAuthErrorErrorUnsupportedTokenType           OAuthErrorError = "unsupported_token_type"
)

Defines values for OAuthErrorError.

func (OAuthErrorError) Valid added in v1.21.0

func (e OAuthErrorError) Valid() bool

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

type OAuthErrorResponse added in v1.21.0

type OAuthErrorResponse = OAuthError

OAuthErrorResponse Error response for OAuth, SAML and discovery routes

type OAuthForbidden added in v1.21.0

type OAuthForbidden = OAuthError

OAuthForbidden Error response for OAuth, SAML and discovery routes

type OAuthInternalServerError added in v1.21.0

type OAuthInternalServerError = OAuthError

OAuthInternalServerError Error response for OAuth, SAML and discovery routes

type OAuthMethodNotAllowed added in v1.21.0

type OAuthMethodNotAllowed = OAuthError

OAuthMethodNotAllowed Error response for OAuth, SAML and discovery routes

type OAuthNotAcceptable added in v1.21.0

type OAuthNotAcceptable = OAuthError

OAuthNotAcceptable Error response for OAuth, SAML and discovery routes

type OAuthNotFound added in v1.21.0

type OAuthNotFound = OAuthError

OAuthNotFound Error response for OAuth, SAML and discovery routes

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 OAuthServiceUnavailable added in v1.21.0

type OAuthServiceUnavailable = OAuthError

OAuthServiceUnavailable Error response for OAuth, SAML and discovery routes

type OAuthTooManyRequests added in v1.21.0

type OAuthTooManyRequests = OAuthError

OAuthTooManyRequests Error response for OAuth, SAML and discovery routes

type OAuthUnauthorized added in v1.21.0

type OAuthUnauthorized = OAuthError

OAuthUnauthorized Error response for OAuth, SAML and discovery routes

type OAuthUnsupportedMediaType added in v1.21.0

type OAuthUnsupportedMediaType = OAuthError

OAuthUnsupportedMediaType Error response for OAuth, SAML and discovery routes

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

func NewOperationHistory

func NewOperationHistory() *OperationHistory

NewOperationHistory creates a new operation history

func (*OperationHistory) AddOperation

func (h *OperationHistory) AddOperation(entry *HistoryEntry)

AddOperation adds a new operation to history and updates current position

func (*OperationHistory) CanRedo

func (h *OperationHistory) CanRedo() bool

CanRedo returns true if there are operations to redo

func (*OperationHistory) CanUndo

func (h *OperationHistory) CanUndo() bool

CanUndo returns true if there are operations to undo

func (*OperationHistory) GetRedoOperation

func (h *OperationHistory) GetRedoOperation() (*HistoryEntry, bool)

GetRedoOperation returns the operation to redo

func (*OperationHistory) GetUndoOperation

func (h *OperationHistory) GetUndoOperation() (*HistoryEntry, map[string]*DfdDiagram_Cells_Item, bool)

GetUndoOperation returns the operation to undo and the previous state

func (*OperationHistory) MoveToPosition

func (h *OperationHistory) MoveToPosition(newPosition uint64)

MoveToPosition updates the current position in history (for undo/redo)

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

func (OperationRejectedMessage) GetMessageType

func (m OperationRejectedMessage) GetMessageType() MessageType

func (OperationRejectedMessage) Validate

func (m OperationRejectedMessage) Validate() error

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

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

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.

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

func NewOwnershipTransferHandler

func NewOwnershipTransferHandler(authService *auth.Service) *OwnershipTransferHandler

NewOwnershipTransferHandler creates a new ownership transfer handler

func (*OwnershipTransferHandler) TransferAdminUserOwnership

func (h *OwnershipTransferHandler) TransferAdminUserOwnership(c *gin.Context, internalUuid openapi_types.UUID)

TransferAdminUserOwnership handles POST /admin/users/{user_id}/transfer

func (*OwnershipTransferHandler) TransferCurrentUserOwnership

func (h *OwnershipTransferHandler) TransferCurrentUserOwnership(c *gin.Context)

TransferCurrentUserOwnership handles POST /me/transfer

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.

func NewPDFEmbeddingSource

func NewPDFEmbeddingSource(ssrfValidator *URIValidator) *PDFEmbeddingSource

NewPDFEmbeddingSource creates a new PDFEmbeddingSource with the given SSRF validator.

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).

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.

func (*PDFEmbeddingSource) Name

func (p *PDFEmbeddingSource) Name() string

Name returns the provider name for logging.

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.

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.

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.

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

func (ParticipantsUpdateMessage) GetMessageType

func (m ParticipantsUpdateMessage) GetMessageType() MessageType

func (ParticipantsUpdateMessage) Validate

func (m ParticipantsUpdateMessage) Validate() error

type PatchAddonApplicationJSONPatchPlusJSONRequestBody

type PatchAddonApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchAddonApplicationJSONPatchPlusJSONRequestBody defines body for PatchAddon for application/json-patch+json ContentType.

type PatchAdminSurveyApplicationJSONPatchPlusJSONRequestBody

type PatchAdminSurveyApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchAdminSurveyApplicationJSONPatchPlusJSONRequestBody defines body for PatchAdminSurvey for application/json-patch+json ContentType.

type PatchAdminWebhookSubscriptionApplicationJSONPatchPlusJSONRequestBody

type PatchAdminWebhookSubscriptionApplicationJSONPatchPlusJSONRequestBody = JsonPatchDocument

PatchAdminWebhookSubscriptionApplicationJSONPatchPlusJSONRequestBody defines body for PatchAdminWebhookSubscription 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.

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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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

func ParsePatchRequest

func ParsePatchRequest(c *gin.Context) ([]PatchOperation, error)

ParsePatchRequest parses JSON Patch operations from the request body

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).

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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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).

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.

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.

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.

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.

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.

func NewPipelineEmbeddingSource

func NewPipelineEmbeddingSource(pipeline *ContentPipeline) *PipelineEmbeddingSource

NewPipelineEmbeddingSource creates an adapter.

func (*PipelineEmbeddingSource) CanHandle

CanHandle returns true for entity references with a URI.

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.

func (*PipelineEmbeddingSource) Name

func (p *PipelineEmbeddingSource) Name() string

Name returns the adapter name.

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.

func DefaultPipelineLimits

func DefaultPipelineLimits() PipelineLimits

DefaultPipelineLimits returns the design-spec default budget; used by tests.

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

func (*PresenterCursorHandler) HandleMessage

func (h *PresenterCursorHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*PresenterCursorHandler) MessageType

func (h *PresenterCursorHandler) MessageType() string

type PresenterCursorMessage

type PresenterCursorMessage struct {
	MessageType    MessageType    `json:"message_type"`
	CursorPosition CursorPosition `json:"cursor_position"`
}

func (PresenterCursorMessage) GetMessageType

func (m PresenterCursorMessage) GetMessageType() MessageType

func (PresenterCursorMessage) Validate

func (m PresenterCursorMessage) Validate() error

type PresenterDeniedEvent

type PresenterDeniedEvent struct {
	MessageType MessageType `json:"message_type"`
	DeniedUser  User        `json:"denied_user"`
}

PresenterDeniedEvent is sent by server to the denied user

func (PresenterDeniedEvent) GetMessageType

func (m PresenterDeniedEvent) GetMessageType() MessageType

func (PresenterDeniedEvent) Validate

func (m PresenterDeniedEvent) Validate() error

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

func (PresenterDeniedRequest) GetMessageType

func (m PresenterDeniedRequest) GetMessageType() MessageType

func (PresenterDeniedRequest) Validate

func (m PresenterDeniedRequest) Validate() error

type PresenterDeniedRequestHandler

type PresenterDeniedRequestHandler struct{}

PresenterDeniedRequestHandler handles presenter denied request messages from host

func (*PresenterDeniedRequestHandler) HandleMessage

func (h *PresenterDeniedRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*PresenterDeniedRequestHandler) MessageType

func (h *PresenterDeniedRequestHandler) MessageType() string

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

func (PresenterRequestEvent) GetMessageType

func (m PresenterRequestEvent) GetMessageType() MessageType

func (PresenterRequestEvent) Validate

func (m PresenterRequestEvent) Validate() error

type PresenterRequestHandler

type PresenterRequestHandler struct{}

PresenterRequestHandler handles presenter request messages

func (*PresenterRequestHandler) HandleMessage

func (h *PresenterRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*PresenterRequestHandler) MessageType

func (h *PresenterRequestHandler) MessageType() string

type PresenterRequestMessage

type PresenterRequestMessage struct {
	MessageType MessageType `json:"message_type"`
}

func (PresenterRequestMessage) GetMessageType

func (m PresenterRequestMessage) GetMessageType() MessageType

func (PresenterRequestMessage) Validate

func (m PresenterRequestMessage) Validate() error

type PresenterSelectionHandler

type PresenterSelectionHandler struct{}

PresenterSelectionHandler handles presenter selection messages

func (*PresenterSelectionHandler) HandleMessage

func (h *PresenterSelectionHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*PresenterSelectionHandler) MessageType

func (h *PresenterSelectionHandler) MessageType() string

type PresenterSelectionMessage

type PresenterSelectionMessage struct {
	MessageType   MessageType `json:"message_type"`
	SelectedCells []string    `json:"selected_cells"`
}

func (PresenterSelectionMessage) GetMessageType

func (m PresenterSelectionMessage) GetMessageType() MessageType

func (PresenterSelectionMessage) Validate

func (m PresenterSelectionMessage) Validate() error

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 (resolved on read)
	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 *TeamSummary `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"`

	// 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

type ProjectInput

type ProjectInput 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 *[]ResponsiblePartyInput `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"`
}

ProjectInput defines model for ProjectInput.

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 applies operations to the stored note, then calls check (when
	// non-nil) with the stored and patched notes before persisting; check may
	// rewrite the patched note, and an error from it aborts the patch.
	Patch(ctx context.Context, id string, operations []PatchOperation, check func(before, after *ProjectNote) error) (*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

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

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.

func NewProviderSettingsReaderAdapter

func NewProviderSettingsReaderAdapter(settings SettingsServiceInterface) *ProviderSettingsReaderAdapter

NewProviderSettingsReaderAdapter creates a new adapter.

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.

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.

type QuotaCache

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

QuotaCache provides in-memory caching for quota lookups with TTL

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

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

func (*QuotaCache) GetWebhookQuota

func (c *QuotaCache) GetWebhookQuota(ctx context.Context, userID string, store WebhookQuotaStoreInterface) DBWebhookQuota

GetWebhookQuota retrieves a webhook quota from cache or store

func (*QuotaCache) InvalidateAll

func (c *QuotaCache) InvalidateAll()

InvalidateAll clears all cached quotas

func (*QuotaCache) InvalidateUserAPIQuota

func (c *QuotaCache) InvalidateUserAPIQuota(userID string)

InvalidateUserAPIQuota removes a user API quota from cache

func (*QuotaCache) InvalidateWebhookQuota

func (c *QuotaCache) InvalidateWebhookQuota(userID string)

InvalidateWebhookQuota removes a webhook quota from cache

func (*QuotaCache) Stop

func (c *QuotaCache) Stop()

Stop stops the cleanup goroutine

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

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).

func NewRedactor

func NewRedactor() Redactor

NewRedactor returns a Redactor configured with the deny-list from #355's design spec.

type RedisTicketStore

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

RedisTicketStore implements TicketStore using Redis with atomic GETDEL for single-use semantics.

func NewRedisTicketStore

func NewRedisTicketStore(redis *db.RedisDB) *RedisTicketStore

NewRedisTicketStore creates a new Redis-backed ticket store.

func (*RedisTicketStore) IssueTicket

func (s *RedisTicketStore) IssueTicket(ctx context.Context, claims TicketClaims, ttl time.Duration) (string, error)

IssueTicket creates a cryptographically random ticket and stores it in Redis with the given TTL.

func (*RedisTicketStore) ValidateTicket

func (s *RedisTicketStore) ValidateTicket(ctx context.Context, ticket string) (TicketClaims, error)

ValidateTicket atomically retrieves and deletes a ticket from Redis (single-use), returning its bound claims.

type RedoRequestHandler

type RedoRequestHandler struct{}

RedoRequestHandler handles redo request messages

func (*RedoRequestHandler) HandleMessage

func (h *RedoRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*RedoRequestHandler) MessageType

func (h *RedoRequestHandler) MessageType() string

type RedoRequestMessage

type RedoRequestMessage struct {
	MessageType    MessageType `json:"message_type"`
	InitiatingUser User        `json:"initiating_user"`
}

func (RedoRequestMessage) GetMessageType

func (m RedoRequestMessage) GetMessageType() MessageType

func (RedoRequestMessage) Validate

func (m RedoRequestMessage) Validate() error

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"`
}

func (RemoveParticipantMessage) GetMessageType

func (m RemoveParticipantMessage) GetMessageType() MessageType

func (RemoveParticipantMessage) Validate

func (m RemoveParticipantMessage) Validate() error

type RemoveParticipantRequest

type RemoveParticipantRequest struct {
	MessageType MessageType `json:"message_type"`
	RemovedUser User        `json:"removed_user"`
}

RemoveParticipantRequest is sent by client to remove a participant

func (RemoveParticipantRequest) GetMessageType

func (m RemoveParticipantRequest) GetMessageType() MessageType

func (RemoveParticipantRequest) Validate

func (m RemoveParticipantRequest) Validate() error

type RemoveParticipantRequestHandler

type RemoveParticipantRequestHandler struct{}

RemoveParticipantRequestHandler handles remove participant request messages

func (*RemoveParticipantRequestHandler) HandleMessage

func (h *RemoveParticipantRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*RemoveParticipantRequestHandler) MessageType

func (h *RemoveParticipantRequestHandler) MessageType() string

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

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"
	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 RepositoryBulkUpdateItem

type RepositoryBulkUpdateItem struct {
	// Description Description of the referenced source code
	Description *string `json:"description,omitempty"`

	// Id Unique identifier of the repository 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"`

	// Name Name for the source code reference
	Name *string `json:"name"`

	// Parameters repo-specific parameters for retrieving the source
	Parameters *struct {
		// RefType Reference type (branch, tag, or commit)
		RefType RepositoryBulkUpdateItemParametersRefType `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 *RepositoryBulkUpdateItemType `json:"type,omitempty"`

	// Uri URL to retrieve the referenced source code
	Uri string `json:"uri"`
}

RepositoryBulkUpdateItem defines model for RepositoryBulkUpdateItem.

type RepositoryBulkUpdateItemParametersRefType

type RepositoryBulkUpdateItemParametersRefType string

RepositoryBulkUpdateItemParametersRefType Reference type (branch, tag, or commit)

Defines values for RepositoryBulkUpdateItemParametersRefType.

func (RepositoryBulkUpdateItemParametersRefType) Valid

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

type RepositoryBulkUpdateItemType

type RepositoryBulkUpdateItemType string

RepositoryBulkUpdateItemType Source code repository type

const (
	RepositoryBulkUpdateItemTypeGit       RepositoryBulkUpdateItemType = "git"
	RepositoryBulkUpdateItemTypeMercurial RepositoryBulkUpdateItemType = "mercurial"
	RepositoryBulkUpdateItemTypeOther     RepositoryBulkUpdateItemType = "other"
	RepositoryBulkUpdateItemTypeSvn       RepositoryBulkUpdateItemType = "svn"
)

Defines values for RepositoryBulkUpdateItemType.

func (RepositoryBulkUpdateItemType) Valid

Valid indicates whether the value is a known member of the RepositoryBulkUpdateItemType 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.)

var GlobalRepositoryRepository RepositoryRepository

type RepositorySubResourceHandler

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

RepositorySubResourceHandler provides handlers for repository code sub-resource operations

func NewRepositorySubResourceHandler

func NewRepositorySubResourceHandler(repositoryStore RepositoryRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *RepositorySubResourceHandler

NewRepositorySubResourceHandler creates a new repository code sub-resource handler

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

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

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

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}

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}

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

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}

func (*RepositorySubResourceHandler) SetRepositoryURIValidator

func (h *RepositorySubResourceHandler) SetRepositoryURIValidator(v *URIValidator)

SetRepositoryURIValidator sets the URI validator for repository uri fields

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}

type RepositoryType

type RepositoryType string

RepositoryType Source code repository type

const (
	RepositoryTypeGit       RepositoryType = "git"
	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    errcode.Code
	Message string
	Details *ErrorDetails
	// contains filtered or unexported fields
}

RequestError represents an error that should be returned as an HTTP response

func ConflictError

func ConflictError(message string) *RequestError

ConflictError creates a RequestError for resource conflicts

func ForbiddenError

func ForbiddenError(message string) *RequestError

ForbiddenError creates a RequestError for forbidden access

func GoneError

func GoneError(message string) *RequestError

GoneError creates a RequestError for a permanently removed resource

func IfMatchRequiredError added in v1.21.0

func IfMatchRequiredError(message string) *RequestError

IfMatchRequiredError creates a RequestError for a missing If-Match header

func InsufficientUserAuthenticationError added in v1.21.0

func InsufficientUserAuthenticationError(message string) *RequestError

InsufficientUserAuthenticationError creates a RequestError requiring step-up authentication

func InvalidIDError

func InvalidIDError(message string) *RequestError

InvalidIDError creates a RequestError for invalid ID formats

func InvalidInputError

func InvalidInputError(message string) *RequestError

InvalidInputError creates a RequestError for validation failures

func InvalidInputErrorWithDetails

func InvalidInputErrorWithDetails(message string, code errcode.Code, context map[string]any, suggestion string) *RequestError

InvalidInputErrorWithDetails creates a RequestError for validation failures with additional context

func InvalidPatchError added in v1.21.0

func InvalidPatchError(message string) *RequestError

InvalidPatchError creates a RequestError for a malformed or inapplicable JSON Patch

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.

func MethodNotAllowedError added in v1.21.0

func MethodNotAllowedError(message string) *RequestError

MethodNotAllowedError creates a RequestError for an unsupported HTTP method

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).

func NotFoundError

func NotFoundError(message string) *RequestError

NotFoundError creates a RequestError for resource not found

func NotFoundErrorWithDetails

func NotFoundErrorWithDetails(message string, code errcode.Code, context map[string]any, suggestion string) *RequestError

NotFoundErrorWithDetails creates a RequestError for resource not found with additional context

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.

func PayloadTooLargeError

func PayloadTooLargeError(message string) *RequestError

PayloadTooLargeError creates a RequestError for an oversized request body

func QuotaExceededError added in v1.21.0

func QuotaExceededError(status int, message string) *RequestError

QuotaExceededError creates a RequestError for a hard cap (status 403 or 429)

func RateLimitExceededError added in v1.21.0

func RateLimitExceededError(message string, retryAfterSeconds int) *RequestError

RateLimitExceededError creates a 429 RequestError; retryAfterSeconds feeds the Retry-After header

func SanitizeRequiredMarkdownContent

func SanitizeRequiredMarkdownContent(field, content string) (string, *RequestError)

SanitizeRequiredMarkdownContent sanitizes a markdown field the schema declares required with minLength 1, and reports a 400 when sanitization emptied it.

The schema's own `pattern` for these fields only excludes control characters, so a body like `{"content": "<script>alert(1)</script>"}` passes OpenAPI validation, reaches the handler, and is then reduced to "" by the policy. Every caller previously handed that empty string straight to its store, whose non-empty check failed and surfaced as a 500 — a client input problem reported as a server fault, and a Zero-500 policy violation (#605). (The sibling `name` field is unaffected because its pattern already rejects `<` and `>` at the validation layer.)

This lives here rather than in each handler so the create, update and patch paths across all four note resources cannot drift on it — the update paths had no such check at all and silently persisted the empty value.

func ServerError

func ServerError(message string) *RequestError

ServerError creates a RequestError for internal server errors

func ServerErrorWithDetails

func ServerErrorWithDetails(message string, code errcode.Code, context map[string]any, suggestion string) *RequestError

ServerErrorWithDetails creates a RequestError for internal server errors with additional context

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.

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).

func UnauthorizedError

func UnauthorizedError(message string) *RequestError

func UnprocessableEntityError added in v1.21.0

func UnprocessableEntityError(message string) *RequestError

UnprocessableEntityError creates a RequestError for a well-formed request that cannot be processed

func UnsupportedMediaTypeError added in v1.21.0

func UnsupportedMediaTypeError(message string) *RequestError

UnsupportedMediaTypeError creates a RequestError for an unaccepted Content-Type

func ValidatePaginationParams

func ValidatePaginationParams(limit, offset *int) *RequestError

ValidatePaginationParams validates limit and offset parameters Returns a RequestError if validation fails, nil otherwise

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.

func ValidatePatchOperationPaths added in v1.21.15

func ValidatePatchOperationPaths(operations []PatchOperation) *RequestError

ValidatePatchOperationPaths rejects whole-document JSON Patch operations: a root path ("") or any path or move/copy "from" that is not a JSON Pointer starting with "/". Exact-path checks on prohibited fields cannot see a root-path operation, so every PATCH handler must reject them up front.

func ValidatePatchPathsAllowed

func ValidatePatchPathsAllowed(allowed []string, ops []PatchOperation) *RequestError

ValidatePatchPathsAllowed rejects any operation whose path is not equal to, or a child of, one of the allowed JSON Pointer prefixes. It is the role-free variant of ValidatePatchAllowlist, for resources whose mutable field set does not vary by caller role. Returns nil when every operation is permitted, otherwise a 400 invalid_patch error naming the offending field.

func ValidatePatchProhibitedPaths

func ValidatePatchProhibitedPaths(operations []PatchOperation) *RequestError

ValidatePatchProhibitedPaths rejects any PATCH operation that targets a server-managed (read-only) path, or moves/copies from one. Returns a *RequestError with HTTP 400 on the first prohibited path found, or nil when all paths are allowed.

func WithDetailCode added in v1.21.0

func WithDetailCode(err *RequestError, code errcode.Code) *RequestError

WithDetailCode attaches a domain-specific details.code reason to err and returns it.

func WithDetailContext added in v1.21.19

func WithDetailContext(err *RequestError, key string, value any) *RequestError

WithDetailContext adds one key/value to err's details.context and returns it.

func WriteErrorToRequestError

func WriteErrorToRequestError(err error, serverErrorMsg string) *RequestError

WriteErrorToRequestError maps the error from a store write that has no domain-specific outcome (create/update/delete fallbacks) to the response. It only distinguishes the transient class: a serialization failure that exhausted its retries (ORA-08177, SQLSTATE 40001), a deadlock, or an ADB connection drop is a documented 503 with Retry-After, not a server bug, so the client can retry instead of reporting a 500 (#900). Every operation documents 503 (#665), so this is safe at any handler's fallback branch. A GORM BeforeSave hook rejection is the caller's bad input, so it is a 400, as in StoreErrorToRequestError (#921).

func (*RequestError) Error

func (e *RequestError) Error() string

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.

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.

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.

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.

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.

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.

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.

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.

func ResolvedUserFromWebSocketClient

func ResolvedUserFromWebSocketClient(client *WebSocketClient) ResolvedUser

ResolvedUserFromWebSocketClient creates a ResolvedUser from a WebSocketClient.

func (ResolvedUser) IsEmpty

func (u ResolvedUser) IsEmpty() bool

IsEmpty returns true if the ResolvedUser has no identity fields set.

func (ResolvedUser) ToPrincipal

func (u ResolvedUser) ToPrincipal() Principal

ToPrincipal converts a ResolvedUser to the API Principal type for wire format serialization.

func (ResolvedUser) ToUser

func (u ResolvedUser) ToUser() User

ToUser converts a ResolvedUser to the API User type for wire format serialization.

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 ResponsiblePartyInput

type ResponsiblePartyInput 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"`

	// UserId UUID of the responsible party user
	UserId openapi_types.UUID `json:"user_id"`
}

ResponsiblePartyInput Client-writable fields of ResponsibleParty (excludes the server-resolved user).

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.

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.

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.

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).

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.

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.

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.

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).

func NewRuntimeConfigReaderAdapter

func NewRuntimeConfigReaderAdapter(settings SettingsServiceInterface) *RuntimeConfigReaderAdapter

NewRuntimeConfigReaderAdapter constructs an adapter over the given SettingsService.

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.

The read goes through GetResolvedString, which applies the converged precedence rule (#794). It used to be database-only, because for #419 runtime keys the DB row must win over the YAML — and reading through GetString would have inverted that, since its env/config-file priority shadows the DB row whenever the YAML also carries the key (#767). GetResolvedString keeps that property for any row an operator actually set, while letting an explicit config value beat a merely-seeded default.

func (*RuntimeConfigReaderAdapter) GetOAuthCallbackURL

func (a *RuntimeConfigReaderAdapter) GetOAuthCallbackURL(ctx context.Context) string

GetOAuthCallbackURL reads auth.oauth_callback_url by the converged precedence rule (#794). An empty string is returned on error or when no layer supplies a value; the caller falls back to the YAML snapshot in h.config.OAuth.CallbackURL.

This is the key that broke production on 2026-08-20. RDS carried a registry-seeded default of http://localhost:8080/oauth2/callback, the database-only read let it outrank a correctly-set TMI_OAUTH_CALLBACK_URL, and every provider rejected the resulting redirect_uri. Under the converged rule a seeded row loses to an explicit env value, so that specific failure cannot recur.

func (*RuntimeConfigReaderAdapter) IsEveryoneAReviewer

func (a *RuntimeConfigReaderAdapter) IsEveryoneAReviewer(ctx context.Context) bool

IsEveryoneAReviewer reads auth.everyone_is_a_reviewer by the converged precedence rule (#794). Fail-closed: any read error, missing value, or unparseable value returns false.

This key previously had no runtime reader at all — its only consumer read the config struct field directly, so the database row was display-only drift and editing it did nothing. It is the fifth and last of the keys #794 catalogued as following inconsistent precedence.

func (*RuntimeConfigReaderAdapter) IsSAMLEnabled

func (a *RuntimeConfigReaderAdapter) IsSAMLEnabled(ctx context.Context) bool

IsSAMLEnabled reads features.saml_enabled by the converged precedence rule (#794), which already consults the config layer when no row exists, so a missing value is final: one DB read per call (#770). Only a transient DB fault falls back to GetString, because that is the one case where GetResolvedString could not report the config layer's value. A read error or garbage value returns false (fail-closed).

Note that TMI_SAML_ENABLED separately gates SAML manager construction at startup (auth/service.go), so the env var stays load-bearing regardless of what this returns, and enabling SAML via the database alone still needs a restart. That asymmetry is called out in #794 and is not fixed here.

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

func NewSSEWriter

func NewSSEWriter(c *gin.Context) *SSEWriter

NewSSEWriter initializes an SSE response stream

func (*SSEWriter) Err

func (w *SSEWriter) Err() error

Err returns the first write failure, or nil while the stream is healthy.

func (*SSEWriter) IsClientGone

func (w *SSEWriter) IsClientGone() bool

IsClientGone reports whether the client can no longer receive events.

Two distinct conditions, and the second is why write errors are latched. A client that closes cleanly cancels the request context. A client whose writes fail — the server's own WriteTimeout expiring mid-stream being the case that motivated this — does NOT cancel the context: from Go's side the request is still in flight, so the context check alone reports a healthy client and the handler keeps generating LLM tokens nobody will receive. Checking the latched write error covers that.

func (*SSEWriter) SendError

func (w *SSEWriter) SendError(code, message string) error

SendError sends an error event

func (*SSEWriter) SendEvent

func (w *SSEWriter) SendEvent(event string, data any) error

SendEvent sends a named SSE event with JSON data

func (*SSEWriter) SendToken

func (w *SSEWriter) SendToken(content string) error

SendToken sends a single token event for LLM streaming

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.

type SafeFetchResult

type SafeFetchResult struct {
	StatusCode int
	Header     http.Header
	Body       []byte
	Truncated  bool
}

SafeFetchResult is returned by Fetch.

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.

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.

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.

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.

type SafeHTTPClientOption

type SafeHTTPClientOption func(*SafeHTTPClient)

SafeHTTPClientOption configures a SafeHTTPClient.

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.

func WithResolver

func WithResolver(r HostResolver) SafeHTTPClientOption

WithResolver overrides the host resolver. Used in tests to drive deterministic resolution.

func WithTransportWrapper

func WithTransportWrapper(f func(http.RoundTripper) http.RoundTripper) SafeHTTPClientOption

WithTransportWrapper registers a wrapper around the pinned transport (e.g. otelhttp.NewTransport).

func WithUserAgent

func WithUserAgent(ua string) SafeHTTPClientOption

WithUserAgent sets a default User-Agent header applied when the request has none.

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

func NewServer

func NewServer(wsLoggingConfig slogging.WebSocketLoggingConfig, inactivityTimeout time.Duration) *Server

NewServer creates a new API server instance

func NewServerForTests

func NewServerForTests() *Server

NewServerForTests creates a server with default test configuration

func (*Server) AddGroupMember

func (s *Server) AddGroupMember(c *gin.Context, internalUuid openapi_types.UUID)

AddGroupMember handles POST /admin/groups/{group_id}/members

func (*Server) AdminDeleteUserContentToken

func (s *Server) AdminDeleteUserContentToken(c *gin.Context, internalUuid openapi_types.UUID, providerId string)

AdminDeleteUserContentToken implements ServerInterface.AdminDeleteUserContentToken.

func (*Server) AdminDeleteUserIdentity

func (s *Server) AdminDeleteUserIdentity(c *gin.Context, userId openapi_types.UUID, identityId openapi_types.UUID)

AdminDeleteUserIdentity handles DELETE /admin/users/{user_id}/identities/{identity_id}. Removes a linked identity from the target user's account. The primary identity has no linked_identities row and so cannot be addressed here; unknown or foreign identity ids return 404.

func (*Server) AdminListUserContentTokens

func (s *Server) AdminListUserContentTokens(c *gin.Context, internalUuid openapi_types.UUID)

AdminListUserContentTokens implements ServerInterface.AdminListUserContentTokens.

func (*Server) AdminListUserIdentities

func (s *Server) AdminListUserIdentities(c *gin.Context, userId openapi_types.UUID)

AdminListUserIdentities handles GET /admin/users/{user_id}/identities. Returns the target user's primary identity (from the user record) and all of their linked identities.

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).

func (*Server) AuthorizeContentToken

func (s *Server) AuthorizeContentToken(c *gin.Context, providerId string)

AuthorizeContentToken implements ServerInterface.AuthorizeContentToken.

func (*Server) AuthorizeOAuthProvider

func (s *Server) AuthorizeOAuthProvider(c *gin.Context, params AuthorizeOAuthProviderParams)

AuthorizeOAuthProvider initiates OAuth flow

func (*Server) BulkCreateAdminSurveyMetadata

func (s *Server) BulkCreateAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

BulkCreateAdminSurveyMetadata bulk creates survey metadata

func (*Server) BulkCreateDiagramMetadata

func (s *Server) BulkCreateDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

BulkCreateDiagramMetadata bulk creates diagram metadata

func (*Server) BulkCreateDocumentMetadata

func (s *Server) BulkCreateDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

BulkCreateDocumentMetadata bulk creates document metadata

func (*Server) BulkCreateIntakeSurveyResponseMetadata

func (s *Server) BulkCreateIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

BulkCreateIntakeSurveyResponseMetadata bulk creates intake survey response metadata

func (*Server) BulkCreateNoteMetadata

func (s *Server) BulkCreateNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

BulkCreateNoteMetadata bulk creates note metadata

func (*Server) BulkCreateProjectMetadata

func (s *Server) BulkCreateProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

func (*Server) BulkCreateRepositoryMetadata

func (s *Server) BulkCreateRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

BulkCreateRepositoryMetadata bulk creates repository metadata

func (*Server) BulkCreateTeamMetadata

func (s *Server) BulkCreateTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

func (*Server) BulkCreateThreatMetadata

func (s *Server) BulkCreateThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

BulkCreateThreatMetadata bulk creates threat metadata

func (*Server) BulkCreateThreatModelAssetMetadata

func (s *Server) BulkCreateThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

BulkCreateThreatModelAssetMetadata bulk creates asset metadata

func (*Server) BulkCreateThreatModelAssets

func (s *Server) BulkCreateThreatModelAssets(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelAssets bulk creates assets

func (*Server) BulkCreateThreatModelDocuments

func (s *Server) BulkCreateThreatModelDocuments(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelDocuments bulk creates documents

func (*Server) BulkCreateThreatModelMetadata

func (s *Server) BulkCreateThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelMetadata bulk creates threat model metadata

func (*Server) BulkCreateThreatModelRepositories

func (s *Server) BulkCreateThreatModelRepositories(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelRepositories bulk creates repositories

func (*Server) BulkCreateThreatModelThreats

func (s *Server) BulkCreateThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID)

BulkCreateThreatModelThreats bulk creates threats

func (*Server) BulkDeleteThreatModelThreats

func (s *Server) BulkDeleteThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID, params BulkDeleteThreatModelThreatsParams)

BulkDeleteThreatModelThreats bulk deletes threats

func (*Server) BulkPatchThreatModelThreats

func (s *Server) BulkPatchThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID)

BulkPatchThreatModelThreats bulk patches threats

func (*Server) BulkReplaceAdminSurveyMetadata

func (s *Server) BulkReplaceAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

BulkReplaceAdminSurveyMetadata replaces all survey metadata (PUT)

func (*Server) BulkReplaceDiagramMetadata

func (s *Server) BulkReplaceDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

BulkReplaceDiagramMetadata replaces all diagram metadata (PUT)

func (*Server) BulkReplaceDocumentMetadata

func (s *Server) BulkReplaceDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

BulkReplaceDocumentMetadata replaces all document metadata (PUT)

func (*Server) BulkReplaceIntakeSurveyResponseMetadata

func (s *Server) BulkReplaceIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

BulkReplaceIntakeSurveyResponseMetadata replaces all survey response metadata (PUT)

func (*Server) BulkReplaceNoteMetadata

func (s *Server) BulkReplaceNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

BulkReplaceNoteMetadata replaces all note metadata (PUT)

func (*Server) BulkReplaceProjectMetadata

func (s *Server) BulkReplaceProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

func (*Server) BulkReplaceRepositoryMetadata

func (s *Server) BulkReplaceRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

BulkReplaceRepositoryMetadata replaces all repository metadata (PUT)

func (*Server) BulkReplaceTeamMetadata

func (s *Server) BulkReplaceTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

func (*Server) BulkReplaceThreatMetadata

func (s *Server) BulkReplaceThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

BulkReplaceThreatMetadata replaces all threat metadata (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)

func (*Server) BulkReplaceThreatModelMetadata

func (s *Server) BulkReplaceThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

BulkReplaceThreatModelMetadata replaces all threat model metadata (PUT)

func (*Server) BulkUpdateThreatModelThreats

func (s *Server) BulkUpdateThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpdateThreatModelThreats bulk updates threats

func (*Server) BulkUpsertAdminSurveyMetadata

func (s *Server) BulkUpsertAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

BulkUpsertAdminSurveyMetadata upserts survey metadata (PATCH)

func (*Server) BulkUpsertDiagramMetadata

func (s *Server) BulkUpsertDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

BulkUpsertDiagramMetadata upserts diagram metadata (PATCH)

func (*Server) BulkUpsertDocumentMetadata

func (s *Server) BulkUpsertDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

BulkUpsertDocumentMetadata upserts document metadata (PATCH)

func (*Server) BulkUpsertIntakeSurveyResponseMetadata

func (s *Server) BulkUpsertIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

BulkUpsertIntakeSurveyResponseMetadata upserts survey response metadata (PATCH)

func (*Server) BulkUpsertNoteMetadata

func (s *Server) BulkUpsertNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

BulkUpsertNoteMetadata upserts note metadata (PATCH)

func (*Server) BulkUpsertProjectMetadata

func (s *Server) BulkUpsertProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

func (*Server) BulkUpsertRepositoryMetadata

func (s *Server) BulkUpsertRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

BulkUpsertRepositoryMetadata upserts repository metadata (PATCH)

func (*Server) BulkUpsertTeamMetadata

func (s *Server) BulkUpsertTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

func (*Server) BulkUpsertThreatMetadata

func (s *Server) BulkUpsertThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

BulkUpsertThreatMetadata upserts threat metadata (PATCH)

func (*Server) BulkUpsertThreatModelAssetMetadata

func (s *Server) BulkUpsertThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

BulkUpsertThreatModelAssetMetadata upserts asset metadata (PATCH)

func (*Server) BulkUpsertThreatModelAssets

func (s *Server) BulkUpsertThreatModelAssets(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelAssets bulk upserts assets

func (*Server) BulkUpsertThreatModelDocuments

func (s *Server) BulkUpsertThreatModelDocuments(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelDocuments bulk upserts documents

func (*Server) BulkUpsertThreatModelMetadata

func (s *Server) BulkUpsertThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelMetadata upserts threat model metadata (PATCH)

func (*Server) BulkUpsertThreatModelRepositories

func (s *Server) BulkUpsertThreatModelRepositories(c *gin.Context, threatModelId openapi_types.UUID)

BulkUpsertThreatModelRepositories bulk upserts repositories

func (*Server) CancelWebhookDelivery

func (s *Server) CancelWebhookDelivery(c *gin.Context, deliveryId DeliveryId)

CancelWebhookDelivery cancels a delivery (JWT authenticated) (#913)

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).

func (s *Server) ConfirmIdentityLink(c *gin.Context)

ConfirmIdentityLink handles POST /me/identities/link/confirm (#383).

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.

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.

func (*Server) CreateAddon

func (s *Server) CreateAddon(c *gin.Context)

CreateAddon creates a new add-on (admin only)

func (*Server) CreateAdminGroup

func (s *Server) CreateAdminGroup(c *gin.Context)

CreateAdminGroup handles POST /admin/groups

func (*Server) CreateAdminSurvey

func (s *Server) CreateAdminSurvey(c *gin.Context)

CreateAdminSurvey creates a new survey. POST /admin/surveys

func (*Server) CreateAdminSurveyMetadata

func (s *Server) CreateAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

CreateAdminSurveyMetadata creates survey metadata

func (*Server) CreateAdminUserClientCredential

func (s *Server) CreateAdminUserClientCredential(c *gin.Context, internalUuid openapi_types.UUID)

CreateAdminUserClientCredential handles POST /admin/users/{user_id}/client_credentials

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.

func (*Server) CreateContentFeedback

func (s *Server) CreateContentFeedback(c *gin.Context, threatModelId ThreatModelId)

CreateContentFeedback creates a content feedback entry for a threat model.

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

func (*Server) CreateCurrentUserPreferences

func (s *Server) CreateCurrentUserPreferences(c *gin.Context)

CreateCurrentUserPreferences handles POST /me/preferences

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

func (*Server) CreateDiagramMetadata

func (s *Server) CreateDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

CreateDiagramMetadata creates diagram metadata

func (*Server) CreateDocumentMetadata

func (s *Server) CreateDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

CreateDocumentMetadata creates document metadata

func (*Server) CreateIntakeSurveyResponse

func (s *Server) CreateIntakeSurveyResponse(c *gin.Context)

CreateIntakeSurveyResponse creates a new survey response in draft status. POST /intake/survey_responses

func (*Server) CreateIntakeSurveyResponseMetadata

func (s *Server) CreateIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

CreateIntakeSurveyResponseMetadata creates intake survey response metadata

func (*Server) CreateNoteMetadata

func (s *Server) CreateNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

CreateNoteMetadata creates note metadata

func (*Server) CreateProject

func (s *Server) CreateProject(c *gin.Context)

CreateProject creates a new project. Requires membership in the referenced team. POST /projects

func (*Server) CreateProjectMetadata

func (s *Server) CreateProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

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

func (*Server) CreateRepositoryMetadata

func (s *Server) CreateRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

CreateRepositoryMetadata creates repository metadata

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

func (*Server) CreateTeamMetadata

func (s *Server) CreateTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

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

func (*Server) CreateThreatMetadata

func (s *Server) CreateThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

CreateThreatMetadata creates threat metadata

func (*Server) CreateThreatModel

func (s *Server) CreateThreatModel(c *gin.Context)

CreateThreatModel creates a new threat model

func (*Server) CreateThreatModelAsset

func (s *Server) CreateThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelAsset creates an asset

func (*Server) CreateThreatModelAssetMetadata

func (s *Server) CreateThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

CreateThreatModelAssetMetadata creates asset metadata

func (*Server) CreateThreatModelDiagram

func (s *Server) CreateThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelDiagram creates a new diagram

func (*Server) CreateThreatModelDocument

func (s *Server) CreateThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelDocument creates a document

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

func (*Server) CreateThreatModelMetadata

func (s *Server) CreateThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelMetadata creates threat model metadata

func (*Server) CreateThreatModelNote

func (s *Server) CreateThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelNote creates a note

func (*Server) CreateThreatModelRepository

func (s *Server) CreateThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelRepository creates a repository

func (*Server) CreateThreatModelThreat

func (s *Server) CreateThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID)

CreateThreatModelThreat creates a threat

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.

func (*Server) CreateTimmyChatSession

func (s *Server) CreateTimmyChatSession(c *gin.Context, threatModelId ThreatModelId)

CreateTimmyChatSession creates a new chat session and streams preparation progress via SSE.

func (*Server) CreateTriageSurveyResponseTriageNote

func (s *Server) CreateTriageSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId)

CreateTriageSurveyResponseTriageNote creates a triage note

func (*Server) CreateUsabilityFeedback

func (s *Server) CreateUsabilityFeedback(c *gin.Context)

CreateUsabilityFeedback creates a usability feedback entry.

func (*Server) CreateWebhookSubscription

func (s *Server) CreateWebhookSubscription(c *gin.Context)

CreateWebhookSubscription creates a new webhook subscription (admin only)

func (*Server) DeleteAddon

func (s *Server) DeleteAddon(c *gin.Context, id openapi_types.UUID)

DeleteAddon deletes an add-on (admin only)

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)

func (*Server) DeleteAdminGroup

func (s *Server) DeleteAdminGroup(c *gin.Context, internalUuid openapi_types.UUID)

DeleteAdminGroup handles DELETE /admin/groups/{group_id}

func (*Server) DeleteAdminSurvey

func (s *Server) DeleteAdminSurvey(c *gin.Context, surveyId SurveyId, params DeleteAdminSurveyParams)

DeleteAdminSurvey deletes a survey. DELETE /admin/surveys/{survey_id}

func (*Server) DeleteAdminSurveyMetadataByKey

func (s *Server) DeleteAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)

DeleteAdminSurveyMetadataByKey deletes survey metadata by key

func (*Server) DeleteAdminUser

func (s *Server) DeleteAdminUser(c *gin.Context, internalUuid openapi_types.UUID)

DeleteAdminUser handles DELETE /admin/users/{user_id}

func (*Server) DeleteAdminUserClientCredential

func (s *Server) DeleteAdminUserClientCredential(c *gin.Context, internalUuid openapi_types.UUID, credentialId openapi_types.UUID)

DeleteAdminUserClientCredential handles DELETE /admin/users/{user_id}/client_credentials/{credential_id}

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

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

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

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}

func (*Server) DeleteIntakeSurveyResponse

func (s *Server) DeleteIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)

DeleteIntakeSurveyResponse deletes a survey response. DELETE /intake/survey_responses/{response_id}

func (*Server) DeleteIntakeSurveyResponseMetadataByKey

func (s *Server) DeleteIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

DeleteIntakeSurveyResponseMetadataByKey deletes intake survey response metadata by key

func (*Server) DeleteMyContentToken

func (s *Server) DeleteMyContentToken(c *gin.Context, providerId string)

DeleteMyContentToken implements ServerInterface.DeleteMyContentToken.

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).

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

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}

func (*Server) DeleteProjectMetadata

func (s *Server) DeleteProjectMetadata(c *gin.Context, projectId openapi_types.UUID, key string)

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}

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

func (*Server) DeleteSystemSetting

func (s *Server) DeleteSystemSetting(c *gin.Context, key string)

DeleteSystemSetting deletes a system setting (admin only)

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}

func (*Server) DeleteTeamMetadata

func (s *Server) DeleteTeamMetadata(c *gin.Context, teamId openapi_types.UUID, key string)

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}

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

func (*Server) DeleteThreatModel

func (s *Server) DeleteThreatModel(c *gin.Context, threatModelId openapi_types.UUID)

DeleteThreatModel deletes a threat model

func (*Server) DeleteThreatModelAsset

func (s *Server) DeleteThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

DeleteThreatModelAsset deletes an 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

func (*Server) DeleteThreatModelDiagram

func (s *Server) DeleteThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

DeleteThreatModelDiagram deletes a diagram

func (*Server) DeleteThreatModelDocument

func (s *Server) DeleteThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

DeleteThreatModelDocument deletes a document

func (*Server) DeleteThreatModelMetadataByKey

func (s *Server) DeleteThreatModelMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, key string)

DeleteThreatModelMetadataByKey deletes threat model metadata by key

func (*Server) DeleteThreatModelNote

func (s *Server) DeleteThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

DeleteThreatModelNote deletes a note

func (*Server) DeleteThreatModelRepository

func (s *Server) DeleteThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

DeleteThreatModelRepository deletes a repository

func (*Server) DeleteThreatModelThreat

func (s *Server) DeleteThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

DeleteThreatModelThreat deletes a threat

func (*Server) DeleteTimmyChatSession

func (s *Server) DeleteTimmyChatSession(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)

DeleteTimmyChatSession soft-deletes a session.

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)

func (*Server) DeleteUserAccount

func (s *Server) DeleteUserAccount(c *gin.Context, params DeleteUserAccountParams)

DeleteUserAccount handles user account deletion (two-step 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)

func (*Server) DeleteWebhookSubscription

func (s *Server) DeleteWebhookSubscription(c *gin.Context, webhookId openapi_types.UUID)

DeleteWebhookSubscription deletes a webhook subscription (admin only)

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

func (*Server) ExchangeOAuthCode

func (s *Server) ExchangeOAuthCode(c *gin.Context, params ExchangeOAuthCodeParams)

ExchangeOAuthCode exchanges auth code for tokens

func (*Server) GetAddon

func (s *Server) GetAddon(c *gin.Context, id openapi_types.UUID)

GetAddon gets a single add-on by ID

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)

func (*Server) GetAdminGroup

func (s *Server) GetAdminGroup(c *gin.Context, internalUuid openapi_types.UUID)

GetAdminGroup handles GET /admin/groups/{group_id}

func (*Server) GetAdminSurvey

func (s *Server) GetAdminSurvey(c *gin.Context, surveyId SurveyId)

GetAdminSurvey returns a specific survey. GET /admin/surveys/{survey_id}

func (*Server) GetAdminSurveyMetadata

func (s *Server) GetAdminSurveyMetadata(c *gin.Context, surveyId SurveyId)

GetAdminSurveyMetadata gets survey metadata

func (*Server) GetAdminSurveyMetadataByKey

func (s *Server) GetAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)

GetAdminSurveyMetadataByKey gets survey metadata by key

func (*Server) GetAdminThreatModelAuditEntry

func (s *Server) GetAdminThreatModelAuditEntry(c *gin.Context, entryId openapi_types.UUID)

GetAdminThreatModelAuditEntry handles GET /admin/audit/threat_models/{entry_id} (#398).

func (*Server) GetAdminUser

func (s *Server) GetAdminUser(c *gin.Context, internalUuid openapi_types.UUID)

GetAdminUser handles GET /admin/users/{user_id}

func (*Server) GetApiInfo

func (s *Server) GetApiInfo(c *gin.Context)

GetApiInfo returns API information

func (*Server) GetAssetAuditTrail

func (s *Server) GetAssetAuditTrail(c *gin.Context, threatModelId ThreatModelId, assetId AssetId, params GetAssetAuditTrailParams)

GetAssetAuditTrail lists audit entries for a specific asset.

func (*Server) GetAuditEntry

func (s *Server) GetAuditEntry(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

GetAuditEntry returns a single audit entry.

func (*Server) GetAuthProviders

func (s *Server) GetAuthProviders(c *gin.Context)

GetAuthProviders lists OAuth providers

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.

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.

func (*Server) GetCurrentUser

func (s *Server) GetCurrentUser(c *gin.Context)

GetCurrentUser gets current user information

func (*Server) GetCurrentUserPreferences

func (s *Server) GetCurrentUserPreferences(c *gin.Context)

GetCurrentUserPreferences handles GET /me/preferences

func (*Server) GetCurrentUserProfile

func (s *Server) GetCurrentUserProfile(c *gin.Context)

GetCurrentUserProfile gets current user profile with groups and admin status (from /me endpoint)

func (*Server) GetCurrentUserSessions

func (s *Server) GetCurrentUserSessions(c *gin.Context)

GetCurrentUserSessions returns all active collaboration sessions that the user has access to

func (*Server) GetDiagramAuditTrail

func (s *Server) GetDiagramAuditTrail(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId, params GetDiagramAuditTrailParams)

GetDiagramAuditTrail lists audit entries for a specific diagram.

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

func (*Server) GetDiagramMetadata

func (s *Server) GetDiagramMetadata(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

GetDiagramMetadata gets diagram metadata

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

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

func (*Server) GetDocumentAuditTrail

func (s *Server) GetDocumentAuditTrail(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId, params GetDocumentAuditTrailParams)

GetDocumentAuditTrail lists audit entries for a specific document.

func (*Server) GetDocumentMetadata

func (s *Server) GetDocumentMetadata(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

GetDocumentMetadata gets document metadata

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

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

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}

func (*Server) GetIntakeSurveyResponse

func (s *Server) GetIntakeSurveyResponse(c *gin.Context, surveyResponseId SurveyResponseId)

GetIntakeSurveyResponse returns a specific survey response. GET /intake/survey_responses/{response_id}

func (*Server) GetIntakeSurveyResponseMetadata

func (s *Server) GetIntakeSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

GetIntakeSurveyResponseMetadata gets intake survey response metadata

func (*Server) GetIntakeSurveyResponseMetadataByKey

func (s *Server) GetIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

GetIntakeSurveyResponseMetadataByKey gets intake survey response metadata by key

func (*Server) GetIntakeSurveyResponseTriageNote

func (s *Server) GetIntakeSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId, triageNoteId TriageNoteId)

GetIntakeSurveyResponseTriageNote gets a specific triage note for submitter (read-only)

func (*Server) GetJWKS

func (s *Server) GetJWKS(c *gin.Context)

GetJWKS returns the JSON Web Key Set 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.

func (*Server) GetNoteMetadata

func (s *Server) GetNoteMetadata(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

GetNoteMetadata gets note metadata

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

func (*Server) GetOAuthAuthorizationServerMetadata

func (s *Server) GetOAuthAuthorizationServerMetadata(c *gin.Context)

GetOAuthAuthorizationServerMetadata returns OAuth 2.0 Authorization Server Metadata

func (*Server) GetOAuthProtectedResourceMetadata

func (s *Server) GetOAuthProtectedResourceMetadata(c *gin.Context)

GetOAuthProtectedResourceMetadata returns OAuth 2.0 protected resource metadata as per RFC 9728

func (*Server) GetOpenIDConfiguration

func (s *Server) GetOpenIDConfiguration(c *gin.Context)

GetOpenIDConfiguration returns OpenID Connect configuration

func (s *Server) GetPendingIdentityLink(c *gin.Context, linkId string)

GetPendingIdentityLink handles GET /me/identities/link/pending/{link_id} (#383).

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}

func (*Server) GetProjectMetadata

func (s *Server) GetProjectMetadata(c *gin.Context, projectId openapi_types.UUID)

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}

func (*Server) GetProviderGroups

func (s *Server) GetProviderGroups(c *gin.Context, idp string)

GetProviderGroups returns groups available from a specific identity provider

func (*Server) GetRepositoryAuditTrail

func (s *Server) GetRepositoryAuditTrail(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId, params GetRepositoryAuditTrailParams)

GetRepositoryAuditTrail lists audit entries for a specific repository.

func (*Server) GetRepositoryMetadata

func (s *Server) GetRepositoryMetadata(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

GetRepositoryMetadata gets repository metadata

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

func (*Server) GetSAMLMetadata

func (s *Server) GetSAMLMetadata(c *gin.Context, provider string)

GetSAMLMetadata returns SAML service provider metadata

func (*Server) GetSAMLProviders

func (s *Server) GetSAMLProviders(c *gin.Context)

GetSAMLProviders implements ServerInterface

func (*Server) GetServerInfo added in v1.21.14

func (s *Server) GetServerInfo(c *gin.Context)

GetServerInfo provides server configuration information to clients (GET /api/server-info)

func (*Server) GetSystemAuditEntry

func (s *Server) GetSystemAuditEntry(c *gin.Context, entryId openapi_types.UUID)

GetSystemAuditEntry handles GET /admin/audit/system/{entry_id} (#398).

func (*Server) GetSystemSetting

func (s *Server) GetSystemSetting(c *gin.Context, key string)

GetSystemSetting returns a specific system setting by key (admin only)

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}

func (*Server) GetTeamMetadata

func (s *Server) GetTeamMetadata(c *gin.Context, teamId openapi_types.UUID)

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}

func (*Server) GetThreatAuditTrail

func (s *Server) GetThreatAuditTrail(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId, params GetThreatAuditTrailParams)

GetThreatAuditTrail lists audit entries for a specific threat.

func (*Server) GetThreatMetadata

func (s *Server) GetThreatMetadata(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

GetThreatMetadata gets threat metadata

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

func (*Server) GetThreatModel

func (s *Server) GetThreatModel(c *gin.Context, threatModelId openapi_types.UUID)

GetThreatModel gets a specific threat model

func (*Server) GetThreatModelAsset

func (s *Server) GetThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

GetThreatModelAsset gets an asset

func (*Server) GetThreatModelAssetMetadata

func (s *Server) GetThreatModelAssetMetadata(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID)

GetThreatModelAssetMetadata gets asset metadata

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

func (*Server) GetThreatModelAssets

func (s *Server) GetThreatModelAssets(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelAssetsParams)

GetThreatModelAssets lists assets

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.

func (*Server) GetThreatModelDiagram

func (s *Server) GetThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID)

GetThreatModelDiagram gets a specific diagram

func (*Server) GetThreatModelDiagrams

func (s *Server) GetThreatModelDiagrams(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelDiagramsParams)

GetThreatModelDiagrams lists diagrams for a threat model

func (*Server) GetThreatModelDocument

func (s *Server) GetThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID)

GetThreatModelDocument gets a document

func (*Server) GetThreatModelDocuments

func (s *Server) GetThreatModelDocuments(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelDocumentsParams)

GetThreatModelDocuments lists documents

func (*Server) GetThreatModelMetadata

func (s *Server) GetThreatModelMetadata(c *gin.Context, threatModelId openapi_types.UUID)

GetThreatModelMetadata gets threat model metadata

func (*Server) GetThreatModelMetadataByKey

func (s *Server) GetThreatModelMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, key string)

GetThreatModelMetadataByKey gets threat model metadata by key

func (*Server) GetThreatModelNote

func (s *Server) GetThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

GetThreatModelNote gets a note

func (*Server) GetThreatModelNotes

func (s *Server) GetThreatModelNotes(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelNotesParams)

GetThreatModelNotes lists notes

func (*Server) GetThreatModelRepositories

func (s *Server) GetThreatModelRepositories(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelRepositoriesParams)

GetThreatModelRepositories lists repositories

func (*Server) GetThreatModelRepository

func (s *Server) GetThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

GetThreatModelRepository gets a repository

func (*Server) GetThreatModelThreat

func (s *Server) GetThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID)

GetThreatModelThreat gets a threat

func (*Server) GetThreatModelThreats

func (s *Server) GetThreatModelThreats(c *gin.Context, threatModelId openapi_types.UUID, params GetThreatModelThreatsParams)

GetThreatModelThreats lists threats

func (*Server) GetTimmyChatSession

func (s *Server) GetTimmyChatSession(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId)

GetTimmyChatSession retrieves a specific session.

func (*Server) GetTimmyStatus

func (s *Server) GetTimmyStatus(c *gin.Context)

GetTimmyStatus returns current memory and index status (admin only).

func (*Server) GetTimmyUsage

func (s *Server) GetTimmyUsage(c *gin.Context, params GetTimmyUsageParams)

GetTimmyUsage returns aggregated usage statistics (admin only).

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}

func (*Server) GetTriageSurveyResponseMetadata

func (s *Server) GetTriageSurveyResponseMetadata(c *gin.Context, surveyResponseId SurveyResponseId)

GetTriageSurveyResponseMetadata gets triage survey response metadata

func (*Server) GetTriageSurveyResponseMetadataByKey

func (s *Server) GetTriageSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

GetTriageSurveyResponseMetadataByKey gets triage survey response metadata by key

func (*Server) GetTriageSurveyResponseTriageNote

func (s *Server) GetTriageSurveyResponseTriageNote(c *gin.Context, surveyResponseId SurveyResponseId, triageNoteId TriageNoteId)

GetTriageSurveyResponseTriageNote gets a specific triage note

func (*Server) GetUsabilityFeedback

func (s *Server) GetUsabilityFeedback(c *gin.Context, id openapi_types.UUID)

GetUsabilityFeedback retrieves a usability feedback entry by ID.

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)

func (*Server) GetWebSocketHub

func (s *Server) GetWebSocketHub() *WebSocketHub

GetWebSocketHub returns the WebSocket hub instance

func (*Server) GetWebhookDelivery

func (s *Server) GetWebhookDelivery(c *gin.Context, deliveryId openapi_types.UUID)

GetWebhookDelivery gets a specific webhook delivery (admin only)

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)

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)

func (*Server) GetWebhookSubscription

func (s *Server) GetWebhookSubscription(c *gin.Context, webhookId openapi_types.UUID)

GetWebhookSubscription gets a specific webhook subscription (admin only)

func (*Server) GetWsTicket

func (s *Server) GetWsTicket(c *gin.Context, params GetWsTicketParams)

GetWsTicket issues a short-lived WebSocket authentication ticket.

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.

func (*Server) HandleNotificationWebSocket

func (s *Server) HandleNotificationWebSocket(c *gin.Context)

HandleNotificationWebSocket handles WebSocket connections for notifications

func (*Server) HandleOAuthCallback

func (s *Server) HandleOAuthCallback(c *gin.Context, params HandleOAuthCallbackParams)

HandleOAuthCallback handles OAuth callback

func (*Server) HandleWebSocket

func (s *Server) HandleWebSocket(c *gin.Context)

HandleWebSocket handles WebSocket connections

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}

func (*Server) InitiateSAMLLogin

func (s *Server) InitiateSAMLLogin(c *gin.Context, provider string, params InitiateSAMLLoginParams)

InitiateSAMLLogin starts SAML authentication flow

func (*Server) IntrospectToken

func (s *Server) IntrospectToken(c *gin.Context)

IntrospectToken handles token introspection requests per RFC 7662

func (*Server) InvokeAddon

func (s *Server) InvokeAddon(c *gin.Context, id openapi_types.UUID)

InvokeAddon invokes an add-on

func (*Server) ListAddonInvocationQuotas

func (s *Server) ListAddonInvocationQuotas(c *gin.Context, params ListAddonInvocationQuotasParams)

ListAddonInvocationQuotas retrieves all custom addon invocation quotas (admin only)

func (*Server) ListAddons

func (s *Server) ListAddons(c *gin.Context, params ListAddonsParams)

ListAddons lists all add-ons

func (*Server) ListAdminGroups

func (s *Server) ListAdminGroups(c *gin.Context, params ListAdminGroupsParams)

ListAdminGroups handles GET /admin/groups

func (*Server) ListAdminSurveys

func (s *Server) ListAdminSurveys(c *gin.Context, params ListAdminSurveysParams)

ListAdminSurveys returns a paginated list of all surveys. GET /admin/surveys

func (*Server) ListAdminThreatModelAuditEntries

func (s *Server) ListAdminThreatModelAuditEntries(c *gin.Context, params ListAdminThreatModelAuditEntriesParams)

ListAdminThreatModelAuditEntries handles GET /admin/audit/threat_models (#398).

func (*Server) ListAdminUserClientCredentials

func (s *Server) ListAdminUserClientCredentials(c *gin.Context, internalUuid openapi_types.UUID, params ListAdminUserClientCredentialsParams)

ListAdminUserClientCredentials handles GET /admin/users/{user_id}/client_credentials

func (*Server) ListAdminUsers

func (s *Server) ListAdminUsers(c *gin.Context, params ListAdminUsersParams)

ListAdminUsers handles GET /admin/users

func (*Server) ListContentFeedback

func (s *Server) ListContentFeedback(c *gin.Context, threatModelId ThreatModelId, params ListContentFeedbackParams)

ListContentFeedback lists content feedback entries for a threat model.

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)

func (*Server) ListGroupMembers

func (s *Server) ListGroupMembers(c *gin.Context, internalUuid openapi_types.UUID, params ListGroupMembersParams)

ListGroupMembers handles GET /admin/groups/{group_id}/members

func (*Server) ListIntakeSurveyResponseTriageNotes

func (s *Server) ListIntakeSurveyResponseTriageNotes(c *gin.Context, surveyResponseId SurveyResponseId, params ListIntakeSurveyResponseTriageNotesParams)

ListIntakeSurveyResponseTriageNotes lists triage notes for submitter (read-only)

func (*Server) ListIntakeSurveyResponses

func (s *Server) ListIntakeSurveyResponses(c *gin.Context, params ListIntakeSurveyResponsesParams)

ListIntakeSurveyResponses returns the current user's survey responses. GET /intake/survey_responses

func (*Server) ListIntakeSurveys

func (s *Server) ListIntakeSurveys(c *gin.Context, params ListIntakeSurveysParams)

ListIntakeSurveys returns a list of active surveys. GET /intake/surveys

func (*Server) ListMyContentTokens

func (s *Server) ListMyContentTokens(c *gin.Context)

ListMyContentTokens implements ServerInterface.ListMyContentTokens.

func (*Server) ListMyGroupMembers

func (s *Server) ListMyGroupMembers(c *gin.Context, internalUuid openapi_types.UUID, params ListMyGroupMembersParams)

ListMyGroupMembers handles GET /me/groups/{group_id}/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.

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.

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.

func (*Server) ListMyWebhookDeliveries

func (s *Server) ListMyWebhookDeliveries(c *gin.Context, params ListMyWebhookDeliveriesParams)

ListMyWebhookDeliveries lists the caller's visible deliveries (#913)

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

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

func (*Server) ListSAMLUsers

func (s *Server) ListSAMLUsers(c *gin.Context, idp string, _ ListSAMLUsersParams)

ListSAMLUsers handles GET /saml/providers/{idp}/users

func (*Server) ListSystemAuditEntries

func (s *Server) ListSystemAuditEntries(c *gin.Context, params ListSystemAuditEntriesParams)

ListSystemAuditEntries handles GET /admin/audit/system (#398).

func (*Server) ListSystemSettings

func (s *Server) ListSystemSettings(c *gin.Context)

ListSystemSettings returns all system settings (admin only)

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

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

func (*Server) ListThreatModels

func (s *Server) ListThreatModels(c *gin.Context, params ListThreatModelsParams)

ListThreatModels lists threat models

func (*Server) ListTimmyChatMessages

func (s *Server) ListTimmyChatMessages(c *gin.Context, threatModelId ThreatModelId, sessionId SessionId, params ListTimmyChatMessagesParams)

ListTimmyChatMessages lists message history for a session.

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.

func (*Server) ListTriageSurveyResponseTriageNotes

func (s *Server) ListTriageSurveyResponseTriageNotes(c *gin.Context, surveyResponseId SurveyResponseId, params ListTriageSurveyResponseTriageNotesParams)

ListTriageSurveyResponseTriageNotes lists triage notes for a survey response

func (*Server) ListTriageSurveyResponses

func (s *Server) ListTriageSurveyResponses(c *gin.Context, params ListTriageSurveyResponsesParams)

ListTriageSurveyResponses returns survey responses for triage. GET /triage/survey_responses

func (*Server) ListUsabilityFeedback

func (s *Server) ListUsabilityFeedback(c *gin.Context, params ListUsabilityFeedbackParams)

ListUsabilityFeedback lists usability feedback entries.

func (*Server) ListUserAPIQuotas

func (s *Server) ListUserAPIQuotas(c *gin.Context, params ListUserAPIQuotasParams)

ListUserAPIQuotas retrieves all custom user API quotas (admin only)

func (*Server) ListWebhookDeliveries

func (s *Server) ListWebhookDeliveries(c *gin.Context, params ListWebhookDeliveriesParams)

ListWebhookDeliveries lists webhook deliveries (admin only)

func (*Server) ListWebhookQuotas

func (s *Server) ListWebhookQuotas(c *gin.Context, params ListWebhookQuotasParams)

ListWebhookQuotas retrieves all custom webhook quotas (admin only)

func (*Server) ListWebhookSubscriptions

func (s *Server) ListWebhookSubscriptions(c *gin.Context, params ListWebhookSubscriptionsParams)

ListWebhookSubscriptions lists webhook subscriptions (admin only)

func (*Server) LogoutCurrentUser

func (s *Server) LogoutCurrentUser(c *gin.Context)

LogoutCurrentUser logs out the current user (POST /me/logout)

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.

func (*Server) PatchAddon

func (s *Server) PatchAddon(c *gin.Context, id openapi_types.UUID)

PatchAddon partially updates an add-on (admin only)

func (*Server) PatchAdminSurvey

func (s *Server) PatchAdminSurvey(c *gin.Context, surveyId SurveyId)

PatchAdminSurvey partially updates a survey. PATCH /admin/surveys/{survey_id}

func (*Server) PatchAdminWebhookSubscription

func (s *Server) PatchAdminWebhookSubscription(c *gin.Context, webhookId openapi_types.UUID)

PatchAdminWebhookSubscription partially updates a webhook subscription (admin only). PATCH /admin/webhooks/subscriptions/{webhook_id}

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

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}

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}

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}

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}

func (*Server) PatchThreatModel

func (s *Server) PatchThreatModel(c *gin.Context, threatModelId openapi_types.UUID, _ PatchThreatModelParams)

PatchThreatModel partially updates a threat model

func (*Server) PatchThreatModelAsset

func (s *Server) PatchThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID, _ PatchThreatModelAssetParams)

PatchThreatModelAsset patches an asset

func (*Server) PatchThreatModelDiagram

func (s *Server) PatchThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID, _ PatchThreatModelDiagramParams)

PatchThreatModelDiagram partially updates a diagram

func (*Server) PatchThreatModelDocument

func (s *Server) PatchThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID, _ PatchThreatModelDocumentParams)

PatchThreatModelDocument patches a document

func (*Server) PatchThreatModelNote

func (s *Server) PatchThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

PatchThreatModelNote patches a note

func (*Server) PatchThreatModelRepository

func (s *Server) PatchThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

PatchThreatModelRepository patches a repository

func (*Server) PatchThreatModelThreat

func (s *Server) PatchThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID, _ PatchThreatModelThreatParams)

PatchThreatModelThreat patches a threat

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

func (*Server) ProcessSAMLLogout

func (s *Server) ProcessSAMLLogout(c *gin.Context, params ProcessSAMLLogoutParams)

ProcessSAMLLogout handles SAML single logout (GET)

func (*Server) ProcessSAMLLogoutPost

func (s *Server) ProcessSAMLLogoutPost(c *gin.Context)

ProcessSAMLLogoutPost handles SAML single logout (POST)

func (*Server) ProcessSAMLResponse

func (s *Server) ProcessSAMLResponse(c *gin.Context)

ProcessSAMLResponse handles SAML assertion consumer service

func (*Server) ReencryptSystemSettings

func (s *Server) ReencryptSystemSettings(c *gin.Context)

ReencryptSystemSettings re-encrypts all system settings with the current encryption key (admin only)

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".

func (*Server) RefreshToken

func (s *Server) RefreshToken(c *gin.Context)

RefreshToken refreshes JWT token

func (*Server) RegisterHandlers

func (s *Server) RegisterHandlers(r *gin.Engine)

RegisterHandlers registers custom API handlers with the router

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/{group_id}/members/{member_uuid}

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.

func (*Server) RestoreAsset

func (s *Server) RestoreAsset(c *gin.Context, threatModelId ThreatModelId, assetId AssetId)

RestoreAsset restores a soft-deleted asset.

func (*Server) RestoreDiagram

func (s *Server) RestoreDiagram(c *gin.Context, threatModelId ThreatModelId, diagramId DiagramId)

RestoreDiagram restores a soft-deleted diagram.

func (*Server) RestoreDocument

func (s *Server) RestoreDocument(c *gin.Context, threatModelId ThreatModelId, documentId DocumentId)

RestoreDocument restores a soft-deleted document.

func (*Server) RestoreNote

func (s *Server) RestoreNote(c *gin.Context, threatModelId ThreatModelId, noteId NoteId)

RestoreNote restores a soft-deleted note.

func (*Server) RestoreRepository

func (s *Server) RestoreRepository(c *gin.Context, threatModelId ThreatModelId, repositoryId RepositoryId)

RestoreRepository restores a soft-deleted repository.

func (*Server) RestoreThreat

func (s *Server) RestoreThreat(c *gin.Context, threatModelId ThreatModelId, threatId ThreatId)

RestoreThreat restores a soft-deleted threat.

func (*Server) RestoreThreatModel

func (s *Server) RestoreThreatModel(c *gin.Context, threatModelId ThreatModelId)

RestoreThreatModel restores 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)

func (*Server) RollbackToVersion

func (s *Server) RollbackToVersion(c *gin.Context, threatModelId ThreatModelId, entryId AuditEntryId)

RollbackToVersion restores an entity to a previous version.

func (*Server) SetAPIRateLimiter

func (s *Server) SetAPIRateLimiter(rateLimiter *APIRateLimiter)

SetAPIRateLimiter sets the API rate limiter

func (*Server) SetAllowHTTPWebhooks

func (s *Server) SetAllowHTTPWebhooks(allow bool)

SetAllowHTTPWebhooks sets whether non-HTTPS webhook URLs are permitted

func (*Server) SetAuthFlowRateLimiter

func (s *Server) SetAuthFlowRateLimiter(rateLimiter *AuthFlowRateLimiter)

SetAuthFlowRateLimiter sets the auth flow rate limiter

func (*Server) SetAuthService

func (s *Server) SetAuthService(authService AuthService)

SetAuthService sets the auth service for delegating auth-related methods

func (*Server) SetConfigProvider

func (s *Server) SetConfigProvider(provider ConfigProvider)

SetConfigProvider sets the config provider for settings migration

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/{user_id}/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.

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.

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.

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.

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.

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.

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.

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).

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).

func (*Server) SetExtractionJobStore

func (s *Server) SetExtractionJobStore(store *ExtractionJobStore)

SetExtractionJobStore injects the extraction_jobs repository.

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.

func (*Server) SetIPRateLimiter

func (s *Server) SetIPRateLimiter(rateLimiter *IPRateLimiter)

SetIPRateLimiter sets the IP rate limiter

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).

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.

func (*Server) SetMicrosoftPickerGrantHandler

func (s *Server) SetMicrosoftPickerGrantHandler(h microsoftPickerGrantHandlerInterface)

SetMicrosoftPickerGrantHandler attaches the Microsoft picker-grant handler. When unset, GrantMicrosoftFilePermission returns 503.

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.

func (*Server) SetProviderRegistry

func (s *Server) SetProviderRegistry(registry auth.ProviderRegistry)

SetProviderRegistry sets the provider registry for cache invalidation from settings handlers.

func (*Server) SetRateLimitingDisabled

func (s *Server) SetRateLimitingDisabled(disabled bool)

SetRateLimitingDisabled disables all rate limiting (dev/test mode only)

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.

func (*Server) SetSettingsService

func (s *Server) SetSettingsService(settingsService SettingsServiceInterface)

SetSettingsService sets the settings service for database-stored configuration

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.

func (*Server) SetTicketStore

func (s *Server) SetTicketStore(ticketStore TicketStore)

SetTicketStore sets the ticket store for WebSocket authentication

func (*Server) SetTimmyConfigReader

func (s *Server) SetTimmyConfigReader(r TimmyConfigReader)

SetTimmyConfigReader provides the live Timmy config source used to advertise availability.

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.

func (*Server) SetTimmySessionManager

func (s *Server) SetTimmySessionManager(manager *TimmySessionManager)

SetTimmySessionManager sets the Timmy session manager for AI assistant endpoints

func (*Server) SetTrustedProxiesConfigured

func (s *Server) SetTrustedProxiesConfigured(configured bool)

SetTrustedProxiesConfigured marks whether trusted proxies have been configured

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.

func (*Server) SetVectorManager

func (s *Server) SetVectorManager(manager *VectorIndexManager)

SetVectorManager sets the vector index manager for Timmy AI assistant

func (*Server) SetWebhookRateLimiter

func (s *Server) SetWebhookRateLimiter(rateLimiter *WebhookRateLimiter)

SetWebhookRateLimiter sets the webhook rate limiter

func (*Server) StartAuditPruner

func (s *Server) StartAuditPruner()

StartAuditPruner starts the background audit pruning goroutine.

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.

func (*Server) StartWebSocketHub

func (s *Server) StartWebSocketHub(ctx context.Context)

StartWebSocketHub starts the WebSocket hub cleanup timer

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.

func (*Server) StopAuditPruner

func (s *Server) StopAuditPruner()

StopAuditPruner stops the background audit pruning goroutine.

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.

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.

func (*Server) TestWebhookSubscription

func (s *Server) TestWebhookSubscription(c *gin.Context, webhookId openapi_types.UUID)

TestWebhookSubscription sends a test event to the webhook (admin only)

func (*Server) TransferAdminUserOwnership

func (s *Server) TransferAdminUserOwnership(c *gin.Context, userID UserIdPathParam)

TransferAdminUserOwnership handles POST /admin/users/{user_id}/transfer

func (*Server) TransferCurrentUserOwnership

func (s *Server) TransferCurrentUserOwnership(c *gin.Context)

TransferCurrentUserOwnership handles POST /me/transfer

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)

func (*Server) UpdateAdminGroup

func (s *Server) UpdateAdminGroup(c *gin.Context, internalUuid openapi_types.UUID)

UpdateAdminGroup handles PATCH /admin/groups/{group_id}

func (*Server) UpdateAdminSurvey

func (s *Server) UpdateAdminSurvey(c *gin.Context, surveyId SurveyId)

UpdateAdminSurvey fully updates a survey. PUT /admin/surveys/{survey_id}

func (*Server) UpdateAdminSurveyMetadataByKey

func (s *Server) UpdateAdminSurveyMetadataByKey(c *gin.Context, surveyId SurveyId, key MetadataKey)

UpdateAdminSurveyMetadataByKey updates survey metadata by key

func (*Server) UpdateAdminUser

func (s *Server) UpdateAdminUser(c *gin.Context, internalUuid openapi_types.UUID)

UpdateAdminUser handles PATCH /admin/users/{user_id}

func (*Server) UpdateCurrentUserPreferences

func (s *Server) UpdateCurrentUserPreferences(c *gin.Context)

UpdateCurrentUserPreferences handles PUT /me/preferences

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

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

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}

func (*Server) UpdateIntakeSurveyResponseMetadataByKey

func (s *Server) UpdateIntakeSurveyResponseMetadataByKey(c *gin.Context, surveyResponseId SurveyResponseId, key MetadataKey)

UpdateIntakeSurveyResponseMetadataByKey updates intake survey response metadata by key

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

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}

func (*Server) UpdateProjectMetadata

func (s *Server) UpdateProjectMetadata(c *gin.Context, projectId openapi_types.UUID, key string)

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}

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

func (*Server) UpdateSystemSetting

func (s *Server) UpdateSystemSetting(c *gin.Context, key string)

UpdateSystemSetting creates or updates a system setting (admin only)

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}

func (*Server) UpdateTeamMetadata

func (s *Server) UpdateTeamMetadata(c *gin.Context, teamId openapi_types.UUID, key string)

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}

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

func (*Server) UpdateThreatModel

func (s *Server) UpdateThreatModel(c *gin.Context, threatModelId openapi_types.UUID, _ UpdateThreatModelParams)

UpdateThreatModel updates a threat model

func (*Server) UpdateThreatModelAsset

func (s *Server) UpdateThreatModelAsset(c *gin.Context, threatModelId openapi_types.UUID, assetId openapi_types.UUID, _ UpdateThreatModelAssetParams)

UpdateThreatModelAsset updates an 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

func (*Server) UpdateThreatModelDiagram

func (s *Server) UpdateThreatModelDiagram(c *gin.Context, threatModelId openapi_types.UUID, diagramId openapi_types.UUID, _ UpdateThreatModelDiagramParams)

UpdateThreatModelDiagram updates a diagram

func (*Server) UpdateThreatModelDocument

func (s *Server) UpdateThreatModelDocument(c *gin.Context, threatModelId openapi_types.UUID, documentId openapi_types.UUID, _ UpdateThreatModelDocumentParams)

UpdateThreatModelDocument updates a document

func (*Server) UpdateThreatModelMetadataByKey

func (s *Server) UpdateThreatModelMetadataByKey(c *gin.Context, threatModelId openapi_types.UUID, key string)

UpdateThreatModelMetadataByKey updates threat model metadata by key

func (*Server) UpdateThreatModelNote

func (s *Server) UpdateThreatModelNote(c *gin.Context, threatModelId openapi_types.UUID, noteId openapi_types.UUID)

UpdateThreatModelNote updates a note

func (*Server) UpdateThreatModelRepository

func (s *Server) UpdateThreatModelRepository(c *gin.Context, threatModelId openapi_types.UUID, repositoryId openapi_types.UUID)

UpdateThreatModelRepository updates a repository

func (*Server) UpdateThreatModelThreat

func (s *Server) UpdateThreatModelThreat(c *gin.Context, threatModelId openapi_types.UUID, threatId openapi_types.UUID, _ UpdateThreatModelThreatParams)

UpdateThreatModelThreat updates a threat

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)

func (*Server) UpdateWebhookDeliveryStatus

func (s *Server) UpdateWebhookDeliveryStatus(c *gin.Context, deliveryId DeliveryId, params UpdateWebhookDeliveryStatusParams)

UpdateWebhookDeliveryStatus updates delivery status (HMAC authenticated)

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)

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.

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

type ServerInfoResponse added in v1.21.14

type ServerInfoResponse struct {
	// TlsEnabled Whether the server itself terminates TLS
	TlsEnabled bool `json:"tls_enabled"`

	// TlsSubjectName Subject name of the server TLS certificate; omitted when empty
	TlsSubjectName *string `json:"tls_subject_name,omitempty"`

	// WebsocketBaseUrl WebSocket base URL derived from the host the client used and the client-facing scheme (wss when the request arrived over TLS directly or through a TLS-terminating proxy that sets X-Forwarded-Proto, otherwise ws)
	WebsocketBaseUrl string `json:"websocket_base_url"`
}

ServerInfoResponse Server TLS and WebSocket connection information for clients

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)
	// Partially update add-on
	// (PATCH /addons/{id})
	PatchAddon(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/{group_id})
	DeleteAdminGroup(c *gin.Context, groupId GroupIdPathParam)
	// Get group details
	// (GET /admin/groups/{group_id})
	GetAdminGroup(c *gin.Context, groupId GroupIdPathParam)
	// Update group metadata
	// (PATCH /admin/groups/{group_id})
	UpdateAdminGroup(c *gin.Context, groupId GroupIdPathParam)
	// List group members
	// (GET /admin/groups/{group_id}/members)
	ListGroupMembers(c *gin.Context, groupId GroupIdPathParam, params ListGroupMembersParams)
	// Add member to group
	// (POST /admin/groups/{group_id}/members)
	AddGroupMember(c *gin.Context, groupId GroupIdPathParam)
	// Remove member from group
	// (DELETE /admin/groups/{group_id}/members/{member_uuid})
	RemoveGroupMember(c *gin.Context, groupId GroupIdPathParam, 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/{user_id})
	DeleteAdminUser(c *gin.Context, userId UserIdPathParam)
	// Get user details
	// (GET /admin/users/{user_id})
	GetAdminUser(c *gin.Context, userId UserIdPathParam)
	// Update user metadata
	// (PATCH /admin/users/{user_id})
	UpdateAdminUser(c *gin.Context, userId UserIdPathParam)
	// List client credentials for an automation user
	// (GET /admin/users/{user_id}/client_credentials)
	ListAdminUserClientCredentials(c *gin.Context, userId UserIdPathParam, params ListAdminUserClientCredentialsParams)
	// Create a client credential for an automation user
	// (POST /admin/users/{user_id}/client_credentials)
	CreateAdminUserClientCredential(c *gin.Context, userId UserIdPathParam)
	// Delete a client credential for an automation user
	// (DELETE /admin/users/{user_id}/client_credentials/{credential_id})
	DeleteAdminUserClientCredential(c *gin.Context, userId UserIdPathParam, credentialId CredentialIdPathParam)
	// List a user's linked content provider tokens (admin)
	// (GET /admin/users/{user_id}/content_tokens)
	AdminListUserContentTokens(c *gin.Context, userId openapi_types.UUID)
	// Revoke a user's linked content provider token (admin)
	// (DELETE /admin/users/{user_id}/content_tokens/{provider_id})
	AdminDeleteUserContentToken(c *gin.Context, userId openapi_types.UUID, providerId string)
	// List a user's primary and linked sign-in identities (admin)
	// (GET /admin/users/{user_id}/identities)
	AdminListUserIdentities(c *gin.Context, userId UserIdPathParam)
	// Unlink a user's linked sign-in identity (admin)
	// (DELETE /admin/users/{user_id}/identities/{identity_id})
	AdminDeleteUserIdentity(c *gin.Context, userId UserIdPathParam, identityId openapi_types.UUID)
	// Transfer user ownership to another user
	// (POST /admin/users/{user_id}/transfer)
	TransferAdminUserOwnership(c *gin.Context, userId UserIdPathParam)
	// 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)
	// Partially update webhook subscription
	// (PATCH /admin/webhooks/subscriptions/{webhook_id})
	PatchAdminWebhookSubscription(c *gin.Context, webhookId WebhookId)
	// Test webhook subscription
	// (POST /admin/webhooks/subscriptions/{webhook_id}/test)
	TestWebhookSubscription(c *gin.Context, webhookId WebhookId)
	// Get server information
	// (GET /api/server-info)
	GetServerInfo(c *gin.Context)
	// 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/{group_id}/members)
	ListMyGroupMembers(c *gin.Context, groupId GroupIdPathParam, 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, params ListSAMLUsersParams)
	// 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)
	// List my webhook deliveries
	// (GET /webhook-deliveries)
	ListMyWebhookDeliveries(c *gin.Context, params ListMyWebhookDeliveriesParams)
	// Cancel a webhook delivery
	// (DELETE /webhook-deliveries/{delivery_id})
	CancelWebhookDelivery(c *gin.Context, deliveryId DeliveryId)
	// 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) AdminDeleteUserIdentity

func (siw *ServerInterfaceWrapper) AdminDeleteUserIdentity(c *gin.Context)

AdminDeleteUserIdentity operation middleware

func (*ServerInterfaceWrapper) AdminListUserContentTokens

func (siw *ServerInterfaceWrapper) AdminListUserContentTokens(c *gin.Context)

AdminListUserContentTokens operation middleware

func (*ServerInterfaceWrapper) AdminListUserIdentities

func (siw *ServerInterfaceWrapper) AdminListUserIdentities(c *gin.Context)

AdminListUserIdentities 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 (*ServerInterfaceWrapper) CancelWebhookDelivery

func (siw *ServerInterfaceWrapper) CancelWebhookDelivery(c *gin.Context)

CancelWebhookDelivery 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) GetServerInfo added in v1.21.14

func (siw *ServerInterfaceWrapper) GetServerInfo(c *gin.Context)

GetServerInfo 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) ListMyWebhookDeliveries

func (siw *ServerInterfaceWrapper) ListMyWebhookDeliveries(c *gin.Context)

ListMyWebhookDeliveries 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) PatchAddon

func (siw *ServerInterfaceWrapper) PatchAddon(c *gin.Context)

PatchAddon operation middleware

func (*ServerInterfaceWrapper) PatchAdminSurvey

func (siw *ServerInterfaceWrapper) PatchAdminSurvey(c *gin.Context)

PatchAdminSurvey operation middleware

func (*ServerInterfaceWrapper) PatchAdminWebhookSubscription

func (siw *ServerInterfaceWrapper) PatchAdminWebhookSubscription(c *gin.Context)

PatchAdminWebhookSubscription 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

type SessionState

type SessionState string

SessionState represents the lifecycle state of a collaboration session

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

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)

func (*SessionValidator) ValidateSessionID

func (v *SessionValidator) ValidateSessionID(session *DiagramSession, providedSessionID string) error

ValidateSessionID validates that the provided session ID matches the actual session

func (*SessionValidator) ValidateSessionState

func (v *SessionValidator) ValidateSessionState(session *DiagramSession) error

ValidateSessionState validates the session is in the correct state for connection

type SettingError

type SettingError struct {
	Key   string `json:"key"`
	Error string `json:"error"`
}

SettingError represents an error for a specific setting during re-encryption.

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.

func NewSettingsService

func NewSettingsService(gormDB *gorm.DB, redisDB *db.RedisDB) *SettingsService

NewSettingsService creates a new settings service

func (*SettingsService) CountValuesWithContextID

func (s *SettingsService) CountValuesWithContextID(ctx context.Context, id int) (int64, error)

CountValuesWithContextID counts rows still encrypted under the given key id; the rotator uses it to decide when the previous key can be dropped.

func (*SettingsService) Delete

func (s *SettingsService) Delete(ctx context.Context, key string) error

Delete removes a setting

func (*SettingsService) Get

Get retrieves a setting by key, checking cache first

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).

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).

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).

func (*SettingsService) GetResolvedString

func (s *SettingsService) GetResolvedString(ctx context.Context, key string) (string, bool, error)

GetResolvedString retrieves a string setting by applying the single precedence rule that governs every scalar operational setting (#794). exists reports whether any layer supplied a usable value, so callers can distinguish "nothing configured anywhere" from an empty value.

This replaced GetDatabaseString, which read the database only. Two accessors used to implement two deliberate, opposite rules — GetString (#415: an explicit config value wins, a bare struct default yields to the database) and GetDatabaseString (#767: the database always wins, config is a first-run fallback). Each was right about half the problem, and the half each got wrong caused a production outage on 2026-08-20: a registry-seeded default row nobody had ever set outranked a correctly-set TMI_OAUTH_CALLBACK_URL, so every OAuth login redirected to localhost.

The missing distinction was on the database side. #415 already knew an operator-supplied config value from a struct default (MigratableSetting .Explicit); the database had no equivalent until SystemSetting.Origin, so a seeded row and an admin-set row were indistinguishable. With both halves present, one rule covers every case:

config explicit?  db explicit?  winner
no                no            database  (both defaults; prefer the hot-reloadable one)
no                yes           database  (#415 preserved)
yes               no            config    (a seeded default never beats an operator)
yes               yes           database  (#419/#767 runtime editability preserved)

Bootstrap settings are exempt: they are never database-backed, so the config layer is their only source.

The read is retried on transient faults and the returned error is classified (dberrors sentinels): callers on the #419 runtime path sit on request hot paths (e.g. /oauth2/authorize) where an unretried ADB blip (ORA-02396/03113/12537 class) would otherwise surface as a hard failure PG testing cannot reproduce (oracle-db-admin review of #767).

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).

func (*SettingsService) InvalidateAll

func (s *SettingsService) InvalidateAll(ctx context.Context)

InvalidateAll clears all settings from cache

func (*SettingsService) List

List retrieves all settings

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.

func (*SettingsService) PlaintextKeys

func (s *SettingsService) PlaintextKeys(ctx context.Context, keys []string) ([]string, error)

PlaintextKeys returns which of the given keys have a non-empty stored value without the ENC: prefix, i.e. rows written before settings encryption was enabled that ReEncryptAll would convert. It reads the raw rows (List and Get decrypt, which hides the prefix) and returns key names only, never values.

func (*SettingsService) ReEncryptAll

func (s *SettingsService) ReEncryptAll(ctx context.Context) (int, []SettingError, error)

ReEncryptAll re-encrypts every system_settings value not already under the current key id. Each row is its own short transaction (#965): a crash or a database error leaves a readable mix of old-id and current-id rows and the next call finishes the job, because the selection is by envelope prefix, not by a full-table pass. Only the value column is written (#805): modified_at and modified_by are left as they were. Rows no key can open are reported in []SettingError and excluded from later batches so the loop always terminates. Returns the number of rows committed so far, also on error.

func (*SettingsService) SeedDefaults

func (s *SettingsService) SeedDefaults(ctx context.Context) error

SeedDefaults seeds the default settings if they don't exist

func (*SettingsService) Set

func (s *SettingsService) Set(ctx context.Context, setting *models.SystemSetting) error

Set creates or updates a setting

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.

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.

type SettingsServiceInterface

type SettingsServiceInterface interface {
	Get(ctx context.Context, key string) (*models.SystemSetting, error)
	GetString(ctx context.Context, key string) (string, error)
	// GetResolvedString applies the single converged precedence rule across
	// the config layer and the database, and reports whether any layer
	// supplied a usable value. Used by the #419 runtime-config path. It
	// replaced GetDatabaseString so the two precedence rules that caused the
	// 2026-08-20 outage cannot re-diverge (#794).
	GetResolvedString(ctx context.Context, key string) (string, bool, 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) (int, []SettingError, error)
	CountValuesWithContextID(ctx context.Context, id int) (int64, error)
}

SettingsServiceInterface defines the operations needed by handlers on 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.

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.

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.

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.

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.

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.

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.

func NewStepUpAuditAdapter

func NewStepUpAuditAdapter(repo SystemAuditRepository) *StepUpAuditAdapter

NewStepUpAuditAdapter constructs the adapter.

func (*StepUpAuditAdapter) WriteSystemAudit

func (a *StepUpAuditAdapter) WriteSystemAudit(ctx context.Context, rec auth.SystemAuditRecord) error

WriteSystemAudit implements auth.SystemAuditWriter.

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 redirects after successful authentication. For OAuth (authorization code with PKCE) the redirect carries the authorization code and state in the query string (?code=...&state=...); the client exchanges the code for tokens at POST /oauth2/token, which returns a JSON body and, when cookie delivery is enabled, also sets HttpOnly token cookies. OAuth never delivers tokens in the URL fragment. SAML login instead redirects with the tokens in the URL fragment (#access_token=...).
	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"`

	// LoginHint User identity hint forwarded to the provider (login_hint), so the provider knows which account to authenticate. For the TMI provider this selects the test identity: either a username (alice) or its address form (alice@tmi.local); other providers receive it as an email address or username, per their own login_hint semantics. Valid characters: letters, digits, periods, underscores, percent signs, plus signs, at signs, and hyphens.
	LoginHint *LoginHintQueryParam `form:"login_hint,omitempty" json:"login_hint,omitempty"`
}

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.

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".

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.

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

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).

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.

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).

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.

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.

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. The server enforces the set of values (an unknown value is rejected with 400 invalid_input; needs_revision also requires revision_notes) but not the order of transitions.
	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 (server-set; response only)
	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 authorization decision on /intake/survey_responses/* paths. Triage paths use RequireTriageAccess (reviewer-group membership) instead; the row ACL grants no triage access (#1100).

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.

func RequireTriageAccess added in v1.21.11

func RequireTriageAccess(c *gin.Context, responseID SurveyResponseId) (*SurveyResponse, bool)

RequireTriageAccess loads a survey response and authorizes the caller to triage it: the caller must belong to the reviewer group matching the response's confidentiality. A missing response and a denied caller both surface as 404 (non-disclosure, T5 #357). On failure it writes the error and returns (nil, false).

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"`

	// 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"`

	// 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

	// IsConfidential, when set, restricts results to responses whose
	// is_confidential flag equals the value (triage reviewer scoping, #1100).
	IsConfidential *bool
}

SurveyResponseFilters defines filter options for listing responses

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. The server enforces the set of values but not the order of transitions.
	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

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)

	// 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

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

var GlobalSurveyStore SurveyStore

type SyncRequestHandler

type SyncRequestHandler struct{}

SyncRequestHandler handles sync request messages

func (*SyncRequestHandler) HandleMessage

func (h *SyncRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*SyncRequestHandler) MessageType

func (h *SyncRequestHandler) MessageType() string

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

func (SyncRequestMessage) GetMessageType

func (m SyncRequestMessage) GetMessageType() MessageType

func (SyncRequestMessage) Validate

func (m SyncRequestMessage) Validate() error

type SyncStatusRequestHandler

type SyncStatusRequestHandler struct{}

SyncStatusRequestHandler handles sync status request messages

func (*SyncStatusRequestHandler) HandleMessage

func (h *SyncStatusRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*SyncStatusRequestHandler) MessageType

func (h *SyncStatusRequestHandler) MessageType() string

type SyncStatusRequestMessage

type SyncStatusRequestMessage struct {
	MessageType MessageType `json:"message_type"`
}

SyncStatusRequestMessage is sent by client to check server's current update vector

func (SyncStatusRequestMessage) GetMessageType

func (m SyncStatusRequestMessage) GetMessageType() MessageType

func (SyncStatusRequestMessage) Validate

func (m SyncStatusRequestMessage) Validate() error

type SyncStatusResponseMessage

type SyncStatusResponseMessage struct {
	MessageType  MessageType `json:"message_type"`
	UpdateVector int64       `json:"update_vector"`
}

SyncStatusResponseMessage is sent by server with current update vector

func (SyncStatusResponseMessage) GetMessageType

func (m SyncStatusResponseMessage) GetMessageType() MessageType

func (SyncStatusResponseMessage) Validate

func (m SyncStatusResponseMessage) Validate() error

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.

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).

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.

func NewSystemAuditRepository

func NewSystemAuditRepository(db *gorm.DB) SystemAuditRepository

NewSystemAuditRepository constructs a GORM-backed SystemAuditRepository.

type SystemHealthResult

type SystemHealthResult struct {
	Database ComponentHealthResult
	Redis    ComponentHealthResult
	Overall  ApiInfoStatusCode
}

SystemHealthResult holds health check results for all components

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

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., websocket.max_participants)
	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"`

	// Origin How the database row for this setting came to exist. seeded: inserted with a registry default at first boot (an explicitly configured config or environment value outranks it). explicit: deliberately set by an operator via the admin API, tmi-dbtool --import-config, or SettingsService.Set (it outranks config). Absent when the setting has no database row (source is config, environment, or vault). Server-managed, not writable.
	Origin *SystemSettingOrigin `json:"origin,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. Read together with origin: source says which layer wins for this key; origin says whether the database row (if any) was deliberately set.
	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 SystemSettingOrigin

type SystemSettingOrigin string

SystemSettingOrigin How the database row for this setting came to exist. seeded: inserted with a registry default at first boot (an explicitly configured config or environment value outranks it). explicit: deliberately set by an operator via the admin API, tmi-dbtool --import-config, or SettingsService.Set (it outranks config). Absent when the setting has no database row (source is config, environment, or vault). Server-managed, not writable.

const (
	Explicit SystemSettingOrigin = "explicit"
	Seeded   SystemSettingOrigin = "seeded"
)

Defines values for SystemSettingOrigin.

func (SystemSettingOrigin) Valid

func (e SystemSettingOrigin) Valid() bool

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

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.

type SystemSettingSource

type SystemSettingSource string

SystemSettingSource Where the effective value of this setting comes from. Server-managed, not writable. Read together with origin: source says which layer wins for this key; origin says whether the database row (if any) was deliberately set.

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"
	SystemSettingTypeFloat  SystemSettingType = "float"
	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"
	Float  SystemSettingUpdateType = "float"
	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 (resolved on read)
	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) (resolved on read)
	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"`

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

	// RelatedTeams Relationships to other teams
	RelatedTeams *[]RelatedTeam `json:"related_teams,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

type TeamInput

type TeamInput 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 *[]TeamMemberInput `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 *[]ResponsiblePartyInput `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"`
}

TeamInput defines model for TeamInput.

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 TeamMemberInput

type TeamMemberInput 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"`

	// UserId UUID of the team member user
	UserId openapi_types.UUID `json:"user_id"`
}

TeamMemberInput Client-writable fields of TeamMember (excludes the server-resolved user).

type TeamMemberRole

type TeamMemberRole string

TeamMemberRole Role of a team member or responsible party

const (
	TeamMemberRoleBusinessLeader     TeamMemberRole = "business_leader"
	TeamMemberRoleEngineer           TeamMemberRole = "engineer"
	TeamMemberRoleEngineeringLead    TeamMemberRole = "engineering_lead"
	TeamMemberRoleOther              TeamMemberRole = "other"
	TeamMemberRoleProductManager     TeamMemberRole = "product_manager"
	TeamMemberRoleSecuritySpecialist 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 applies operations to the stored note, then calls check (when
	// non-nil) with the stored and patched notes before persisting; check may
	// rewrite the patched note, and an error from it aborts the patch.
	Patch(ctx context.Context, id string, operations []PatchOperation, check func(before, after *TeamNote) error) (*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

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

var GlobalTeamStore TeamStoreInterface

type TeamSummary

type TeamSummary struct {
	// Description Team description
	Description *string `json:"description,omitempty"`

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

	// Name Team name
	Name string `json:"name"`
}

TeamSummary Minimal team reference embedded in other resources. Only the identifying fields are resolved; fetch /teams/{team_id} for the complete team.

type TestUserIdentity

type TestUserIdentity struct {
	Email        string
	ProviderID   string
	InternalUUID string
	IdP          string
	Groups       []string
}

TestUserIdentity represents a test user with all identity attributes

func (TestUserIdentity) SetContext

func (u TestUserIdentity) SetContext(c *gin.Context)

SetContext sets the user identity in a Gin context

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

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)

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

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 *[]DfdDiagram `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

func (*ThreatModel) SetModifiedAt

func (t *ThreatModel) SetModifiedAt(time time.Time)

SetModifiedAt implements WithTimestamps interface

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

func NewThreatModelDiagramHandler

func NewThreatModelDiagramHandler(wsHub *WebSocketHub) *ThreatModelDiagramHandler

NewThreatModelDiagramHandler creates a new handler for diagrams within threat models

func (*ThreatModelDiagramHandler) CreateDiagram

func (h *ThreatModelDiagramHandler) CreateDiagram(c *gin.Context, threatModelId string)

CreateDiagram creates a new diagram for a threat model

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

func (*ThreatModelDiagramHandler) DeleteDiagram

func (h *ThreatModelDiagramHandler) DeleteDiagram(c *gin.Context, threatModelId, diagramId string)

DeleteDiagram deletes a diagram within a threat model

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

func (*ThreatModelDiagramHandler) GetDiagramByID

func (h *ThreatModelDiagramHandler) GetDiagramByID(c *gin.Context, threatModelId, diagramId string)

GetDiagramByID retrieves a specific diagram within a threat model

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

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

func (*ThreatModelDiagramHandler) GetDiagrams

func (h *ThreatModelDiagramHandler) GetDiagrams(c *gin.Context, threatModelId string)

GetDiagrams returns a list of diagrams for a threat model

func (*ThreatModelDiagramHandler) PatchDiagram

func (h *ThreatModelDiagramHandler) PatchDiagram(c *gin.Context, threatModelId, diagramId string)

PatchDiagram partially updates a diagram within a threat model

func (*ThreatModelDiagramHandler) UpdateDiagram

func (h *ThreatModelDiagramHandler) UpdateDiagram(c *gin.Context, threatModelId, diagramId string)

UpdateDiagram fully updates a diagram within a threat model

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

type ThreatModelHandler

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

ThreatModelHandler provides handlers for threat model operations

func NewThreatModelHandler

func NewThreatModelHandler(wsHub *WebSocketHub) *ThreatModelHandler

NewThreatModelHandler creates a new threat model handler

func (*ThreatModelHandler) CreateThreatModel

func (h *ThreatModelHandler) CreateThreatModel(c *gin.Context)

CreateThreatModel creates a new threat model

func (*ThreatModelHandler) DeleteThreatModel

func (h *ThreatModelHandler) DeleteThreatModel(c *gin.Context)

DeleteThreatModel deletes a threat model

func (*ThreatModelHandler) GetThreatModelByID

func (h *ThreatModelHandler) GetThreatModelByID(c *gin.Context)

GetThreatModelByID retrieves a specific threat model

func (*ThreatModelHandler) GetThreatModels

func (h *ThreatModelHandler) GetThreatModels(c *gin.Context)

GetThreatModels returns a list of threat models

func (*ThreatModelHandler) PatchThreatModel

func (h *ThreatModelHandler) PatchThreatModel(c *gin.Context)

PatchThreatModel partially updates a threat model

func (*ThreatModelHandler) SetIssueURIValidator

func (h *ThreatModelHandler) SetIssueURIValidator(v *URIValidator)

SetIssueURIValidator sets the URI validator for issue_uri fields

func (*ThreatModelHandler) UpdateThreatModel

func (h *ThreatModelHandler) UpdateThreatModel(c *gin.Context)

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

func (*ThreatModelInternal) FromThreatModel

func (tm *ThreatModelInternal) FromThreatModel(external *ThreatModel)

FromThreatModel converts external API model to internal representation

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

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

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

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

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)
	// 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, error)
	// Create accepts a context.Context so a client disconnect cancels the transaction (#911).
	Create(ctx context.Context, 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
}
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. threatModelID scopes the load and
	// write-back to the parent threat model so a bulk-patch caller cannot
	// reach a child of a different threat model by id alone (#664 follow-up).
	Patch(ctx context.Context, threatModelID string, id string, operations []PatchOperation) (*Threat, error)

	// Bulk operations
	BulkCreate(ctx context.Context, threats []Threat) error
	BulkUpdate(ctx context.Context, threats []Threat) error

	// BulkSoftDelete soft-deletes every id in one transaction, scoped to the
	// owning threat model. It is all-or-nothing: if any id is missing, already
	// deleted, or belongs to a different threat model, nothing is deleted and
	// ErrThreatNotFound is returned. Deleting per id in a loop instead would
	// commit each one separately, so a failure partway through would leave the
	// batch half-applied with no way for the caller to find out which half --
	// and on Oracle a mid-batch abort (ORA-08177 under SERIALIZABLE, ORA-00060,
	// or an ADB autoscale connection drop) is routine rather than exotic.
	BulkSoftDelete(ctx context.Context, threatModelID string, ids []string) 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

var GlobalThreatRepository ThreatRepository

type ThreatSubResourceHandler

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

ThreatSubResourceHandler provides handlers for threat sub-resource operations

func NewThreatSubResourceHandler

func NewThreatSubResourceHandler(threatStore ThreatRepository, db *sql.DB, cache *CacheService, invalidator *CacheInvalidator) *ThreatSubResourceHandler

NewThreatSubResourceHandler creates a new threat sub-resource handler

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

func (*ThreatSubResourceHandler) BulkDeleteThreats

func (h *ThreatSubResourceHandler) BulkDeleteThreats(c *gin.Context, threatIDs ThreatIdsQueryParam)

BulkDeleteThreats deletes multiple threats DELETE /threat_models/{threat_model_id}/threats/bulk

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

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

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

func (*ThreatSubResourceHandler) DeleteThreat

func (h *ThreatSubResourceHandler) DeleteThreat(c *gin.Context)

DeleteThreat deletes a threat DELETE /threat_models/{threat_model_id}/threats/{threat_id}

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}

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

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

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}

func (*ThreatSubResourceHandler) SetIssueURIValidator

func (h *ThreatSubResourceHandler) SetIssueURIValidator(v *URIValidator)

SetIssueURIValidator sets the URI validator for issue_uri fields

func (*ThreatSubResourceHandler) UpdateThreat

func (h *ThreatSubResourceHandler) UpdateThreat(c *gin.Context)

UpdateThreat updates an existing threat PUT /threat_models/{threat_model_id}/threats/{threat_id}

type ThreatTypeQueryParam

type ThreatTypeQueryParam = []string

ThreatTypeQueryParam defines model for ThreatTypeQueryParam.

type TicketClaims

type TicketClaims struct {
	UserID       string `json:"user_id"`
	Provider     string `json:"provider"`
	InternalUUID string `json:"internal_uuid,omitempty"`
	SessionID    string `json:"session_id"`
	TokenHash    string `json:"token_hash,omitempty"`
	CredentialID string `json:"credential_id,omitempty"`
	// Groups are the minting token's group claims, frozen at issue time so the
	// ticket-authenticated upgrade can make group-aware access checks. Absent
	// (nil) on tickets issued before this field existed, which fails closed.
	Groups []string `json:"groups,omitempty"`
}

TicketClaims is the identity bound to a WebSocket ticket. TokenHash and CredentialID identify the token that minted the ticket so the upgrade can be refused after that token or its client credential is revoked (#869).

type TicketStore

type TicketStore interface {
	// IssueTicket creates a ticket bound to the given claims, returning the ticket string.
	IssueTicket(ctx context.Context, claims TicketClaims, ttl time.Duration) (string, error)
	// ValidateTicket validates and consumes a ticket (single-use), returning its bound claims.
	ValidateTicket(ctx context.Context, ticket string) (TicketClaims, error)
}

TicketStore manages short-lived, single-use WebSocket authentication tickets.

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.

func NewTimmyConfigProvider

func NewTimmyConfigProvider(settings SettingsServiceInterface) *TimmyConfigProvider

NewTimmyConfigProvider constructs a provider over the given settings service.

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.

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.

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.

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.

func NewTimmyCore

func NewTimmyCore(provider *TimmyConfigProvider, build TimmyRuntimeBuilder) *TimmyCore

NewTimmyCore constructs a core over the given provider and builder.

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.

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

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 internal/llm (a thin, provider-agnostic seam; see #754).

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).

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.

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.

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.

func (*TimmyLLMService) GenerateStreamingResponse

func (s *TimmyLLMService) GenerateStreamingResponse(
	ctx context.Context,
	systemPrompt string,
	messages []llm.Message,
	onToken func(token string),
) (string, int, error)

GenerateStreamingResponse sends a chat request and streams tokens via callback. It returns the full response text, a token count, and any error. The token count prefers the provider's reported completion-token usage when available (openai-go surfaces this via stream_options.include_usage); otherwise it falls back to the stream-chunk count, matching the pre-#754 approximation.

func (*TimmyLLMService) GetBasePrompt

func (s *TimmyLLMService) GetBasePrompt() string

GetBasePrompt returns the system prompt (base + operator extension)

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

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

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).

func (*TimmyRateLimiter) AcquireLLMSlot

func (rl *TimmyRateLimiter) AcquireLLMSlot() bool

AcquireLLMSlot tries to acquire a concurrent LLM request slot

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.

func (*TimmyRateLimiter) ReleaseLLMSlot

func (rl *TimmyRateLimiter) ReleaseLLMSlot()

ReleaseLLMSlot releases a concurrent LLM request slot

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.

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.

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

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

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.

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.

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).

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.

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.

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

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

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 received from OAuth provider. Per RFC 6749, can contain any visible ASCII characters (VSCHAR: 0x20-0x7E). maxLength is deliberately generous: Microsoft Entra v2.0 codes routinely exceed 700 characters and can pass 2000 with additional scopes/claims. A 512 limit silently broke Microsoft sign-in with a 400 from request validation before the handler ran (Google codes are ~100 chars, so only Microsoft was affected). Do not tighten without checking real Entra code lengths.
	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"
	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.

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.

func NewTriageNoteSubResourceHandler

func NewTriageNoteSubResourceHandler(store TriageNoteStore) *TriageNoteSubResourceHandler

NewTriageNoteSubResourceHandler creates a new triage note sub-resource handler

func (*TriageNoteSubResourceHandler) CreateTriageNote

func (h *TriageNoteSubResourceHandler) CreateTriageNote(c *gin.Context)

CreateTriageNote creates a new triage note in a survey response

func (*TriageNoteSubResourceHandler) GetTriageNote

func (h *TriageNoteSubResourceHandler) GetTriageNote(c *gin.Context)

GetTriageNote retrieves a specific triage note by ID

func (*TriageNoteSubResourceHandler) ListTriageNotes

func (h *TriageNoteSubResourceHandler) ListTriageNotes(c *gin.Context)

ListTriageNotes retrieves all triage notes for a survey response with pagination

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

func ParseUUID

func ParseUUID(s string) (TypesUUID, error)

ParseUUID converts a string to a TypesUUID

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.

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"].

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.

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.

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.

func NewURLPatternMatcher

func NewURLPatternMatcher() *URLPatternMatcher

NewURLPatternMatcher creates a matcher with all known provider patterns.

func (*URLPatternMatcher) Identify

func (m *URLPatternMatcher) Identify(uri string) string

Identify returns the provider name for a URI, or "" if unrecognized.

func (*URLPatternMatcher) IsKnownProvider

func (m *URLPatternMatcher) IsKnownProvider(name string) bool

IsKnownProvider returns true if the provider name is recognized.

type Unauthorized

type Unauthorized = Error

Unauthorized Standard error response format

type UndoRequestHandler

type UndoRequestHandler struct{}

UndoRequestHandler handles undo request messages

func (*UndoRequestHandler) HandleMessage

func (h *UndoRequestHandler) HandleMessage(session *DiagramSession, client *WebSocketClient, message []byte) error

func (*UndoRequestHandler) MessageType

func (h *UndoRequestHandler) MessageType() string

type UndoRequestMessage

type UndoRequestMessage struct {
	MessageType    MessageType `json:"message_type"`
	InitiatingUser User        `json:"initiating_user"`
}

func (UndoRequestMessage) GetMessageType

func (m UndoRequestMessage) GetMessageType() MessageType

func (UndoRequestMessage) Validate

func (m UndoRequestMessage) Validate() error

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
	// LockVersion is the new optimistic-lock version (api/optimistic_locking.go),
	// set only when expectedVersion was non-nil.
	LockVersion int
}

UpdateDiagramResult contains the result of a centralized diagram update

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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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. Accepts an integer version (bare or ETag-quoted) or "*" for an unconditional write (RFC 7232).
	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 (
	UpdateWebhookDeliveryStatusResponseStatusCancelled  UpdateWebhookDeliveryStatusResponseStatus = "cancelled"
	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*.

func NewUsabilityFeedbackHandler

func NewUsabilityFeedbackHandler(repo UsabilityFeedbackRepository) *UsabilityFeedbackHandler

NewUsabilityFeedbackHandler constructs the handler.

func (*UsabilityFeedbackHandler) Create

func (h *UsabilityFeedbackHandler) Create(c *gin.Context)

Create handles POST /usability_feedback.

func (*UsabilityFeedbackHandler) Get

Get handles GET /usability_feedback/{id}.

func (*UsabilityFeedbackHandler) List

func (h *UsabilityFeedbackHandler) List(c *gin.Context)

List handles GET /usability_feedback with filters and pagination.

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).

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.

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

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

func (*UserAPIQuota) SetModifiedAt

func (q *UserAPIQuota) SetModifiedAt(t time.Time)

SetModifiedAt implements WithTimestamps for UserAPIQuota

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().

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

type UserDeletionHandler

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

UserDeletionHandler handles user self-deletion operations

func NewUserDeletionHandler

func NewUserDeletionHandler(authService *auth.Service) *UserDeletionHandler

NewUserDeletionHandler creates a new user deletion handler

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

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

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
	// Groups are the caller's group claims from the "userGroups" gin context
	// value (JWT claim, or the minting token's claims for a ticket upgrade).
	Groups []string
}

UserInfo represents extracted user information

type UserInfoExtractor

type UserInfoExtractor struct{}

UserInfoExtractor handles extracting user information from the request context

func (*UserInfoExtractor) ExtractUserInfo

func (u *UserInfoExtractor) ExtractUserInfo(c *gin.Context) (*UserInfo, error)

ExtractUserInfo extracts user information from the gin context

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.

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

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)

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

func GetValidationConfig

func GetValidationConfig(endpoint string) (ValidationConfig, bool)

GetValidationConfig returns the validation config for an endpoint

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

ValidationError represents a validation error

type ValidationResult

type ValidationResult struct {
	Valid  bool
	Errors []string
}

ValidationResult provides validation outcome details

func ValidateStruct

func ValidateStruct(s any, config ValidationConfig) ValidationResult

ValidateStruct performs validation on any struct and returns detailed results

type ValidatorFunc

type ValidatorFunc func(any) error

ValidatorFunc is a function that validates a parsed request

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).

func NewVectorIndex

func NewVectorIndex(dimension int) *VectorIndex

NewVectorIndex creates a new vector index for vectors of the given dimension

func (*VectorIndex) Add

func (vi *VectorIndex) Add(id string, vector []float32, chunkText string)

Add inserts a vector into the index

func (*VectorIndex) Count

func (vi *VectorIndex) Count() int

Count returns the number of vectors in the index

func (*VectorIndex) Delete

func (vi *VectorIndex) Delete(id string)

Delete removes a vector by ID

func (*VectorIndex) MemorySize

func (vi *VectorIndex) MemorySize() int64

MemorySize estimates the memory used by this index in bytes

func (*VectorIndex) Search

func (vi *VectorIndex) Search(query []float32, topK int) []VectorSearchResult

Search returns the top-K most similar vectors to the query

type VectorIndexManager

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

VectorIndexManager manages in-memory vector indexes per threat model

func NewVectorIndexManager

func NewVectorIndexManager(embeddingStore TimmyEmbeddingStore, maxMemoryMB int, inactivityTimeoutSeconds int) *VectorIndexManager

NewVectorIndexManager creates a new manager with the given memory budget

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.

func (*VectorIndexManager) GetStatus

func (m *VectorIndexManager) GetStatus() map[string]any

GetStatus returns current memory and index status for the admin endpoint

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.

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.

func (*VectorIndexManager) ReleaseIndex

func (m *VectorIndexManager) ReleaseIndex(threatModelID, indexType string)

ReleaseIndex decrements the active session count for the given threat model and index type

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.

type VectorSearchResult

type VectorSearchResult struct {
	ID         string
	ChunkText  string
	Similarity float32
}

VectorSearchResult represents a search result with similarity score

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

func GetVersion

func GetVersion() Version

GetVersion returns the current application version

type WWWAuthenticateError

type WWWAuthenticateError string

WWWAuthenticateError represents error types per RFC 6750 section 3.1

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

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

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

type WarmingStrategy

type WarmingStrategy int

WarmingStrategy defines different cache warming approaches

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
	// Groups are the user's group claims, captured at connect time. They are
	// frozen for the socket's lifetime, like JWT claims on REST requests; the
	// heartbeat re-check (checkReadPermission) still observes ACL changes.
	Groups []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

func (*WebSocketClient) ReadPump

func (c *WebSocketClient) ReadPump()

ReadPump pumps messages from WebSocket to hub

func (*WebSocketClient) WritePump

func (c *WebSocketClient) WritePump()

WritePump pumps messages from hub to WebSocket

type WebSocketConnectionManager

type WebSocketConnectionManager struct{}

WebSocketConnectionManager handles WebSocket connection setup and error handling

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

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

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

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

func NewWebSocketHub

func NewWebSocketHub(loggingConfig slogging.WebSocketLoggingConfig, inactivityTimeout time.Duration) *WebSocketHub

NewWebSocketHub creates a new WebSocket hub

func NewWebSocketHubForTests

func NewWebSocketHubForTests() *WebSocketHub

NewWebSocketHubForTests creates a WebSocket hub with default test configuration

func (*WebSocketHub) CleanupAllSessions

func (h *WebSocketHub) CleanupAllSessions()

CleanupAllSessions removes all active sessions (used at server startup)

func (*WebSocketHub) CleanupEmptySessions

func (h *WebSocketHub) CleanupEmptySessions()

CleanupEmptySessions performs immediate cleanup of empty sessions

func (*WebSocketHub) CleanupInactiveSessions

func (h *WebSocketHub) CleanupInactiveSessions()

CleanupInactiveSessions removes sessions that are inactive or empty with grace period

func (*WebSocketHub) CloseSession

func (h *WebSocketHub) CloseSession(diagramID string)

CloseSession closes a session and removes it

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.

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.

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

func (*WebSocketHub) FindSessionByID

func (h *WebSocketHub) FindSessionByID(sessionID string) *DiagramSession

FindSessionByID finds a collaboration session by its session ID.

func (*WebSocketHub) GetActiveSessions

func (h *WebSocketHub) GetActiveSessions() []CollaborationSession

GetActiveSessions returns all active collaboration sessions

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

func (*WebSocketHub) GetOrCreateSession

func (h *WebSocketHub) GetOrCreateSession(diagramID string, threatModelID string, hostUser ResolvedUser) *DiagramSession

GetOrCreateSession returns an existing session or creates a new one

func (*WebSocketHub) GetSession

func (h *WebSocketHub) GetSession(diagramID string) *DiagramSession

GetSession returns an existing session or nil if none exists

func (*WebSocketHub) HandleWS

func (h *WebSocketHub) HandleWS(c *gin.Context)

HandleWS handles WebSocket connections

func (*WebSocketHub) HasActiveSession

func (h *WebSocketHub) HasActiveSession(diagramID string) bool

HasActiveSession checks if there is an active collaboration session for a diagram

func (*WebSocketHub) JoinSession

func (h *WebSocketHub) JoinSession(diagramID string, userID string) (*DiagramSession, error)

JoinSession joins an existing collaboration session, returns error if none exists

func (*WebSocketHub) StartCleanupTimer

func (h *WebSocketHub) StartCleanupTimer(ctx context.Context)

StartCleanupTimer starts a periodic cleanup timer

func (*WebSocketHub) UpdateDiagram

func (h *WebSocketHub) UpdateDiagram(diagramID string, updateFunc func(DfdDiagram) (DfdDiagram, bool, error), updateSource string, excludeUserID string, expectedVersion *int) (*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

expectedVersion, when non-nil, is the caller's optimistic-lock expected version (#385); the CAS then runs in the same transaction as the content write via DiagramStore.UpdateWithVersion (#594).

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)

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).

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.

func (*WebhookChallengeWorker) Start

func (bw *WebhookChallengeWorker) Start(ctx context.Context) error

Start begins the worker's processing loop.

func (*WebhookChallengeWorker) Stop

func (bw *WebhookChallengeWorker) Stop()

Stop gracefully stops the worker.

type WebhookCleanupWorker

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

WebhookCleanupWorker handles cleanup of old deliveries, idle subscriptions, and broken subscriptions

func NewWebhookCleanupWorker

func NewWebhookCleanupWorker() *WebhookCleanupWorker

NewWebhookCleanupWorker creates a new cleanup worker

func (*WebhookCleanupWorker) Start

func (bw *WebhookCleanupWorker) Start(ctx context.Context) error

Start begins the worker's processing loop.

func (*WebhookCleanupWorker) Stop

func (bw *WebhookCleanupWorker) Stop()

Stop gracefully stops the worker.

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. cancelled is terminal and set only by DELETE /webhook-deliveries/{delivery_id}.
	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.

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).

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, cancelled
	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"`
	// Invoker's IdP identity so invoked_by can be a valid User in responses (#913)
	InvokedByProvider   string `json:"invoked_by_provider,omitempty"`
	InvokedByProviderID string `json:"invoked_by_provider_id,omitempty"`
}

WebhookDeliveryRecord is the unified delivery record used for both resource-change events and addon invocations, backed by Redis.

type WebhookDeliveryRedisStore

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

WebhookDeliveryRedisStore implements WebhookDeliveryRedisStoreInterface using Redis

func NewWebhookDeliveryRedisStore

func NewWebhookDeliveryRedisStore(redisDB *db.RedisDB) *WebhookDeliveryRedisStore

NewWebhookDeliveryRedisStore creates a new Redis-backed webhook delivery store

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.

func (*WebhookDeliveryRedisStore) Create

Create creates a new delivery record in Redis

func (*WebhookDeliveryRedisStore) Delete

Delete removes a delivery record from Redis

func (*WebhookDeliveryRedisStore) Get

Get retrieves a delivery record by ID

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.

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.

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).

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).

func (*WebhookDeliveryRedisStore) ListStale

ListStale returns in_progress delivery records with no activity within the given timeout.

func (*WebhookDeliveryRedisStore) Update

Update updates an existing delivery record in Redis

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

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

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

var GlobalWebhookDeliveryRedisStore WebhookDeliveryRedisStoreInterface

GlobalWebhookDeliveryRedisStore is the global singleton for the unified webhook delivery store

type WebhookDeliveryStatus

type WebhookDeliveryStatus string

WebhookDeliveryStatus Delivery status. cancelled is terminal and set only by DELETE /webhook-deliveries/{delivery_id}.

const (
	WebhookDeliveryStatusCancelled  WebhookDeliveryStatus = "cancelled"
	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.

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.

func (*WebhookDeliveryWorker) Start

func (bw *WebhookDeliveryWorker) Start(ctx context.Context) error

Start begins the worker's processing loop.

func (*WebhookDeliveryWorker) Stop

func (bw *WebhookDeliveryWorker) Stop()

Stop gracefully stops the worker.

type WebhookEventConsumer

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

WebhookEventConsumer consumes events from Redis Streams and creates webhook deliveries

func NewWebhookEventConsumer

func NewWebhookEventConsumer(redisClient *redis.Client, streamKey, groupName, consumerID string) *WebhookEventConsumer

NewWebhookEventConsumer creates a new event consumer

func (*WebhookEventConsumer) Start

func (c *WebhookEventConsumer) Start(ctx context.Context) error

Start begins consuming events from the Redis Stream

func (*WebhookEventConsumer) Stop

func (c *WebhookEventConsumer) Stop()

Stop gracefully stops the consumer

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.

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

func NewWebhookRateLimiter

func NewWebhookRateLimiter(redisClient *redis.Client) *WebhookRateLimiter

NewWebhookRateLimiter creates a new rate limiter

func (*WebhookRateLimiter) CheckEventPublicationLimit

func (r *WebhookRateLimiter) CheckEventPublicationLimit(ctx context.Context, ownerID string) error

CheckEventPublicationLimit checks rate limit for event publications

func (*WebhookRateLimiter) CheckSubscriptionLimit

func (r *WebhookRateLimiter) CheckSubscriptionLimit(ctx context.Context, ownerID string) error

CheckSubscriptionLimit checks if owner can create a new subscription

func (*WebhookRateLimiter) CheckSubscriptionRequestLimit

func (r *WebhookRateLimiter) CheckSubscriptionRequestLimit(ctx context.Context, ownerID string) error

CheckSubscriptionRequestLimit checks rate limit for subscription creation requests

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

func (*WebhookRateLimiter) RecordEventPublication

func (r *WebhookRateLimiter) RecordEventPublication(ctx context.Context, ownerID string) error

RecordEventPublication records an event publication for rate limiting

func (*WebhookRateLimiter) RecordSubscriptionRequest

func (r *WebhookRateLimiter) RecordSubscriptionRequest(ctx context.Context, ownerID string) error

RecordSubscriptionRequest records a subscription creation request for rate limiting

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. 'inactive' means the subscription was deactivated (for example, an operator-pinned subscription whose pin configuration was removed): no deliveries are made, and the subscription is retained and can be re-activated by the server when its pin configuration is restored.
	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. 'inactive' means the subscription was deactivated (for example, an operator-pinned subscription whose pin configuration was removed): no deliveries are made, and the subscription is retained and can be re-activated by the server when its pin configuration is restored.

const (
	WebhookSubscriptionStatusActive              WebhookSubscriptionStatus = "active"
	WebhookSubscriptionStatusInactive            WebhookSubscriptionStatus = "inactive"
	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 writes item over the subscription with the given id. With no
	// fields, a default set of mutable fields is written; passing struct field
	// names narrows the write to exactly those fields.
	Update(ctx context.Context, id string, item DBWebhookSubscription, fields ...string) 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.

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

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.

var GlobalWebhookUrlDenyListStore WebhookUrlDenyListStoreInterface

type WebhookUrlValidator

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

WebhookUrlValidator validates webhook URLs against security rules

func NewWebhookUrlValidator

func NewWebhookUrlValidator(denyListStore WebhookUrlDenyListStoreInterface) *WebhookUrlValidator

NewWebhookUrlValidator creates a new URL validator

func NewWebhookUrlValidatorWithHTTP

func NewWebhookUrlValidatorWithHTTP(denyListStore WebhookUrlDenyListStoreInterface, allowHTTP bool) *WebhookUrlValidator

NewWebhookUrlValidatorWithHTTP creates a new URL validator that optionally allows HTTP URLs

func (*WebhookUrlValidator) ValidateWebhookURL

func (v *WebhookUrlValidator) ValidateWebhookURL(ctx context.Context, rawURL string) error

ValidateWebhookURL validates a webhook URL according to security requirements

type WithTimestamps

type WithTimestamps interface {
	SetCreatedAt(time.Time)
	SetModifiedAt(time.Time)
}

WithTimestamps is a mixin interface for entities with timestamps

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