Resource management methods for data isolation and permission inheritance in multi-tenant environments

By injecting tenant identifier filtering conditions, service layer quota verification, and depth-first search algorithm to resolve role inheritance relationships into the ORM framework, the problems of data isolation and access control in multi-tenant environments are solved, and the performance optimization of tenant identifier constraints, quota verification, and tenant deregistration process are standardized.

CN123115091APending Publication Date: 2026-11-17HUANENG INFORMATION TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611351267.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-02
Publication Date
2026-11-17

AI Technical Summary

Technical Problem

Multi-tenant shared platforms suffer from issues such as incomplete data isolation, loop risks in permission inheritance relationships, lack of a unified entry point for quota verification, and lack of data integrity guarantees in the tenant deregistration process.

Method used

By injecting tenant identifier filtering conditions through a global query scope hook in the ORM framework, multi-dimensional quota verification is performed at a unified entry point in the service layer. A depth-first search algorithm recursively parses role inheritance relationships, and precondition verification, data archiving, and logical deletion scheduling are performed when a tenant is deregistered. The tenant lifecycle is managed in conjunction with caching and atomic transactions.

Benefits of technology

It implements tenant identification constraints on data access paths, reduces the performance impact of quota verification on business processes, ensures immediate effectiveness and controllable overhead of permission calculation, and solves the compliance audit and data recovery needs during the tenant deregistration process.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123115091A_ABST
    Figure CN123115091A_ABST
Patent Text Reader

Abstract

This invention relates to the field of multi-tenant resource management technology and discloses a resource management method for data isolation and permission inheritance in a multi-tenant environment. The method includes: declaring indexed, non-empty tenant identifier fields in all core business data tables; automatically injecting tenant filtering conditions through a global query scope hook in the ORM framework; uniformly performing multi-dimensional resource quota verification and early warning at the Service layer; recursively parsing role inheritance chains and merging effective permission sets using a depth-first search algorithm; performing aggregate statistical queries under tenant isolation constraints; and executing a standardized tenant lifecycle management process that includes data archiving, logical deletion, and physical deletion scheduling.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of multi-tenant resource management technology, specifically to a resource management method for data isolation and permission inheritance in a multi-tenant environment. Background Technology

[0002] In multi-tenant shared platforms, business data from multiple enterprise tenants are stored in the same database instance within the same set of table structures. Existing technologies typically rely on developers manually adding tenant filtering conditions in various parts of the business code and implementing permission verification and resource quota control at the business code level, while lacking a standardized tenant data lifecycle management process.

[0003] The above approach has the following drawbacks: First, tenant filtering conditions rely on manual addition at each location, and any omission may lead to cross-tenant data reading or writing, and clients can pollute tenant data by tampering with request parameters. Second, it lacks multi-dimensional quota control at the tenant level, and excessive resource consumption by a single tenant will affect the normal use of other tenants. Third, when there is a multi-level structure in the role inheritance chain, the recursive parsing of permission sets faces the challenge of increased computational complexity, and there is a lack of means to detect circular dependencies. Fourth, there is a lack of standardized data lifecycle management processes when tenants are deregistered, making it impossible to simultaneously meet the historical traceability requirements of compliance audits and the data recovery requirements after erroneous operations. These drawbacks lead to systemic risks in multi-tenant platforms regarding data security isolation, fair resource allocation, fine-grained permission control, and data compliance management. Summary of the Invention

[0004] This invention provides a resource management method for data isolation and permission inheritance in a multi-tenant environment, which solves the technical problems in related technologies such as incomplete data isolation in a multi-tenant environment, the risk of loops in permission inheritance relationships, the lack of a unified entry point for quota verification, and the lack of data integrity guarantees in the tenant deregistration process.

[0005] This invention discloses a resource management method for data isolation and permission inheritance in a multi-tenant environment, comprising the following steps: Declare indexed, non-nullable tenant identifier fields in all core business data tables, automatically inject tenant identifier filtering conditions through the global query scope hook of the ORM framework, and inject the data model from the identity token on the server side before the write operation. At the unified entry point of the service layer, multi-dimensional quota verification is performed, comparing the current usage with the quota limit, and rejecting the request if the limit is exceeded. The role inheritance relationship is recursively traversed by a depth-first search algorithm, and the duplicates are merged to obtain the set of valid user permissions. The request path and permission type are then matched and validated. When a tenant is deregistered, precondition checks, data archiving, integrity checks, logical deletion, and physical deletion scheduling are performed sequentially. Tenant data recovery is performed using atomic transactions within the retention window.

[0006] Furthermore, the automatic injection of tenant identifier filtering conditions through the global query scope hook of the ORM framework includes: defining a global scope function to read the tenant identifier of the authenticated user from the current request context and append the tenant filtering condition to the current database operation chain; if there is no authenticated user information in the context, the injection of the filtering condition is skipped; the global scope function is registered at the session level and bound to the request context; in query scenarios involving multiple table joins, the corresponding tenant identifier filtering condition is independently appended to each business data table involved in the join.

