BI system code security isolation execution method based on k8s container sandbox

By employing the Kubernetes container sandbox approach to securely isolate and execute BI system code, the security risks and resource management issues of the ChatBI system were resolved. This approach enabled efficient and stable code execution and system scalability, reduced the risk of code escape, and improved system robustness and operational flexibility.

CN122333451APending Publication Date: 2026-07-03HANGZHOU GUANSHU INFORMATION TECH CO LTD (CHINA)

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
HANGZHOU GUANSHU INFORMATION TECH CO LTD (CHINA)
Filing Date
2026-04-21
Publication Date
2026-07-03

Smart Images

  • Figure CN122333451A_ABST
    Figure CN122333451A_ABST
Patent Text Reader

Abstract

This invention provides a method for secure code isolation and execution in a BI system based on a K8s container sandbox. It addresses the security isolation and resource management requirements for Python code generated by the AI ​​Agent in the ChatBI system during server-side execution. A multi-layered, defense-in-depth code isolation and execution scheme is proposed, and a three-tiered system architecture consisting of an application service layer, a sandbox management layer, and a container execution layer is designed. Five core processes are defined: code submission and security verification, sandbox Pod creation and code execution, Pod lifecycle management and automatic cleanup, container security isolation, and mode switching and degradation. This achieves full lifecycle security control and efficient resource management for Python code from submission to execution completion.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of secure execution management technology for BI systems, and in particular to a method for secure code isolation and execution of BI systems based on a K8s container sandbox, as well as a system, electronic device, and computer-readable storage medium for secure code isolation and execution of BI systems based on a K8s container sandbox. Background Technology

[0002] The existing code execution scheme of the ChatBI system has multiple technical flaws, failing to meet the requirements of secure, efficient, and stable execution. The specific flaws are as follows:

[0003] High security risks in execution mode: The mainstream approach is to execute code directly in the main process or rely solely on simple static checks for security filtering. There is no effective security isolation mechanism, resulting in a very high risk of code escape and a high risk of server-side security incidents.

[0004] The isolation method has an inherent flaw: some systems use process pool isolation, but the process pool still shares the kernel and file system with the host machine, making it impossible to build a true security boundary and greatly reducing the isolation effect.

[0005] Lack of resource control: The lack of resource quota limits for code execution makes it vulnerable to resource exhaustion attacks, and the resource consumption of a single code execution can affect the operation of the entire service.

[0006] Single point of failure has a wide impact: Without an independent execution environment isolation design, a failure in the execution of a single piece of code will be directly transmitted to the main service, causing global service anomalies, resulting in poor system robustness.

[0007] Lack of flexible fault degradation mechanism: The existing solution does not have the ability to smoothly switch execution modes. When the isolated execution infrastructure fails, the code execution function will fail directly, resulting in low system availability. Summary of the Invention

[0008] To address the technical problems existing in the prior art, the present invention provides the following technical solution:

[0009] On the one hand, a method for securely isolating and executing BI system code based on a Kubernetes container sandbox is provided, including the following steps:

[0010] Code Submission and Security Verification: Receive Python code submitted by users or AI Agents, preprocess and verify the code's validity. If the verification passes, complete the AST (Abstract Syntax Tree) parsing, and then perform multi-dimensional security checks by traversing the AST nodes. If the security verification passes, proceed to the execution phase; if the verification fails, return the corresponding error message.

[0011] Execution mode determination and switching: Determine whether the system sandbox mode is enabled. If not, switch to local secure execution mode and complete code execution through the runtime secure sandbox. If the sandbox mode is enabled, proceed with Pod management and code execution.

[0012] Sandbox Pod Reuse and Creation: Check if there is an available Pod in the current session. If it exists, reuse the existing Pod directly. If it does not exist, start a concurrent and safe Pod creation process. After completing the Pod specification configuration, call the K8s API to create the Pod. After the Pod is ready, complete the session registration and reuse.

[0013] Code transmission and execution: Securely transmit code to the target Pod via archive stream, execute the code in the Pod isolation environment, and stream the standard output and error output of the code execution in real time through the container execution interface, and send the execution results back to the application service layer;

