forked from Ikalus1988/MisakaNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken_manager.py
More file actions
249 lines (212 loc) · 8.29 KB
/
Copy pathtoken_manager.py
File metadata and controls
249 lines (212 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""
Token Manager - Master token generation and keyring storage
"""
import secrets
import hashlib
from datetime import datetime, timedelta
from typing import Optional
import json
import os
import warnings
class TokenManager:
"""
Manages Master mode tokens with keyring storage.
Token TTL: 24 hours (configurable)
"""
def __init__(self, keyring_service: str = "hermes-hub",
ttl_hours: int = 24):
self.keyring_service = keyring_service
self.ttl_hours = ttl_hours
self._tokens: dict[str, dict] = {}
self._keyring_available = False
try:
import keyring
self._keyring_available = True
except ImportError:
pass
self._load_tokens()
def _load_tokens(self):
"""Load tokens — try keyring first, fall back to plaintext file with restricted permissions."""
if self._keyring_available:
import keyring
try:
stored = keyring.get_password(self.keyring_service, "master_tokens")
if stored:
import ast
self._tokens = json.loads(stored)
self._cleanup_expired()
return
except Exception:
pass
# Fallback: plaintext JSON file with owner-only permissions (chmod 600)
# WARNING: This is NOT encrypted. Do NOT rely on this for high-security environments.
# On shared hosts or compromised machines, any process running as this user can read the file.
warnings.warn(
"Master token fallback: storing tokens as plaintext JSON in ~/.hermes-tokens. "
"This is NOT encrypted. For production, ensure keyring is available or use a secrets manager."
)
token_path = os.path.expanduser("~/.hermes-tokens")
try:
with open(token_path, 'r') as f:
self._tokens = json.load(f)
self._cleanup_expired()
self._restrict_plaintext_file(token_path)
except FileNotFoundError:
self._tokens = {}
def _restrict_plaintext_file(self, token_path: str) -> bool:
"""Best-effort owner-only permissions for the plaintext fallback file.
Returns True when POSIX mode bits confirm 0600. On Windows, Python's
chmod/stat mode bits do not express owner-only ACLs, so callers must
treat this fallback as weaker than keyring-backed storage.
"""
if os.name == "nt":
warnings.warn(
"Master token fallback on Windows cannot guarantee POSIX 0600 "
"owner-only permissions. Use keyring or a secrets manager for production."
)
return False
os.chmod(token_path, 0o600)
return (os.stat(token_path).st_mode & 0o777) == 0o600
def _save_tokens(self):
"""Save tokens — use keyring if available, else plaintext JSON fallback (NOT encrypted)"""
if self._keyring_available:
import keyring
try:
keyring.set_password(self.keyring_service, "master_tokens",
json.dumps(self._tokens, default=str))
return
except Exception:
pass
# Fallback: plaintext JSON with owner-only permissions (NOT encrypted)
token_path = os.path.expanduser("~/.hermes-tokens")
os.makedirs(os.path.dirname(token_path), exist_ok=True)
with open(token_path, 'w') as f:
json.dump(self._tokens, f, default=str)
self._restrict_plaintext_file(token_path)
def _cleanup_expired(self):
"""Remove expired tokens"""
now = datetime.now()
expired = [
token for token, info in self._tokens.items()
if datetime.fromisoformat(info["expires_at"]) < now
]
for token in expired:
del self._tokens[token]
if expired:
self._save_tokens()
def generate_token(self, secret: str) -> Optional[str]:
"""
Generate a new Master token.
Args:
secret: The shared secret (e.g., "贾恒龙")
Returns:
Token string if secret is valid, None otherwise
"""
# Validate secret from config
config_path = os.path.join(os.path.dirname(__file__), '..', 'config.yaml')
try:
import yaml
with open(config_path, 'r') as f:
cfg = yaml.safe_load(f)
expected_secret = cfg.get("master", {}).get("shared_secret", "")
except Exception:
expected_secret = ""
if not expected_secret:
raise ValueError("master.shared_secret not configured in config.yaml")
if secret != expected_secret:
return None
token = secrets.token_urlsafe(32)
expires_at = datetime.now() + timedelta(hours=self.ttl_hours)
self._tokens[token] = {
"created_at": datetime.now().isoformat(),
"expires_at": expires_at.isoformat(),
"secret_hash": hashlib.sha256(secret.encode()).hexdigest()
}
self._save_tokens()
print(f"Master token generated, expires at {expires_at}")
return token
def validate_token(self, token: str) -> bool:
"""
Validate a Master token.
Args:
token: Token to validate
Returns:
True if valid and not expired
"""
self._cleanup_expired()
if token not in self._tokens:
return False
expires_at = datetime.fromisoformat(self._tokens[token]["expires_at"])
return expires_at > datetime.now()
def revoke_token(self, token: str) -> bool:
"""Revoke a token"""
if token in self._tokens:
del self._tokens[token]
self._save_tokens()
return True
return False
def revoke_all_tokens(self):
"""Revoke all Master tokens"""
self._tokens = {}
self._save_tokens()
def get_token_info(self, token: str) -> Optional[dict]:
"""Get token metadata"""
if token in self._tokens:
info = self._tokens[token].copy()
info["is_valid"] = self.validate_token(token)
return info
return None
class AuditLogger:
"""
Audit logger for Master mode operations.
Retention: 30 days
"""
def __init__(self, log_path: str = "./storage/audit.jsonl",
retention_days: int = 30):
self.log_path = log_path
self.retention_days = retention_days
os.makedirs(os.path.dirname(log_path), exist_ok=True)
def log(self, action: str, actor: str, details: dict):
"""
Log a Master mode action.
Args:
action: Action type (UNLOCK, ADD_AGENT, REMOVE_AGENT, etc.)
actor: Who performed the action (token prefix for security)
details: Additional details
"""
entry = {
"timestamp": datetime.now().isoformat(),
"action": action,
"actor": actor[:8] + "...", # Truncate for safety
"details": details
}
with open(self.log_path, 'a') as f:
f.write(json.dumps(entry, default=str) + "\n")
def get_recent_logs(self, days: int = 7) -> list[dict]:
"""Get logs from last N days"""
cutoff = datetime.now() - timedelta(days=days)
logs = []
try:
with open(self.log_path, 'r') as f:
for line in f:
entry = json.loads(line)
if datetime.fromisoformat(entry["timestamp"]) > cutoff:
logs.append(entry)
except FileNotFoundError:
pass
return logs
def cleanup_old_logs(self):
"""Remove logs older than retention period"""
cutoff = datetime.now() - timedelta(days=self.retention_days)
valid_logs = []
try:
with open(self.log_path, 'r') as f:
for line in f:
entry = json.loads(line)
if datetime.fromisoformat(entry["timestamp"]) > cutoff:
valid_logs.append(entry)
with open(self.log_path, 'w') as f:
for entry in valid_logs:
f.write(json.dumps(entry, default=str) + "\n")
except FileNotFoundError:
pass