[0007] Furthermore, the multi-dimensional quota verification performed at the unified entry point of the service layer includes: extracting the current tenant identifier from the request context, and reading the quota configuration from the cache using the tenant identifier as the key; if the cache misses, querying the quota configuration table and writing it into the cache; querying the current actual usage for the corresponding resource dimension, and setting the current usage... With quota limit Compare; if If the current usage is not met, the request will be rejected and an error response containing the current usage and quota limit will be returned; if If the resource creation process continues, the resource creation process will continue. The multiple resource dimensions include the number of concurrent tasks, the number of verification nodes, the number of security assets, the number of test scenarios, storage space, and interface call rate.

[0008] Furthermore, the recursive traversal of role inheritance relationships using a depth-first search algorithm to merge and deduplicate to obtain the set of valid user permissions includes: extracting the current user identifier from the identity token, and reading the set of valid user permissions from the cache using the user identifier as the key; if the cache misses, querying all role identifiers associated with the user, recursively parsing the inheritance chain for each role, merging the permission entries of all roles and deduplicating them, and writing the result to the cache; traversing the set of valid permissions, performing wildcard matching on the interface path field of the permission entries, mapping the request method to the corresponding permission type identifier, and determining whether there is a matching permission entry with a valid corresponding permission type; before adding a new role inheritance relationship, modeling the inheritance relationship as a directed graph and detecting whether a cycle is generated, and rejecting the operation if a cycle exists.

[0009] Furthermore, the sequential execution of precondition verification, data archiving, integrity verification, logical deletion, and physical deletion scheduling during tenant deregistration includes: verifying whether the target tenant has any task records that are in execution or queued; if so, rejecting the deregistration operation; asynchronously performing archive export on all business data of the target tenant, and calculating the integrity verification value of the archived file. ; in, For the complete binary content of the archive file, The output hash value; the verification value along with the archived metadata is written to the archived record table; after the archived verification is passed, a batch logical deletion is performed on all business data tables of the target tenant, and a scheduled physical deletion task is created, with the planned execution time being the logical deletion completion time plus the retention window period.

[0010] Furthermore, it also includes: periodically iterating through all tenants in an operational state and calculating the current utilization rate for each tenant's quota dimension. : ; in, This represents the current actual usage. For the corresponding quota limit; when When the preset warning threshold is reached, a warning notification containing the warning dimension, current usage, and quota limit is sent to the tenant administrator; a deduplication key is set in the cache using the combination of tenant identifier and resource dimension as the key, and no duplicate warning notifications are sent to the same tenant for the same dimension within the validity period of the deduplication key; when the usage rate falls below the warning threshold, the corresponding deduplication key is cleared.

[0011] Furthermore, it also includes: performing aggregate calculations on the verification tasks completed within the current tenant scope under tenant isolation constraints to calculate the defense score. : ; in, This represents the total number of verification test cases completed within a specified statistical period. The number of successful attack simulation test cases. The range of values ​​is .

[0012] This invention discloses a resource management system for data isolation and permission inheritance in a multi-tenant environment, comprising: The data isolation module is used to declare indexed, non-nullable tenant identifier fields in all core business data tables. It automatically injects tenant identifier filtering conditions into all database operations through the global query scope hook of the ORM framework, and injects the data model into the server after extracting the tenant identifier from the identity token and before the write operation. The quota management module is used to maintain multi-dimensional tenant quota configurations. It performs quota verification and interception at a unified entry point in the service layer, compares the current usage with the quota limit, and rejects requests when the limit is exceeded. The permission verification module is used to maintain role, permission and role inheritance relationship data. It uses a depth-first search algorithm to recursively parse the role inheritance chain and merge the valid permission set. It performs permission verification based on identity token at the interface routing layer. The lifecycle management module is used to atomically execute the tenant creation process in a single database transaction, as well as the tenant deregistration process, which includes precondition verification, data archiving, integrity verification, logical deletion, and physical deletion scheduling, and to perform complete tenant data recovery in an atomic transaction manner within the retention window.

[0013] Furthermore, the permission verification module also includes: caching the user's final valid permission set with the user identifier as the key; actively invalidating the permission cache key of the affected user when the role permission configuration or user role association changes; and modeling the inheritance relationship as a directed graph and detecting whether a cycle is generated before adding a new role inheritance relationship. If a cycle exists, the operation is rejected and an error message is returned.

[0014] Furthermore, the lifecycle management module also includes: in the tenant creation process, inserting tenant records into the tenant master record table sequentially within a single database transaction, reading default quota parameters from the quota template according to the payment level and inserting quota records, generating an initial administrator account and associating it with a pre-defined role; in the tenant deregistration process, using the passing of archive file hash integrity verification as a prerequisite for executing logical deletion; in the tenant recovery process, identifying the affected record set by accurately matching the timestamp of this deregistration operation, performing batch recovery on the set, and ensuring full success or full rollback of the recovery operation with atomic transactions.