[0014] Pod lifecycle management and resource reclamation: A three-level cleanup mechanism is used to manage the entire lifecycle of Pods. Pod resources are actively released after the session ends, idle Pods that have timed out are automatically cleaned up, and Pods in abnormal states are cleaned up by a fallback scan. At the same time, non-blocking resource reclamation is completed through an asynchronous architecture that separates marking and deletion.

[0015] End-to-end security isolation and control: Through a multi-layered defense-in-depth security isolation mechanism, security control is exercised over the entire code execution process, from code submission, runtime protection, container isolation, session data isolation to global resource control, achieving security protection and risk interception layer by layer.

[0016] On the other hand, a BI system code security isolation execution system based on a Kubernetes container sandbox is provided to implement the above-described method, comprising an application service layer, a sandbox management layer, and a container execution layer that are sequentially connected by communication, wherein:

[0017] The application service layer is used to receive Python code submitted by users or AI Agents, initiate code execution requests, and return the code execution results to users.

[0018] The sandbox management layer includes an AST static security verification module, a Pod lifecycle manager, a K8s API encapsulation module, a concurrency control module, and a dual-mode execution engine switching module. The AST static security verification module verifies the legality, syntax, and security risks of submitted Python code. The Pod lifecycle manager manages the creation, reuse, deletion, and full lifecycle of Pods. The K8s API encapsulation module interacts with the K8s cluster in the container execution layer. The concurrency control module manages the global number of Pods and allocates resource quotas. The dual-mode execution engine switching module enables smooth switching between K8s sandbox mode and local secure execution mode.

[0019] The container execution layer includes a K8s API Server and multiple independent session-level Pod sandbox containers. Each Pod sandbox container is an independent code execution environment, completely isolated from the main service, and is used to receive instructions from the sandbox management layer to complete code execution and return results.

[0020] On the other hand, an electronic device is provided, comprising: a processor; and a memory storing computer-readable instructions, which, when executed by the processor, implement the method described above.

[0021] On the other hand, a computer-readable storage medium is provided, wherein at least one instruction is stored therein, the at least one instruction being loaded and executed by a processor to implement the above method.

[0022] The beneficial effects of the technical solutions provided in the embodiments of the present invention include at least the following:

[0023] This invention achieves a precise solution, ensuring the security of ChatBI system code execution while also considering execution efficiency, resource utilization, and system scalability, as detailed below:

[0024] Completely solves the problems of code escape and security isolation: Through a multi-layered, defense-in-depth security isolation mechanism, it achieves full-dimensional isolation from static to dynamic, from code to environment, and from single session to global. Compared with existing single static checks or process pool isolation solutions, it builds a true security boundary, significantly reduces the risk of code escape, and ensures the security of server-side code execution from the source.

[0025] Achieve fine-grained management and isolation of resources: Through resource quota configuration of K8s Pods, global semaphore concurrency control, and automatic cleanup of Pod lifecycle, precise management and control of code execution resources can be achieved, effectively preventing resource exhaustion attacks. The resource consumption of a single Pod will not affect the main service and other Pods, solving the problem of resource isolation in existing technologies.

[0026] Avoid the global impact of a single point of failure: Deploy the code execution environment in an independent K8s Pod container, completely isolated from the main service. Failures of a single Pod and exceptions in code execution are confined within the container and will not propagate to the application service layer and sandbox management layer. This solves the defect of existing technologies where a single point of failure affects the whole system and improves system robustness.

[0027] Improve resource utilization and execution efficiency: Adopt an on-demand delayed Pod pooling management strategy to avoid the waste of idle resources caused by pre-creating Pods at system startup. At the same time, reduce resource overhead and result return latency by reusing Pods at session level and outputting code execution results in real time, thus balancing resource utilization and code execution efficiency.

[0028] Ensuring high availability and operational flexibility of the system: A smooth degradation switching mechanism between sandbox mode and local mode is designed. When the sandbox infrastructure fails, the system can still provide code execution services through the local secure execution mode, which solves the problem of fault-free degradation mechanism in existing technologies. At the same time, mode switching does not require system restart, and configurable operation improves operational flexibility.

[0029] Achieve full lifecycle control and traceability for code execution: From security verification of code submission to Pod creation, code execution, and Pod resource reclamation, the system achieves precise control over every step. All operations are recorded in terms of status and resource counts, solving the problem of ineffective control over the code execution process in existing technologies, and facilitating system operation and maintenance and troubleshooting. Attached Figure Description

