middleware

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DummyUserID is the fixed external identity ID for dummy auth mode.
	DummyUserID = "00000000-0000-0000-0000-000000000001"
	// DummyUserEmail is the fixed email for dummy auth mode.
	DummyUserEmail = "admin@docengine.local"
	// DummyUserName is the fixed name for dummy auth mode.
	DummyUserName = "Doc Engine Admin"
)
View Source
const APIKeyHeader = "X-API-Key" //nolint:gosec // This is a header name, not a credential

APIKeyHeader is the HTTP header name for API key authentication.

View Source
const (
	AutomationKeyHeader = "X-Automation-Key" //nolint:gosec // This is a header name, not a credential

)
View Source
const (
	// OperationIDHeader is the header name for the operation ID.
	OperationIDHeader = "X-Operation-ID"
)
View Source
const (
	// SandboxModeHeader is the header name for enabling sandbox mode.
	SandboxModeHeader = "X-Sandbox-Mode"
)
View Source
const (
	// TenantIDHeader is the header name for the tenant ID.
	TenantIDHeader = "X-Tenant-ID"
)
View Source
const (
	// WorkspaceIDHeader is the header name for the workspace ID.
	WorkspaceIDHeader = "X-Workspace-ID"
)

Variables

This section is empty.

Functions

func AuthorizeRole

func AuthorizeRole(requiredRole entity.WorkspaceRole) gin.HandlerFunc

AuthorizeRole creates a middleware that checks if the user has at least the required role. This middleware must be applied after WorkspaceContext.

func AuthorizeSystemRole

func AuthorizeSystemRole(requiredRole entity.SystemRole) gin.HandlerFunc

AuthorizeSystemRole creates a middleware that checks if the user has at least the required system role. This middleware must be applied after SystemRoleContext.

func AuthorizeTenantRole

func AuthorizeTenantRole(requiredRole entity.TenantRole) gin.HandlerFunc

AuthorizeTenantRole creates a middleware that checks if the user has at least the required tenant role. This middleware must be applied after TenantContext.

func AutomationAuditLogger

func AutomationAuditLogger(auditRepo port.AutomationAuditLogRepository) gin.HandlerFunc

AutomationAuditLogger is a Gin middleware that asynchronously records all automation API calls to the audit log table. It must run AFTER AutomationKeyAuth so that the key ID is available in the context.

func AutomationKeyAuth

func AutomationKeyAuth(keyRepo port.AutomationAPIKeyRepository) gin.HandlerFunc

AutomationKeyAuth validates the X-Automation-Key header against the database. On success, injects automationKeyID, automationKeyPrefix, and automationAllowedTenants into the Gin context.

func AutomationSandboxContext

func AutomationSandboxContext(workspaceRepo port.WorkspaceRepository) gin.HandlerFunc

AutomationSandboxContext creates a middleware that resolves sandbox workspace for automation routes. Unlike SandboxContext, it reads the workspace ID from the :workspaceId URL path parameter instead of the X-Workspace-ID header, and does not require user identity context. When X-Sandbox-Mode header is "true", it resolves or auto-creates the sandbox workspace and replaces the workspace ID in context.

func CustomPublicDocumentAccess

func CustomPublicDocumentAccess(auth port.PublicDocumentAccessAuthenticator) gin.HandlerFunc

CustomPublicDocumentAccess runs a custom authenticator for public /public/doc/:documentId requests (GET and POST).

By default this middleware does not block requests: on auth success, claims are stored in context so the controller can redirect directly to /public/sign/:token or return a signing URL. On auth failure/miss, flow falls back to the standard email gate. If the authenticator explicitly aborts the context, the chain stops.

func DummyAuth

func DummyAuth() gin.HandlerFunc

DummyAuth creates a middleware that bypasses JWT validation and injects a fixed superadmin identity. Used when no auth config is provided (dev mode).

func DummyIdentityAndRoles

func DummyIdentityAndRoles(internalUserID string) gin.HandlerFunc

DummyIdentityAndRoles creates a middleware that sets the internal user ID and grants SUPERADMIN system role. Used in dummy auth mode to bypass IdentityContext and SystemRoleContext middlewares.