[0015] The beneficial effects of this invention are as follows: This invention addresses the technical issues of missed manual concatenation of filtering conditions in business code and cross-tenant data pollution caused by client-side tampering with tenant identifier parameters by injecting the tenant identifier into the global query scope hook layer of the ORM framework. It achieves the technical effect that both data access and write paths are constrained by the tenant identifier. Furthermore, by performing multi-dimensional quota verification at a unified entry point in the Service layer and combining it with Redis caching to reduce database access frequency, it solves the technical problem of excessive resource consumption by a single tenant affecting the normal use of other tenants, achieving a controllable impact of quota verification on the performance of normal business processes. Finally, by employing a depth-first search algorithm to recursively parse the role inheritance chain, caching the parsing results, and actively invalidating the cache key when permissions change, it solves the technical problem of increased computational complexity of permission sets in multi-level role inheritance scenarios, achieving the technical effect that permission changes take effect immediately and reduce the overhead of repeated parsing and computation. By breaking down the tenant deregistration process into four stages—precondition verification, data archiving, logical deletion, and physical deletion scheduling—and calculating SHA-256 checksums to verify the integrity of archived files during the archiving stage, and achieving atomic data recovery by precisely matching the deregistration operation timestamps within the retention window, the technical problem of the tenant deregistration process being unable to simultaneously meet the requirements for compliance audit traceability and the requirements for data recovery from erroneous operations has been solved. This has achieved the technical effect that data has been verifiable and archived before physical deletion is executed, and that the recovery operation can restore historical proactively deleted records without error. Attached Figure Description

[0016] Figure 1 This is a flowchart of a resource management method for data isolation and permission inheritance in a multi-tenant environment provided in an embodiment of the present invention; Figure 2 This is a sub-flowchart of the resource management method for data isolation and permission inheritance in a multi-tenant environment provided in this embodiment of the invention, which calculates the current usage of tenant resources and performs quota verification. Figure 3 This is a sub-flowchart of parsing the set of valid user permissions and performing permission verification in the resource management method for data isolation and permission inheritance in a multi-tenant environment provided in this embodiment of the invention; Figure 4 This is a sub-flowchart of the resource management method for data isolation and permission inheritance in a multi-tenant environment provided in this embodiment of the invention, which performs full lifecycle management of tenants. Detailed Implementation

[0017] The subject matter described herein will now be discussed with reference to exemplary embodiments. It should be understood that these embodiments are discussed only to enable those skilled in the art to better understand and implement the subject matter described herein, and changes may be made to the function and arrangement of the elements discussed without departing from the scope of this specification. Various processes or components may be omitted, substituted, or added as needed in the examples. Furthermore, some features described in the examples may be combined in other examples.

[0018] At least one embodiment of the present invention discloses a resource management method for data isolation and permission inheritance in a multi-tenant environment, see [link to relevant documentation]. Figures 1-4 This includes the following steps: Step 1: Establish a database layer data isolation structure based on the tenant identifier field.

[0019] At the database schema level, a `tenant_id` field is declared for all core business data tables of the platform. The data type is defined as `bigint unsigned` with an additional `NOT NULL` constraint. A separate B-Tree index is created on this field, defined as `INDEX idx_tenant_id (tenant_id)`, to support efficient tenant-range filtering queries. The aforementioned core business data tables include: `plan`, `job`, `scenario`, `target`, `secure_assets`, `phish_test`, and `report`. Each business table also contains a `deleted_at` field (data type `datetime(3)`, `DEFAULT NULL`), a `created_at` field, and an `updated_at` field, which are used for soft deletion marking and data lineage tracking, respectively.

[0020] When a tenant user initiates an API request to create a resource, the request body does not include the `tenant_id` parameter. Upon receiving the request, the server's business logic layer extracts the authenticated user information from the current HTTP request context, parses the tenant ID from this information, and injects the tenant ID into the data model to be written before performing a database INSERT operation. The user information, after being parsed from the JWT token by the authentication middleware, is stored in the request context as key-value pairs. The key is designated as `authenticated_user`, and the corresponding value is a structure object containing fields such as user ID, tenant ID, and a list of roles.

[0021] It's important to note that the assignment of the tenant_id is entirely determined by the server based on the verified JWT token payload, not by the client's request body. Even if the requester actively constructs or tampers with the tenant_id parameter in the request body, this parameter will not be read by the business logic layer, thus eliminating the path of cross-tenant data corruption during the data writing process.

[0022] In this embodiment, to ensure data isolation capabilities are completely transparent to upper-layer business code, the system utilizes the Global Scope hook mechanism provided by the GORMv2 framework to automatically inject tenant ID filtering conditions at the ORM level. The specific processing method is as follows: The system defines a global scope function, TenantScope, which accepts the current request context as input and returns a closure conforming to the GORM function signature `func(*gorm.DB) *gorm.DB`. Inside the closure, the TenantScope function first attempts to read the tenant ID of the authenticated user from the passed context; if successful, it appends the tenant filtering condition to the current database operation chain using the `db.Where(“tenant_id = ?”, tenantID)` method; if the authenticated user information does not exist in the context (e.g., in a system-internal scheduled task scenario), the tenant filtering condition injection is skipped. The TenantScope function is registered at the GORM session level and bound to the request context when the database connection is established, ensuring that each request uses an independent database session carrying the correct tenant context.