[0030] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0031] Figure 1 This is a system architecture diagram provided in an embodiment of the present invention;

[0032] Figure 2 This is a flowchart of code submission and security verification provided by an embodiment of the present invention;

[0033] Figure 3 This is a flowchart of sandbox Pod creation and code execution provided by an embodiment of the present invention;

[0034] Figure 4 This is a flowchart of a container security isolation mechanism provided in an embodiment of the present invention;

[0035] Figure 5This is a flowchart of a mode switching and degradation mechanism provided in an embodiment of the present invention. Detailed Implementation

[0036] The technical solution of the present invention will now be described with reference to the accompanying drawings.

[0037] In embodiments of the present invention, words such as "exemplarily," "for example," etc., are used to indicate that something is an example, illustration, or description. Any embodiment or design described as "exemplary" in the present invention should not be construed as being more preferred or advantageous than other embodiments or designs. Specifically, the use of the word "exemplary" is intended to present the concept in a concrete manner. Furthermore, in embodiments of the present invention, the meaning expressed by "and / or" can be both, or either one.

[0038] In the embodiments of this invention, the terms "image" and "picture" may sometimes be used interchangeably. It should be noted that, without emphasizing the distinction between them, they convey the same meaning. Similarly, the terms "of," "corresponding (relevant)," and "corresponding" may sometimes be used interchangeably. It should be noted that, without emphasizing the distinction between them, they convey the same meaning.

[0039] In this embodiment of the invention, sometimes a subscript such as W1 may be mistakenly written as a non-subscript form such as W1. When the difference is not emphasized, the meaning they express is the same.

[0040] To make the technical problems, technical solutions and advantages of the present invention clearer, a detailed description will be given below in conjunction with the accompanying drawings and specific embodiments.

[0041] This invention proposes a multi-layered, defense-in-depth code isolation and execution scheme, and designs a three-level system architecture consisting of an application service layer, a sandbox management layer, and a container execution layer. It also defines five core processes: code submission and security verification, sandbox Pod creation and code execution, Pod lifecycle management and automatic cleanup, container security isolation, and mode switching and degradation, so as to achieve full lifecycle security control and efficient resource management of Python code from submission to execution completion.

[0042] like Figure 1 As shown, the system architecture of this invention is divided into three core layers. Each layer works together to achieve full-process control of isolated code execution. The responsibilities and linkage logic of each layer are as follows:

[0043] Application Service Layer: As the system entry point, it receives Python code submitted by users or AI Agents, initiates code execution requests, interacts with users, and returns code execution results. This layer interfaces with the sandbox management layer to complete the security verification of the code and issue execution instructions.

[0044] Sandbox Management Layer: This is the core control layer, responsible for code security verification, dynamic creation and lifecycle management of Pod containers, resource quota control, and execution mode switching (if executing in local rollback mode, the local executor is activated; if executing in sandbox mode, the Pod lifecycle manager is activated, which can perform the following functions: creating / deleting Pods, encapsulating Pods and distributing them to the container execution layer, or performing signal concurrency control, session management and registration, and background expiration cleanup). It connects upwards to the application service layer to receive code and instructions, and downwards to call the K8s API to interact with the container execution layer, achieving precise control over the container execution environment.

[0045] Container execution layer: This is the actual code execution layer, consisting of dynamically created independent Kubernetes Pod containers. Each Pod is an independent code execution sandbox (e.g., including N sandboxes: Pod-A (session 1), Pod-B (session 2)...Pod-N (session N), which can be called according to actual execution needs), completely isolated from the main service; it receives instructions from the sandbox management layer, completes code reception, execution, and result feedback, and strictly follows the resource quota and security configuration requirements of the sandbox management layer.

[0046] The system employs a multi-layered defense-in-depth mechanism to achieve code isolation and execution between the application service layer and the sandbox management layer. The specific defense mechanism is as follows:

[0047] The first layer uses static analysis of the AST (Abstract Syntax Tree) to intercept dangerous operations during the code submission phase (such as prohibiting the import of non-whitelisted modules, blocking dangerous built-in function calls, and intercepting reflection attribute access).

