Documentation
¶
Index ¶
- Constants
- func BadRequest(w http.ResponseWriter, message string)
- func ClientIP(r *http.Request) string
- func Forbidden(w http.ResponseWriter, message string)
- func FriendlyErrorMessage(err error) string
- func GetImpersonatedConfig(baseConfig *rest.Config, role string, cfg *ImpersonationConfig) *rest.Config
- func HTTPError(w http.ResponseWriter, message string, statusCode int)
- func InternalError(w http.ResponseWriter, message string)
- func K8sError(w http.ResponseWriter, err error)
- func LLMError(w http.ResponseWriter, err error, provider string)
- func MethodNotAllowed(w http.ResponseWriter, allowedMethods ...string)
- func NotFound(w http.ResponseWriter, message string)
- func RateLimitMiddleware(apiLimiter, authLimiter *RateLimiter) func(http.Handler) http.Handler
- func Unauthorized(w http.ResponseWriter, message string)
- func ValidateImpersonationConfig(cfg *ImpersonationConfig) error
- func WriteError(w http.ResponseWriter, err *APIError)
- func WriteErrorSimple(w http.ResponseWriter, statusCode int, message string)
- type APIError
- type AccessRequest
- type AccessRequestManager
- func (m *AccessRequestManager) ApproveRequest(id, reviewer, note string) error
- func (m *AccessRequestManager) CleanupExpired()
- func (m *AccessRequestManager) CreateRequest(requestedBy string, action Action, resource, namespace, reason string) (string, error)
- func (m *AccessRequestManager) DenyRequest(id, reviewer, note string) error
- func (m *AccessRequestManager) GetPendingRequests() []*AccessRequest
- func (m *AccessRequestManager) GetRequest(id string) *AccessRequest
- func (m *AccessRequestManager) HandleApproveAccessRequest(w http.ResponseWriter, r *http.Request)
- func (m *AccessRequestManager) HandleCreateAccessRequest(w http.ResponseWriter, r *http.Request)
- func (m *AccessRequestManager) HandleDenyAccessRequest(w http.ResponseWriter, r *http.Request)
- func (m *AccessRequestManager) HandleListAccessRequests(w http.ResponseWriter, r *http.Request)
- func (m *AccessRequestManager) IsApproved(username, resource string, action Action, namespace string) bool
- type AccessRequestState
- type AccountLockout
- type Action
- type ApplicationGroup
- type AuthConfig
- type AuthManager
- func (am *AuthManager) AdminMiddleware(next http.HandlerFunc) http.HandlerFunc
- func (am *AuthManager) AuthMiddleware(next http.HandlerFunc) http.HandlerFunc
- func (am *AuthManager) Authenticate(username, password string) (*Session, error)
- func (am *AuthManager) AuthenticateLDAP(username, password string) (*Session, error)
- func (am *AuthManager) CSRFMiddleware(next http.Handler) http.Handler
- func (am *AuthManager) ChangePassword(username, oldPassword, newPassword string) error
- func (am *AuthManager) CleanupExpiredCSRFTokens()
- func (am *AuthManager) CreateUser(username, password, role string) error
- func (am *AuthManager) DeleteUser(username string) error
- func (am *AuthManager) GenerateCSRFToken() string
- func (am *AuthManager) GetAuthMode() string
- func (am *AuthManager) GetLDAPConfig() *LDAPConfig
- func (am *AuthManager) GetUsers() []*User
- func (am *AuthManager) HandleAuthStatus(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleCSRFToken(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleCreateUser(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleCurrentUser(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleDeleteUser(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleKubeconfigLogin(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleLDAPStatus(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleLDAPTest(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleListUsers(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleLockUser(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleLogin(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleLogout(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleOIDCCallback(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleOIDCLogin(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleOIDCStatus(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleResetPassword(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleUnlockUser(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) HandleUpdateUser(w http.ResponseWriter, r *http.Request)
- func (am *AuthManager) InvalidateSession(sessionID string)
- func (am *AuthManager) IsLDAPEnabled() bool
- func (am *AuthManager) IsUserLocked(username string) bool
- func (am *AuthManager) LoadUserLocks()
- func (am *AuthManager) LockUser(username, lockedBy string) error
- func (am *AuthManager) SetRoleValidator(fn func(string) bool)
- func (am *AuthManager) StopCleanup()
- func (am *AuthManager) TestLDAPConnection() error
- func (am *AuthManager) UnlockUser(username string) error
- func (am *AuthManager) ValidateCSRFToken(token string) bool
- func (am *AuthManager) ValidateK8sToken(ctx context.Context, token string) (*Session, error)
- func (am *AuthManager) ValidateSession(sessionID string) (*Session, error)
- type AuthOptions
- type Authorizer
- func (az *Authorizer) AuthzMiddleware(resource string, action Action) func(http.HandlerFunc) http.HandlerFunc
- func (az *Authorizer) DeleteRole(name string) error
- func (az *Authorizer) FeatureMiddleware(feature Feature) func(http.HandlerFunc) http.HandlerFunc
- func (az *Authorizer) GetFeaturePermissions(role string) map[Feature]bool
- func (az *Authorizer) GetRole(name string) *RoleDefinition
- func (az *Authorizer) IsAllowed(role, resource string, action Action, namespace string) (bool, string)
- func (az *Authorizer) IsFeatureAllowed(role string, feature Feature) bool
- func (az *Authorizer) ListRoles() []*RoleDefinition
- func (az *Authorizer) RegisterRole(role *RoleDefinition)
- type BruteForceProtector
- type CISBenchmarkReport
- type ChatRequest
- type ChatResponse
- type ClusterInfo
- type ClusterMetricPoint
- type ComprehensiveReport
- type ContextInfo
- type ContextsResponse
- type CostEstimate
- type CostOptimization
- type CostRecommendation
- type DeploymentInfo
- type DeploymentRollbackRequest
- type DeploymentScaleRequest
- type DiffResponse
- type EventInfo
- type EventSummary
- type EventTimeWindow
- type EventTimelineResponse
- type Feature
- type FinOpsAnalysis
- type GitOpsApplication
- type GitOpsStatusResponse
- type HealingAction
- type HealingCondition
- type HealingEvent
- type HealingRule
- type HealingStore
- func (hs *HealingStore) AddRule(rule HealingRule) (HealingRule, error)
- func (hs *HealingStore) DeleteRule(id string) error
- func (hs *HealingStore) GetEvents(limit int) []HealingEvent
- func (hs *HealingStore) GetRules() []HealingRule
- func (hs *HealingStore) RecordEvent(event HealingEvent)
- func (hs *HealingStore) UpdateRule(id string, rule HealingRule) error
- type ImageInfo
- type ImageVulnerabilitySummary
- type ImpersonationConfig
- type ImpersonationTarget
- type JWTClaims
- type JWTConfig
- type JWTManager
- type K8sResourceResponse
- type K8sTokenValidator
- type LDAPConfig
- type LDAPProvider
- type LDAPUser
- type LLMCapabilities
- type LoginRequest
- type LoginResponse
- type MetricsHistory
- type MetricsHistorySummary
- type NamespaceCost
- type NamespaceInfo
- type NamespaceSummary
- type NetPolEdge
- type NetPolNode
- type NetPolPolicySummary
- type NetPolVisualizationResponse
- type NetworkIssueReport
- type NodeInfo
- type NodeSummary
- type NotificationConfig
- type NotificationHistoryEntry
- type NotificationManager
- func (nm *NotificationManager) DedupCount() int
- func (nm *NotificationManager) GetHistory() []NotificationHistoryEntry
- func (nm *NotificationManager) IsRunning() bool
- func (nm *NotificationManager) Restart()
- func (nm *NotificationManager) SendTestEmail() error
- func (nm *NotificationManager) Start()
- func (nm *NotificationManager) Stop()
- type OIDCConfig
- type OIDCDiscovery
- type OIDCProvider
- func (p *OIDCProvider) DetermineRole(userInfo *OIDCUserInfo) string
- func (p *OIDCProvider) ExchangeCode(ctx context.Context, code, redirectURI string) (*OIDCTokenResponse, error)
- func (p *OIDCProvider) GetAuthorizationURL(redirectURI string) (string, string, error)
- func (p *OIDCProvider) GetUserInfo(ctx context.Context, accessToken string) (*OIDCUserInfo, error)
- func (p *OIDCProvider) ValidateState(state string) bool
- type OIDCTokenResponse
- type OIDCUserInfo
- type OllamaPullRequest
- type OllamaStatusResponse
- type OverprovisionedWorkload
- type PendingToolApproval
- type PodInfo
- type PodMetricItem
- type PodSecurityIssueReport
- type PortForwardSession
- type RBACBindingDetail
- type RBACEdge
- type RBACIssueReport
- type RBACNode
- type RBACPolicyRule
- type RBACRoleRef
- type RBACSubjectDetailResponse
- type RBACSubjectInfo
- type RBACVisualizationResponse
- type RateLimiter
- type ReportGenerator
- func (rg *ReportGenerator) ExportToCSV(report *ComprehensiveReport) ([]byte, error)
- func (rg *ReportGenerator) ExportToHTML(report *ComprehensiveReport) string
- func (rg *ReportGenerator) GenerateAIAnalysis(ctx context.Context, report *ComprehensiveReport) (string, error)
- func (rg *ReportGenerator) GenerateComprehensiveReport(ctx context.Context, username string) (*ComprehensiveReport, error)
- func (rg *ReportGenerator) GenerateReport(ctx context.Context, username string, sections *ReportSections) (*ComprehensiveReport, error)
- func (rg *ReportGenerator) HandleReportPreview(w http.ResponseWriter, r *http.Request)
- func (rg *ReportGenerator) HandleReports(w http.ResponseWriter, r *http.Request)
- type ReportSections
- type ResourceCost
- type ResourceEfficiencyInfo
- type ResourceRef
- type ResourceReference
- type ResourceReferencesResponse
- type ResourceRule
- type RoleDefinition
- type RuntimeEnvironment
- type SMTPConfigJSON
- type SSEAgentListener
- func (l *SSEAgentListener) AgentApprovalRequested(choice *agent.ChoiceRequest)
- func (l *SSEAgentListener) AgentApprovalTimeout(choiceID string)
- func (l *SSEAgentListener) AgentError(err error)
- func (l *SSEAgentListener) AgentStateChanged(state agent.State)
- func (l *SSEAgentListener) AgentStreamChunk(chunk string)
- func (l *SSEAgentListener) AgentStreamEnd()
- func (l *SSEAgentListener) AgentTextReceived(text string)
- func (l *SSEAgentListener) AgentToolCallCompleted(tc *agent.ToolCallInfo)
- func (l *SSEAgentListener) AgentToolCallRequested(tc *agent.ToolCallInfo)
- func (l *SSEAgentListener) HandleApproval(choiceID string, approved bool) bool
- func (l *SSEAgentListener) WaitForApproval() bool
- type SSEApprovalHandler
- type SSEWriter
- type SafetyAnalysisRequest
- type SafetyAnalysisResponse
- type SearchResult
- type SecurityInfo
- type SecurityRecommendationReport
- type SecurityScanReport
- type Server
- type ServiceInfo
- type Session
- type TerminalHandler
- type TerminalMessage
- type TerminalSession
- type TokenReview
- type TopologyEdge
- type TopologyNode
- type TopologyResponse
- type TroubleshootFinding
- type TroubleshootReport
- type UnderutilizedResource
- type User
- type UserRequest
- type VeleroBackup
- type VeleroResponse
- type VeleroSchedule
- type VersionInfo
- type WebPulseData
- type WebPulseEvent
- type WorkloadCost
- type WorkloadSummary
- type XRayResponse
- type XRayTreeNode
- type YamlApplyRequest
Constants ¶
const ( ErrCodeInternalError = "INTERNAL_ERROR" ErrCodeBadRequest = "BAD_REQUEST" ErrCodeForbidden = "FORBIDDEN" ErrCodeNotFound = "NOT_FOUND" ErrCodeConflict = "CONFLICT" ErrCodeValidation = "VALIDATION_ERROR" ErrCodeK8sError = "K8S_ERROR" ErrCodeLLMError = "LLM_ERROR" ErrCodeLLMNotConfigured = "LLM_NOT_CONFIGURED" ErrCodeLLMNoToolCalling = "LLM_NO_TOOL_CALLING" ErrCodeHelmError = "HELM_ERROR" ErrCodeDatabaseError = "DATABASE_ERROR" ErrCodeTimeout = "TIMEOUT" ErrCodeRateLimited = "RATE_LIMITED" ErrCodeMethodNotAllowed = "METHOD_NOT_ALLOWED" )
Error codes for categorization
Variables ¶
This section is empty.
Functions ¶
func BadRequest ¶
func BadRequest(w http.ResponseWriter, message string)
BadRequest writes a 400 Bad Request error response
func ClientIP ¶ added in v0.9.3
ClientIP extracts the real client IP from a request, respecting X-Forwarded-For and X-Real-IP headers (for reverse proxy setups like nginx).
func Forbidden ¶
func Forbidden(w http.ResponseWriter, message string)
Forbidden writes a 403 Forbidden error response
func FriendlyErrorMessage ¶
FriendlyErrorMessage returns a user-friendly error message for display
func GetImpersonatedConfig ¶
func GetImpersonatedConfig(baseConfig *rest.Config, role string, cfg *ImpersonationConfig) *rest.Config
GetImpersonatedConfig returns a copy of the base config with impersonation headers set based on the user's role. If impersonation is disabled or the role is not mapped, returns the original config unchanged.
func HTTPError ¶
func HTTPError(w http.ResponseWriter, message string, statusCode int)
HTTPError is a convenience wrapper for common HTTP error responses. Use this as a drop-in replacement for http.Error() calls.
func InternalError ¶
func InternalError(w http.ResponseWriter, message string)
InternalError writes a 500 Internal Server Error response
func K8sError ¶
func K8sError(w http.ResponseWriter, err error)
K8sError writes an error response for Kubernetes API errors
func LLMError ¶
func LLMError(w http.ResponseWriter, err error, provider string)
LLMError writes an error response for LLM API errors
func MethodNotAllowed ¶
func MethodNotAllowed(w http.ResponseWriter, allowedMethods ...string)
MethodNotAllowed writes a 405 Method Not Allowed response
func NotFound ¶
func NotFound(w http.ResponseWriter, message string)
NotFound writes a 404 Not Found error response
func RateLimitMiddleware ¶
func RateLimitMiddleware(apiLimiter, authLimiter *RateLimiter) func(http.Handler) http.Handler
RateLimitMiddleware creates a rate limiting middleware Different limits for different endpoint categories
func Unauthorized ¶
func Unauthorized(w http.ResponseWriter, message string)
Unauthorized writes a 401 Unauthorized error response
func ValidateImpersonationConfig ¶
func ValidateImpersonationConfig(cfg *ImpersonationConfig) error
ValidateImpersonationConfig validates the impersonation configuration
func WriteError ¶
func WriteError(w http.ResponseWriter, err *APIError)
WriteError writes an API error to the response
func WriteErrorSimple ¶
func WriteErrorSimple(w http.ResponseWriter, statusCode int, message string)
WriteErrorSimple writes a simple error message (backward compatibility)
Types ¶
type APIError ¶
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Detail string `json:"detail,omitempty"`
Suggestion string `json:"suggestion,omitempty"`
StatusCode int `json:"-"`
}
APIError represents a user-friendly error response
func NewAPIError ¶
NewAPIError creates a new API error with a user-friendly message
func NewAPIErrorWithSuggestion ¶
NewAPIErrorWithSuggestion creates a new API error with a custom suggestion
func ParseK8sError ¶
ParseK8sError converts Kubernetes errors to user-friendly messages
func ParseLLMError ¶
ParseLLMError converts LLM errors to user-friendly messages
type AccessRequest ¶
type AccessRequest struct {
ID string `json:"id"`
RequestedBy string `json:"requested_by"`
Action Action `json:"action"`
Resource string `json:"resource"`
Namespace string `json:"namespace"`
Reason string `json:"reason"`
State AccessRequestState `json:"state"`
ReviewedBy string `json:"reviewed_by,omitempty"`
ReviewNote string `json:"review_note,omitempty"`
CreatedAt time.Time `json:"created_at"`
ReviewedAt time.Time `json:"reviewed_at,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
}
AccessRequest represents a request for elevated access (Teleport-inspired)
type AccessRequestManager ¶
type AccessRequestManager struct {
// contains filtered or unexported fields
}
AccessRequestManager manages access requests (Teleport-inspired workflow)
func NewAccessRequestManager ¶
func NewAccessRequestManager(ttl time.Duration) *AccessRequestManager
NewAccessRequestManager creates a new access request manager
func (*AccessRequestManager) ApproveRequest ¶
func (m *AccessRequestManager) ApproveRequest(id, reviewer, note string) error
ApproveRequest approves an access request (reviewer must be different from requester)
func (*AccessRequestManager) CleanupExpired ¶
func (m *AccessRequestManager) CleanupExpired()
CleanupExpired removes expired requests
func (*AccessRequestManager) CreateRequest ¶
func (m *AccessRequestManager) CreateRequest(requestedBy string, action Action, resource, namespace, reason string) (string, error)
CreateRequest creates a new access request
func (*AccessRequestManager) DenyRequest ¶
func (m *AccessRequestManager) DenyRequest(id, reviewer, note string) error
DenyRequest denies an access request
func (*AccessRequestManager) GetPendingRequests ¶
func (m *AccessRequestManager) GetPendingRequests() []*AccessRequest
GetPendingRequests returns all pending access requests
func (*AccessRequestManager) GetRequest ¶
func (m *AccessRequestManager) GetRequest(id string) *AccessRequest
GetRequest returns a specific access request
func (*AccessRequestManager) HandleApproveAccessRequest ¶
func (m *AccessRequestManager) HandleApproveAccessRequest(w http.ResponseWriter, r *http.Request)
HandleApproveAccessRequest handles POST /api/access/approve/{id}
func (*AccessRequestManager) HandleCreateAccessRequest ¶
func (m *AccessRequestManager) HandleCreateAccessRequest(w http.ResponseWriter, r *http.Request)
HandleCreateAccessRequest handles POST /api/access/request
func (*AccessRequestManager) HandleDenyAccessRequest ¶
func (m *AccessRequestManager) HandleDenyAccessRequest(w http.ResponseWriter, r *http.Request)
HandleDenyAccessRequest handles POST /api/access/deny/{id}
func (*AccessRequestManager) HandleListAccessRequests ¶
func (m *AccessRequestManager) HandleListAccessRequests(w http.ResponseWriter, r *http.Request)
HandleListAccessRequests handles GET /api/access/requests
func (*AccessRequestManager) IsApproved ¶
func (m *AccessRequestManager) IsApproved(username, resource string, action Action, namespace string) bool
IsApproved checks if a user has an approved access request for a specific action
type AccessRequestState ¶
type AccessRequestState string
AccessRequestState represents the state of an access request
const ( AccessRequestPending AccessRequestState = "pending" AccessRequestApproved AccessRequestState = "approved" AccessRequestDenied AccessRequestState = "denied" AccessRequestExpired AccessRequestState = "expired" )
type AccountLockout ¶ added in v0.9.3
type AccountLockout struct {
MaxFailures int // failures before lock (default: 10)
LockDuration time.Duration // how long the lock lasts (default: 30min)
// contains filtered or unexported fields
}
AccountLockout tracks per-account failed login attempts and temporarily locks accounts after too many consecutive failures (independent of IP).
func NewAccountLockout ¶ added in v0.9.3
func NewAccountLockout() *AccountLockout
NewAccountLockout creates an AccountLockout with default settings.
func (*AccountLockout) FailureCount ¶ added in v0.9.3
func (al *AccountLockout) FailureCount(username string) int
FailureCount returns the current failure count for a username (for testing).
func (*AccountLockout) IsLocked ¶ added in v0.9.3
func (al *AccountLockout) IsLocked(username string) bool
IsLocked returns true if the account is currently locked due to failed attempts.
func (*AccountLockout) RecordFailure ¶ added in v0.9.3
func (al *AccountLockout) RecordFailure(username string) bool
RecordFailure increments the failure counter for a username. Returns true if the account just became locked.
func (*AccountLockout) RecordSuccess ¶ added in v0.9.3
func (al *AccountLockout) RecordSuccess(username string)
RecordSuccess resets the failure counter on successful login.
func (*AccountLockout) Stop ¶ added in v0.9.3
func (al *AccountLockout) Stop()
Stop signals the cleanup goroutine to exit.
type Action ¶
type Action string
Action represents a resource action type for RBAC (Teleport-inspired)
const ( ActionView Action = "view" ActionDelete Action = "delete" ActionScale Action = "scale" ActionRestart Action = "restart" ActionExec Action = "exec" ActionPortForward Action = "port-forward" ActionApply Action = "apply" ActionLogs Action = "logs" ActionCreate Action = "create" ActionEdit Action = "edit" )
type ApplicationGroup ¶
type ApplicationGroup struct {
Name string `json:"name"`
Version string `json:"version,omitempty"`
Component string `json:"component,omitempty"`
Status string `json:"status"` // "healthy", "degraded", "failing"
PodCount int `json:"podCount"`
ReadyPods int `json:"readyPods"`
Resources map[string][]ResourceRef `json:"resources"`
}
ApplicationGroup is the API response type for application grouping
type AuthConfig ¶
type AuthConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
SessionDuration time.Duration `yaml:"session_duration" json:"session_duration"`
DefaultAdmin string `yaml:"default_admin" json:"default_admin"`
DefaultPassword string `yaml:"default_password" json:"-"`
LDAP *LDAPConfig `yaml:"ldap" json:"ldap"`
OIDC *OIDCConfig `yaml:"oidc" json:"oidc"`
// AuthMode: "token" (K8s RBAC token - default), "local" (username/password), "ldap", "oidc"
AuthMode string `yaml:"auth_mode" json:"auth_mode"`
// Quiet suppresses informational output (useful for tests)
Quiet bool `yaml:"-" json:"-"`
}
AuthConfig holds authentication configuration
type AuthManager ¶
type AuthManager struct {
// contains filtered or unexported fields
}
AuthManager handles authentication
func NewAuthManager ¶
func NewAuthManager(cfg *AuthConfig) *AuthManager
NewAuthManager creates a new AuthManager
func (*AuthManager) AdminMiddleware ¶
func (am *AuthManager) AdminMiddleware(next http.HandlerFunc) http.HandlerFunc
AdminMiddleware is a middleware that requires admin role
func (*AuthManager) AuthMiddleware ¶
func (am *AuthManager) AuthMiddleware(next http.HandlerFunc) http.HandlerFunc
AuthMiddleware is a middleware that validates authentication
func (*AuthManager) Authenticate ¶
func (am *AuthManager) Authenticate(username, password string) (*Session, error)
Authenticate validates credentials and creates a session
func (*AuthManager) AuthenticateLDAP ¶
func (am *AuthManager) AuthenticateLDAP(username, password string) (*Session, error)
func (*AuthManager) CSRFMiddleware ¶
func (am *AuthManager) CSRFMiddleware(next http.Handler) http.Handler
CSRFMiddleware handles CSRF protection
func (*AuthManager) ChangePassword ¶
func (am *AuthManager) ChangePassword(username, oldPassword, newPassword string) error
func (*AuthManager) CleanupExpiredCSRFTokens ¶
func (am *AuthManager) CleanupExpiredCSRFTokens()
CleanupExpiredCSRFTokens removes expired CSRF tokens
func (*AuthManager) CreateUser ¶
func (am *AuthManager) CreateUser(username, password, role string) error
CreateUser creates a new local user
func (*AuthManager) DeleteUser ¶
func (am *AuthManager) DeleteUser(username string) error
DeleteUser removes a user
func (*AuthManager) GenerateCSRFToken ¶
func (am *AuthManager) GenerateCSRFToken() string
GenerateCSRFToken generates a new CSRF token
func (*AuthManager) GetAuthMode ¶
func (am *AuthManager) GetAuthMode() string
GetAuthMode returns the current authentication mode
func (*AuthManager) GetLDAPConfig ¶
func (am *AuthManager) GetLDAPConfig() *LDAPConfig
GetLDAPConfig returns the LDAP configuration (without sensitive data)
func (*AuthManager) GetUsers ¶
func (am *AuthManager) GetUsers() []*User
GetUsers returns all local users
func (*AuthManager) HandleAuthStatus ¶
func (am *AuthManager) HandleAuthStatus(w http.ResponseWriter, r *http.Request)
HandleAuthStatus returns the current authentication status
func (*AuthManager) HandleCSRFToken ¶
func (am *AuthManager) HandleCSRFToken(w http.ResponseWriter, r *http.Request)
HandleCSRFToken returns a new CSRF token
func (*AuthManager) HandleCreateUser ¶
func (am *AuthManager) HandleCreateUser(w http.ResponseWriter, r *http.Request)
HandleCreateUser creates a new user (admin only)
func (*AuthManager) HandleCurrentUser ¶
func (am *AuthManager) HandleCurrentUser(w http.ResponseWriter, r *http.Request)
HandleCurrentUser returns the current user info
func (*AuthManager) HandleDeleteUser ¶
func (am *AuthManager) HandleDeleteUser(w http.ResponseWriter, r *http.Request)
HandleDeleteUser deletes a user (admin only)
func (*AuthManager) HandleKubeconfigLogin ¶
func (am *AuthManager) HandleKubeconfigLogin(w http.ResponseWriter, r *http.Request)
HandleKubeconfigLogin handles auto-login using current kubeconfig credentials This is only available when running locally (not in-cluster)
func (*AuthManager) HandleLDAPStatus ¶
func (am *AuthManager) HandleLDAPStatus(w http.ResponseWriter, r *http.Request)
HandleLDAPStatus returns LDAP configuration status
func (*AuthManager) HandleLDAPTest ¶
func (am *AuthManager) HandleLDAPTest(w http.ResponseWriter, r *http.Request)
HandleLDAPTest tests the LDAP connection
func (*AuthManager) HandleListUsers ¶
func (am *AuthManager) HandleListUsers(w http.ResponseWriter, r *http.Request)
HandleListUsers returns list of all users (admin only)
func (*AuthManager) HandleLockUser ¶
func (am *AuthManager) HandleLockUser(w http.ResponseWriter, r *http.Request)
HandleLockUser handles POST /api/admin/lock - locks a user account (admin only)
func (*AuthManager) HandleLogin ¶
func (am *AuthManager) HandleLogin(w http.ResponseWriter, r *http.Request)
HandleLogin handles login requests
func (*AuthManager) HandleLogout ¶
func (am *AuthManager) HandleLogout(w http.ResponseWriter, r *http.Request)
HandleLogout handles logout requests
func (*AuthManager) HandleOIDCCallback ¶
func (am *AuthManager) HandleOIDCCallback(w http.ResponseWriter, r *http.Request)
HandleOIDCCallback handles the OIDC callback
func (*AuthManager) HandleOIDCLogin ¶
func (am *AuthManager) HandleOIDCLogin(w http.ResponseWriter, r *http.Request)
HandleOIDCLogin initiates OIDC login flow
func (*AuthManager) HandleOIDCStatus ¶
func (am *AuthManager) HandleOIDCStatus(w http.ResponseWriter, r *http.Request)
HandleOIDCStatus returns OIDC configuration status
func (*AuthManager) HandleResetPassword ¶
func (am *AuthManager) HandleResetPassword(w http.ResponseWriter, r *http.Request)
HandleResetPassword resets a user's password (admin only)
func (*AuthManager) HandleUnlockUser ¶
func (am *AuthManager) HandleUnlockUser(w http.ResponseWriter, r *http.Request)
HandleUnlockUser handles POST /api/admin/unlock - unlocks a user account (admin only)
func (*AuthManager) HandleUpdateUser ¶
func (am *AuthManager) HandleUpdateUser(w http.ResponseWriter, r *http.Request)
HandleUpdateUser updates an existing user (admin only)
func (*AuthManager) InvalidateSession ¶
func (am *AuthManager) InvalidateSession(sessionID string)
InvalidateSession removes a session
func (*AuthManager) IsLDAPEnabled ¶
func (am *AuthManager) IsLDAPEnabled() bool
IsLDAPEnabled returns whether LDAP is enabled
func (*AuthManager) IsUserLocked ¶
func (am *AuthManager) IsUserLocked(username string) bool
IsUserLocked checks if a user is locked (fast path: in-memory, fallback: DB)
func (*AuthManager) LoadUserLocks ¶
func (am *AuthManager) LoadUserLocks()
LoadUserLocks loads persisted user locks from the database on startup
func (*AuthManager) LockUser ¶
func (am *AuthManager) LockUser(username, lockedBy string) error
LockUser locks a user account immediately and invalidates all sessions (Teleport-inspired)
func (*AuthManager) SetRoleValidator ¶
func (am *AuthManager) SetRoleValidator(fn func(string) bool)
SetRoleValidator sets a function that validates custom role names
func (*AuthManager) StopCleanup ¶ added in v0.9.3
func (am *AuthManager) StopCleanup()
StopCleanup stops the cleanup goroutine
func (*AuthManager) TestLDAPConnection ¶
func (am *AuthManager) TestLDAPConnection() error
TestLDAPConnection tests the LDAP connection
func (*AuthManager) UnlockUser ¶
func (am *AuthManager) UnlockUser(username string) error
UnlockUser unlocks a previously locked user account
func (*AuthManager) ValidateCSRFToken ¶
func (am *AuthManager) ValidateCSRFToken(token string) bool
ValidateCSRFToken validates a CSRF token
func (*AuthManager) ValidateK8sToken ¶
ValidateK8sToken validates a Kubernetes service account token
func (*AuthManager) ValidateSession ¶
func (am *AuthManager) ValidateSession(sessionID string) (*Session, error)
ValidateSession checks if a session ID is valid and returns the session
type AuthOptions ¶
type AuthOptions struct {
Mode string // token, local, ldap
Disabled bool // Disable authentication entirely
DefaultAdmin string // Default admin username for local mode
DefaultPassword string // Default admin password for local mode
Experimental bool // Enable experimental features (unstable)
}
AuthOptions holds CLI authentication options
type Authorizer ¶
type Authorizer struct {
// contains filtered or unexported fields
}
Authorizer manages RBAC authorization (Teleport-inspired)
func NewAuthorizer ¶
func NewAuthorizer() *Authorizer
NewAuthorizer creates a new Authorizer with default roles
func NewAuthorizerWithRoles ¶
func NewAuthorizerWithRoles(customRoles []RoleDefinition) *Authorizer
NewAuthorizerWithRoles creates an Authorizer with custom roles merged with defaults
func (*Authorizer) AuthzMiddleware ¶
func (az *Authorizer) AuthzMiddleware(resource string, action Action) func(http.HandlerFunc) http.HandlerFunc
AuthzMiddleware creates an HTTP middleware that checks RBAC authorization It extracts the user role from the X-User-Role header (set by AuthMiddleware)
func (*Authorizer) DeleteRole ¶
func (az *Authorizer) DeleteRole(name string) error
DeleteRole removes a custom role. Built-in roles (admin, user, viewer) cannot be deleted.
func (*Authorizer) FeatureMiddleware ¶
func (az *Authorizer) FeatureMiddleware(feature Feature) func(http.HandlerFunc) http.HandlerFunc
FeatureMiddleware creates HTTP middleware that checks feature-level access
func (*Authorizer) GetFeaturePermissions ¶
func (az *Authorizer) GetFeaturePermissions(role string) map[Feature]bool
GetFeaturePermissions returns a map of all features to their allowed/denied status for a role
func (*Authorizer) GetRole ¶
func (az *Authorizer) GetRole(name string) *RoleDefinition
GetRole returns a role definition by name
func (*Authorizer) IsAllowed ¶
func (az *Authorizer) IsAllowed(role, resource string, action Action, namespace string) (bool, string)
IsAllowed checks if a role is allowed to perform an action on a resource in a namespace Returns (allowed, reason) - deny always overrides allow (Teleport pattern)
func (*Authorizer) IsFeatureAllowed ¶
func (az *Authorizer) IsFeatureAllowed(role string, feature Feature) bool
IsFeatureAllowed checks if a role is allowed to access a feature. Deny overrides allow. "*" in AllowedFeatures means all features.
func (*Authorizer) ListRoles ¶
func (az *Authorizer) ListRoles() []*RoleDefinition
ListRoles returns all registered role definitions
func (*Authorizer) RegisterRole ¶
func (az *Authorizer) RegisterRole(role *RoleDefinition)
RegisterRole adds or replaces a role definition
type BruteForceProtector ¶ added in v0.9.3
type BruteForceProtector struct {
// Configuration (exported for testing).
MaxFailures int // consecutive failures before blocking (default: 5)
BlockDuration time.Duration // how long an IP stays blocked (default: 15min)
Delays []time.Duration // progressive delay per failure count (index = failure #)
// contains filtered or unexported fields
}
BruteForceProtector tracks failed login attempts per IP and applies progressive delays and temporary bans.
func NewBruteForceProtector ¶ added in v0.9.3
func NewBruteForceProtector() *BruteForceProtector
NewBruteForceProtector creates a protector with sensible defaults.
func (*BruteForceProtector) FailureCount ¶ added in v0.9.3
func (bp *BruteForceProtector) FailureCount(ip string) int
FailureCount returns the current consecutive failure count for an IP (for testing/monitoring).
func (*BruteForceProtector) IsBlocked ¶ added in v0.9.3
func (bp *BruteForceProtector) IsBlocked(ip string) bool
IsBlocked returns true if the IP is currently blocked.
func (*BruteForceProtector) RecordFailure ¶ added in v0.9.3
func (bp *BruteForceProtector) RecordFailure(ip string) time.Duration
RecordFailure increments the failure counter for an IP. Returns the delay the caller should apply before responding.
func (*BruteForceProtector) RecordSuccess ¶ added in v0.9.3
func (bp *BruteForceProtector) RecordSuccess(ip string)
RecordSuccess resets the failure counter for an IP on successful login.
func (*BruteForceProtector) Stop ¶ added in v0.9.3
func (bp *BruteForceProtector) Stop()
Stop signals the cleanup goroutine to exit.
type CISBenchmarkReport ¶
type CISBenchmarkReport struct {
Version string `json:"version"`
TotalChecks int `json:"total_checks"`
PassCount int `json:"pass_count"`
FailCount int `json:"fail_count"`
WarnCount int `json:"warn_count"`
Score float64 `json:"score"`
}
CISBenchmarkReport contains CIS benchmark results for reports
type ChatRequest ¶
type ChatRequest struct {
Message string `json:"message"`
Context string `json:"context,omitempty"` // Selected resource context for the AI prompt only
SessionID string `json:"session_id,omitempty"` // Session ID for conversation history
Language string `json:"language,omitempty"` // Display language preference (e.g., "ko", "en")
}
type ChatResponse ¶
type ClusterInfo ¶
type ClusterMetricPoint ¶
type ClusterMetricPoint struct {
Timestamp string `json:"timestamp"`
CPUUsage int64 `json:"cpu_usage_millis"`
MemoryUsage int64 `json:"memory_usage_mb"`
RunningPods int `json:"running_pods"`
ReadyNodes int `json:"ready_nodes"`
}
ClusterMetricPoint is a single point in time-series
type ComprehensiveReport ¶
type ComprehensiveReport struct {
GeneratedAt time.Time `json:"generated_at"`
GeneratedBy string `json:"generated_by"`
IncludedSections ReportSections `json:"included_sections"`
ClusterInfo ClusterInfo `json:"cluster_info"`
NodeSummary NodeSummary `json:"node_summary"`
Nodes []NodeInfo `json:"nodes"`
NamespaceSummary NamespaceSummary `json:"namespace_summary"`
Namespaces []NamespaceInfo `json:"namespaces"`
Workloads WorkloadSummary `json:"workloads"`
Pods []PodInfo `json:"pods"`
Deployments []DeploymentInfo `json:"deployments"`
Services []ServiceInfo `json:"services"`
SecurityInfo SecurityInfo `json:"security_info"`
SecurityScan *SecurityScanReport `json:"security_scan,omitempty"`
FinOpsAnalysis FinOpsAnalysis `json:"finops_analysis"`
Images []ImageInfo `json:"images"`
Events []EventInfo `json:"events"`
MetricsHistory *MetricsHistory `json:"metrics_history,omitempty"`
AIAnalysis string `json:"ai_analysis,omitempty"`
HealthScore float64 `json:"health_score"`
}
type ContextInfo ¶
type ContextInfo struct {
Name string `json:"name"`
Cluster string `json:"cluster"`
User string `json:"user"`
Namespace string `json:"namespace,omitempty"`
IsCurrent bool `json:"isCurrent"`
}
ContextInfo represents a kubeconfig context
type ContextsResponse ¶
type ContextsResponse struct {
Contexts []ContextInfo `json:"contexts"`
CurrentContext string `json:"currentContext"`
}
ContextsResponse is the response for listing contexts
type CostEstimate ¶
type CostEstimate struct {
Namespace string `json:"namespace"`
TotalCPU ResourceCost `json:"totalCPU"`
TotalMemory ResourceCost `json:"totalMemory"`
Workloads []WorkloadCost `json:"workloads"`
Efficiency float64 `json:"efficiency"`
Recommendations []CostRecommendation `json:"recommendations,omitempty"`
}
CostEstimate represents resource cost data for a namespace or cluster.
type CostOptimization ¶
type CostOptimization struct {
Category string `json:"category"`
Description string `json:"description"`
Impact string `json:"impact"`
EstimatedSaving float64 `json:"estimated_saving"`
Priority string `json:"priority"` // high, medium, low
}
CostOptimization represents a cost saving recommendation
type CostRecommendation ¶
type CostRecommendation struct {
Workload string `json:"workload"`
Type string `json:"type"` // "oversized", "undersized", "idle"
Description string `json:"description"`
Savings string `json:"savings,omitempty"`
}
CostRecommendation provides optimization guidance for a workload.
type DeploymentInfo ¶
type DeploymentRollbackRequest ¶
type DeploymentRollbackRequest struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Revision int64 `json:"revision,omitempty"` // 0 means rollback to previous
}
DeploymentRollbackRequest represents a rollback request
type DeploymentScaleRequest ¶
type DeploymentScaleRequest struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Replicas int32 `json:"replicas"`
}
DeploymentScaleRequest represents a scale request
type DiffResponse ¶
type DiffResponse struct {
Resource string `json:"resource"`
Name string `json:"name"`
Namespace string `json:"namespace"`
CurrentYAML string `json:"currentYaml"`
LastApplied string `json:"lastApplied"`
HasDiff bool `json:"hasDiff"`
}
DiffResponse is the response for the resource diff endpoint
type EventSummary ¶
type EventSummary struct {
Type string `json:"type"`
Reason string `json:"reason"`
Message string `json:"message"`
Object string `json:"object"` // Kind/Name
Count int32 `json:"count"`
FirstSeen time.Time `json:"firstSeen"`
LastSeen time.Time `json:"lastSeen"`
}
EventSummary is a condensed event for timeline display
type EventTimeWindow ¶
type EventTimeWindow struct {
Timestamp time.Time `json:"timestamp"`
NormalCount int `json:"normalCount"`
WarningCount int `json:"warningCount"`
Events []EventSummary `json:"events,omitempty"`
}
EventTimeWindow represents events grouped by a time window
type EventTimelineResponse ¶
type EventTimelineResponse struct {
Windows []EventTimeWindow `json:"windows"`
TotalNormal int `json:"totalNormal"`
TotalWarning int `json:"totalWarning"`
Namespace string `json:"namespace"`
Hours int `json:"hours"`
}
EventTimelineResponse is the response for the event timeline endpoint
type Feature ¶
type Feature string
Feature represents a UI/API feature that can be gated by role
const ( FeatureDashboard Feature = "dashboard" FeatureTopology Feature = "topology" FeatureMetrics Feature = "metrics" FeatureHelmManagement Feature = "helm_management" FeatureSecurityScan Feature = "security_scan" FeatureAIAssistant Feature = "ai_assistant" FeatureTerminal Feature = "terminal" FeatureReports Feature = "reports" FeatureEventTimeline Feature = "event_timeline" FeatureAuditLogs Feature = "audit_logs" FeaturePortForward Feature = "port_forward" FeatureGitOps Feature = "gitops" FeatureVelero Feature = "velero" FeatureCostEstimate Feature = "cost_estimate" FeatureNetworkPolicy Feature = "network_policy" FeatureRBACViz Feature = "rbac_viz" FeatureSettingsGeneral Feature = "settings_general" FeatureSettingsAdmin Feature = "settings_admin" FeatureSettingsSecurity Feature = "settings_security" FeatureSettingsNotif Feature = "settings_notif" FeatureHostTerminal Feature = "host_terminal" )
type FinOpsAnalysis ¶
type FinOpsAnalysis struct {
TotalEstimatedMonthlyCost float64 `json:"total_estimated_monthly_cost"`
EstimationModel string `json:"estimation_model"`
EstimationNotes []string `json:"estimation_notes,omitempty"`
CostByNamespace []NamespaceCost `json:"cost_by_namespace"`
ResourceEfficiency ResourceEfficiencyInfo `json:"resource_efficiency"`
CostOptimizations []CostOptimization `json:"cost_optimizations"`
UnderutilizedResources []UnderutilizedResource `json:"underutilized_resources"`
OverprovisionedWorkloads []OverprovisionedWorkload `json:"overprovisioned_workloads"`
}
FinOpsAnalysis contains cost optimization insights
type GitOpsApplication ¶
type GitOpsApplication struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Status string `json:"status"`
SyncStatus string `json:"syncStatus,omitempty"`
Source string `json:"source,omitempty"`
Revision string `json:"revision,omitempty"`
Message string `json:"message,omitempty"`
}
GitOpsApplication represents an ArgoCD or Flux application
type GitOpsStatusResponse ¶
type GitOpsStatusResponse struct {
ArgoCD []GitOpsApplication `json:"argocd"`
Flux []GitOpsApplication `json:"flux"`
Message string `json:"message,omitempty"`
}
GitOpsStatusResponse is the response for the GitOps status endpoint
type HealingAction ¶
type HealingAction struct {
Type string `json:"type"` // "restart", "scale_up", "notify", "delete_pod"
Parameters map[string]string `json:"parameters,omitempty"`
}
HealingAction describes the remediation action to take.
type HealingCondition ¶
type HealingCondition struct {
Type string `json:"type"` // "crashloop", "oom", "pending", "high_restart"
Threshold int `json:"threshold,omitempty"` // e.g., restart count threshold
Duration string `json:"duration,omitempty"` // e.g., "5m" for how long condition must persist
}
HealingCondition describes the trigger condition for a healing rule.
type HealingEvent ¶
type HealingEvent struct {
Timestamp string `json:"timestamp"`
RuleName string `json:"ruleName"`
Resource string `json:"resource"`
Namespace string `json:"namespace"`
Action string `json:"action"`
Result string `json:"result"` // "success", "failed", "skipped"
Details string `json:"details,omitempty"`
}
HealingEvent records a healing action taken.
type HealingRule ¶
type HealingRule struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Condition HealingCondition `json:"condition"`
Action HealingAction `json:"action"`
Cooldown string `json:"cooldown"`
MaxRetries int `json:"maxRetries"`
Namespaces []string `json:"namespaces,omitempty"`
}
HealingRule defines an auto-remediation rule.
type HealingStore ¶
type HealingStore struct {
// contains filtered or unexported fields
}
HealingStore provides thread-safe in-memory storage for healing rules and events.
func NewHealingStore ¶
func NewHealingStore() *HealingStore
NewHealingStore creates a new in-memory healing store.
func (*HealingStore) AddRule ¶
func (hs *HealingStore) AddRule(rule HealingRule) (HealingRule, error)
AddRule adds a new healing rule and assigns an ID.
func (*HealingStore) DeleteRule ¶
func (hs *HealingStore) DeleteRule(id string) error
DeleteRule removes a healing rule by ID.
func (*HealingStore) GetEvents ¶
func (hs *HealingStore) GetEvents(limit int) []HealingEvent
GetEvents returns the most recent healing events, limited by count.
func (*HealingStore) GetRules ¶
func (hs *HealingStore) GetRules() []HealingRule
GetRules returns all healing rules.
func (*HealingStore) RecordEvent ¶
func (hs *HealingStore) RecordEvent(event HealingEvent)
RecordEvent records a healing event.
func (*HealingStore) UpdateRule ¶
func (hs *HealingStore) UpdateRule(id string, rule HealingRule) error
UpdateRule updates an existing healing rule by ID.
type ImageVulnerabilitySummary ¶
type ImageVulnerabilitySummary struct {
TotalImages int `json:"total_images"`
ScannedImages int `json:"scanned_images"`
VulnerableImages int `json:"vulnerable_images"`
CriticalCount int `json:"critical_count"`
HighCount int `json:"high_count"`
MediumCount int `json:"medium_count"`
LowCount int `json:"low_count"`
}
ImageVulnerabilitySummary summarizes container image vulnerabilities
type ImpersonationConfig ¶
type ImpersonationConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"` // Default: false (opt-in)
Mappings map[string]ImpersonationTarget `yaml:"mappings" json:"mappings"` // role -> impersonation target
}
ImpersonationConfig controls K8s impersonation behavior (Teleport-inspired)
func DefaultImpersonationConfig ¶
func DefaultImpersonationConfig() *ImpersonationConfig
DefaultImpersonationConfig returns the default impersonation configuration
type ImpersonationTarget ¶
type ImpersonationTarget struct {
User string `yaml:"user" json:"user"` // K8s username to impersonate
Groups []string `yaml:"groups" json:"groups"` // K8s groups to impersonate
}
ImpersonationTarget defines the K8s user/groups to impersonate for a role
type JWTClaims ¶
type JWTClaims struct {
Subject string `json:"sub"` // User ID
Username string `json:"username"` // Username
Role string `json:"role"` // User role
SessionID string `json:"sid"` // Associated session ID
IssuedAt int64 `json:"iat"` // Issued at (unix timestamp)
ExpiresAt int64 `json:"exp"` // Expires at (unix timestamp)
}
JWTClaims represents the claims in a k13d JWT token
type JWTConfig ¶
type JWTConfig struct {
Secret []byte // HMAC-SHA256 signing secret
TokenDuration time.Duration // Token lifetime (default: 1h)
RefreshWindow time.Duration // Window before expiry to auto-refresh (default: 15m)
}
JWTConfig holds JWT configuration
type JWTManager ¶
type JWTManager struct {
// contains filtered or unexported fields
}
JWTManager handles JWT generation and validation (stdlib only, no external deps)
func NewJWTManager ¶
func NewJWTManager(cfg JWTConfig) *JWTManager
NewJWTManager creates a new JWT manager. NOTE: If no secret is provided, a random secret is generated on each server start. This means all JWT tokens are invalidated on server restart, which is the intended behavior for short-lived tokens. For persistent JWT validation across restarts, provide a stable secret via JWTConfig.Secret.
func (*JWTManager) GenerateToken ¶
func (j *JWTManager) GenerateToken(claims JWTClaims) (string, error)
GenerateToken creates a signed JWT token from claims
func (*JWTManager) NeedsRefresh ¶
func (j *JWTManager) NeedsRefresh(tokenString string) bool
NeedsRefresh checks if a token is within the refresh window
func (*JWTManager) RefreshToken ¶
func (j *JWTManager) RefreshToken(tokenString string) (string, error)
RefreshToken creates a new token if the current one is within the refresh window
func (*JWTManager) ValidateToken ¶
func (j *JWTManager) ValidateToken(tokenString string) (*JWTClaims, error)
ValidateToken validates a JWT token and returns the claims
type K8sResourceResponse ¶
type K8sTokenValidator ¶
type K8sTokenValidator struct {
// contains filtered or unexported fields
}
K8sTokenValidator validates Kubernetes service account tokens
func NewK8sTokenValidator ¶
func NewK8sTokenValidator() (*K8sTokenValidator, error)
NewK8sTokenValidator creates a new K8s token validator
func (*K8sTokenValidator) GetEnvironment ¶
func (v *K8sTokenValidator) GetEnvironment() RuntimeEnvironment
GetEnvironment returns the runtime environment
func (*K8sTokenValidator) GetKubeconfigUser ¶
func (v *K8sTokenValidator) GetKubeconfigUser() string
GetKubeconfigUser returns the current kubeconfig user (for local mode)
func (*K8sTokenValidator) ValidateToken ¶
func (v *K8sTokenValidator) ValidateToken(ctx context.Context, token string) (*TokenReview, error)
ValidateToken validates a Kubernetes token and returns user info
type LDAPConfig ¶
type LDAPConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
UseTLS bool `yaml:"use_tls" json:"use_tls"`
StartTLS bool `yaml:"start_tls" json:"start_tls"`
InsecureSkipTLS bool `yaml:"insecure_skip_tls" json:"insecure_skip_tls"`
BindDN string `yaml:"bind_dn" json:"bind_dn"`
BindPassword string `yaml:"bind_password" json:"-"`
BaseDN string `yaml:"base_dn" json:"base_dn"`
UserSearchFilter string `yaml:"user_search_filter" json:"user_search_filter"` // e.g., "(uid=%s)" or "(sAMAccountName=%s)"
UserSearchBase string `yaml:"user_search_base" json:"user_search_base"`
GroupSearchBase string `yaml:"group_search_base" json:"group_search_base"`
GroupSearchFilter string `yaml:"group_search_filter" json:"group_search_filter"` // e.g., "(member=%s)"
AdminGroups []string `yaml:"admin_groups" json:"admin_groups"` // Groups that grant admin role
UserGroups []string `yaml:"user_groups" json:"user_groups"` // Groups that grant user role
ViewerGroups []string `yaml:"viewer_groups" json:"viewer_groups"` // Groups that grant viewer role
UsernameAttr string `yaml:"username_attr" json:"username_attr"` // e.g., "uid" or "sAMAccountName"
EmailAttr string `yaml:"email_attr" json:"email_attr"` // e.g., "mail"
DisplayNameAttr string `yaml:"display_name_attr" json:"display_name_attr"` // e.g., "cn" or "displayName"
}
LDAPConfig holds LDAP configuration
type LDAPProvider ¶
type LDAPProvider struct {
// contains filtered or unexported fields
}
LDAPProvider handles LDAP authentication
func NewLDAPProvider ¶
func NewLDAPProvider(cfg *LDAPConfig) *LDAPProvider
NewLDAPProvider creates a new LDAP provider
func (*LDAPProvider) Authenticate ¶
func (p *LDAPProvider) Authenticate(username, password string) (*LDAPUser, error)
Authenticate validates user credentials against LDAP
func (*LDAPProvider) GetConfig ¶
func (p *LDAPProvider) GetConfig() *LDAPConfig
GetConfig returns a copy of the LDAP config (without sensitive data)
func (*LDAPProvider) IsEnabled ¶
func (p *LDAPProvider) IsEnabled() bool
IsEnabled returns whether LDAP is enabled
func (*LDAPProvider) TestConnection ¶
func (p *LDAPProvider) TestConnection() error
TestConnection tests the LDAP connection
type LDAPUser ¶
type LDAPUser struct {
Username string `json:"username"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
DN string `json:"dn"`
Groups []string `json:"groups"`
Role string `json:"role"`
}
LDAPUser represents a user retrieved from LDAP
type LLMCapabilities ¶
type LLMCapabilities struct {
ToolCalling bool `json:"tool_calling"`
JSONMode bool `json:"json_mode"`
Streaming bool `json:"streaming"`
MaxTokens int `json:"max_tokens,omitempty"`
Recommendation string `json:"recommendation,omitempty"`
}
LLMCapabilities represents the capabilities of the configured LLM
type LoginRequest ¶
type LoginRequest struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Token string `json:"token,omitempty"` // K8s service account token
}
LoginRequest represents a login request
type LoginResponse ¶
type LoginResponse struct {
Token string `json:"token"`
JWTToken string `json:"jwt_token,omitempty"` // JWT token (Teleport-inspired short-lived)
Username string `json:"username"`
Role string `json:"role"`
ExpiresAt time.Time `json:"expires_at"`
AuthMode string `json:"auth_mode"`
}
LoginResponse represents a login response
type MetricsHistory ¶
type MetricsHistory struct {
Period string `json:"period"` // e.g., "24h", "7d"
DataPoints int `json:"data_points"`
ClusterMetrics []ClusterMetricPoint `json:"cluster_metrics"`
Summary MetricsHistorySummary `json:"summary"`
}
MetricsHistory contains time-series data for the report
type MetricsHistorySummary ¶
type MetricsHistorySummary struct {
AvgCPUUsage int64 `json:"avg_cpu_usage_millis"`
MaxCPUUsage int64 `json:"max_cpu_usage_millis"`
AvgMemoryUsage int64 `json:"avg_memory_usage_mb"`
MaxMemoryUsage int64 `json:"max_memory_usage_mb"`
AvgRunningPods float64 `json:"avg_running_pods"`
MaxRunningPods int `json:"max_running_pods"`
}
MetricsHistorySummary provides statistical summary of metrics
type NamespaceCost ¶
type NamespaceCost struct {
Namespace string `json:"namespace"`
PodCount int `json:"pod_count"`
RunningPodCount int `json:"running_pod_count"`
CPURequests string `json:"cpu_requests"`
MemoryRequests string `json:"memory_requests"`
CPUUsage string `json:"cpu_usage"`
MemoryUsage string `json:"memory_usage"`
EstimatedCost float64 `json:"estimated_cost"`
CostPercentage float64 `json:"cost_percentage"`
}
NamespaceCost represents estimated cost per namespace
type NamespaceInfo ¶
type NamespaceSummary ¶
type NetPolEdge ¶
type NetPolEdge struct {
Source string `json:"source"`
Target string `json:"target"`
Type string `json:"type"` // "allow-ingress", "allow-egress"
Policy string `json:"policy"` // NetworkPolicy name
Ports string `json:"ports,omitempty"`
}
NetPolEdge represents an edge in the network policy graph
type NetPolNode ¶
type NetPolNode struct {
ID string `json:"id"`
Kind string `json:"kind"` // "Pod", "Namespace", "External"
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
}
NetPolNode represents a node in the network policy graph
type NetPolPolicySummary ¶
type NetPolPolicySummary struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
PodSelector string `json:"pod_selector"`
IngressRules []string `json:"ingress_rules"`
EgressRules []string `json:"egress_rules"`
}
NetPolPolicySummary represents a network policy summary for card-based UI
type NetPolVisualizationResponse ¶
type NetPolVisualizationResponse struct {
Nodes []NetPolNode `json:"nodes"`
Edges []NetPolEdge `json:"edges"`
Policies []NetPolPolicySummary `json:"policies"`
PolicyCount int `json:"policyCount"`
}
NetPolVisualizationResponse is the response for the network policy visualization endpoint
type NetworkIssueReport ¶
type NetworkIssueReport struct {
Namespace string `json:"namespace"`
Resource string `json:"resource"`
Issue string `json:"issue"`
Severity string `json:"severity"`
Remediation string `json:"remediation"`
}
NetworkIssueReport represents a network issue for reports
type NodeInfo ¶
type NodeInfo struct {
Name string `json:"name"`
Status string `json:"status"`
Roles []string `json:"roles"`
KubeletVersion string `json:"kubelet_version"`
OS string `json:"os"`
Architecture string `json:"architecture"`
CPUCapacity string `json:"cpu_capacity"`
MemoryCapacity string `json:"memory_capacity"`
CPUAllocatable string `json:"cpu_allocatable"`
MemoryAllocatable string `json:"memory_allocatable"`
PodCapacity string `json:"pod_capacity"`
ContainerRuntime string `json:"container_runtime"`
InternalIP string `json:"internal_ip"`
CreationTime string `json:"creation_time"`
Unschedulable bool `json:"unschedulable"`
Taints []string `json:"taints,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
type NodeSummary ¶
type NotificationConfig ¶
type NotificationConfig struct {
Enabled bool `json:"enabled"`
WebhookURL string `json:"webhook_url"`
Channel string `json:"channel,omitempty"`
Events []string `json:"events"`
Provider string `json:"provider"`
SMTP *SMTPConfigJSON `json:"smtp,omitempty"`
PreserveWebhookURL bool `json:"preserve_webhook_url,omitempty"`
}
NotificationConfig represents webhook notification settings (API contract)
type NotificationHistoryEntry ¶
type NotificationHistoryEntry struct {
Timestamp time.Time `json:"timestamp"`
EventType string `json:"event_type"`
Resource string `json:"resource"`
Namespace string `json:"namespace"`
Message string `json:"message"`
Provider string `json:"provider"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
NotificationHistoryEntry records a sent notification.
type NotificationManager ¶
type NotificationManager struct {
// contains filtered or unexported fields
}
NotificationManager watches K8s events and dispatches notifications.
func NewNotificationManager ¶
func NewNotificationManager(k8sClient *k8s.Client, cfg *config.Config) *NotificationManager
NewNotificationManager creates a new notification manager.
func (*NotificationManager) DedupCount ¶
func (nm *NotificationManager) DedupCount() int
DedupCount returns the number of entries in the dedup map.
func (*NotificationManager) GetHistory ¶
func (nm *NotificationManager) GetHistory() []NotificationHistoryEntry
GetHistory returns recent notification history.
func (*NotificationManager) IsRunning ¶
func (nm *NotificationManager) IsRunning() bool
IsRunning returns whether the manager is actively watching.
func (*NotificationManager) Restart ¶
func (nm *NotificationManager) Restart()
Restart stops and starts the manager (used after config change).
func (*NotificationManager) SendTestEmail ¶
func (nm *NotificationManager) SendTestEmail() error
SendTestEmail sends a test email to verify SMTP configuration.
func (*NotificationManager) Start ¶
func (nm *NotificationManager) Start()
Start begins the event watching goroutines.
func (*NotificationManager) Stop ¶
func (nm *NotificationManager) Stop()
Stop halts the event watching.
type OIDCConfig ¶
type OIDCConfig struct {
ProviderName string `yaml:"provider_name" json:"provider_name"`
ProviderURL string `yaml:"provider_url" json:"provider_url"`
ClientID string `yaml:"client_id" json:"client_id"`
ClientSecret string `yaml:"client_secret" json:"-"`
RedirectURI string `yaml:"redirect_uri" json:"redirect_uri"`
Scopes string `yaml:"scopes" json:"scopes"`
// Role mapping
RolesClaim string `yaml:"roles_claim" json:"roles_claim"`
AdminRoles []string `yaml:"admin_roles" json:"admin_roles"`
UserRoles []string `yaml:"user_roles" json:"user_roles"`
DefaultRole string `yaml:"default_role" json:"default_role"`
GroupMappings map[string]string `yaml:"group_mappings" json:"group_mappings"`
}
OIDCConfig holds OIDC provider configuration
type OIDCDiscovery ¶
type OIDCDiscovery struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
JwksURI string `json:"jwks_uri"`
ScopesSupported []string `json:"scopes_supported"`
}
OIDCDiscovery holds OIDC discovery document data
type OIDCProvider ¶
type OIDCProvider struct {
// contains filtered or unexported fields
}
OIDCProvider handles OIDC authentication
func NewOIDCProvider ¶
func NewOIDCProvider(config *OIDCConfig) (*OIDCProvider, error)
NewOIDCProvider creates a new OIDC provider
func (*OIDCProvider) DetermineRole ¶
func (p *OIDCProvider) DetermineRole(userInfo *OIDCUserInfo) string
DetermineRole determines user role based on claims
func (*OIDCProvider) ExchangeCode ¶
func (p *OIDCProvider) ExchangeCode(ctx context.Context, code, redirectURI string) (*OIDCTokenResponse, error)
ExchangeCode exchanges authorization code for tokens
func (*OIDCProvider) GetAuthorizationURL ¶
func (p *OIDCProvider) GetAuthorizationURL(redirectURI string) (string, string, error)
GetAuthorizationURL returns the URL to redirect user for authentication
func (*OIDCProvider) GetUserInfo ¶
func (p *OIDCProvider) GetUserInfo(ctx context.Context, accessToken string) (*OIDCUserInfo, error)
GetUserInfo fetches user info using access token
func (*OIDCProvider) ValidateState ¶
func (p *OIDCProvider) ValidateState(state string) bool
ValidateState validates the state parameter from callback
type OIDCTokenResponse ¶
type OIDCTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
Scope string `json:"scope,omitempty"`
}
OIDCTokenResponse represents the token response from OIDC provider
type OIDCUserInfo ¶
type OIDCUserInfo struct {
Sub string `json:"sub"`
Name string `json:"name"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Picture string `json:"picture,omitempty"`
Groups []string `json:"groups,omitempty"`
Roles []string `json:"roles,omitempty"`
}
OIDCUserInfo represents user info from OIDC provider
type OllamaPullRequest ¶
type OllamaPullRequest struct {
Model string `json:"model"`
}
OllamaPullRequest represents a request to pull a model
type OllamaStatusResponse ¶
type OllamaStatusResponse struct {
Running bool `json:"running"`
Models []map[string]interface{} `json:"models"`
Error string `json:"error,omitempty"`
}
OllamaStatusResponse represents the response from Ollama status check
type OverprovisionedWorkload ¶
type OverprovisionedWorkload struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
WorkloadType string `json:"workload_type"`
CurrentReplicas int `json:"current_replicas"`
SuggestedReplicas int `json:"suggested_replicas"`
Reason string `json:"reason"`
}
OverprovisionedWorkload represents a workload with excessive resources
type PendingToolApproval ¶
type PendingToolApproval struct {
ID string `json:"id"`
ToolName string `json:"tool_name"`
Command string `json:"command"`
Category string `json:"category"` // read-only, write, dangerous
Timestamp time.Time `json:"timestamp"`
Response chan bool `json:"-"`
}
PendingToolApproval represents a tool call waiting for user approval
type PodMetricItem ¶
type PodMetricItem struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
CPU float64 `json:"cpu"` // millicores
Memory float64 `json:"memory"` // MiB
}
PodMetricItem represents pod resource usage for API response
type PodSecurityIssueReport ¶
type PodSecurityIssueReport struct {
Namespace string `json:"namespace"`
Pod string `json:"pod"`
Container string `json:"container,omitempty"`
Issue string `json:"issue"`
Severity string `json:"severity"`
Remediation string `json:"remediation"`
}
PodSecurityIssueReport represents a pod security issue for reports
type PortForwardSession ¶
type PortForwardSession struct {
ID string `json:"id"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
LocalPort int `json:"localPort"`
RemotePort int `json:"remotePort"`
Active bool `json:"active"`
StartedAt time.Time `json:"startedAt"`
// contains filtered or unexported fields
}
PortForwardSession represents an active port forward
type RBACBindingDetail ¶ added in v0.9.4
type RBACBindingDetail struct {
BindingName string `json:"binding_name"`
BindingKind string `json:"binding_kind"`
RoleName string `json:"role_name"`
RoleKind string `json:"role_kind"`
Namespace string `json:"namespace,omitempty"`
Rules []RBACPolicyRule `json:"rules"`
}
RBACBindingDetail represents a binding with its resolved role rules.
type RBACEdge ¶
type RBACEdge struct {
Source string `json:"source"`
Target string `json:"target"`
BindingName string `json:"bindingName"`
BindingKind string `json:"bindingKind"` // "RoleBinding" or "ClusterRoleBinding"
Namespace string `json:"namespace,omitempty"`
}
RBACEdge represents an edge in the RBAC graph (binding -> role)
type RBACIssueReport ¶
type RBACIssueReport struct {
Kind string `json:"kind"`
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
Issue string `json:"issue"`
Severity string `json:"severity"`
Remediation string `json:"remediation"`
}
RBACIssueReport represents an RBAC issue for reports
type RBACNode ¶
type RBACNode struct {
ID string `json:"id"`
Kind string `json:"kind"` // "User", "Group", "ServiceAccount", "Role", "ClusterRole"
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
}
RBACNode represents a node in the RBAC graph
type RBACPolicyRule ¶ added in v0.9.4
type RBACPolicyRule struct {
Verbs []string `json:"verbs"`
Resources []string `json:"resources"`
APIGroups []string `json:"api_groups"`
}
RBACPolicyRule represents a single RBAC policy rule.
type RBACRoleRef ¶
type RBACRoleRef struct {
RoleName string `json:"role_name"`
ClusterScope bool `json:"cluster_scope"`
}
RBACRoleRef represents a role reference for a subject
type RBACSubjectDetailResponse ¶ added in v0.9.4
type RBACSubjectDetailResponse struct {
Name string `json:"name"`
Kind string `json:"kind"`
Namespace string `json:"namespace,omitempty"`
Bindings []RBACBindingDetail `json:"bindings"`
}
RBACSubjectDetailResponse is the response for the subject detail endpoint.
type RBACSubjectInfo ¶
type RBACSubjectInfo struct {
Name string `json:"name"`
Kind string `json:"kind"`
Namespace string `json:"namespace,omitempty"`
Roles []RBACRoleRef `json:"roles"`
}
RBACSubjectInfo represents a subject with its associated roles (for card-based UI)
type RBACVisualizationResponse ¶
type RBACVisualizationResponse struct {
Nodes []RBACNode `json:"nodes"`
Edges []RBACEdge `json:"edges"`
Subjects []RBACSubjectInfo `json:"subjects"`
}
RBACVisualizationResponse is the response for the RBAC visualization endpoint
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiter
func NewRateLimiter ¶
func NewRateLimiter(limit int, window time.Duration) *RateLimiter
NewRateLimiter creates a new rate limiter limit: maximum requests per window window: time window for rate limiting (e.g., 1 minute)
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(identifier string) bool
Allow checks if a request from the given identifier should be allowed
func (*RateLimiter) GetRetryAfter ¶
func (rl *RateLimiter) GetRetryAfter(identifier string) time.Duration
GetRetryAfter returns the time until the rate limit resets
type ReportGenerator ¶
type ReportGenerator struct {
// contains filtered or unexported fields
}
ReportGenerator handles report generation
func NewReportGenerator ¶
func NewReportGenerator(server *Server) *ReportGenerator
NewReportGenerator creates a new report generator
func (*ReportGenerator) ExportToCSV ¶
func (rg *ReportGenerator) ExportToCSV(report *ComprehensiveReport) ([]byte, error)
func (*ReportGenerator) ExportToHTML ¶
func (rg *ReportGenerator) ExportToHTML(report *ComprehensiveReport) string
ExportToHTML generates HTML format for PDF conversion
func (*ReportGenerator) GenerateAIAnalysis ¶
func (rg *ReportGenerator) GenerateAIAnalysis(ctx context.Context, report *ComprehensiveReport) (string, error)
func (*ReportGenerator) GenerateComprehensiveReport ¶
func (rg *ReportGenerator) GenerateComprehensiveReport(ctx context.Context, username string) (*ComprehensiveReport, error)
GenerateComprehensiveReport gathers all cluster data
func (*ReportGenerator) GenerateReport ¶
func (rg *ReportGenerator) GenerateReport(ctx context.Context, username string, sections *ReportSections) (*ComprehensiveReport, error)
GenerateReport gathers cluster data for the specified sections. If sections is nil, all sections are included.
func (*ReportGenerator) HandleReportPreview ¶
func (rg *ReportGenerator) HandleReportPreview(w http.ResponseWriter, r *http.Request)
HandleReportPreview handles report preview in a new window
func (*ReportGenerator) HandleReports ¶
func (rg *ReportGenerator) HandleReports(w http.ResponseWriter, r *http.Request)
type ReportSections ¶
type ReportSections struct {
Nodes bool `json:"nodes"`
Namespaces bool `json:"namespaces"`
Workloads bool `json:"workloads"` // pods, deployments, services, images
Events bool `json:"events"`
SecurityBasic bool `json:"security_basic"` // pod security, RBAC, network (no Trivy)
SecurityFull bool `json:"security_full"` // full scan with Trivy image vulnerability scanning
FinOps bool `json:"finops"`
Metrics bool `json:"metrics"`
}
ReportSections defines which sections to include in the report. If nil or empty, all sections are included (backward compatible).
func AllSections ¶
func AllSections() *ReportSections
AllSections returns ReportSections with everything enabled.
func ParseSections ¶
func ParseSections(s string) *ReportSections
ParseSections parses a comma-separated sections string into ReportSections. Returns nil (meaning all sections) if the input is empty.
type ResourceCost ¶
type ResourceCost struct {
Requested string `json:"requested"`
Used string `json:"used"`
Efficiency float64 `json:"efficiency"` // used/requested * 100
}
ResourceCost represents requested vs used for a single resource type.
type ResourceEfficiencyInfo ¶
type ResourceEfficiencyInfo struct {
TotalCPURequests string `json:"total_cpu_requests"`
TotalCPULimits string `json:"total_cpu_limits"`
TotalMemoryRequests string `json:"total_memory_requests"`
TotalMemoryLimits string `json:"total_memory_limits"`
TotalCPUUsage string `json:"total_cpu_usage"`
TotalMemoryUsage string `json:"total_memory_usage"`
CPURequestsVsCapacity float64 `json:"cpu_requests_vs_capacity"`
MemoryRequestsVsCapacity float64 `json:"memory_requests_vs_capacity"`
CPUUsageVsRequests float64 `json:"cpu_usage_vs_requests"`
MemoryUsageVsRequests float64 `json:"memory_usage_vs_requests"`
CPUUsageVsCapacity float64 `json:"cpu_usage_vs_capacity"`
MemoryUsageVsCapacity float64 `json:"memory_usage_vs_capacity"`
PodsWithoutRequests int `json:"pods_without_requests"`
PodsWithoutLimits int `json:"pods_without_limits"`
MetricsSource string `json:"metrics_source"`
}
ResourceEfficiencyInfo contains resource utilization metrics
type ResourceRef ¶
type ResourceRef struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Status string `json:"status,omitempty"`
}
ResourceRef identifies a single Kubernetes resource
type ResourceReference ¶ added in v0.9.4
type ResourceReference struct {
Kind string `json:"kind"`
Name string `json:"name"`
Namespace string `json:"namespace"`
RefType string `json:"ref_type"` // "volume", "envFrom", "env"
}
ResourceReference represents a resource that references a Secret or ConfigMap.
type ResourceReferencesResponse ¶ added in v0.9.4
type ResourceReferencesResponse struct {
Kind string `json:"kind"`
Name string `json:"name"`
Namespace string `json:"namespace"`
References []ResourceReference `json:"references"`
}
ResourceReferencesResponse is the API response for the resource references endpoint.
type ResourceRule ¶
type ResourceRule struct {
Resources []string `yaml:"resources" json:"resources"` // ["pods", "deployments", "*"]
Actions []Action `yaml:"actions" json:"actions"` // ["view", "scale"]
Namespaces []string `yaml:"namespaces" json:"namespaces"` // ["default", "*"]
}
ResourceRule defines permissions for a set of resources (Teleport allow/deny block)
type RoleDefinition ¶
type RoleDefinition struct {
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
Allow []ResourceRule `yaml:"allow" json:"allow"`
Deny []ResourceRule `yaml:"deny" json:"deny"` // Deny always overrides Allow
AllowedFeatures []Feature `yaml:"allowed_features" json:"allowed_features"` // Features this role can access ("*" = all)
DeniedFeatures []Feature `yaml:"denied_features" json:"denied_features"` // Features explicitly denied (overrides allow)
IsCustom bool `yaml:"is_custom" json:"is_custom"` // True for user-created roles
}
RoleDefinition defines a role with allow and deny rules (Teleport pattern: deny overrides allow)
type RuntimeEnvironment ¶
type RuntimeEnvironment string
RuntimeEnvironment indicates where k13d is running
const ( // RuntimeInCluster - running inside Kubernetes cluster (needs token auth) RuntimeInCluster RuntimeEnvironment = "in-cluster" // RuntimeLocal - running locally with kubeconfig (can use kubeconfig auth) RuntimeLocal RuntimeEnvironment = "local" )
type SMTPConfigJSON ¶
type SMTPConfigJSON struct {
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password,omitempty"` // accepted on POST, never returned on GET
From string `json:"from"`
To []string `json:"to"`
UseTLS bool `json:"use_tls"`
}
SMTPConfigJSON is the JSON API contract for SMTP settings
type SSEAgentListener ¶
type SSEAgentListener struct {
// contains filtered or unexported fields
}
SSEAgentListener implements agent.AgentListener for WebUI. It sends Server-Sent Events to the browser for each agent event.
func NewSSEAgentListener ¶
func NewSSEAgentListener(w *SSEWriter) *SSEAgentListener
NewSSEAgentListener creates a new SSE-based agent listener
func (*SSEAgentListener) AgentApprovalRequested ¶
func (l *SSEAgentListener) AgentApprovalRequested(choice *agent.ChoiceRequest)
AgentApprovalRequested handles approval request events
func (*SSEAgentListener) AgentApprovalTimeout ¶
func (l *SSEAgentListener) AgentApprovalTimeout(choiceID string)
AgentApprovalTimeout handles approval timeout events
func (*SSEAgentListener) AgentError ¶
func (l *SSEAgentListener) AgentError(err error)
AgentError handles error events
func (*SSEAgentListener) AgentStateChanged ¶
func (l *SSEAgentListener) AgentStateChanged(state agent.State)
AgentStateChanged handles state change events
func (*SSEAgentListener) AgentStreamChunk ¶
func (l *SSEAgentListener) AgentStreamChunk(chunk string)
AgentStreamChunk handles streaming chunks
func (*SSEAgentListener) AgentStreamEnd ¶
func (l *SSEAgentListener) AgentStreamEnd()
AgentStreamEnd handles stream end events
func (*SSEAgentListener) AgentTextReceived ¶
func (l *SSEAgentListener) AgentTextReceived(text string)
AgentTextReceived handles text events
func (*SSEAgentListener) AgentToolCallCompleted ¶
func (l *SSEAgentListener) AgentToolCallCompleted(tc *agent.ToolCallInfo)
AgentToolCallCompleted handles tool call completion events
func (*SSEAgentListener) AgentToolCallRequested ¶
func (l *SSEAgentListener) AgentToolCallRequested(tc *agent.ToolCallInfo)
AgentToolCallRequested handles tool call request events
func (*SSEAgentListener) HandleApproval ¶
func (l *SSEAgentListener) HandleApproval(choiceID string, approved bool) bool
HandleApproval processes an approval response from the browser Returns true if the approval was handled, false if there was no pending approval
func (*SSEAgentListener) WaitForApproval ¶
func (l *SSEAgentListener) WaitForApproval() bool
WaitForApproval waits for an approval response This is used when the agent is using the approval handler pattern
type SSEApprovalHandler ¶
type SSEApprovalHandler struct {
// contains filtered or unexported fields
}
SSEApprovalHandler implements agent.AgentApprovalHandler for WebUI
func NewSSEApprovalHandler ¶
func NewSSEApprovalHandler(listener *SSEAgentListener) *SSEApprovalHandler
NewSSEApprovalHandler creates a new SSE-based approval handler
func (*SSEApprovalHandler) RequestApproval ¶
func (h *SSEApprovalHandler) RequestApproval(choice *agent.ChoiceRequest, callback func(bool))
RequestApproval handles synchronous approval requests
type SafetyAnalysisRequest ¶
type SafetyAnalysisRequest struct {
Command string `json:"command"` // The command or action to analyze
Context string `json:"context,omitempty"` // Additional context (e.g., namespace, resource)
Namespace string `json:"namespace,omitempty"` // Target namespace
}
SafetyAnalysisRequest represents a request to analyze K8s command safety
type SafetyAnalysisResponse ¶
type SafetyAnalysisResponse struct {
Safe bool `json:"safe"` // Overall safety assessment
RiskLevel string `json:"risk_level"` // safe, warning, dangerous, critical
RequiresApproval bool `json:"requires_approval"` // Whether user confirmation is needed
Warnings []string `json:"warnings"` // List of warning messages
Recommendations []string `json:"recommendations"` // Suggested alternatives or precautions
Category string `json:"category"` // read-only, write, delete, admin
AffectedScope string `json:"affected_scope"` // pod, namespace, cluster
Explanation string `json:"explanation"` // Human-readable explanation
}
SafetyAnalysisResponse represents the safety analysis result
type SearchResult ¶
type SearchResult struct {
Kind string `json:"kind"`
Name string `json:"name"`
Namespace string `json:"namespace"`
Status string `json:"status,omitempty"`
Age string `json:"age,omitempty"`
}
SearchResult represents a single search result item
type SecurityInfo ¶
type SecurityInfo struct {
ServiceAccounts int `json:"service_accounts"`
Roles int `json:"roles"`
RoleBindings int `json:"role_bindings"`
ClusterRoles int `json:"cluster_roles"`
ClusterRoleBindings int `json:"cluster_role_bindings"`
Secrets int `json:"secrets"`
PrivilegedPods int `json:"privileged_pods"`
HostNetworkPods int `json:"host_network_pods"`
RootContainers int `json:"root_containers"`
}
type SecurityRecommendationReport ¶
type SecurityRecommendationReport struct {
Priority int `json:"priority"`
Category string `json:"category"`
Title string `json:"title"`
Description string `json:"description"`
Impact string `json:"impact"`
Remediation string `json:"remediation"`
}
SecurityRecommendationReport represents a security recommendation
type SecurityScanReport ¶
type SecurityScanReport struct {
ScanTime time.Time `json:"scan_time"`
Duration string `json:"duration"`
OverallScore float64 `json:"overall_score"`
RiskLevel string `json:"risk_level"`
ToolsUsed []string `json:"tools_used"`
ImageVulnSummary *ImageVulnerabilitySummary `json:"image_vulnerabilities,omitempty"`
PodSecurityIssues []PodSecurityIssueReport `json:"pod_security_issues,omitempty"`
RBACIssues []RBACIssueReport `json:"rbac_issues,omitempty"`
NetworkIssues []NetworkIssueReport `json:"network_issues,omitempty"`
CISBenchmark *CISBenchmarkReport `json:"cis_benchmark,omitempty"`
Recommendations []SecurityRecommendationReport `json:"recommendations,omitempty"`
}
SecurityScanReport contains results from security scanning tools
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
func NewServerWithAuth ¶
func NewServerWithAuth(cfg *config.Config, port int, authOpts *AuthOptions, versionInfo *VersionInfo) (*Server, error)
NewServerWithAuth creates a new server with custom authentication options
func (*Server) HandleTUIShell ¶ added in v1.1.0
func (s *Server) HandleTUIShell(w http.ResponseWriter, r *http.Request)
HandleTUIShell handles a WebSocket connection that provides a local shell on the host. This is used for the "TUI Mode" in the AI panel (experimental feature).
type ServiceInfo ¶
type Session ¶
type Session struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
Source string `json:"source"` // local, ldap
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
Session represents an authenticated session
type TerminalHandler ¶
type TerminalHandler struct {
// contains filtered or unexported fields
}
TerminalHandler handles WebSocket terminal connections
func NewTerminalHandler ¶
func NewTerminalHandler(k8sClient *k8s.Client) *TerminalHandler
NewTerminalHandler creates a new terminal handler
func (*TerminalHandler) HandleTerminal ¶
func (h *TerminalHandler) HandleTerminal(w http.ResponseWriter, r *http.Request)
HandleTerminal handles WebSocket terminal requests URL: /api/terminal/{namespace}/{pod}?container={container}
type TerminalMessage ¶
type TerminalMessage struct {
Type string `json:"type"` // "input", "output", "resize", "error"
Data string `json:"data,omitempty"`
Cols uint16 `json:"cols,omitempty"`
Rows uint16 `json:"rows,omitempty"`
}
TerminalMessage represents a message to/from the terminal
type TerminalSession ¶
type TerminalSession struct {
// contains filtered or unexported fields
}
TerminalSession manages a single terminal session
func NewTerminalSession ¶
func NewTerminalSession(conn *websocket.Conn) *TerminalSession
NewTerminalSession creates a new terminal session
func (*TerminalSession) Next ¶
func (t *TerminalSession) Next() *remotecommand.TerminalSize
Next implements remotecommand.TerminalSizeQueue
func (*TerminalSession) Read ¶
func (t *TerminalSession) Read(p []byte) (int, error)
Read implements io.Reader for terminal input
func (*TerminalSession) SendError ¶
func (t *TerminalSession) SendError(err error)
SendError sends an error message to the client
type TokenReview ¶
type TokenReview struct {
Authenticated bool `json:"authenticated"`
Username string `json:"username"`
UID string `json:"uid"`
Groups []string `json:"groups"`
}
TokenReview represents the result of a token validation
type TopologyEdge ¶
type TopologyEdge struct {
Source string `json:"source"`
Target string `json:"target"`
Type string `json:"type"` // "owns", "selects", "mounts", "routes", "scales"
}
TopologyEdge represents a relationship between two resources.
type TopologyNode ¶
type TopologyNode struct {
ID string `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
Namespace string `json:"namespace"`
Status string `json:"status"`
Info map[string]string `json:"info,omitempty"`
Group string `json:"group,omitempty"` // app.kubernetes.io/name for grouping
}
TopologyNode represents a Kubernetes resource as a graph node.
type TopologyResponse ¶
type TopologyResponse struct {
Nodes []TopologyNode `json:"nodes"`
Edges []TopologyEdge `json:"edges"`
}
TopologyResponse is the API response for the topology endpoint.
type TroubleshootFinding ¶
type TroubleshootFinding struct {
Resource string `json:"resource"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Issue string `json:"issue"`
Severity string `json:"severity"` // "critical", "warning", "info"
Details string `json:"details,omitempty"`
}
TroubleshootFinding represents a single issue found during troubleshooting
type TroubleshootReport ¶
type TroubleshootReport struct {
Namespace string `json:"namespace"`
Findings []TroubleshootFinding `json:"findings"`
Recommendations []string `json:"recommendations"`
Severity string `json:"severity"` // overall: "critical", "warning", "healthy"
Timestamp time.Time `json:"timestamp"`
}
TroubleshootReport is the response for the troubleshoot endpoint
type UnderutilizedResource ¶
type UnderutilizedResource struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
ResourceType string `json:"resource_type"`
CPUUsage float64 `json:"cpu_usage_percent"`
MemoryUsage float64 `json:"memory_usage_percent"`
Suggestion string `json:"suggestion"`
}
UnderutilizedResource represents a resource with low utilization
type User ¶
type User struct {
ID string `json:"id"`
Username string `json:"username"`
PasswordHash string `json:"-"`
Role string `json:"role"` // admin, user, viewer
Email string `json:"email,omitempty"`
DisplayName string `json:"display_name,omitempty"`
Source string `json:"source"` // local, ldap
CreatedAt time.Time `json:"created_at"`
LastLogin time.Time `json:"last_login,omitempty"`
// Emergency locking (Teleport-inspired)
Locked bool `json:"locked"`
LockedAt time.Time `json:"locked_at,omitempty"`
LockedBy string `json:"locked_by,omitempty"`
}
User represents a user in the system
type UserRequest ¶
type UserRequest struct {
Username string `json:"username"`
Password string `json:"password,omitempty"`
Role string `json:"role"`
Email string `json:"email,omitempty"`
}
UserRequest represents a user creation/update request
type VeleroBackup ¶
type VeleroBackup struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Status string `json:"status"`
Created string `json:"created,omitempty"`
Expiration string `json:"expiration,omitempty"`
IncludedNS string `json:"includedNamespaces,omitempty"`
StorageLocation string `json:"storageLocation,omitempty"`
}
VeleroBackup represents a Velero backup resource
type VeleroResponse ¶
type VeleroResponse struct {
Installed bool `json:"installed"`
Items interface{} `json:"items,omitempty"`
Message string `json:"message,omitempty"`
}
VeleroResponse is the response for Velero endpoints
type VeleroSchedule ¶
type VeleroSchedule struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Schedule string `json:"schedule"`
LastBackup string `json:"lastBackup,omitempty"`
Status string `json:"status"`
}
VeleroSchedule represents a Velero schedule resource
type VersionInfo ¶
type VersionInfo struct {
Version string `json:"version"`
BuildTime string `json:"build_time"`
GitCommit string `json:"git_commit"`
}
VersionInfo holds build version information
type WebPulseData ¶
type WebPulseData struct {
// Pod counts
PodsRunning int `json:"pods_running"`
PodsPending int `json:"pods_pending"`
PodsFailed int `json:"pods_failed"`
PodsOther int `json:"pods_other"`
PodsTotal int `json:"pods_total"`
// Deployment counts
DeploysReady int `json:"deploys_ready"`
DeploysUpdating int `json:"deploys_updating"`
DeploysTotal int `json:"deploys_total"`
// StatefulSet counts
STSReady int `json:"sts_ready"`
STSTotal int `json:"sts_total"`
// DaemonSet counts
DSReady int `json:"ds_ready"`
DSTotal int `json:"ds_total"`
// Job counts
JobsComplete int `json:"jobs_complete"`
JobsActive int `json:"jobs_active"`
JobsFailed int `json:"jobs_failed"`
JobsTotal int `json:"jobs_total"`
// Node counts
NodesReady int `json:"nodes_ready"`
NodesNotReady int `json:"nodes_not_ready"`
NodesTotal int `json:"nodes_total"`
// CPU metrics (millicores)
CPUUsed int64 `json:"cpu_used_milli"`
CPUCapacity int64 `json:"cpu_capacity_milli"`
CPUAvail bool `json:"cpu_avail"`
// Memory metrics (MiB)
MemUsed int64 `json:"mem_used_mib"`
MemCapacity int64 `json:"mem_capacity_mib"`
MemAvail bool `json:"mem_avail"`
// Recent events
Events []WebPulseEvent `json:"events"`
Timestamp time.Time `json:"timestamp"`
}
WebPulseData is the JSON response for /api/pulse. Mirrors ui.PulseData but decoupled from the TUI package.
type WebPulseEvent ¶
type WebPulseEvent struct {
Type string `json:"type"`
Reason string `json:"reason"`
Message string `json:"message"`
Age string `json:"age"`
}
WebPulseEvent is a simplified event for the pulse response.
type WorkloadCost ¶
type WorkloadCost struct {
Kind string `json:"kind"`
Name string `json:"name"`
Namespace string `json:"namespace"`
CPUReq string `json:"cpuRequested"`
CPUUsed string `json:"cpuUsed"`
MemReq string `json:"memRequested"`
MemUsed string `json:"memUsed"`
Replicas int32 `json:"replicas"`
Efficiency float64 `json:"efficiency"`
}
WorkloadCost represents cost data for a single workload (pod).
type WorkloadSummary ¶
type WorkloadSummary struct {
TotalPods int `json:"total_pods"`
RunningPods int `json:"running_pods"`
PendingPods int `json:"pending_pods"`
FailedPods int `json:"failed_pods"`
TotalDeployments int `json:"total_deployments"`
HealthyDeploys int `json:"healthy_deployments"`
TotalServices int `json:"total_services"`
TotalConfigMaps int `json:"total_configmaps"`
TotalSecrets int `json:"total_secrets"`
}
type XRayResponse ¶
type XRayResponse struct {
Type string `json:"type"`
Namespace string `json:"namespace"`
Nodes []*XRayTreeNode `json:"nodes"`
Timestamp time.Time `json:"timestamp"`
}
XRayResponse is the JSON envelope for /api/xray.
type XRayTreeNode ¶
type XRayTreeNode struct {
Kind string `json:"kind"`
Name string `json:"name"`
Status string `json:"status"`
Children []*XRayTreeNode `json:"children,omitempty"`
}
XRayTreeNode represents a node in the resource hierarchy JSON tree.
type YamlApplyRequest ¶
type YamlApplyRequest struct {
YAML string `json:"yaml"`
Namespace string `json:"namespace"`
DryRun bool `json:"dryRun"`
}
YamlApplyRequest represents a request to apply YAML to the cluster
Source Files
¶
- access_request.go
- agent_listener.go
- ai_access.go
- ai_tool_policy.go
- auth_core.go
- auth_k8s.go
- auth_ldap.go
- auth_local.go
- auth_oidc.go
- authz.go
- bruteforce.go
- errors.go
- github_automation.go
- github_preview_proxy.go
- handlers_admin.go
- handlers_ai.go
- handlers_applications.go
- handlers_cost.go
- handlers_diff.go
- handlers_events_timeline.go
- handlers_gitops.go
- handlers_healing.go
- handlers_helm.go
- handlers_k8s.go
- handlers_k8s_security.go
- handlers_k8s_workloads.go
- handlers_llm_usage.go
- handlers_metrics.go
- handlers_multicluster.go
- handlers_netpol_viz.go
- handlers_notifications.go
- handlers_portforward.go
- handlers_prometheus.go
- handlers_pulse.go
- handlers_rbac_viz.go
- handlers_roles.go
- handlers_safety.go
- handlers_security.go
- handlers_settings.go
- handlers_topology.go
- handlers_troubleshoot.go
- handlers_velero.go
- handlers_xray.go
- helpers.go
- impersonation.go
- jwt.go
- llm_runtime.go
- llm_warnings.go
- notification_manager.go
- operations.go
- ratelimit.go
- reports_ai.go
- reports_export.go
- reports_finops.go
- reports_generator.go
- reports_handlers.go
- reports_helpers.go
- reports_metrics.go
- reports_security.go
- reports_types.go
- routes.go
- server.go
- terminal.go
- tui_shell_handler.go