[0023] In this embodiment, based on step 1, for complex query scenarios involving multi-table JOINs, the system independently adds a corresponding tenant_id filter condition to each business data table participating in the JOIN. For example, in the join query between plan and job, the SQL statement adds corresponding tenant ID filter clauses to each of the two tables, thereby preventing cross-tenant data leakage in the join query path.

[0024] Step 2: Calculate the current usage of tenant resources and perform quota verification.

[0025] The system maintains a tenant quota configuration table `tenant_quota` in the database, with `tenant_id` as the primary key. It stores the quota limits for each tenant across the following six resource dimensions: `max_concurrent_jobs` (unit: jobs), representing the maximum number of tasks a single tenant can execute simultaneously; `max_simulators` (unit: simulators), representing the maximum number of verifier nodes that can be registered; `max_secure_assets` (unit: secure assets), representing the maximum number of manageable security asset entries; `max_scenarios` (unit: scenarios), representing the maximum number of custom test scenarios that can be created; `storage_quota_gb` (unit: GB), representing the maximum total storage space occupied by the tenant's persistent data; and `api_rate_limit_per_minute` (unit: API calls per minute), representing the maximum number of API calls a tenant can initiate per minute, with rate limiting implemented at the API gateway layer using a token bucket algorithm.

[0026] When a tenant user initiates a request to create a new resource, the system executes a quota verification process at the business logic entry point of the Service layer. The specific steps are as follows: Step 201: Extract the current tenant ID from the request context, and read the tenant quota configuration from the Redis cache using the tenant ID as the key; if the cache is not hit, query the tenant_quota table and write it to the cache, and set the cache TTL to 300 seconds.

[0027] Step 202: Query the current actual usage of the corresponding resource dimension. Taking task concurrency as an example, the system counts the number of task records that are currently in the queue (status = 1) and executing (status = 2) and have not been logically deleted (deleted_at ISNULL), which is taken as the current concurrent task usage of the tenant.

[0028] Step 203: Compare the current usage with the quota limit. Let the current usage be... The quota limit is ;like If the system rejects the creation request, it returns an HTTP 429 status code and a structured error response body to the caller. The error response includes the error code, error description, and the specific values ​​of the current usage and quota limit. If so, then the subsequent resource creation logic can continue to be executed.

[0029] It should be noted that the quota verification logic described above is handled uniformly in the Service layer. All resource creation entry points—whether through the front-end page or directly called via API—are routed to the same Service method, ensuring that there are no bypass paths that can circumvent quota verification.

[0030] In this embodiment, the system administrator dynamically adjusts the quota parameters of a specified tenant across various dimensions online by calling the quota management API interface PUT / admin / tenants / {tenant_id} / quota. The quota adjustment operation directly updates the record of the corresponding tenant in the `tenant_quota` table and invalidates the cache by performing a DEL operation on the tenant's quota cache key in Redis, ensuring that the adjustment result takes effect immediately during the next quota verification. To prevent the quota from being set below the currently used amount, the system verifies whether the target quota value is not less than the current actual usage of the corresponding dimension before saving. If it is lower than the current usage, the adjustment is rejected and an error message containing the current usage value is returned.

[0031] In this embodiment, the system further includes the following steps: deploying a periodically running quota monitoring task, iterating through all tenants in normal operation status, and calculating the current utilization rate for each quota dimension of each tenant. : ; in, This represents the current actual usage. This corresponds to the upper limit of the quota. When When the system determines that a quota alert exists for that dimension, it sends an alert email containing the alert dimension, current usage, quota limit, and usage rate to the email address associated with the tenant administrator account. Simultaneously, it pushes an in-platform alert message with the same content to the tenant administrator account via the platform's internal message center and notifies the platform system administrator. To prevent duplicate alert notifications for the same tenant and the same dimension within the same alert period, the system sets a deduplication key for each alert record in Redis. The key format is quota:alert:{tenant_id}:{dimension}, and the TTL is set to 3600 seconds, ensuring that alert notifications for the same tenant and the same dimension are sent at most once per hour. When the usage rate falls below the 0.8 threshold, the system automatically removes the corresponding deduplication key.

[0032] Step 3: Parse the user's valid permission set and perform permission verification.

[0033] The core data tables related to system permissions include the following: `role` (role table) stores role definitions, with fields including `id`, `tenant_id`, `role_code`, `role_name`, and `is_preset`; `permission` (permission table) stores API-level permission entries, with fields including `id`, `api_path` (supports wildcards), `module`, `is_view` (whether it's view permission), and `is_manage` (whether it's management permission); `role_permission` (role permission association table) stores the many-to-many mapping relationship between roles and permission entries; `role_inheritance` (role inheritance relationship table) stores the parent-child inheritance relationship between roles, with fields including `child_role_id` and `parent_role_id`, supporting a child role having multiple parent roles; and `user_role` (user role association table) stores the many-to-many mapping relationship between users and roles, with an `tenant_id` field to limit the tenant scope of the association relationship.