func GetAutomationAllowedTenants

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

GetAutomationAllowedTenants returns the allowed tenants slice from the Gin context. Returns nil if the key has global access (all tenants allowed).

func GetAutomationKeyID

func GetAutomationKeyID(c *gin.Context) (string, bool)

GetAutomationKeyID returns the automation API key ID from the Gin context.

func GetAutomationKeyPrefix

func GetAutomationKeyPrefix(c *gin.Context) (string, bool)

GetAutomationKeyPrefix returns the automation API key prefix from the Gin context.

func GetEnvironment

func GetEnvironment(c *gin.Context) entity.Environment

GetEnvironment returns the environment derived from the request context.

func GetInternalUserID

func GetInternalUserID(c *gin.Context) (string, bool)

GetInternalUserID retrieves the internal user ID from the Gin context.

func GetOIDCProvider

func GetOIDCProvider(c *gin.Context) (string, bool)

GetOIDCProvider retrieves the matched OIDC provider name from the Gin context.

func GetOperationID

func GetOperationID(c *gin.Context) string

GetOperationID retrieves the operation ID from the Gin context.

func GetParentWorkspaceID

func GetParentWorkspaceID(c *gin.Context) (string, bool)

GetParentWorkspaceID returns the parent workspace ID when in sandbox mode. Returns empty string and false if not in sandbox mode or if parent ID is not set.

func GetPublicDocumentAccessClaims

func GetPublicDocumentAccessClaims(c *gin.Context) (*port.PublicDocumentAccessClaims, bool)

GetPublicDocumentAccessClaims returns claims injected by CustomPublicDocumentAccess.

func GetSigningSessionAuthClaims

func GetSigningSessionAuthClaims(c *gin.Context) (*port.SigningSessionAuthClaims, bool)

GetSigningSessionAuthClaims returns claims previously stored by SigningSessionCustomAuth or SigningSessionOIDCClaims.

func GetSystemRole

func GetSystemRole(c *gin.Context) (entity.SystemRole, bool)

GetSystemRole retrieves the user's system role from the Gin context.

func GetTenantID

func GetTenantID(c *gin.Context) (string, bool)

GetTenantID retrieves the current tenant ID from the Gin context.

func GetTenantIDFromHeader

func GetTenantIDFromHeader(c *gin.Context) (string, bool)

GetTenantIDFromHeader retrieves the tenant ID directly from the X-Tenant-ID header. Use this when you need to check the header without requiring full TenantContext middleware. Returns false if the header is missing or contains an invalid UUID.

func GetTenantRole

func GetTenantRole(c *gin.Context) (entity.TenantRole, bool)

GetTenantRole retrieves the user's role in the current tenant.

func GetUserEmail

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

GetUserEmail retrieves the authenticated user email from the Gin context.

func GetUserID

func GetUserID(c *gin.Context) (string, bool)

GetUserID retrieves the authenticated user ID from the Gin context.

func GetUserName

func GetUserName(c *gin.Context) (string, bool)

GetUserName retrieves the authenticated user name from the Gin context.

func GetWorkspaceID

func GetWorkspaceID(c *gin.Context) (string, bool)

GetWorkspaceID retrieves the current workspace ID from the Gin context.

func GetWorkspaceIDFromHeader

func GetWorkspaceIDFromHeader(c *gin.Context) (string, bool)

GetWorkspaceIDFromHeader retrieves the workspace ID directly from the X-Workspace-ID header. Use this when you need to check the header without requiring full WorkspaceContext middleware.

func GetWorkspaceRole

func GetWorkspaceRole(c *gin.Context) (entity.WorkspaceRole, bool)

GetWorkspaceRole retrieves the user's role in the current workspace.

func HasSystemRole

func HasSystemRole(c *gin.Context) bool

HasSystemRole checks if the user has any system role.

func IdentityContext

func IdentityContext(pool *pgxpool.Pool, bootstrapEnabled bool, userRepo port.UserRepository, workspaceMemberRepo port.WorkspaceMemberRepository) gin.HandlerFunc

