Authentication and Security
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendices
Introduction
This document provides comprehensive authentication and security documentation for the BI Analysis Platform. It covers JWT token-based authentication, including token generation, validation, refresh cycles, and expiration handling. It explains Role-Based Access Control (RBAC) implementation with role hierarchies, permission matrices, and tenant isolation. It also documents multi-tenant authentication patterns, user context propagation, and cross-tenant access controls. Additional topics include API key management, OAuth2 flows, and third-party authentication integrations, along with security middleware configurations, CORS policies, and CSRF protection mechanisms. Secure communication protocols (TLS), certificate management, and service-to-service authentication are addressed, alongside security best practices, threat mitigation strategies, and compliance considerations for enterprise deployments.
Project Structure
The authentication and security capabilities are primarily implemented in the bi-common/auth package and integrated across tenant and system services. Key areas:
- JWT token generation, parsing, refresh threshold checks, and token pair creation
- RBAC middleware with configurable providers and caching
- User context propagation via Kratos metadata and HTTP headers
- Token blacklist support (memory and Redis)
- CORS middleware configuration
- Tenant and system authentication APIs defined via protobuf
Diagram sources
- [jwt.go]
- [claims.go]
- [context.go]
- [rbac.go]
- [middleware.go]
- [blacklist.go]
- [cache.go]
- [auth.proto (tenant)]
- [auth.pb.go (tenant)]
- [auth.proto (sys)]
- [cors.go]
- [security-patterns.md]
Section sources
- [jwt.go]
- [claims.go]
- [context.go]
- [rbac.go]
- [middleware.go]
- [blacklist.go]
- [cache.go]
- [auth.proto (tenant)]
- [auth.proto (sys)]
- [auth.pb.go (tenant)]
- [cors.go]
- [security-patterns.md]
Core Components
- JWT utilities: token pair generation, access/refresh token signing, parsing, expiration checks, and refresh threshold evaluation
- Claims and configuration: unified claims structure supporting system and tenant contexts, environment-driven defaults
- Authentication middleware: JWTAuthMiddleware for bearer token validation and user context injection; HeaderAuthMiddleware for downstream trust patterns
- RBAC middleware: path-based permission enforcement, provider abstraction, caching, and admin bypass rules
- Token blacklist: in-memory and Redis-backed implementations for logout and forced revocation
- Permission cache: Redis-backed caching for user permissions to reduce provider load
- CORS middleware: configurable origins, methods, headers, credentials, and preflight handling
- Security headers: patterns for content-type options, frame options, XSS protection, CSP, HSTS, and cache-control
Section sources
Architecture Overview
The authentication pipeline integrates JWT validation and RBAC checks across services. For tenant-facing APIs, the tenant service exposes login, logout, refresh, and user info endpoints. For system-facing APIs, the system service provides similar endpoints. Downstream services can trust the gateway and rely on header-based user propagation.
Diagram sources
Detailed Component Analysis
JWT Token Management
- Token pair generation: access and refresh tokens with issuer, issued-at, and expiration claims
- Parsing and validation: HS256 signature verification, error categorization for malformed/expired/not-yet-valid tokens
- Refresh threshold: automatic determination of whether a token needs refreshing based on configured threshold
- Environment-driven configuration: secrets and issuer loaded from environment variables with safe defaults
Diagram sources
Section sources
Authentication Middleware and User Context Propagation
- JWTAuthMiddleware validates Authorization header, strips Bearer prefix, checks blacklist, parses claims, injects user info into context, and sets Kratos metadata for cross-service propagation
- HeaderAuthMiddleware trusts upstream gateways and reads user info from headers
- Cross-service propagation uses standardized metadata keys and supports both server and client metadata contexts
Diagram sources
Section sources
RBAC Implementation and Tenant Isolation
- RBACMiddleware enforces permissions based on path patterns (-m for management APIs), user roles, and configured providers
- Supports wildcard permissions and module/resource/action mapping
- Tenant isolation: management APIs require TenantID=0; super admins bypass checks; admin users bypass for tenant APIs
- Permission caching reduces provider load and improves latency
Diagram sources
Section sources
Token Blacklist and Refresh Cycles
- TokenBlacklist interface enables logout and forced revocation
- MemoryBlacklist for single-node testing; Redis-backed implementation for distributed environments
- Refresh threshold triggers automatic refresh before access token expiry
Diagram sources
Section sources
Multi-Tenant Authentication Patterns and Cross-Tenant Controls
- Tenant APIs exposed under tenant service; system APIs under system service
- Management APIs (paths containing -m) routed to system service for admin-only access
- Cross-tenant access controls enforced by tenant ID checks and admin role bypass rules
- User context carries tenant and role information for downstream decisions
Section sources
API Key Management, OAuth2, and Third-Party Integrations
- API key management: not implemented in the referenced code; consider adding a dedicated API key service and middleware for HMAC or symmetric signature verification
- OAuth2 flows: not implemented in the referenced code; implement authorization code flow with PKCE and integrate with identity providers via OIDC
- Third-party authentication: not implemented in the referenced code; design an extensible provider interface and pluggable middleware for SSO integrations
[No sources needed since this section provides general guidance]
Security Middleware, CORS Policies, and CSRF Protection
- CORS middleware supports allow-listed origins, methods, headers, credentials, and preflight caching
- Security headers pattern includes X-Content-Type-Options, X-Frame-Options, X-XSS-Protection, Content-Security-Policy, HSTS, and cache-control
- CSRF protection: not implemented in the referenced code; implement SameSite cookies, CSRF tokens for state-changing requests, and anti-CSRF middleware
Section sources
Secure Communication Protocols and Certificate Management
- TLS termination: configure TLS at the gateway/load balancer; enforce minimum TLS versions and strong cipher suites
- Certificate management: automate issuance and renewal via ACME or internal CA; rotate certificates regularly and monitor expirations
- Service-to-service authentication: mutual TLS (mTLS) for internal services; use short-lived certificates and strict SAN validation
[No sources needed since this section provides general guidance]
Dependency Analysis
The authentication system exhibits low coupling between JWT utilities, RBAC middleware, and context propagation. Providers and caches are injected via interfaces, enabling flexible implementations. The tenant and system services depend on the common auth package for shared behavior.
Diagram sources
Section sources
Performance Considerations
- Enable Redis-backed permission caching to minimize RPC calls and reduce latency
- Tune refresh threshold to balance token reuse and refresh overhead
- Use efficient CORS configuration to avoid excessive preflight requests
- Monitor token parsing and RBAC checks for hotspots; consider batching permission queries where appropriate
[No sources needed since this section provides general guidance]
Troubleshooting Guide
- Unauthorized errors: verify Authorization header format, token presence, and whitelist configuration
- Expired tokens: implement refresh logic using refresh tokens; ensure refresh threshold is set appropriately
- Blacklisted tokens: confirm blacklist storage and TTL; clear stale entries
- Permission failures: validate provider implementation, cache population, and path-to-permission mapping
- Cross-service propagation: ensure metadata keys are present and correctly formatted in both server and client contexts
Section sources
Conclusion
The BI Analysis Platform implements a robust, extensible authentication and authorization framework centered on JWT and RBAC. It supports tenant isolation, cross-service user context propagation, and scalable permission caching. While API key management, OAuth2, and CSRF protection are not currently implemented, the modular design allows for incremental enhancements. Secure communication, certificate management, and enterprise-grade compliance can be achieved through proper TLS configuration, certificate automation, and adherence to security best practices.
[No sources needed since this section summarizes without analyzing specific files]
Appendices
API Definitions: Authentication Endpoints
- Tenant Auth API: login, logout, refresh, get user info, get menus, favorites, captcha, BI initialization
- System Auth API: login, logout, refresh, get user info, get menus
Section sources