File size: 5,203 Bytes
ad5f1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21fbec4
ad5f1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
security/auth.py
================
Phase 2/3: Security & Authentication Foundations

Provides:
- **JWT tokens** via ``python-jose`` for secure API authentication.
- **Password hashing** via ``bcrypt`` — plaintext is NEVER stored.
- **AES-256 Fernet encryption** via ``cryptography`` for stress history at rest.

Design Guardrails
-----------------
- Raw text / scores must NEVER be persisted in plaintext.
- JWT secret is loaded from the ``JWT_SECRET_KEY`` environment variable
  (falls back to a generated key for development only).
- Fernet key is loaded from ``FERNET_KEY`` environment variable
  (falls back to a generated key for development only).
"""

from __future__ import annotations

import json
import os
import time
from datetime import datetime, timedelta, timezone
from typing import Any

import bcrypt
from cryptography.fernet import Fernet, InvalidToken
from jose import JWTError, jwt

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------

# JWT settings
JWT_SECRET_KEY: str = os.environ.get(
    "JWT_SECRET_KEY",
    "dev-secret-key-change-in-production-f8a3b2c1d4e5",
)
JWT_ALGORITHM: str = "HS256"
JWT_EXPIRATION_MINUTES: int = int(os.environ.get("JWT_EXPIRATION_MINUTES", "10080"))  # 7 days default
# Fernet key for AES-256 encryption
_fernet_key: str = os.environ.get("FERNET_KEY", "")
if not _fernet_key:
    _fernet_key = Fernet.generate_key().decode()
FERNET_KEY: bytes = (
    _fernet_key.encode() if isinstance(_fernet_key, str) else _fernet_key
)

# Fernet cipher singleton
_fernet = Fernet(FERNET_KEY)


# ---------------------------------------------------------------------------
# Password hashing (bcrypt)
# ---------------------------------------------------------------------------


def hash_password(password: str) -> str:
    """Hash a plaintext password using bcrypt.

    Parameters
    ----------
    password : str
        The plaintext password to hash.

    Returns
    -------
    str
        The bcrypt hash string.
    """
    password_bytes = password.encode("utf-8")
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(password_bytes, salt)
    return hashed.decode("utf-8")


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """Verify a plaintext password against its bcrypt hash.

    Parameters
    ----------
    plain_password : str
        The plaintext password to check.
    hashed_password : str
        The stored bcrypt hash.

    Returns
    -------
    bool
        ``True`` if the password matches.
    """
    return bcrypt.checkpw(
        plain_password.encode("utf-8"),
        hashed_password.encode("utf-8"),
    )


# ---------------------------------------------------------------------------
# JWT token management
# ---------------------------------------------------------------------------


def create_jwt_token(
    data: dict[str, Any],
    expires_delta: timedelta | None = None,
) -> str:
    """Create a signed JWT token.

    Parameters
    ----------
    data : dict
        Payload data. Must include ``"sub"`` (subject / user identifier).
    expires_delta : timedelta, optional
        Custom expiry. Defaults to ``JWT_EXPIRATION_MINUTES``.

    Returns
    -------
    str
        Encoded JWT string.
    """
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + (
        expires_delta or timedelta(minutes=JWT_EXPIRATION_MINUTES)
    )
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM)


def decode_jwt_token(token: str) -> dict[str, Any]:
    """Decode and verify a JWT token.

    Parameters
    ----------
    token : str
        The JWT string.

    Returns
    -------
    dict
        The decoded payload.

    Raises
    ------
    JWTError
        If the token is invalid, expired, or tampered with.
    """
    return jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])


# ---------------------------------------------------------------------------
# AES-256 Fernet encryption (for stress history at rest)
# ---------------------------------------------------------------------------


def encrypt_data(data: Any) -> str:
    """Encrypt arbitrary JSON-serialisable data with Fernet (AES-256).

    Parameters
    ----------
    data : Any
        A JSON-serialisable Python object (list, dict, etc.).

    Returns
    -------
    str
        Base64-encoded ciphertext string.
    """
    plaintext = json.dumps(data).encode("utf-8")
    return _fernet.encrypt(plaintext).decode("utf-8")


def decrypt_data(encrypted: str) -> Any:
    """Decrypt a Fernet-encrypted string back to a Python object.

    Parameters
    ----------
    encrypted : str
        Base64-encoded ciphertext produced by :func:`encrypt_data`.

    Returns
    -------
    Any
        The original Python object, or ``None`` if decryption fails
        (e.g. wrong key, corrupted ciphertext, or expired token).
    """
    try:
        plaintext = _fernet.decrypt(encrypted.encode("utf-8"))
        return json.loads(plaintext.decode("utf-8"))
    except InvalidToken:
        return None