IdentityContext creates a middleware that syncs the user from IdP and loads workspace context. It requires MultiOIDCAuth middleware to be applied before this. If bootstrapEnabled is true and no users exist in the database, the first user to login will be automatically created as SUPERADMIN.

func InternalKeyAuth

func InternalKeyAuth(keyRepo port.AutomationAPIKeyRepository) gin.HandlerFunc

InternalKeyAuth creates a middleware that validates an internal API key against the database. Uses SHA-256 hashing for key lookup.

func InternalKeyAuthPreloaded

func InternalKeyAuthPreloaded(keyRepo port.AutomationAPIKeyRepository) gin.HandlerFunc

InternalKeyAuthPreloaded creates a middleware that validates internal API keys from a snapshot loaded once at service startup. It intentionally avoids any request-path lookup; key changes require service restart when this mode is used.

func IsSandboxMode

func IsSandboxMode(c *gin.Context) bool

IsSandboxMode returns true if the request is operating in sandbox mode.

func MultiOIDCAuth

func MultiOIDCAuth(providers []config.OIDCProvider) gin.HandlerFunc

MultiOIDCAuth creates middleware supporting multiple OIDC providers. Matches incoming token's issuer against configured providers. Returns 401 if issuer is not in the configured list. When no providers have JWKS configured (dev mode), tokens are parsed without validation.

func Operation

func Operation() gin.HandlerFunc

Operation creates a middleware that generates a unique operation ID for each request. The operation ID is used for request tracing and logging.

func PanelAuth

func PanelAuth(cfg *config.AuthConfig) gin.HandlerFunc

PanelAuth creates middleware for panel (login/UI) authentication. Uses only the panel OIDC provider configured in auth.panel.

func RequestTimeout

func RequestTimeout(timeout time.Duration) gin.HandlerFunc

RequestTimeout creates a middleware that sets a deadline on the request context. If the handler doesn't complete within the given duration, the context is cancelled.

func RequireAdmin

func RequireAdmin() gin.HandlerFunc

RequireAdmin is a convenience middleware that requires at least ADMIN role.

func RequireEditor

func RequireEditor() gin.HandlerFunc

RequireEditor is a convenience middleware that requires at least EDITOR role.

func RequireOperator

func RequireOperator() gin.HandlerFunc

RequireOperator is a convenience middleware that requires at least OPERATOR role.

func RequireOwner

func RequireOwner() gin.HandlerFunc

RequireOwner is a convenience middleware that requires OWNER role.

func RequirePlatformAdmin

func RequirePlatformAdmin() gin.HandlerFunc

RequirePlatformAdmin is a convenience middleware that requires at least PLATFORM_ADMIN role.

func RequireSuperAdmin

func RequireSuperAdmin() gin.HandlerFunc

RequireSuperAdmin is a convenience middleware that requires SUPERADMIN role.

func RequireTenantAccess

func RequireTenantAccess() gin.HandlerFunc

RequireTenantAccess creates a middleware that ensures the user has access to the tenant. This is a simpler check - it just verifies the user is a member.

func RequireTenantAdmin

func RequireTenantAdmin() gin.HandlerFunc

RequireTenantAdmin is a convenience middleware that requires at least TENANT_ADMIN role.

func RequireTenantOwner

func RequireTenantOwner() gin.HandlerFunc

RequireTenantOwner is a convenience middleware that requires TENANT_OWNER role.

func RequireViewer

func RequireViewer() gin.HandlerFunc

RequireViewer is a convenience middleware that requires at least VIEWER role.

func RequireWorkspaceAccess

func RequireWorkspaceAccess() gin.HandlerFunc

RequireWorkspaceAccess creates a middleware that ensures the user has access to the workspace. This is a simpler check than AuthorizeRole - it just verifies the user is a member.

func SandboxContext

func SandboxContext(workspaceRepo port.WorkspaceRepository) gin.HandlerFunc

