mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-03-12 19:12:36 +01:00
📜 feat: Implement System Grants for Capability-Based Authorization (#11896)
* feat: Implement System Grants for Role-Based Capabilities
- Added a new `systemGrant` model and associated methods to manage role-based capabilities within the application.
- Introduced middleware functions `hasCapability` and `requireCapability` to check user permissions based on their roles.
- Updated the database seeding process to include system grants for the ADMIN role, ensuring all necessary capabilities are assigned on startup.
- Enhanced type definitions and schemas to support the new system grant functionality, improving overall type safety and clarity in the codebase.
* test: Add unit tests for capabilities middleware and system grant methods
- Introduced comprehensive unit tests for the capabilities middleware, including `hasCapability` and `requireCapability`, ensuring proper permission checks based on user roles.
- Added tests for the `SystemGrant` methods, verifying the seeding of system grants, capability granting, and revocation processes.
- Enhanced test coverage for edge cases, including idempotency of grant operations and handling of unexpected errors in middleware.
- Utilized mocks for database interactions to isolate tests and improve reliability.
* refactor: Transition to Capability-Based Access Control
- Replaced role-based access checks with capability-based checks across various middleware and routes, enhancing permission management.
- Introduced `hasCapability` and `requireCapability` functions to streamline capability verification for user actions.
- Updated relevant routes and middleware to utilize the new capability system, ensuring consistent permission enforcement.
- Enhanced type definitions and added tests for the new capability functions, improving overall code reliability and maintainability.
* test: Enhance capability-based access tests for ADMIN role
- Updated tests to reflect the new capability-based access control, specifically for the ADMIN role.
- Modified test descriptions to clarify that users with the MANAGE_AGENTS capability can bypass permission checks.
- Seeded capabilities for the ADMIN role in multiple test files to ensure consistent permission checks across different routes and middleware.
- Improved overall test coverage for capability verification, ensuring robust permission management.
* test: Update capability tests for MCP server access
- Renamed test to reflect the correct capability for bypassing permission checks, changing from MANAGE_AGENTS to MANAGE_MCP_SERVERS.
- Updated seeding of capabilities for the ADMIN role to align with the new capability structure.
- Ensured consistency in capability definitions across tests and middleware for improved permission management.
* feat: Add hasConfigCapability for enhanced config access control
- Introduced `hasConfigCapability` function to check user permissions for managing or reading specific config sections.
- Updated middleware to export the new capability function, ensuring consistent access control across the application.
- Enhanced unit tests to cover various scenarios for the new capability, improving overall test coverage and reliability.
* fix: Update tenantId filter in createSystemGrantMethods
- Added a condition to set tenantId filter to { $exists: false } when tenantId is null, ensuring proper handling of cases where tenantId is not provided.
- This change improves the robustness of the system grant methods by explicitly managing the absence of tenantId in the filter logic.
* fix: account deletion capability check
- Updated the `canDeleteAccount` middleware to ensure that the `hasManageUsers` capability check only occurs if a user is present, preventing potential errors when the user object is undefined.
- This change improves the robustness of the account deletion logic by ensuring proper handling of user permissions.
* refactor: Optimize seeding of system grants for ADMIN role
- Replaced sequential capability granting with parallel execution using Promise.all in the seedSystemGrants function.
- This change improves performance and efficiency during the initialization of system grants, ensuring all capabilities are granted concurrently.
* refactor: Simplify systemGrantSchema index definition
- Removed the sparse option from the unique index on principalType, principalId, capability, and tenantId in the systemGrantSchema.
- This change streamlines the index definition, potentially improving query performance and clarity in the schema design.
* refactor: Reorganize role capability check in roles route
- Moved the capability check for reading roles to occur after parsing the roleName, improving code clarity and structure.
- This change ensures that the authorization logic is consistently applied before fetching role details, enhancing overall permission management.
* refactor: Remove unused ISystemGrant interface from systemCapabilities.ts
- Deleted the ISystemGrant interface as it was no longer needed, streamlining the code and improving clarity.
- This change helps reduce clutter in the file and focuses on relevant capabilities for the system.
* refactor: Migrate SystemCapabilities to data-schemas
- Replaced imports of SystemCapabilities from 'librechat-data-provider' with imports from '@librechat/data-schemas' across multiple files.
- This change centralizes the management of system capabilities, improving code organization and maintainability.
* refactor: Update account deletion middleware and capability checks
- Modified the `canDeleteAccount` middleware to ensure that the account deletion permission is only granted to users with the `MANAGE_USERS` capability, improving security and clarity in permission management.
- Enhanced error logging for unauthorized account deletion attempts, providing better insights into permission issues.
- Updated the `capabilities.ts` file to ensure consistent handling of user authentication checks, improving robustness in capability verification.
- Refined type definitions in `systemGrant.ts` and `systemGrantMethods.ts` to utilize the `PrincipalType` enum, enhancing type safety and code clarity.
* refactor: Extract principal ID normalization into a separate function
- Introduced `normalizePrincipalId` function to streamline the normalization of principal IDs based on their type, enhancing code clarity and reusability.
- Updated references in `createSystemGrantMethods` to utilize the new normalization function, improving maintainability and reducing code duplication.
* test: Add unit tests for principalId normalization in systemGrant
- Introduced tests for the `grantCapability`, `revokeCapability`, and `getCapabilitiesForPrincipal` methods to verify correct handling of principalId normalization between string and ObjectId formats.
- Enhanced the `capabilities.ts` middleware to utilize the `PrincipalType` enum for improved type safety.
- Added a new utility function `normalizePrincipalId` to streamline principal ID normalization logic, ensuring consistent behavior across the application.
* feat: Introduce capability implications and enhance system grant methods
- Added `CapabilityImplications` to define relationships between broader and implied capabilities, allowing for more intuitive permission checks.
- Updated `createSystemGrantMethods` to expand capability queries to include implied capabilities, improving authorization logic.
- Enhanced `systemGrantSchema` to include an `expiresAt` field for future TTL enforcement of grants, and added validation to ensure `tenantId` is not set to null.
- Documented authorization requirements for prompt group and prompt deletion methods to clarify access control expectations.
* test: Add unit tests for canDeleteAccount middleware
- Introduced unit tests for the `canDeleteAccount` middleware to verify account deletion permissions based on user roles and capabilities.
- Covered scenarios for both allowed and blocked account deletions, including checks for ADMIN users with the `MANAGE_USERS` capability and handling of undefined user cases.
- Enhanced test structure to ensure clarity and maintainability of permission checks in the middleware.
* fix: Add principalType enum validation to SystemGrant schema
Without enum validation, any string value was accepted for principalType
and silently stored. Invalid documents would never match capability
queries, creating phantom grants impossible to diagnose without raw DB
inspection. All other ACL models in the codebase validate this field.
* fix: Replace seedSystemGrants Promise.all with bulkWrite for concurrency safety
When two server instances start simultaneously (K8s rolling deploy, PM2
cluster), both call seedSystemGrants. With Promise.all + findOneAndUpdate
upsert, both instances may attempt to insert the same documents, causing
E11000 duplicate key errors that crash server startup.
bulkWrite with ordered:false handles concurrent upserts gracefully and
reduces 17 individual round trips to a single network call. The returned
documents (previously discarded) are no longer fetched.
* perf: Add AsyncLocalStorage per-request cache for capability checks
Every hasCapability call previously required 2 DB round trips
(getUserPrincipals + SystemGrant.exists) — replacing what were O(1)
string comparisons. Routes like patchPromptGroup triggered this twice,
and hasConfigCapability's fallback path resolved principals twice.
This adds a per-request AsyncLocalStorage cache that:
- Caches resolved principals (same for all checks within one request)
- Caches capability check results (same user+cap = same answer)
- Automatically scoped to request lifetime (no stale grants)
- Falls through to DB when no store exists (background jobs, tests)
- Requires no signature changes to hasCapability
The capabilityContextMiddleware is registered at the app level before
all routes, initializing a fresh store per request.
* fix: Add error handling for inline hasCapability calls
canDeleteAccount, fetchAssistants, and validateAuthor all call
hasCapability without try-catch. These were previously O(1) string
comparisons that could never throw. Now they hit the database and can
fail on connection timeout or transient errors.
Wrap each call in try-catch, defaulting to deny (false) on error.
This ensures a DB hiccup returns a clean 403 instead of an unhandled
500 with a stack trace.
* test: Add canDeleteAccount DB-error resilience test
Tests that hasCapability rejection (e.g., DB timeout) results in a clean
403 rather than an unhandled exception. Validates the error handling
added in the previous commit.
* refactor: Use barrel import for hasCapability in validateAuthor
Import from ~/server/middleware barrel instead of directly from
~/server/middleware/roles/capabilities for consistency with other
non-middleware consumers. Files within the middleware barrel itself
must continue using direct imports to avoid circular requires.
* refactor: Remove misleading pre('save') hook from SystemGrant schema
The pre('save') hook normalized principalId for USER/GROUP principals,
but the primary write path (grantCapability) uses findOneAndUpdate —
which does not trigger save hooks. The normalization was already handled
explicitly in grantCapability itself. The hook created a false impression
of schema-level enforcement that only covered save()/create() paths.
Replace with a comment documenting that all writes must go through
grantCapability.
* feat: Add READ_ASSISTANTS capability to complete manage/read pair
Every other managed resource had a paired READ_X / MANAGE_X capability
except assistants. This adds READ_ASSISTANTS and registers the
MANAGE_ASSISTANTS → READ_ASSISTANTS implication in CapabilityImplications,
enabling future read-only assistant visibility grants.
* chore: Reorder systemGrant methods for clarity
Moved hasCapabilityForPrincipals to a more logical position in the returned object of createSystemGrantMethods, improving code readability. This change also maintains the inclusion of seedSystemGrants in the export, ensuring all necessary methods are available.
* fix: Wrap seedSystemGrants in try-catch to avoid blocking startup
Seeding capabilities is idempotent and will succeed on the next restart.
A transient DB error during seeding should not prevent the server from
starting — log the error and continue.
* refactor: Improve capability check efficiency and add audit logging
Move hasCapability calls after cheap early-exits in validateAuthor and
fetchAssistants so the DB check only runs when its result matters. Add
logger.debug on every capability bypass grant across all 7 call sites
for auditability, and log errors in catch blocks instead of silently
swallowing them.
* test: Add integration tests for AsyncLocalStorage capability caching
Exercises the full vertical — ALS context, generateCapabilityCheck,
real getUserPrincipals, real hasCapabilityForPrincipals, real MongoDB
via MongoMemoryServer. Covers per-request caching, cross-context
isolation, concurrent request isolation, negative caching, capability
implications, tenant scoping, group-based grants, and requireCapability
middleware.
* test: Add systemGrant data-layer and ALS edge-case integration tests
systemGrant.spec.ts (51 tests): Full integration tests for all
systemGrant methods against real MongoDB — grant/revoke lifecycle,
principalId normalization (string→ObjectId for USER/GROUP, string for
ROLE), capability implications (both directions), tenant scoping,
schema validation (null tenantId, invalid enum, required fields,
unique compound index).
capabilities.integration.spec.ts (27 tests): Adds ALS edge cases —
missing context degrades gracefully with no caching (background jobs,
child processes), nested middleware creates independent inner context,
optional-chaining safety when store is undefined, mid-request grant
changes are invisible due to result caching, requireCapability works
without ALS, and interleaved concurrent contexts maintain isolation.
* fix: Add worker thread guards to capability ALS usage
Detect when hasCapability or capabilityContextMiddleware is called from
a worker thread (where ALS context does not propagate from the parent).
hasCapability logs a warn-once per factory instance; the middleware logs
an error since mounting Express middleware in a worker is likely a
misconfiguration. Both continue to function correctly — the guard is
observability, not a hard block.
* fix: Include tenantId in ALS principal cache key for tenant isolation
The principal cache key was user.id:user.role, which would reuse
cached principals across tenants for the same user within a request.
When getUserPrincipals gains tenant-scoped group resolution, principals
from tenant-a would incorrectly serve tenant-b checks. Changed to
user.id:user.role:user.tenantId to prevent cross-tenant cache hits.
Adds integration test proving separate principal lookups per tenantId.
* test: Remove redundant mocked capabilities.spec.js
The JS wrapper test (7 tests, all mocked) is a strict subset of
capabilities.integration.spec.ts (28 tests, real MongoDB). Every
scenario it covered — hasCapability true/false, tenantId passthrough,
requireCapability 403/500, error handling — is tested with higher
fidelity in the integration suite.
* test: Replace mocked canDeleteAccount tests with real MongoDB integration
Remove hasCapability mock — tests now exercise the full capability
chain against real MongoDB (getUserPrincipals, hasCapabilityForPrincipals,
SystemGrant collection). Only mocks remaining are logger and cache.
Adds new coverage: admin role without grant is blocked, user-level
grant bypasses deletion restriction, null user handling.
* test: Add comprehensive tests for ACL entry management and user group methods
Introduces new tests for `deleteAclEntries`, `bulkWriteAclEntries`, and `findPublicResourceIds` in `aclEntry.spec.ts`, ensuring proper functionality for deleting and bulk managing ACL entries. Additionally, enhances `userGroup.spec.ts` with tests for finding groups by ID and name pattern, including external ID matching and source filtering. These changes improve coverage and validate the integrity of ACL and user group operations against real MongoDB interactions.
* refactor: Update capability checks and logging for better clarity and error handling
Replaced `MANAGE_USERS` with `ACCESS_ADMIN` in the `canDeleteAccount` middleware and related tests to align with updated permission structure. Enhanced logging in various middleware functions to use `logger.warn` for capability check failures, providing clearer error messages. Additionally, refactored capability checks in the `patchPromptGroup` and `validateAuthor` functions to improve readability and maintainability. This commit also includes adjustments to the `systemGrant` methods to implement retry logic for transient failures during capability seeding, ensuring robustness in the face of database errors.
* refactor: Enhance logging and retry logic in seedSystemGrants method
Updated the logging format in the seedSystemGrants method to include error messages for better clarity. Improved the retry mechanism by explicitly mocking multiple failures in tests, ensuring robust error handling during transient database issues. Additionally, refined imports in the systemGrant schema for better type management.
* refactor: Consolidate imports in canDeleteAccount middleware
Merged logger and SystemCapabilities imports from the data-schemas module into a single line for improved readability and maintainability of the code. This change streamlines the import statements in the canDeleteAccount middleware.
* test: Enhance systemGrant tests for error handling and capability validation
Added tests to the systemGrant methods to handle various error scenarios, including E11000 race conditions, invalid ObjectId strings for USER and GROUP principals, and invalid capability strings. These enhancements improve the robustness of the capability granting and revoking logic, ensuring proper error propagation and validation of inputs.
* fix: Wrap hasCapability calls in deny-by-default try-catch at remaining sites
canAccessResource, files.js, and roles.js all had hasCapability inside
outer try-catch blocks that returned 500 on DB failure instead of
falling through to the regular ACL check. This contradicts the
deny-by-default pattern used everywhere else.
Also removes raw error.message from the roles.js 500 response to
prevent internal host/connection info leaking to clients.
* fix: Normalize user ID in canDeleteAccount before passing to hasCapability
requireCapability normalizes req.user.id via _id?.toString() fallback,
but canDeleteAccount passed raw req.user directly. If req.user.id is
absent (some auth layers only populate _id), getUserPrincipals received
undefined, silently returning empty principals and blocking the bypass.
* fix: Harden systemGrant schema and type safety
- Reject empty string tenantId in schema validator (was only blocking
null; empty string silently orphaned documents)
- Fix reverseImplications to use BaseSystemCapability[] instead of
string[], preserving the narrow discriminated type
- Document READ_ASSISTANTS as reserved/unenforced
* test: Use fake timers for seedSystemGrants retry tests and add tenantId validation
- Switch retry tests to jest.useFakeTimers() to eliminate 3+ seconds
of real setTimeout delays per test run
- Add regression test for empty-string tenantId rejection
* docs: Add TODO(#12091) comments for tenant-scoped capability gaps
In multi-tenant mode, platform-level grants (no tenantId) won't match
tenant-scoped queries, breaking admin access. getUserPrincipals also
returns cross-tenant group memberships. Both need fixes in #12091.
This commit is contained in:
parent
abf3742efb
commit
530b401e7b
39 changed files with 4200 additions and 532 deletions
407
api/server/services/systemGrant.spec.js
Normal file
407
api/server/services/systemGrant.spec.js
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
const mongoose = require('mongoose');
|
||||
const { createModels, createMethods } = require('@librechat/data-schemas');
|
||||
const { MongoMemoryServer } = require('mongodb-memory-server');
|
||||
const { SystemRoles, PrincipalType } = require('librechat-data-provider');
|
||||
const { SystemCapabilities } = require('@librechat/data-schemas');
|
||||
|
||||
jest.mock('@librechat/data-schemas', () => ({
|
||||
...jest.requireActual('@librechat/data-schemas'),
|
||||
getTransactionSupport: jest.fn().mockResolvedValue(false),
|
||||
createModels: jest.requireActual('@librechat/data-schemas').createModels,
|
||||
createMethods: jest.requireActual('@librechat/data-schemas').createMethods,
|
||||
}));
|
||||
|
||||
jest.mock('~/server/services/GraphApiService', () => ({
|
||||
entraIdPrincipalFeatureEnabled: jest.fn().mockReturnValue(false),
|
||||
getUserOwnedEntraGroups: jest.fn().mockResolvedValue([]),
|
||||
getUserEntraGroups: jest.fn().mockResolvedValue([]),
|
||||
getGroupMembers: jest.fn().mockResolvedValue([]),
|
||||
getGroupOwners: jest.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
jest.mock('~/config', () => ({
|
||||
logger: { error: jest.fn() },
|
||||
}));
|
||||
|
||||
let mongoServer;
|
||||
let methods;
|
||||
let SystemGrant;
|
||||
|
||||
beforeAll(async () => {
|
||||
mongoServer = await MongoMemoryServer.create();
|
||||
await mongoose.connect(mongoServer.getUri());
|
||||
|
||||
createModels(mongoose);
|
||||
const dbModels = require('~/db/models');
|
||||
Object.assign(mongoose.models, dbModels);
|
||||
SystemGrant = dbModels.SystemGrant;
|
||||
|
||||
methods = createMethods(mongoose, {
|
||||
matchModelName: () => null,
|
||||
findMatchingPattern: () => null,
|
||||
getCache: () => ({
|
||||
get: async () => null,
|
||||
set: async () => {},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await mongoose.disconnect();
|
||||
await mongoServer.stop();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await SystemGrant.deleteMany({});
|
||||
});
|
||||
|
||||
describe('SystemGrant methods', () => {
|
||||
describe('seedSystemGrants', () => {
|
||||
it('seeds all capabilities for the ADMIN role', async () => {
|
||||
await methods.seedSystemGrants();
|
||||
|
||||
const grants = await SystemGrant.find({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: SystemRoles.ADMIN,
|
||||
}).lean();
|
||||
|
||||
const expectedCount = Object.values(SystemCapabilities).length;
|
||||
expect(grants).toHaveLength(expectedCount);
|
||||
|
||||
const capabilities = grants.map((g) => g.capability).sort();
|
||||
const expected = Object.values(SystemCapabilities).sort();
|
||||
expect(capabilities).toEqual(expected);
|
||||
});
|
||||
|
||||
it('is idempotent — calling twice does not duplicate grants', async () => {
|
||||
await methods.seedSystemGrants();
|
||||
await methods.seedSystemGrants();
|
||||
|
||||
const count = await SystemGrant.countDocuments({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: SystemRoles.ADMIN,
|
||||
});
|
||||
|
||||
expect(count).toBe(Object.values(SystemCapabilities).length);
|
||||
});
|
||||
|
||||
it('seeds grants with no tenantId', async () => {
|
||||
await methods.seedSystemGrants();
|
||||
|
||||
const withTenant = await SystemGrant.countDocuments({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: SystemRoles.ADMIN,
|
||||
tenantId: { $exists: true },
|
||||
});
|
||||
|
||||
expect(withTenant).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('grantCapability / revokeCapability', () => {
|
||||
it('grants a capability to a user', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
});
|
||||
|
||||
const grant = await SystemGrant.findOne({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
}).lean();
|
||||
|
||||
expect(grant).toBeTruthy();
|
||||
expect(grant.grantedAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('upsert does not create duplicates', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
});
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
});
|
||||
|
||||
const count = await SystemGrant.countDocuments({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
});
|
||||
|
||||
expect(count).toBe(1);
|
||||
});
|
||||
|
||||
it('revokes a capability', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
});
|
||||
|
||||
await methods.revokeCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
});
|
||||
|
||||
const grant = await SystemGrant.findOne({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_USERS,
|
||||
}).lean();
|
||||
|
||||
expect(grant).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasCapabilityForPrincipals', () => {
|
||||
it('returns true when role principal has the capability', async () => {
|
||||
await methods.seedSystemGrants();
|
||||
|
||||
const principals = [
|
||||
{ principalType: PrincipalType.USER, principalId: new mongoose.Types.ObjectId() },
|
||||
{ principalType: PrincipalType.ROLE, principalId: SystemRoles.ADMIN },
|
||||
{ principalType: PrincipalType.PUBLIC },
|
||||
];
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals,
|
||||
capability: SystemCapabilities.ACCESS_ADMIN,
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when no principal has the capability', async () => {
|
||||
const principals = [
|
||||
{ principalType: PrincipalType.USER, principalId: new mongoose.Types.ObjectId() },
|
||||
{ principalType: PrincipalType.ROLE, principalId: SystemRoles.USER },
|
||||
{ principalType: PrincipalType.PUBLIC },
|
||||
];
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals,
|
||||
capability: SystemCapabilities.ACCESS_ADMIN,
|
||||
});
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for an empty principals list', async () => {
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals: [],
|
||||
capability: SystemCapabilities.ACCESS_ADMIN,
|
||||
});
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores PUBLIC principals', async () => {
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals: [{ principalType: PrincipalType.PUBLIC }],
|
||||
capability: SystemCapabilities.ACCESS_ADMIN,
|
||||
});
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('matches user-level grants', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
});
|
||||
|
||||
const principals = [
|
||||
{ principalType: PrincipalType.USER, principalId: userId },
|
||||
{ principalType: PrincipalType.ROLE, principalId: SystemRoles.USER },
|
||||
{ principalType: PrincipalType.PUBLIC },
|
||||
];
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals,
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('matches group-level grants', async () => {
|
||||
const groupId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.GROUP,
|
||||
principalId: groupId,
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
const principals = [
|
||||
{ principalType: PrincipalType.USER, principalId: new mongoose.Types.ObjectId() },
|
||||
{ principalType: PrincipalType.GROUP, principalId: groupId },
|
||||
{ principalType: PrincipalType.PUBLIC },
|
||||
];
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals,
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCapabilitiesForPrincipal', () => {
|
||||
it('lists all capabilities for a principal', async () => {
|
||||
await methods.seedSystemGrants();
|
||||
|
||||
const grants = await methods.getCapabilitiesForPrincipal({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: SystemRoles.ADMIN,
|
||||
});
|
||||
|
||||
expect(grants).toHaveLength(Object.values(SystemCapabilities).length);
|
||||
});
|
||||
|
||||
it('returns empty array for a principal with no grants', async () => {
|
||||
const grants = await methods.getCapabilitiesForPrincipal({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: SystemRoles.USER,
|
||||
});
|
||||
|
||||
expect(grants).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('principalId normalization', () => {
|
||||
it('grant with string userId is found by hasCapabilityForPrincipals with ObjectId', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId.toString(), // string input
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals: [{ principalType: PrincipalType.USER, principalId: userId }], // ObjectId input
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('revoke with string userId removes the grant stored as ObjectId', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId.toString(),
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
await methods.revokeCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId.toString(), // string revoke
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals: [{ principalType: PrincipalType.USER, principalId: userId }],
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('getCapabilitiesForPrincipal with string userId returns grants stored as ObjectId', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId.toString(),
|
||||
capability: SystemCapabilities.READ_USAGE,
|
||||
});
|
||||
|
||||
const grants = await methods.getCapabilitiesForPrincipal({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId.toString(), // string lookup
|
||||
});
|
||||
|
||||
expect(grants).toHaveLength(1);
|
||||
expect(grants[0].capability).toBe(SystemCapabilities.READ_USAGE);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tenant scoping', () => {
|
||||
it('tenant-scoped grant does not match platform-level query', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
tenantId: 'tenant-1',
|
||||
});
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals: [{ principalType: PrincipalType.USER, principalId: userId }],
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
});
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('tenant-scoped grant matches same-tenant query', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
tenantId: 'tenant-1',
|
||||
});
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals: [{ principalType: PrincipalType.USER, principalId: userId }],
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
tenantId: 'tenant-1',
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('tenant-scoped grant does not match different tenant', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
|
||||
await methods.grantCapability({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: userId,
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
tenantId: 'tenant-1',
|
||||
});
|
||||
|
||||
const result = await methods.hasCapabilityForPrincipals({
|
||||
principals: [{ principalType: PrincipalType.USER, principalId: userId }],
|
||||
capability: SystemCapabilities.READ_CONFIGS,
|
||||
tenantId: 'tenant-2',
|
||||
});
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue