-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.py
More file actions
215 lines (175 loc) · 6.25 KB
/
Copy pathsecurity.py
File metadata and controls
215 lines (175 loc) · 6.25 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
import base64
import hashlib
import hmac
import json
import os
import secrets
import time
from typing import Any
from cryptography.fernet import Fernet, InvalidToken
from loguru import logger
_PASSWORD_ITERATIONS = 390000
ACCESS_TOKEN_TTL_SECONDS = 30 * 60
REFRESH_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 7
_DEFAULT_PROMPTMAN_KEY = "promptman-default-key-change-me"
def _active_machine_secret() -> str:
configured = (os.getenv("PROMPTMAN_KEY") or "").strip()
if configured:
return configured
logger.warning("security.key.default_used set PROMPTMAN_KEY for persistent deployments")
return _DEFAULT_PROMPTMAN_KEY
def _previous_machine_secrets() -> list[str]:
previous = (os.getenv("PROMPTMAN_KEY_PREVIOUS") or "").strip()
if not previous:
return []
return [item.strip() for item in previous.split(",") if item.strip()]
def _derive_key(label: str, secret: str) -> bytes:
material = hashlib.sha256(f"{label}:{secret}".encode()).digest()
return base64.urlsafe_b64encode(material)
def _build_cipher(secret: str) -> Fernet:
return Fernet(_derive_key("fernet", secret))
_ACTIVE_SECRET = _active_machine_secret()
_CIPHER = _build_cipher(_ACTIVE_SECRET)
_PREVIOUS_CIPHERS = [_build_cipher(secret) for secret in _previous_machine_secrets() if secret != _ACTIVE_SECRET]
_TOKEN_SECRET = hashlib.sha256(_derive_key("token", _ACTIVE_SECRET)).digest()
__all__ = [
"ACCESS_TOKEN_TTL_SECONDS",
"REFRESH_TOKEN_TTL_SECONDS",
"time",
]
def encrypt_secret(value: str | None) -> str | None:
if not value or not value.strip():
return None
try:
return _CIPHER.encrypt(value.strip().encode()).decode("utf-8")
except Exception as exc:
logger.warning("security.encrypt.failed error={}", exc)
return None
def decrypt_secret(value: str | None) -> str | None:
if not value:
return None
try:
return _CIPHER.decrypt(value.encode()).decode("utf-8")
except InvalidToken:
for previous_cipher in _PREVIOUS_CIPHERS:
try:
plaintext = previous_cipher.decrypt(value.encode()).decode("utf-8")
logger.warning("security.decrypt.used_previous_key")
return plaintext
except InvalidToken:
continue
logger.warning("security.decrypt.invalid_token")
return None
except Exception as exc:
logger.warning("security.decrypt.failed error={}", exc)
return None
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, _PASSWORD_ITERATIONS)
return "$".join(
[
"pbkdf2_sha256",
str(_PASSWORD_ITERATIONS),
base64.urlsafe_b64encode(salt).decode("ascii"),
base64.urlsafe_b64encode(digest).decode("ascii"),
]
)
def verify_password(password: str, encoded_hash: str | None) -> bool:
if not encoded_hash:
return False
try:
algorithm, raw_iterations, salt_b64, digest_b64 = encoded_hash.split("$", 3)
if algorithm != "pbkdf2_sha256":
return False
iterations = int(raw_iterations)
salt = base64.urlsafe_b64decode(salt_b64.encode("ascii"))
expected = base64.urlsafe_b64decode(digest_b64.encode("ascii"))
actual = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)
return hmac.compare_digest(actual, expected)
except Exception:
return False
def _b64url_encode(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def _b64url_decode(data: str) -> bytes:
padding = "=" * (-len(data) % 4)
return base64.urlsafe_b64decode((data + padding).encode("ascii"))
def _create_signed_token(
*,
token_type: str,
user_id: int,
username: str,
role: str,
ttl_seconds: int,
now_ts: int | None = None,
) -> str:
header = {"alg": "HS256", "typ": "JWT"}
issued_at = int(time.time()) if now_ts is None else int(now_ts)
payload = {
"type": token_type,
"sub": str(user_id),
"username": username,
"role": role,
"iat": issued_at,
"exp": issued_at + max(60, ttl_seconds),
}
header_part = _b64url_encode(json.dumps(header, separators=(",", ":")).encode())
payload_part = _b64url_encode(json.dumps(payload, separators=(",", ":")).encode())
signature = hmac.new(_TOKEN_SECRET, f"{header_part}.{payload_part}".encode(), hashlib.sha256).digest()
return f"{header_part}.{payload_part}.{_b64url_encode(signature)}"
def create_access_token(
*,
user_id: int,
username: str,
role: str,
ttl_seconds: int = ACCESS_TOKEN_TTL_SECONDS,
now_ts: int | None = None,
) -> str:
return _create_signed_token(
token_type="access",
user_id=user_id,
username=username,
role=role,
ttl_seconds=ttl_seconds,
now_ts=now_ts,
)
def create_refresh_token(
*,
user_id: int,
username: str,
role: str,
ttl_seconds: int = REFRESH_TOKEN_TTL_SECONDS,
now_ts: int | None = None,
) -> str:
return _create_signed_token(
token_type="refresh",
user_id=user_id,
username=username,
role=role,
ttl_seconds=ttl_seconds,
now_ts=now_ts,
)
def _verify_signed_token(token: str, expected_type: str) -> dict[str, Any] | None:
try:
header_part, payload_part, signature_part = token.split(".", 2)
except ValueError:
return None
expected = hmac.new(_TOKEN_SECRET, f"{header_part}.{payload_part}".encode(), hashlib.sha256).digest()
actual = _b64url_decode(signature_part)
if not hmac.compare_digest(expected, actual):
return None
try:
payload = json.loads(_b64url_decode(payload_part))
except Exception:
return None
if not isinstance(payload, dict):
return None
if payload.get("type") != expected_type:
return None
exp = payload.get("exp")
if not isinstance(exp, int) or exp < int(time.time()):
return None
return payload
def verify_access_token(token: str) -> dict[str, Any] | None:
return _verify_signed_token(token, "access")
def verify_refresh_token(token: str) -> dict[str, Any] | None:
return _verify_signed_token(token, "refresh")