[0034] The system pre-defines five core roles in the role table, which are automatically created by the database seed script during system initialization: `super_admin` has the highest operational privileges for all platform functional modules, including cross-tenant data viewing, tenant management, and platform configuration changes; its `tenant_id` field is set to 0 to identify platform-level attributes. `sys_admin` has full functional privileges within its tenant scope. `security_officer` has permissions to create and execute security test plans and tasks, manage security assets and test scenarios, view task execution results, and generate security reports. `auditor` has read-only permissions to view system operation logs and various statistical reports. `normal_user` has basic read-only permissions and can view the plans, tasks, and reports assigned to it.

[0035] Let the set of characters be ,Role The direct permission set is ,Role The set of parent roles is Then the role valid permission set Calculated using the following recursive formula: ; in, For character collection Any character in the game, For the role Parent Role Collection Any parent role in This represents a set union operation, with permission entries in triples. Deduplication and merging are performed for unique identifiers.

[0036] The system employs a depth-first search algorithm to recursively traverse the role inheritance graph, obtaining the final set of valid user permissions. Its input consists of a list of all role IDs belonging to the current user and inheritance relationship records from the `role_inheritance` table. The output is a deduplicated and merged set of valid permission entries. To prevent circular dependencies in inheritance relationships, when a tenant administrator creates or modifies a role inheritance relationship, the system models the role inheritance relationship as a directed graph. Before adding a new inheritance relationship, it checks for loops; if a loop exists, the operation is rejected and an error message is returned.

[0037] The specific steps of the permission verification process are as follows: Step 301: Extract the Bearer Token from the Authorization field in the HTTP request header, parse the JWTToken to obtain the payload, and extract the current user ID and tenant ID from it; if the token does not exist, has an invalid format, or the signature verification fails, return an HTTP 401 response directly.

[0038] Step 302: Read the set of valid user permissions from the Redis cache using user_id as the key; if the cache is not found, perform the following processing from the database: query the user_role table to obtain a list of all role IDs to which the user belongs; recursively parse the inheritance chain of each role ID to collect the set of IDs of all related roles; batch query the role_permission table, merge the permission entries of all roles and remove duplicates to obtain the final set of valid permissions; write the final set of valid permissions to the Redis cache, with TTL set to 1800 seconds.

[0039] Step 303: Obtain the URL path and HTTP method of the current HTTP request, and map the HTTP method to the permission type identifier: GET method corresponds to is_view, and POST / PUT / PATCH / DELETE methods correspond to is_manage.

[0040] Step 304: Iterate through each permission entry in the valid permission set and perform a wildcard matching check on the api_path field: If api_path ends with / *, check if the request path starts with that prefix; if it is an exact path, perform an equality comparison. If a matching entry exists and the corresponding permission type identifier is true, the permission verification is considered successful, and the request is forwarded to the subsequent processor; if no entry matches, return an HTTP 403 response, with the response body containing the structured error code ERR_PERMISSION_DENIED and descriptive information.

[0041] In this embodiment, the system caches the calculation result of the final valid set of user permissions in Redis using user_permissions:{user_id} as the key. When a tenant administrator changes the role permission configuration or user role association, the system proactively invalidates the cached permission key for the affected user, ensuring that the permission changes take effect immediately upon the next request, thus avoiding inconsistencies in permission status caused by cache latency.

[0042] Step 4: Perform data statistics and aggregation analysis within the tenant isolation scope.

[0043] The data access layer of the statistics module reuses the global query scope hook described in step 1. All aggregated statistical queries are automatically injected with the WHERE tenant_id = ? filter condition before execution. Taking the calculation of the comprehensive defense score as an example, the system performs aggregate calculations on all completed verification tasks within the current tenant's scope, resulting in the defense score. The calculation formula is: ; in, Specify the total number of verification test cases that have been completed within the statistical period for the tenant scope. This represents the number of attack simulations that were successful (i.e., the defense failed to intercept them). The range of values ​​is A higher value indicates a stronger overall defense capability. Statistical views such as security capability assessment, verification result statistics, security domain asset distribution, ATT&CK tactical and technical coverage ranking statistics, and tag dimension statistical analysis are all executed under the same tenant isolation constraint.

[0044] In this embodiment, the aggregated statistics view accessed by the platform super administrator in the management backend performs statistical queries without additional tenant ID filtering conditions, or performs grouped aggregation on the full data using the GROUP BY tenant_id method, thereby presenting a global view across tenants. The super administrator's dedicated statistics interface route is mounted on an independent route group and protected by configuring exclusive permission entries for the super_admin role through the permission verification process described in step 3. Platform-level aggregated statistical indicators include: total number of tenants, total number of tasks created and completed for each tenant, total number of verification test cases, frequency distribution histogram of the platform's overall protection score, and ranking of resource usage for each tenant.

[0045] In this embodiment, the method further includes the following steps: a system scheduled task performs de-identification and aggregation processing on historical statistical data of all tenants across the platform, calculating the platform-wide average value (as the industry average benchmark) and the 75th percentile value (as the higher industry benchmark) for each statistical dimension. During the aggregation calculation, the raw data is statistically analyzed on a tenant-by-tenant basis, and the aggregation result only outputs the summary value, without containing any identification information that can be associated with a specific tenant. After de-identification processing, the data is written to the benchmark data table industry_benchmark, and the benchmark data is stored in partitions according to statistical dimensions and date. The tenant statistical analysis page provides a display switch that can be controlled by the user. The user can use this switch to decide whether to overlay the industry benchmark data line in the current chart. This preference setting is persistently stored in the user configuration table.