[0048] The second layer completely isolates the code execution environment from the main service by dynamically creating independent K8s Pod containers, uses container security context to prohibit privilege escalation and remove dangerous network capabilities, and prevents resource exhaustion attacks through resource quotas.

[0049] The third layer achieves efficient reuse and automatic reclamation of sandbox resources through session-level Pod lifecycle management (concurrency control, automatic expiration, and asynchronous cleanup). This solution ensures code execution security while also considering execution efficiency and system scalability.

[0050] The following section, based on the above architecture, details the implementation process of the BI system code security isolation execution method based on K8s container sandbox in this application:

[0051] 1. Code Submission and Security Verification Process

[0052] like Figure 2As shown, Python code submitted by users / AI Agents must undergo a three-level verification process: validity check, syntax check, and security check. Only code that passes all checks can proceed to the execution stage; otherwise, a corresponding error will be returned. The specific process and verification rules are as follows:

[0053] (1). Pre-verification: First, the code is preprocessed to check the legality of the code format. If it is not legal, an error is returned directly; if it is legal, it enters the AST (Abstract Syntax Tree) syntax parsing. If the parsing fails, a syntax error is returned. If the parsing is successful, the AST node traversal security check is entered.

[0054] (2). AST node traversal security check: This is the core security verification step, which executes strict interception rules from four dimensions. If a dangerous operation is detected in any dimension, the code will be directly intercepted. Examples of specific verification dimensions, strategies and interception rules are shown in Table 1 below:

[0055] Verification Dimensions Verification strategy Interception Example Import whitelist for modules Only predefined sets of security modules are allowed to be imported. Dangerous modules such as system-level modules and subprocess modules are intercepted. Dangerous built-in functions Block the calling behavior of many types of dangerous built-in functions. Functions related to file operations, dynamic execution, and dynamic imports are intercepted. Accessing Reflection Properties Intercepting magic attribute access that can be used to escape from the sandbox Access to attributes such as class inheritance chains, global variables, and code objects is intercepted. Relative import Disable relative import statements in all code Preventing the introduction of unsafe custom modules via relative paths

[0056] Table 1

[0057] The module in the whitelist continues to check for dangerous functions; the code module that calls dangerous functions is blocked and "disables dangerous built-in functions" is blocked. If it is safe, a reflection attribute check is performed; if "access to dangerous attributes" is detected, it is blocked: the sandbox escape related attributes are prohibited. If it is safe, it is allowed to proceed and execution is performed.

[0058] (3) Process exit: After all security checks pass, the code enters the execution phase; if any check fails, the system directly intercepts the code and returns the corresponding security error information.

[0059] 2. Sandbox Pod Creation and Code Execution Process

[0060] like Figure 3 As shown, after the code security verification is passed, the system adopts a lazy initialization strategy to manage sandbox Pods, balancing resource utilization and execution efficiency. At the same time, it avoids resource abuse through multiple control mechanisms. The specific process is as follows:

[0061] Mode determination: First, determine whether the sandbox mode is enabled. If it is not enabled, fall back to the local secure execution mode; if it is enabled, enter the Pod management process.

[0062] Pod reuse judgment: Check if there is an available Pod in the current session. If there is, reuse the existing Pod and enter the code transmission and execution stage; otherwise, enter the Pod creation process.

[0063] Concurrent resource control: Initiate a concurrent and safe Pod creation process. First, determine whether the global maximum Pod limit has been reached. If it has, block and wait for resources to be released. If it has not been reached, obtain the corresponding resource quota and enter the Pod specification building stage.

[0064] Pod specification building: Complete the Pod specification configuration from the following aspects, including resource quota configuration (CPU, memory, etc.), session-level storage isolation configuration, container image and security context configuration (disabling privilege escalation, removing dangerous network capabilities, etc.).

[0065] Pod creation and readiness detection: The system calls the Kubernetes API to create a Pod and then waits for the Pod to be ready. If the Pod creation fails or times out, the system releases the requested resources and returns an error. If the Pod is ready, the system completes session registration to achieve session-level reuse of the Pod.

[0066] Code execution and result return: The code is securely transmitted to the Pod via an archive stream (including path traversal protection), the code is executed within the Pod, and the standard output and error output are read in real time through the container execution interface without blocking and waiting for the execution to complete. Finally, the execution result is sent back to the application service layer.