SandboxContext creates a middleware that resolves sandbox workspace when X-Sandbox-Mode header is set. This middleware must be applied after WorkspaceContext. When the header is set to "true", it looks up the sandbox workspace associated with the parent workspace ID and replaces the workspace ID in context with the sandbox ID.

func SigningSessionCustomAuth

func SigningSessionCustomAuth(auth port.SigningSessionAuthenticator) gin.HandlerFunc

SigningSessionCustomAuth authenticates requests to /api/v1/signing-sessions/:documentId using a custom authenticator.

func SigningSessionOIDCClaims

func SigningSessionOIDCClaims(emailClaim, fallbackProvider string) gin.HandlerFunc

SigningSessionOIDCClaims extracts signing session claims after OIDC auth middleware validated the JWT.

func SystemRoleContext

func SystemRoleContext(systemRoleRepo port.SystemRoleRepository) gin.HandlerFunc

SystemRoleContext creates a middleware that loads the user's system role if they have one. This middleware is optional - it does not fail if the user has no system role. It should be applied after IdentityContext.

func TenantContext

func TenantContext(tenantMemberRepo port.TenantMemberRepository) gin.HandlerFunc

TenantContext creates a middleware that requires and loads the user's role for a specific tenant. The tenant ID must come from the X-Tenant-ID header. This middleware should only be applied to routes that require tenant context. Users with system roles (SUPERADMIN) get automatic access as TENANT_OWNER.

func WorkspaceContext

func WorkspaceContext(
	workspaceRepo port.WorkspaceRepository,
	workspaceMemberRepo port.WorkspaceMemberRepository,
	tenantMemberRepo port.TenantMemberRepository,
) gin.HandlerFunc

WorkspaceContext creates a middleware that requires and loads the user's role for a specific workspace. The workspace ID must come from the X-Workspace-ID header. This middleware should only be applied to routes that require workspace context. Users with system roles (SUPERADMIN) get automatic access as OWNER. Users with tenant roles (TENANT_OWNER) get automatic access as OWNER for workspaces in their tenant.

Types

type OIDCClaims

type OIDCClaims struct {
	jwt.RegisteredClaims
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"email_verified,omitempty"`
	Name          string `json:"name,omitempty"`
	PreferredUser string `json:"preferred_username,omitempty"`
}

OIDCClaims represents standard OIDC JWT claims.

type Provider

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

Provider centralizes middleware construction with their required dependencies. This avoids passing repositories through multiple layers just to initialize middlewares.

func NewProvider

func NewProvider(
	pool *pgxpool.Pool,
	bootstrapEnabled bool,
	userRepo port.UserRepository,
	systemRoleRepo port.SystemRoleRepository,
	workspaceRepo port.WorkspaceRepository,
	workspaceMemberRepo port.WorkspaceMemberRepository,
	tenantMemberRepo port.TenantMemberRepository,
) *Provider

NewProvider creates a new middleware provider with all required repositories.

func (*Provider) AutomationSandboxContext

func (p *Provider) AutomationSandboxContext() gin.HandlerFunc

AutomationSandboxContext returns a middleware that resolves sandbox workspace for automation routes. It reads workspace ID from URL path params instead of headers.

func (*Provider) IdentityContext

func (p *Provider) IdentityContext() gin.HandlerFunc

IdentityContext returns a middleware that loads user identity from the database. If bootstrap is enabled and no users exist, creates the first user as SUPERADMIN.

func (*Provider) SandboxContext

func (p *Provider) SandboxContext() gin.HandlerFunc

SandboxContext returns a middleware that resolves sandbox workspace when X-Sandbox-Mode header is set.

func (*Provider) SystemRoleContext

func (p *Provider) SystemRoleContext() gin.HandlerFunc

SystemRoleContext returns a middleware that loads the user's system role if they have one.

func (*Provider) TenantContext

func (p *Provider) TenantContext() gin.HandlerFunc

TenantContext returns a middleware that loads tenant context and user's role.

func (*Provider) WorkspaceContext

func (p *Provider) WorkspaceContext() gin.HandlerFunc

WorkspaceContext returns a middleware that loads workspace context and user's role.

Jump to

Keyboard shortcuts

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