[0046] Step 5: Perform full lifecycle management for tenants.

[0047] The system administrator initiates a new tenant creation operation by calling the tenant creation interface POST / admin / tenants. The request body must include basic information fields such as tenant name, company contact person's name, contact person's email address, contact phone number, and company size. After receiving the request, the system executes the following atomic creation process within a single database transaction: Step 501: Insert a tenant master record into the tenant table, and the database will automatically assign a tenant ID.

[0048] Step 502: Based on the payment level field (optional: basic / professional / enterprise) carried in the request, read the default quota parameters of the corresponding level from the preset quota template table quota_template, and insert the initial quota record of the tenant in the tenant_quota table; the administrator can manually adjust and override individual quota items by carrying the quota_overrides field in the creation request.

[0049] Step 503: Generate an initial administrator account for the tenant in the user table. The username is admin@{tenant_domain} by default. The login password is a 16-character high-strength random password (containing uppercase letters, lowercase letters, numbers and special characters) generated by an encrypted random number generator. The plaintext password is hashed using the bcrypt algorithm and stored in the database. At the same time, the initial administrator account is associated with the sys_admin role.

[0050] Step 504: After the transaction is successfully committed, the system asynchronously triggers an email sending task, sending the login address, initial username, and initial password in plaintext to the contact's email address through an encrypted email channel.

[0051] It should be noted that in the above creation process, the plaintext password only exists briefly in memory during the transaction execution. After being hashed by bcrypt, it is stored in the database. The hash value stored in the database cannot be reversed to restore the plaintext. Once the bcrypt hash is completed, the plaintext password is cleared from memory.

[0052] When a system administrator performs a deregistration operation on a tenant, the system follows the standardized procedure below: Step 505: Query the job table of the target tenant to check if there are any task records with a status of "in execution" or "in queue". If they exist, reject the cancellation operation and return an error response containing a summary of the list of tasks in progress.

[0053] Step 506: Asynchronously trigger the data archiving task to export all data from the target tenant, including plans, tasks, scenarios, objectives, security assets, phishing tests, reports, and related attachments. Structured data is exported in JSONLines format by data table; large-scale datasets can use Parquet columnar storage format. Attachment files are exported in their original format, and the directory structure is preserved in the archive package. After the archiving task is completed, the system calculates the SHA-256 checksum for the generated archive files. ; in, For the complete binary content of the archive file, The output 256-bit hash value is recorded as a hexadecimal string in the archive_metadata table. It also records information such as the archive file path, file size, archive completion time, and operator account ID. The archive file is then uploaded to a long-term archive storage medium.

[0054] Step 507: After the archiving task is successfully completed (the integrity of the archived files is verified through checksum and comparison), the system performs a batch logical deletion operation on all business data tables of the target tenant, updates the deleted_at field of all records where deleted_at is NULL to the current timestamp, updates the status field of the tenant master record to deactivated, and records the deactivation operation time deactivated_at.

[0055] Step 508: The system creates a scheduled physical deletion task record for the target tenant. The planned execution time is the logical deletion completion time plus the retention window period (default 30 days, controlled by the configuration item tenant.physical_delete_delay_days). After the window period expires, the scheduled physical deletion task is triggered, and batch physical DELETE operations are performed on all relevant tables of the target tenant.

[0056] In this embodiment, if a deregistered tenant needs to be restored within the retention window, the system administrator initiates a restoration operation through the tenant restoration interface POST / admin / tenants / {tenant_id} / restore. The system first verifies whether the target tenant's deactivated_at time is within the retention window. If the verification passes, the following processing is performed in the database transaction: the status field of the tenant master record is restored to active, and the deactivated_at field is cleared; batch restoration is performed on records in all business data tables of the target tenant whose deleted_at value is equal to the timestamp of this deregistration operation (deleted_at is reset to NULL), accurately identifying the set of records affected by this deregistration operation and avoiding accidental restoration of historical records that were actively deleted by the user before deregistration; the user account status is restored; and the tenant quota configuration is restored. The entire restoration process is executed atomically within a single database transaction. If an error occurs in any step, a complete rollback is performed, ensuring that either all data is restored successfully, or a complete rollback does not produce an intermediate state of partial restoration.

[0057] On the other hand, this invention also proposes a resource management system for data isolation and permission inheritance in a multi-tenant environment, comprising: The data isolation module is used to declare a non-nullable tenant_id field with indexes in all core business data tables. It automatically injects filtering conditions based on the tenant ID in the JWT Token into all database operations through the GORM global query scope hook. After extracting the tenant ID from the JWT Token on the server side, it injects the data model before the INSERT operation, covering all data access paths such as direct queries, join queries, and subqueries. The quota management module is used to maintain a multi-dimensional tenant quota configuration table, uniformly perform quota verification and interception at the Service layer, support online dynamic adjustment of quota limits for each dimension, periodically calculate the utilization rate of each tenant for each dimension, and push early warning notifications through email and in-site messages when the utilization rate reaches the threshold. The permission verification module is used to maintain core data tables such as roles, permissions, role inheritance relationships, and user role associations. It uses a depth-first search algorithm to recursively parse the role inheritance chain and merge the set of valid permissions. It performs permission verification based on JWT tokens at the API routing layer and caches the permission parsing results and actively invalidates the cache key when permissions change. The statistical analysis module is used to execute various aggregated statistical queries under tenant isolation constraints, provide super administrators with cross-tenant aggregated statistical views without additional tenant filtering conditions, and periodically perform de-identification aggregation processing on the entire platform data to generate industry benchmark data for tenants to overlay and display. The lifecycle management module is used to atomically execute the tenant creation process within a single database transaction, execute a standardized deregistration process that includes precondition verification, data archiving, SHA-256 integrity verification, logical deletion and physical deletion scheduling, and perform complete tenant data recovery operations in an atomic manner within the retention window.

[0058] By way of example, the system proposed in this invention may also include various features and combinations thereof in the method embodiments, which will not be elaborated here.

[0059] Regarding data isolation, this invention moves the injection of tenant ID filtering conditions from the business code layer to the GORM global query scope hook layer. Any data access path must pass through this filtering condition, thus eliminating the path dependency problem of cross-tenant data leakage caused by manually concatenating filtering conditions in the business code. Simultaneously, by extracting the tenant ID from the JWTToken on the server side and injecting it into the data model before the INSERT operation, the possibility of data pollution caused by the client actively passing in or tampering with the tenant_id parameter is eliminated.

[0060] Regarding resource quota management, this invention performs quota verification at a unified entry point in the Service layer and combines this with Redis caching to reduce the frequency of database accesses for quota queries, thus keeping the performance impact of quota verification on normal business processes at a low level. Quota alerts use Redis deduplication to prevent duplicate notifications to the same tenant and the same dimension within a short period, avoiding notification overload that could hinder effective administrator decision-making.

[0061] In terms of permission management, this invention constructs a multi-level chained permission inheritance structure based on a role inheritance table and recursively parses the set of valid permissions for a role using a depth-first search algorithm. This allows the expansion and hierarchical adjustment of permissions to be accomplished by modifying the inheritance relationship data, rather than changing the business code. By caching the user's final set of valid permissions and actively invalidating the cache key when permission configuration changes, a balance is struck between ensuring immediate effect of permission changes and reducing the computational overhead of permission parsing.

[0062] In terms of tenant lifecycle management, this invention breaks down the deregistration process into four stages: precondition verification, data archiving, logical deletion, and physical deletion scheduling. During the archiving stage, SHA-256 checksums are calculated to verify the integrity of the archived files, ensuring that data has been verifiablely archived before physical deletion is executed. The recovery process within the retention window identifies the affected record set by precisely matching the timestamp of the current deregistration operation, avoiding the accidental recovery of historical data that the user had actively deleted before deregistration. The recovery operation is atomically guaranteed by database transactions.

[0063] The embodiments of the present invention have been described above. However, the embodiments are not limited to the specific implementation methods described above. The specific implementation methods described above are merely illustrative and not restrictive. Those skilled in the art can make more equivalent embodiments under the guidance of the present embodiments, and all of them are within the protection scope of the present embodiments.

Claims

1. A resource management method for data isolation and permission inheritance in a multi-tenant environment, characterized in that, Includes the following steps: Declare indexed, non-nullable tenant identifier fields in all core business data tables, automatically inject tenant identifier filtering conditions through the global query scope hook of the ORM framework, and inject the data model from the identity token on the server side before the write operation. At the unified entry point of the service layer, multi-dimensional quota verification is performed, comparing the current usage with the quota limit, and rejecting the request if the limit is exceeded. The role inheritance relationship is recursively traversed by a depth-first search algorithm, and the duplicates are merged to obtain the set of valid user permissions. The request path and permission type are then matched and validated. When a tenant is deregistered, precondition checks, data archiving, integrity checks, logical deletion, and physical deletion scheduling are performed sequentially. Tenant data recovery is performed using atomic transactions within the retention window.

2. The method for resource management of data isolation and permission inheritance in multi-tenant environment according to claim 1, wherein, The automatic injection of tenant identifier filtering conditions through the global query scope hook of the ORM framework includes: Define a global scope function that reads the tenant identifier of the authenticated user from the current request context and appends the tenant filter condition to the current database operation chain; if the authenticated user information does not exist in the context, the filter condition injection is skipped; the global scope function is registered at the session level and bound to the request context; In query scenarios involving multiple table joins, add corresponding tenant identifier filtering conditions independently to each business data table involved in the join.

3. The method for resource management of data isolation and permission inheritance in multi-tenant environment according to claim 1, wherein, The multi-dimensional quota verification performed at the unified entry point of the service layer includes: Extract the current tenant identifier from the request context, and use that tenant identifier as the key to read the quota configuration from the cache; if the cache is not hit, query the quota configuration table and write it to the cache. Query the current actual usage of the corresponding resource dimension, compare the current usage with the quota upper limit ; if , reject the current request and return an error response containing the current usage and the quota upper limit; if , continue to execute the resource creation process ; The multiple resource dimensions include the number of concurrent tasks, the number of verification nodes, the number of security assets, the number of test scenarios, storage space, and interface call rate.

4. The method for resource management of data isolation and permission inheritance in multi-tenant environment according to claim 1, wherein, The process of recursively traversing the role inheritance relationship using a depth-first search algorithm and merging and deduplicating to obtain the set of valid user permissions includes: Extract the current user identifier from the identity token, and read the set of valid user permissions from the cache using the user identifier as the key; if the cache is not hit, query all role identifiers associated with the user, recursively parse the inheritance chain for each role, merge the permission entries of all roles and remove duplicates, and write the result to the cache. Iterate through the set of valid permissions, perform wildcard matching on the interface path field of the permission entries, map the request method to the corresponding permission type identifier, and determine whether there are any matching permission entries with valid permission types. Before adding a new character inheritance relationship, the inheritance relationship is modeled as a directed graph and the loop is checked. If a loop exists, the operation is rejected.

5. The method for resource management with data isolation and permission inheritance in multi-tenant environment according to claim 1, wherein, The process of sequentially executing precondition verification, data archiving, integrity verification, logical deletion, and physical deletion scheduling during tenant deregistration includes: Verify if the target tenant has any task records that are in execution or queued; if so, reject the cancellation operation. Asynchronously perform an archive export of all business data for the target tenant, and calculate the integrity check value of the archive file: ; wherein, is the complete binary content of the archive file, is the hash value of the output; the check value is written to the archive record table together with the archive metadata; After the archive verification is passed, perform batch logical deletion on all business data tables of the target tenant, and create a scheduled physical deletion task with a planned execution time of the logical deletion completion time plus the retention window period.

6. The method for resource management of data isolation and permission inheritance in multi-tenant environment according to claim 3, wherein, Also includes: Periodically iterate through all tenants in an operational state, calculating current usage for each quota dimension for each tenant : ; wherein, is the current actual usage, is the corresponding quota upper limit; When When a preset early warning threshold is reached, an early warning notification containing an early warning dimension, a current usage amount and an upper limit of a quota is sent to a tenant administrator; a deduplication key is set in a cache with a combination of a tenant identifier and a resource dimension as a key, and a same tenant and a same dimension are not sent a repeated early warning notification within a deduplication key validity period; when the usage rate falls below the early warning threshold, the corresponding deduplication key is cleared.

7. The method for resource management with data isolation and permission inheritance in multi-tenant environment according to claim 1, wherein, Also includes: Performing aggregated computation on the completed verification tasks within the current tenant scope under the tenant isolation constraint, computing a defense score : ; wherein, is the total number of completed verification use cases in the specified statistical period, is the number of successful use cases for attack simulation, the value range of is .

8. A resource management system for data isolation and permission inheritance in a multi-tenant environment, comprising: The data isolation module is used to declare indexed, non-nullable tenant identifier fields in all core business data tables. It automatically injects tenant identifier filtering conditions into all database operations through the global query scope hook of the ORM framework, and injects the data model into the server after extracting the tenant identifier from the identity token and before the write operation. The quota management module is used to maintain multi-dimensional tenant quota configurations. It performs quota verification and interception at a unified entry point in the service layer, compares the current usage with the quota limit, and rejects requests when the limit is exceeded. The permission verification module is used to maintain role, permission and role inheritance relationship data. It uses a depth-first search algorithm to recursively parse the role inheritance chain and merge the valid permission set. It performs permission verification based on identity token at the interface routing layer. The lifecycle management module is used to atomically execute the tenant creation process in a single database transaction, as well as the tenant deregistration process, which includes precondition verification, data archiving, integrity verification, logical deletion, and physical deletion scheduling, and to perform complete tenant data recovery in an atomic transaction manner within the retention window.

9. The resource management system for data isolation and permission inheritance in multi-tenant environment according to claim 8, wherein, The permission verification module also includes: The final set of valid user permissions is cached using the user identifier as the key; when the role permission configuration or user role association changes, the cached permission key for the affected user is proactively invalidated. Before adding a new character inheritance relationship, model the inheritance relationship as a directed graph and check whether a cycle is generated. If a cycle exists, reject the operation and return an error message.

10. The resource management system for data isolation and permission inheritance in multi-tenant environment according to claim 8, wherein, The lifecycle management module also includes: In the tenant creation process, within a single database transaction, tenant records are inserted into the tenant master record table in sequence, default quota parameters are read from the quota template according to the payment level and inserted into the quota record, and an initial administrator account is generated and associated with the preset role. In the tenant deregistration process, passing the archive file hash integrity check is used as a prerequisite for executing logical deletion. In the tenant recovery process, the affected set of records is identified by accurately matching the timestamp of this deregistration operation, and batch recovery is performed on the set to ensure full success or full rollback of the recovery operation with atomic transactions.