[0067] Key technical features: This process incorporates four key technologies to ensure the security and efficiency of Pod creation and code execution: delayed creation + double-checked locking (preventing the concurrent creation of multiple Pods in the same session), semaphore concurrency control (allocating quotas evenly among worker processes to control the total number of global Pods, and blocking and waiting when the limit is reached), secure file transfer (code is transferred to Pods via archive streams to avoid relying on shared file systems, and the transfer process includes path traversal protection), and real-time streaming output (reading standard output and error output in real time through the container execution interface without blocking and waiting for execution to complete).

[0068] 3. Pod lifecycle management and automatic cleanup process

[0069] To prevent cluster resource exhaustion caused by Pod leaks, the system is designed with a full-scenario Pod lifecycle management mechanism. The core of this mechanism is a three-level cleanup mechanism and an asynchronous cleanup architecture, coupled with resource count consistency and graceful shutdown strategies. The specific design is as follows:

[0070] A three-tiered cleanup mechanism: Pods are comprehensively reclaimed based on priority, with each tier providing a safety net to ensure no Pod is missed, covering both normal and abnormal scenarios.

[0071] Level 1 cleanup: Normal release; the system actively releases the Pod resources of the current session after the session ends.

[0072] Secondary cleanup: When the TTL expires, the background periodically checks the Pod status and automatically cleans up idle Pods that have exceeded their lifespan.

[0073] Level 3 cleanup: anomaly fallback. The system continuously scans the cluster for Pods in an abnormal state and immediately performs cleanup operations upon discovery.

[0074] Non-blocking asynchronous cleanup: Adopting an architecture that separates marking deletion and actual deletion, the Pods that need to be cleaned up are first marked. This operation is completed immediately without blocking business requests. The actual Pod deletion operation is handled asynchronously in the background, balancing business smoothness and resource reclamation efficiency.

[0075] Resource count consistency: After a Pod is deleted, the system immediately releases the corresponding resource quota and updates the global Pod count to ensure the accuracy of resource quota statistics and provide a reliable basis for resource judgment in subsequent Pod creation.

[0076] Graceful shutdown strategy: When the system receives a shutdown signal, it first stops the background Pod cleanup loop, and then deletes all remaining Pods in the cluster in a concurrent manner to ensure that resources are reclaimed in an orderly manner and no Pods remain during the shutdown process.

[0077] Core design of the cleanup strategy:

[0078] Three-level cleanup mechanism: Normal release (active release upon session end) → TTL expiration (automatic background detection) → Abnormal fallback (abnormal Pod scanning and cleanup);

[0079] Non-blocking deletion: The marking for deletion is separated from the actual deletion. The marking operation is completed immediately without blocking the business, while the actual deletion is processed asynchronously in the background.

[0080] Resource count consistency: The corresponding resource quota is released immediately after a Pod is deleted to ensure accurate global counts;

[0081] Graceful shutdown: Upon receiving a shutdown signal, first stop the cleanup loop, then concurrently delete all remaining Pods.

[0082] 4. Container safety isolation mechanism process

[0083] like Figure 4 As shown, this invention constructs a multi-layered, defense-in-depth container security isolation mechanism, setting up five independent security barriers from code submission to execution completion. Even if one layer is bypassed, subsequent layers can still achieve effective protection. The following five-layer isolation mechanism is adopted from shallow to deep and from static to dynamic:

[0084] First layer: Static AST analysis: This involves traversing and checking the AST nodes during the code submission phase to intercept dangerous code from four aspects: module import, function call, attribute access, and import method, thus preventing unsafe code from entering the execution phase at the source.

[0085] The second layer: runtime security sandbox: provides security protection for the local execution layer, rewrites the Python built-in namespace, retains only safe built-in functions and attributes, and designs a controlled import mechanism to perform secondary security checks at runtime.

[0086] The third layer: K8s container isolation: This is the core isolation layer. It achieves complete isolation between the code execution environment and the main service through K8s Pods, configures security contexts (disallows privilege escalation, removes dangerous network capabilities), sets resource limits such as CPU / memory, and formulates a rapid failure strategy that does not restart if the Pod fails.

