Bella OpenAPI Security Measures for API Access Control: A Layered Defense Architecture
Bella OpenAPI implements a defense-in-depth strategy combining API key authentication, role-based access control, per-key rate limiting, and monthly quota enforcement through a chain of Spring MVC interceptors.
The lianjiatech/bella-openapi repository provides a comprehensive security framework for protecting AI model endpoints. Its architecture employs multiple independent layers of access control to ensure only authorized clients can consume API resources while preventing abuse through fine-grained rate and quota management.
API Key Authentication and Identity Verification
At the entry point of every request, Bella OpenAPI validates caller identity through the AuthorizationInterceptor located at api/server/src/main/java/com/ke/bella/openapi/intercept/AuthorizationInterceptor.java. This component extracts credentials from HTTP headers and verifies them against the stored key registry.
Primary Authentication via Authorization Header
The interceptor extracts the standard Authorization header and delegates verification to ApikeyService.verifyAuth. Upon successful validation, the system loads the complete ApikeyInfo object—including role permissions, QPS limits, and quota allocations—into the EndpointContext for downstream consumption.
// AuthorizationInterceptor.java (lines 32-44)
// Extracts header and verifies via ApikeyService
ApikeyInfo apikeyInfo = apikeyService.verifyAuth(authHeader);
if (apikeyInfo == null) {
throw new UnauthorizedException("Invalid API key");
}
Provider-Specific Alternative Headers
For compatibility with provider-specific SDKs, the system supports alternative header patterns. When processing Gemini endpoints, AuthorizationInterceptor.getAlternativeHeader returns "x-goog-api-key", allowing seamless integration with Google's native client libraries.
Request request = new Request.Builder()
.url(host + "/v1beta/models/gemini-pro")
.addHeader("x-goog-api-key", geminiKey) // alternative header for Gemini
.build();
Sub-Key Delegation for Multi-Tenant Scenarios
Bella OpenAPI supports acting on behalf of other users through the X-BELLA-USER-AK-CODE header. After verifying the master API key, the interceptor loads the corresponding sub-key at lines 61-67 of AuthorizationInterceptor.java and replaces the security context, enabling delegated access patterns without exposing master credentials.
Request request = new Request.Builder()
.url(host + "/v1/chat/completions")
.post(RequestBody.create(jsonBody, MediaType.parse("application/json")))
.addHeader(HttpHeaders.AUTHORIZATION, masterKey) // master key
.addHeader(BellaContext.BELLA_USER_AK_HEADER, subUserKey) // sub-key
.build();
Role-Based Access Control (RBAC)
Following authentication, Bella OpenAPI enforces fine-grained authorization using path-based permission trees stored within each ApikeyInfo object. The hasPermission(url) method evaluates whether the requested URI matches the key's inclusion or exclusion patterns before allowing the request to proceed.
This RBAC layer prevents lateral movement between different API capabilities—such as restricting a key created for chat completions from accessing embedding or image generation endpoints. The permission check occurs immediately after authentication in the interceptor chain, ensuring rejected requests fail fast before consuming backend resources.
Rate Limiting and Consumption Quotas
To prevent resource exhaustion and ensure fair usage, Bella OpenAPI implements two distinct resource protection mechanisms through dedicated interceptors configured in WebConfig.java.
QPS Rate Limiting with Sliding Windows
The QpsRateLimitInterceptor (api/server/src/main/java/com/ke/bella/openapi/intercept/QpsRateLimitInterceptor.java) enforces per-key queries-per-second limits using a sliding-window counter managed by QpsLimiterManager. When a key exceeds its configured qpsLimit, the interceptor adds a Retry-After header and throws a RateLimitException, returning HTTP 429 to the client.
// QpsRateLimitInterceptor retrieves limits from ApikeyInfo
int qpsLimit = apikeyInfo.getQpsLimit();
if (!qpsLimiterManager.allow(apikeyInfo.getCode(), qpsLimit)) {
throw new RateLimitException("QPS limit exceeded");
}
Monthly Quota Enforcement
For commercial usage controls, MonthQuotaInterceptor (api/server/src/main/java/com/ke/bella/openapi/intercept/MonthQuotaInterceptor.java) tracks accumulated costs via ApikeyService.loadCost. The interceptor compares current month usage against the monthQuota property (inherited from parent keys if not set directly) and rejects requests exceeding the prepaid allocation.
Request Context Propagation
Security context travels beyond the initial request through BellaContext, a thread-local storage mechanism that maintains operator identity, API key metadata, and request attributes throughout the call chain. When using the Bella SDK, BellaInterceptor (api/sdk/src/main/java/com/ke/bella/openapi/request/BellaInterceptor.java) automatically injects this context into outbound HTTP calls, ensuring propagated requests retain authentication and tracing information.
String host = "https://api.bella.openapi.com";
String apiKey = "sk-xxxxxx"; // your Bella API key
BellaContext.setOperator(new Operator()); // optional operator info
// The SDK automatically adds the BellaInterceptor which injects the context.
HttpResponse resp = HttpUtils.httpRequest(
new Request.Builder()
.url(host + "/v1/chat/completions")
.post(RequestBody.create(jsonBody, MediaType.parse("application/json")))
.addHeader(HttpHeaders.AUTHORIZATION, apiKey) // main auth header
.build(),
10_000, 30_000, null);
Security Documentation and Interceptor Configuration
The ApiDocConfig class (api/server/src/main/java/com/ke/bella/openapi/configuration/ApiDocConfig.java) registers the security scheme for OpenAPI/Swagger documentation, defining a bearer token pattern that maps to the Authorization header. This ensures client developers understand authentication requirements when generating integration code.
The interceptor chain order is explicitly defined in WebConfig.java to guarantee correct enforcement priority:
AuthorizationInterceptor(authentication + RBAC)QpsRateLimitInterceptor(rate limiting)MonthQuotaInterceptor(quota enforcement)
// WebConfig.java excerpt showing interceptor registration
registry.addInterceptor(authorizationInterceptor); // order = 108
registry.addInterceptor(qpsRateLimitInterceptor); // order = 109
registry.addInterceptor(monthQuotaInterceptor); // order = 110
Summary
- Authentication Layer:
AuthorizationInterceptorvalidates API keys viaApikeyService.verifyAuthand supports both standard headers and provider-specific alternatives likex-goog-api-key. - Authorization Layer: RBAC enforcement through
ApikeyInfo.hasPermission(url)restricts endpoint access based on per-key permission trees. - Rate Protection:
QpsRateLimitInterceptorimplements sliding-window QPS limits, whileMonthQuotaInterceptorenforces prepaid monthly usage caps. - Delegated Access: Sub-key support via
X-BELLA-USER-AK-CODEenables secure multi-tenant scenarios without master key exposure. - Context Management:
BellaContextandBellaInterceptormaintain security metadata across distributed call chains.
Frequently Asked Questions
How does Bella OpenAPI handle authentication for different AI providers?
Bella OpenAPI supports provider-specific header patterns through the getAlternativeHeader method in AuthorizationInterceptor.java. For example, when calling Gemini endpoints, the system accepts x-goog-api-key instead of the standard Authorization header, enabling seamless integration with Google's native SDKs while maintaining the same verification backend.
What happens when an API key exceeds its rate limit or monthly quota?
When QPS limits are exceeded, QpsRateLimitInterceptor returns HTTP 429 with a Retry-After header indicating when to retry. For monthly quota violations, MonthQuotaInterceptor throws a RateLimitException without automatic retry guidance. Both interceptors check the ApikeyInfo retrieved from EndpointContext, ensuring limits apply to delegated sub-keys rather than master keys when applicable.
Can a single API key restrict access to specific endpoints only?
Yes. Each ApikeyInfo object stores a permission tree defining included and excluded URL patterns. The hasPermission(url) method evaluates these rules during the authorization phase in AuthorizationInterceptor.java (lines 32-44), allowing administrators to create keys restricted to specific capabilities such as chat completions while blocking access to embeddings or image generation endpoints.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →