Spaces:
Paused
Paused
Update modules/secure_memory_loader.py
Browse files- modules/secure_memory_loader.py +13 -47
modules/secure_memory_loader.py
CHANGED
@@ -1,50 +1,16 @@
|
|
1 |
import importlib.util
|
2 |
-
import
|
3 |
-
import os
|
4 |
-
import tempfile
|
5 |
-
import atexit
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
import base64
|
13 |
-
class SecureMemorySession:
|
14 |
-
def __init__(self, encryption_key: bytes = None):
|
15 |
-
self.key = encryption_key or Fernet.generate_key()
|
16 |
-
self.fernet = Fernet(self.key)
|
17 |
-
self.sessions = {}
|
18 |
-
def encrypt_vector(self, user_id: int, vector: np.ndarray) -> str:
|
19 |
-
vector_bytes = vector.tobytes()
|
20 |
-
encrypted = self.fernet.encrypt(vector_bytes)
|
21 |
-
encoded = base64.b64encode(encrypted).decode('utf-8')
|
22 |
-
self.sessions.setdefault(user_id, []).append(encoded)
|
23 |
-
return encoded
|
24 |
-
def decrypt_vectors(self, user_id: int) -> list:
|
25 |
-
if user_id not in self.sessions:
|
26 |
-
return []
|
27 |
-
decrypted_vectors = []
|
28 |
-
for encoded in self.sessions[user_id]:
|
29 |
-
encrypted = base64.b64decode(encoded)
|
30 |
-
decrypted = self.fernet.decrypt(encrypted)
|
31 |
-
vector = np.frombuffer(decrypted, dtype=np.int64)
|
32 |
-
decrypted_vectors.append(vector)
|
33 |
-
return decrypted_vectors
|
34 |
-
def get_encryption_key(self) -> bytes:
|
35 |
-
return self.key
|
36 |
-
"""
|
37 |
-
|
38 |
-
def create_secure_memory_module():
|
39 |
-
# Create a temporary file that acts as our secure_memory module
|
40 |
-
with tempfile.NamedTemporaryFile("w+", suffix="_secure_memory.py", delete=False) as tmp:
|
41 |
-
tmp.write(memory_isolation_code)
|
42 |
-
tmp_path = tmp.name
|
43 |
-
|
44 |
-
# Insert the temp file directory into sys.path so it can be imported
|
45 |
-
import sys
|
46 |
-
module_dir = os.path.dirname(tmp_path)
|
47 |
-
if module_dir not in sys.path:
|
48 |
-
sys.path.insert(0, module_dir)
|
49 |
-
|
50 |
-
return os.path.basename(tmp_path).replace(".py", "")
|
|
|
1 |
import importlib.util
|
2 |
+
from pathlib import Path
|
|
|
|
|
|
|
3 |
|
4 |
+
def load_secure_memory_module(temp_path="/mnt/data/secure_memory.py"):
|
5 |
+
"""
|
6 |
+
Dynamically loads secure_memory.py from a temporary path.
|
7 |
+
Returns the module object.
|
8 |
+
"""
|
9 |
+
secure_memory = Path(temp_path)
|
10 |
+
if not secure_memory.exists():
|
11 |
+
raise FileNotFoundError(f"{temp_path} not found.")
|
12 |
|
13 |
+
spec = importlib.util.spec_from_file_location("secure_memory", temp_path)
|
14 |
+
module = importlib.util.module_from_spec(spec)
|
15 |
+
spec.loader.exec_module(module)
|
16 |
+
return module
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|