[0087] Layer 4: Session-level data isolation: Each Pod is allocated an independent storage path based on its session ID. Code transmission uses a secure archive stream method. Path traversal attack detection is added during the decompression stage to ensure complete data isolation between different users / sessions and eliminate the risk of cross-access.

[0088] Fifth layer: Global resource management: Implement resource rate limiting at the global level, control the number of concurrent Pods through semaphores, set automatic expiration of Pod TTL, configure code execution timeout control, and implement automatic cleanup of abnormal Pods to prevent a single session / code from consuming too many cluster resources.

[0089] 5. Mode switching and downgrade mechanism process

[0090] like Figure 5 As shown, the system supports smooth switching between K8s sandbox mode and local secure execution mode. Flexible switching between the two execution engines is achieved through configuration control, creating fault degradation capabilities and ensuring that the system can still provide code execution services normally when the sandbox infrastructure fails. The specific process and design are as follows:

[0091] 1. Mode Triggering Logic: Sandbox mode is the default preferred mode. When the sandbox management layer detects that the sandbox infrastructure such as K8s cluster and Pod creation is available, the system automatically uses sandbox mode to execute code. When the sandbox infrastructure is detected to be unavailable (such as K8s API call failure, continuous Pod creation timeout, etc.), the system can automatically or manually switch to local secure execution mode through configuration.

[0092] 2. Local secure execution mode guarantee: The local mode is not a direct execution without protection, but provides basic security through a second-layer runtime security sandbox mechanism. It rewrites the built-in namespace and adopts controlled imports to ensure the availability of code execution while minimizing security risks.

[0093] 3. Smooth switching feature: Switching between the two modes does not require restarting the system. The switch is instantaneous after the configuration takes effect, and the code execution requests are unaffected. This not only improves the system's operational flexibility but also ensures the overall availability of the system.

[0094] Therefore, this invention incorporates the following innovative points to achieve a breakthrough improvement over existing technologies. Each innovative point is deeply integrated with the aforementioned architecture and process, becoming the core support for the implementation of the solution:

[0095] 1. Multi-layered, defense-in-depth code security isolation architecture: This architecture comprises five layers: AST static analysis → runtime security sandbox → Kubernetes container isolation → session-level data isolation → global resource management. This achieves full lifecycle security control, with multiple layers of barriers providing comprehensive protection, significantly enhancing security capabilities from code submission to execution completion. Compared to existing solutions that rely solely on single static checks or simple process isolation, each layer of this invention is an independent security barrier. Even if one layer is bypassed, subsequent layers can still provide effective protection, significantly improving the security of the ChatBI system's code execution environment.

[0096] 2. Kubernetes Pod Dynamic Pooling Management Based on Delayed Initialization and Semaphores: Delayed Pod creation on demand + double-checked locking + semaphore concurrency control avoids wasting idle resources, prevents concurrent Pod creation within the same session, precisely controls the total number of global Pods, and gracefully limits rates under high concurrency; Pods are created only when the first code execution request arrives, avoiding wasting idle resources; double-checked locking prevents the concurrent creation of multiple Pods within the same session; semaphores distribute quotas evenly among worker processes, precisely controlling the maximum number of Pods in the cluster, achieving graceful rate limiting rather than hard rejection in high-concurrency scenarios;

[0097] 3. Three-tiered automatic Pod lifecycle management: A three-tiered cleanup system—normal release, TTL expiration, and fallback for exceptions—combined with an asynchronous cleanup architecture that separates marking and deletion, ensures reliable Pod resource reclamation in all scenarios and prevents resource exhaustion. The operation of marking a Pod for deletion is separated from the actual deletion operation; the marking operation is completed immediately without blocking business requests, while the actual deletion is handled asynchronously in the background. Combined with a concurrent batch deletion strategy during graceful shutdown, this ensures reliable resource reclamation under various abnormal scenarios, preventing cluster resource exhaustion caused by Pod leaks.

[0098] 4. Secure Code Transfer and Path Traversal Protection Based on Archive Streams: Code transfer via archive streams avoids the security risks of shared file systems. Path traversal detection is added during the decompression stage, combined with session-level subpath mounting, to achieve complete data isolation. The scheme of transferring code files between the main service and Kubernetes Pods via archive streams avoids the complexity and security risks introduced by relying on shared file systems. Simultaneously, path traversal attack detection is added during the decompression stage (verifying that file paths do not escape the target directory), and combined with session-level subpath mounting, complete data isolation between different user sessions is achieved.

[0099] 5. Smooth Degradation Switching Mechanism between Sandbox and Local Execution: A configurable dual-mode execution engine switches to local secure execution mode in case of sandbox failure, ensuring code execution capability and improving system availability and operational flexibility. Through a configuration-controlled dual-mode execution engine (K8s sandbox mode / local secure execution mode), the system can switch to local execution mode when the sandbox infrastructure is unavailable. Local mode provides basic security through a secure sandbox mechanism (restricted built-in namespaces and controlled import functions). This design ensures the system maintains code execution capability even in the event of sandbox failure, improving the overall availability and operational flexibility of the ChatBI system.

[0100] The above description is merely a specific embodiment of the present invention, but the scope of protection of the present invention is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the technical scope disclosed in the present invention should be included within the scope of protection of the present invention. Therefore, the scope of protection of the present invention should be determined by the scope of the claims.

Claims

1. A K8s container sandbox-based BI system code security isolation execution method, characterized in that, Includes the following steps: Code Submission and Security Verification: Receive Python code submitted by users or AI Agents, preprocess and verify the code's validity. If the verification passes, complete the AST (Abstract Syntax Tree) parsing, and then perform multi-dimensional security checks by traversing the AST nodes. If the security verification passes, proceed to the execution phase; if the verification fails, return the corresponding error message. Execution mode judgment and switching: Determine whether the system sandbox mode is enabled. If not, switch to the local secure execution mode and complete code execution through the runtime secure sandbox. If sandbox mode is enabled, the Pod management and code execution process will begin. Sandbox Pod Reuse and Creation: Check if there is an available Pod in the current session. If it exists, reuse the existing Pod directly. If it does not exist, start a concurrent and safe Pod creation process. After completing the Pod specification configuration, call the K8s API to create the Pod. After the Pod is ready, complete the session registration and reuse. Code transmission and execution: Securely transmit code to the target Pod via archive stream, execute the code in the Pod isolation environment, and stream the standard output and error output of the code execution in real time through the container execution interface, and send the execution results back to the application service layer; Pod lifecycle management and resource reclamation: A three-level cleanup mechanism is used to manage the entire lifecycle of Pods. Pod resources are actively released after the session ends, idle Pods that have timed out are automatically cleaned up, and Pods in abnormal states are cleaned up by a fallback scan. At the same time, non-blocking resource reclamation is completed through an asynchronous architecture that separates marking and deletion. End-to-end security isolation and control: Through a multi-layered defense-in-depth security isolation mechanism, security control is exercised over the entire code execution process, from code submission, runtime protection, container isolation, session data isolation to global resource control, achieving security protection and risk interception layer by layer.

2. The K8s container sandbox-based BI system code security isolation execution method according to claim 1, characterized in that, In step S1, the AST node traversal security check includes four verification dimensions: module import whitelist verification, dangerous built-in function interception, reflection attribute access interception, and relative import statement prohibition. The module import whitelist verification only allows the import of a predefined set of secure modules; dangerous built-in functions are blocked from file operations and dynamic execution of class function calls; reflection attribute access is blocked from magic attribute access related to sandbox escape; and relative import statements are prohibited from blocking all relative import behaviors in the code.

3. The K8s container sandbox-based BI system code security isolation execution method according to claim 1, characterized in that, In step S3, Pod creation adopts an on-demand delayed creation strategy, creating Pods only when the first code execution request arrives, while preventing the concurrent creation of multiple Pods in the same session through a double-checked locking mode; Pod specification configuration includes resource quota configuration, session-level storage isolation configuration, container image configuration, and security context configuration. The security context configuration is used to disable container privilege escalation and remove dangerous network capabilities, while the resource quota configuration is used to limit the CPU and memory resource usage of the Pod.

4. The method for secure code isolation and execution in a BI system based on a K8s container sandbox according to claim 1, characterized in that, In step S3, the concurrent and safe Pod creation process uses semaphores to achieve concurrent control of the global number of Pods. The global Pod total limit is evenly allocated according to the number of worker processes. When the number of Pods reaches the limit, the request is blocked and the resource is released. The Pod creation operation is then executed after the resource quota is obtained.

