How Authentication Works in the TencentDB Memory Core Service
The Memory Core service implements a rigorous three-layer authentication model that validates every incoming request through kernel-level Bearer tokens, service instance identifiers, and user-specific keys for protected metadata endpoints.
The TencentDB-Agent-Memory repository secures its Memory Core component through a coordinated defense-in-depth strategy. Understanding how authentication is handled for the Memory Core service requires analyzing the specific TypeScript implementations across the gateway server and metadata routers, where each layer performs distinct validation checks before granting access to system resources.
The Three-Layer Authentication Architecture
The authentication system operates through sequential validation stages implemented in separate modules:
- Kernel Authentication — Validates the
Authorization: Bearer <KERNEL_AUTH_TOKEN>header inMemoryCore/src/gateway/server.ts - Service Instance Authentication — Extracts and verifies the
x-tdai-service-idheader and API key inMemoryCore/src/gateway/v2-router.ts - User-Key Authentication — Validates the
x-tdai-user-keyheader for metadata APIs inMemoryCore/src/metadata/router/auth.ts
Each layer returns an HTTP 401 error immediately upon validation failure, preventing unauthorized requests from reaching business logic.
Layer 1: Kernel-Level Bearer Token Validation
The gateway server (MemoryCore/src/gateway/server.ts) serves as the first line of defense through the checkAuth and checkAuthForV2 methods. Both functions invoke verifyAuth to validate the Bearer token before any routing logic executes.
private checkAuth(req, res): boolean {
const result = this.verifyAuth(req);
if (result === "ok") return true;
// 401 plain-text response for v1 admin callers
}
private checkAuthForV2(req, res): boolean {
const result = this.verifyAuth(req);
if (result === "ok") return true;
// 401 JSON envelope for v2/v3 callers
}
When verifyAuth detects a missing or invalid Authorization header, the gateway terminates the request with a 401 status code. This kernel-level gate ensures that only requests bearing valid kernel tokens proceed to subsequent routing layers.
Layer 2: Service Instance Verification
After kernel authentication succeeds, the parseV2Auth function in MemoryCore/src/gateway/v2-router.ts performs the second validation layer. This function extracts both the API key and service instance identifier from incoming headers.
export function parseV2Auth(req, res, requestId, sendJsonFn) {
const authHeader = req.headers["authorization"] ?? "";
const serviceId = (req.headers["x-tdai-service-id"] as string) ?? "";
if (!authHeader.startsWith("Bearer ") || !authHeader.slice(7).trim()) {
sendJsonFn(res, 401, errorEnvelope(...));
return null;
}
if (!serviceId.trim()) {
sendJsonFn(res, 401, errorEnvelope(...));
return null;
}
return {
apiKey: authHeader.slice(7).trim(),
serviceId: serviceId.trim()
};
}
The function enforces that both the Bearer token (after the "Bearer " prefix) and the x-tdai-service-id header contain non-empty values. Failure to provide either credential results in an immediate 401 JSON response, preventing unqualified requests from reaching V2 or V3 endpoints.
Layer 3: Metadata API User-Key Authentication
For routes under /v3/meta/*, the system applies an additional authentication layer through the authenticateV3 function in MemoryCore/src/metadata/router/auth.ts. This validates the x-tdai-user-key header against the MetadataService, except for explicitly whitelisted routes.
The whitelist is defined as:
export const V3_NO_USER_KEY_ROUTES = new Set([
"/v3/meta/auth/verify",
]);
The authentication logic implements three specific checks:
export async function authenticateV3(
userKey: string,
service: MetadataService
): Promise<V3AuthResult> {
if (!userKey) return { ok: false, status: 401, reason: "missing_user_key" };
if (service.isConfiguredMemorySystemUserKey(userKey)) {
return { ok: false, status: 401, reason: "invalid_user_key" };
}
const user = await service.verifyAuth(userKey);
if (!user) return { ok: false, status: 401, reason: "invalid_user_key" };
const isSystemAdmin = user.user_type === "system_admin";
return {
ok: true,
ctx: {
token: userKey,
userId: user.user_id,
isAdmin: false,
isSystemAdmin
}
};
}
Successful authentication yields a V3AuthContext containing the user ID and administrative flags, which downstream handlers use for permission enforcement throughout the metadata service.
Step-by-Step Request Validation Flow
When a client request arrives at the Memory Core service, it undergoes the following validation sequence:
- Kernel Gate:
checkAuthorcheckAuthForV2inserver.tsvalidates the Bearer token. Invalid tokens trigger immediate 401 responses. - Instance Parsing:
parseV2Authinv2-router.tsextractsapiKeyandserviceId. Empty values result in 401 errors. - Metadata Protection: For
/v3/meta/*endpoints (excluding whitelisted routes),authenticateV3validatesx-tdai-user-key. Invalid or missing keys return 401 with specific reason codes. - Context Propagation: Valid requests receive either a
V2AuthContextorV3AuthContext, enabling conversation, knowledge, and skill modules to enforce granular permissions.
Summary
- The Memory Core service employs a three-layer authentication model combining kernel tokens, service instance identifiers, and user keys.
- Kernel authentication in
MemoryCore/src/gateway/server.tsvalidates Bearer tokens throughverifyAuth, rejecting requests with 401 errors before routing occurs. - Service instance validation in
MemoryCore/src/gateway/v2-router.tsensures bothAuthorizationandx-tdai-service-idheaders contain valid data viaparseV2Auth. - Metadata API protection in
MemoryCore/src/metadata/router/auth.tsrequiresx-tdai-user-keyheaders for all/v3/meta/*routes except/v3/meta/auth/verify, which is whitelisted inV3_NO_USER_KEY_ROUTES. - Each layer returns specific 401 error responses with distinct reason codes, enabling precise debugging while maintaining security boundaries.
Frequently Asked Questions
What happens if the kernel Bearer token is missing or invalid?
The gateway server in MemoryCore/src/gateway/server.ts intercepts the request through checkAuth or checkAuthForV2. Both methods call verifyAuth, and if validation fails, they immediately return an HTTP 401 status code. V1 callers receive a plain-text response, while V2/V3 callers receive a JSON envelope containing the error details. The request never reaches the router or business logic.
Why does the /v3/meta/auth/verify endpoint not require a user key?
This endpoint is explicitly whitelisted in the V3_NO_USER_KEY_ROUTES Set defined in MemoryCore/src/metadata/router/auth.ts. This exception exists because the endpoint's purpose is to verify user key credentials—it cannot require the very credential it is designed to validate. All other /v3/meta/* endpoints require the x-tdai-user-key header processed by authenticateV3.
How does the service distinguish between different types of authentication failures?
Each validation layer returns specific 401 responses with distinct reason codes. The authenticateV3 function returns "missing_user_key" for empty headers and "invalid_user_key" for credentials that fail verification against the MetadataService. Similarly, parseV2Auth in the gateway generates 401 errors when the Bearer prefix is missing or the x-tdai-service-id header is empty, allowing clients to identify which authentication layer rejected their request.
What authentication context is passed to downstream handlers?
After successful validation, the system creates either a V2AuthContext or V3AuthContext object. The V3 context, generated by authenticateV3 in MemoryCore/src/metadata/router/auth.ts, contains the token, userId, isAdmin flag, and isSystemAdmin boolean derived from user.user_type. These contexts enable conversation, knowledge, and skill modules to enforce fine-grained permissions beyond the initial authentication gates.
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 →