test(api-keys): add unit tests for tenant API key validation
Introduce unit tests for the tenant API key validation logic, ensuring that scoped keys require capabilities, while full-access keys are validated without them. The tests cover various scenarios, reinforcing the expected behavior of the API key validation function.
This commit is contained in:
@@ -154,12 +154,19 @@ func MCPOAuthPrincipalFromContext(ctx context.Context) Principal {
|
||||
|
||||
// SessionOwnerIDFromContext returns the sessions.user_id scope for the current
|
||||
// caller. API external users and embed chat sessions use principal-derived IDs;
|
||||
// MCP OAuth token storage uses MCPOAuthPrincipalFromContext (visitor-level for embed).
|
||||
// tenant API keys are isolated per key id; MCP OAuth token storage uses
|
||||
// MCPOAuthPrincipalFromContext (visitor-level for embed).
|
||||
func SessionOwnerIDFromContext(ctx context.Context) string {
|
||||
if p, ok := PrincipalFromContext(ctx); ok {
|
||||
switch p.Type {
|
||||
case PrincipalAPIExternalUser, PrincipalEmbedSession:
|
||||
return p.StorageID()
|
||||
case PrincipalAPITenant:
|
||||
if scope, ok := TenantAPIKeyScopeFromContext(ctx); ok && scope.KeyID > 0 {
|
||||
if tenantID, ok := TenantIDFromContext(ctx); ok && tenantID > 0 {
|
||||
return fmt.Sprintf("api_tenant_key:%d:%d", tenantID, scope.KeyID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
userID, _ := UserIDFromContext(ctx)
|
||||
|
||||
@@ -53,6 +53,17 @@ func TestSessionOwnerIDFromContextFallsBackToUserID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionOwnerIDFromContextIsolatesTenantAPIKeys(t *testing.T) {
|
||||
ctx := WithPrincipal(context.Background(), Principal{Type: PrincipalAPITenant, ID: "7"})
|
||||
ctx = context.WithValue(ctx, TenantIDContextKey, uint64(7))
|
||||
ctx = context.WithValue(ctx, UserIDContextKey, "system-7")
|
||||
ctx = WithTenantAPIKeyScope(ctx, TenantAPIKeyScope{KeyID: 99})
|
||||
|
||||
if got := SessionOwnerIDFromContext(ctx); got != "api_tenant_key:7:99" {
|
||||
t.Fatalf("SessionOwnerIDFromContext() = %q, want per-key isolation", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionOwnerIDFromContextUsesEmbedSessionPrincipal(t *testing.T) {
|
||||
ctx := WithPrincipal(context.Background(), EmbedSessionPrincipal(10000, "ch1", "sess1"))
|
||||
ctx = context.WithValue(ctx, UserIDContextKey, "embed-ch1")
|
||||
|
||||
Reference in New Issue
Block a user