5. The method for secure code isolation and execution in a BI system based on a K8s container sandbox according to claim 1, characterized in that, In step S5, the three-level cleanup mechanism is as follows: Level 1 is normal release, which actively releases the Pod resources of the current session after the session ends; Level 2 is TTL expiration cleanup, which periodically checks the Pod status in the background and automatically cleans up idle Pods that have exceeded the preset lifespan time; Level 3 is abnormal fallback cleanup, which continuously scans for Pods in abnormal states in the cluster and immediately performs cleanup operations upon discovery; The asynchronous architecture of mark-delete separation first performs a mark operation on the Pods to be cleaned up, and the mark operation is completed immediately without blocking business requests, while the actual Pod deletion operation is executed asynchronously in the background.

6. The method for secure code isolation and execution in a BI system based on a K8s container sandbox according to claim 1, characterized in that, In step S6, the specific implementation of the multi-layered defense-in-depth security isolation mechanism is as follows: The first layer is AST static analysis, which intercepts dangerous operations during the code submission stage; the second layer is runtime security sandbox, which rewrites the Python built-in namespace, retaining only secure built-in functions and attributes, and performs secondary security verification during code runtime through a controlled import mechanism; the third layer is K8s container isolation, which achieves complete isolation between the code execution environment and the main service through independent Pods, and configures resource quotas and security protection policies; the fourth layer is session-level data isolation, which divides each Pod into an independent storage path according to the session ID, adds path traversal attack detection during code transmission, and achieves complete data isolation between different sessions; the fifth layer is global resource management, which controls the number of concurrent Pods through semaphores, sets automatic expiration of Pod TTL, and configures code execution timeout control to achieve global rate limiting and management of cluster resources.

7. The method for secure code isolation and execution in a BI system based on a K8s container sandbox according to claim 1, characterized in that, In step S2, the switching between local secure execution mode and K8s sandbox mode does not require a system restart. The smooth switching can be completed automatically or manually through configuration. When the sandbox infrastructure is found to be unavailable due to K8s API call failure or continuous Pod creation timeout, the system automatically switches to local secure execution mode. Local secure execution mode provides runtime security protection by rewriting Python's built-in namespace and controlled import mechanism.

8. The method for secure code isolation and execution in a BI system based on a K8s container sandbox according to claim 1, characterized in that, In step S4, during the process of transmitting the code to the Pod via the archive stream, it does not rely on the shared file system. Path traversal attack detection is added during the code decompression stage to verify that the file path does not escape the target directory. At the same time, combined with session-level sub-path mounting, complete data isolation between different user sessions is achieved.

9. The method for secure code isolation and execution in a BI system based on a K8s container sandbox according to claim 1, characterized in that, Step S5 also includes a graceful shutdown strategy. When the system receives a shutdown signal, it first stops the background Pod cleanup loop, then deletes all remaining Pods in the cluster in a concurrent manner. After the Pods are deleted, the corresponding resource quota is released immediately, and the global Pod count is updated to ensure the consistency of the resource count.

10. A BI system code security isolation execution system based on Kubernetes container sandbox, used to implement the method described in any one of claims 1-9, characterized in that, This includes the application service layer, sandbox management layer, and container execution layer, which are connected sequentially. The application service layer is used to receive Python code submitted by users or AI Agents, initiate code execution requests, and return the code execution results to users. The sandbox management layer includes an AST static security verification module, a Pod lifecycle manager, a K8s API encapsulation module, a concurrency control module, and a dual-mode execution engine switching module. The AST static security verification module verifies the legality, syntax, and security risks of submitted Python code. The Pod lifecycle manager manages the creation, reuse, deletion, and full lifecycle of Pods. The K8s API encapsulation module interacts with the K8s cluster in the container execution layer. The concurrency control module manages the global number of Pods and allocates resource quotas. The dual-mode execution engine switching module enables smooth switching between K8s sandbox mode and local secure execution mode. The container execution layer includes a K8s API Server and multiple independent session-level Pod sandbox containers. Each Pod sandbox container is an independent code execution environment, completely isolated from the main service, and is used to receive instructions from the sandbox management layer to complete code execution and return results.