Skip to content

Security

Security utilities for authentication and authorisation.

This module provides cryptographic functions for: - Password hashing and verification (Argon2) - JWT token creation and decoding (HS256) - TOTP two-factor authentication (RFC 6238) - CSRF token generation and validation

All functions use industry-standard algorithms and handle secrets securely.

hash_password

hash_password(p)

Hash Password with Argon2.

Hashes a plain text password using the Argon2id algorithm, which is recommended by OWASP for password storage. Uses argon2-cffi's default parameters (time_cost=3, memory_cost=65536, parallelism=4).

Parameters:

Name Type Description Default
p str

Plain text password to hash.

required

Returns:

Name Type Description
str str

Argon2 hash string in PHC format, suitable for database storage.

Raises:

Type Description
ValueError

If password is empty or None.

Source code in app/security.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def hash_password(p: str) -> str:
    """Hash Password with Argon2.

    Hashes a plain text password using the Argon2id algorithm, which is
    recommended by OWASP for password storage. Uses argon2-cffi's default
    parameters (time_cost=3, memory_cost=65536, parallelism=4).

    Args:
        p: Plain text password to hash.

    Returns:
        str: Argon2 hash string in PHC format, suitable for database storage.

    Raises:
        ValueError: If password is empty or None.
    """
    # Defensive programming: validate input
    if not p:
        raise ValueError("Password cannot be empty")
    return _ph.hash(p)

verify_password

verify_password(p, h)

Verify Password Against Hash.

Verifies a plain text password against an Argon2 hash stored in the database. Uses constant-time comparison to prevent timing attacks.

Parameters:

Name Type Description Default
p str

Plain text password to verify.

required
h str

Argon2 hash from database (PHC format).

required

Returns:

Name Type Description
bool bool

True if password matches hash, False otherwise.

Raises:

Type Description
ValueError

If password or hash is empty.

Source code in app/security.py
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
def verify_password(p: str, h: str) -> bool:
    """Verify Password Against Hash.

    Verifies a plain text password against an Argon2 hash stored in the
    database. Uses constant-time comparison to prevent timing attacks.

    Args:
        p: Plain text password to verify.
        h: Argon2 hash from database (PHC format).

    Returns:
        bool: True if password matches hash, False otherwise.

    Raises:
        ValueError: If password or hash is empty.
    """
    # Defensive programming: validate inputs
    if not p:
        raise ValueError("Password cannot be empty")
    if not h:
        raise ValueError("Hash cannot be empty")
    try:
        return _ph.verify(h, p)
    except VerifyMismatchError:
        return False

create_access_token

create_access_token(sub, roles, token_version=0)

Create JWT Access Token.

Creates a short-lived JWT access token containing the user's identity and assigned roles. The token is signed with HS256 and expires after ACCESS_TTL_MIN minutes (default: 15). Used for authenticating API requests.

Parameters:

Name Type Description Default
sub str

Subject (username) for the token.

required
roles list[str]

List of role names assigned to the user (e.g., ["Clinician"]).

required
token_version int

User's token version for session invalidation.

0

Returns:

Name Type Description
str str

Encoded JWT access token valid for ACCESS_TTL_MIN minutes.

Raises:

Type Description
ValueError

If subject is empty.

Source code in app/security.py
 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
def create_access_token(
    sub: str, roles: list[str], token_version: int = 0
) -> str:
    """Create JWT Access Token.

    Creates a short-lived JWT access token containing the user's identity
    and assigned roles. The token is signed with HS256 and expires after
    ACCESS_TTL_MIN minutes (default: 15). Used for authenticating API requests.

    Args:
        sub: Subject (username) for the token.
        roles: List of role names assigned to the user (e.g., ["Clinician"]).
        token_version: User's token version for session invalidation.

    Returns:
        str: Encoded JWT access token valid for ACCESS_TTL_MIN minutes.

    Raises:
        ValueError: If subject is empty.
    """
    # Defensive programming: validate inputs
    if not sub or not sub.strip():
        raise ValueError("Subject (username) cannot be empty")
    payload: dict[str, Any] = {
        "sub": sub,
        "roles": roles,
        "tv": token_version,
        "exp": _now() + timedelta(minutes=settings.ACCESS_TTL_MIN),
    }
    return jwt.encode(  # type: ignore[no-any-return]
        payload,
        settings.JWT_SECRET.get_secret_value(),
        algorithm=settings.JWT_ALG,
    )

create_refresh_token

create_refresh_token(sub, token_version=0)

Create JWT Refresh Token.

Creates a long-lived JWT refresh token used to obtain new access tokens without requiring the user to log in again. Expires after REFRESH_TTL_DAYS (default: 7 days). Stored in HTTP-only cookie with restricted path.

Parameters:

Name Type Description Default
sub str

Subject (username) for the token.

required
token_version int

User's token version for session invalidation.

0

Returns:

Name Type Description
str str

Encoded JWT refresh token valid for REFRESH_TTL_DAYS days.

Source code in app/security.py
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
def create_refresh_token(sub: str, token_version: int = 0) -> str:
    """Create JWT Refresh Token.

    Creates a long-lived JWT refresh token used to obtain new access tokens
    without requiring the user to log in again. Expires after REFRESH_TTL_DAYS
    (default: 7 days). Stored in HTTP-only cookie with restricted path.

    Args:
        sub: Subject (username) for the token.
        token_version: User's token version for session invalidation.

    Returns:
        str: Encoded JWT refresh token valid for REFRESH_TTL_DAYS days.
    """
    payload: dict[str, Any] = {
        "sub": sub,
        "type": "refresh",
        "tv": token_version,
        "exp": _now() + timedelta(days=settings.REFRESH_TTL_DAYS),
    }
    return jwt.encode(  # type: ignore[no-any-return]
        payload,
        settings.JWT_SECRET.get_secret_value(),
        algorithm=settings.JWT_ALG,
    )

decode_token

decode_token(tok)

Decode and Verify JWT Token.

Decodes a JWT token and verifies its signature using the configured JWT_SECRET. Also validates the token hasn't expired. Used by authentication middleware to extract user identity from access and refresh tokens.

Parameters:

Name Type Description Default
tok str

JWT token string to decode.

required

Returns:

Name Type Description
dict dict[str, Any]

Decoded token payload containing 'sub' (username), 'roles', 'exp' (expiration), and other claims.

Raises:

Type Description
JWTError

If token signature is invalid.

ExpiredSignatureError

If token has expired.

JWTClaimsError

If token claims are invalid.

Source code in app/security.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def decode_token(tok: str) -> dict[str, Any]:
    """Decode and Verify JWT Token.

    Decodes a JWT token and verifies its signature using the configured
    JWT_SECRET. Also validates the token hasn't expired. Used by authentication
    middleware to extract user identity from access and refresh tokens.

    Args:
        tok: JWT token string to decode.

    Returns:
        dict: Decoded token payload containing 'sub' (username), 'roles',
            'exp' (expiration), and other claims.

    Raises:
        jose.JWTError: If token signature is invalid.
        jose.ExpiredSignatureError: If token has expired.
        jose.JWTClaimsError: If token claims are invalid.
    """
    return jwt.decode(  # type: ignore[no-any-return]
        tok,
        settings.JWT_SECRET.get_secret_value(),
        algorithms=[settings.JWT_ALG],
    )

create_csrf_token

create_csrf_token(username)

Create CSRF Protection Token.

Generates a CSRF token for protecting state-changing operations against cross-site request forgery attacks. The token is signed with the JWT_SECRET and tied to the user's identity. Must be included in X-CSRF-Token header for POST/PUT/PATCH/DELETE requests.

Parameters:

Name Type Description Default
username str

Username to tie the token to.

required

Returns:

Name Type Description
str str

URL-safe CSRF token signed with JWT_SECRET.

Raises:

Type Description
ValueError

If username is empty.

Source code in app/security.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def create_csrf_token(username: str) -> str:
    """Create CSRF Protection Token.

    Generates a CSRF token for protecting state-changing operations against
    cross-site request forgery attacks. The token is signed with the JWT_SECRET
    and tied to the user's identity. Must be included in X-CSRF-Token header
    for POST/PUT/PATCH/DELETE requests.

    Args:
        username: Username to tie the token to.

    Returns:
        str: URL-safe CSRF token signed with JWT_SECRET.

    Raises:
        ValueError: If username is empty.
    """
    # Defensive programming: validate input
    if not username or not username.strip():
        raise ValueError("Username cannot be empty")
    return _csrf.dumps({"sub": username})

make_csrf

make_csrf(sub)

Create CSRF Token (Legacy).

Legacy alias for create_csrf_token. Generates a CSRF token signed with the user's identity. Maintained for backward compatibility with existing code that uses this function name.

Parameters:

Name Type Description Default
sub str

Subject (username) to sign the token with.

required

Returns:

Name Type Description
str str

URL-safe CSRF token.

Source code in app/security.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def make_csrf(sub: str) -> str:
    """Create CSRF Token (Legacy).

    Legacy alias for create_csrf_token. Generates a CSRF token signed with
    the user's identity. Maintained for backward compatibility with existing
    code that uses this function name.

    Args:
        sub: Subject (username) to sign the token with.

    Returns:
        str: URL-safe CSRF token.
    """
    return _csrf.dumps({"sub": sub})

verify_csrf

verify_csrf(token, sub)

Verify CSRF Token.

Verifies a CSRF token matches the expected username. Used by the require_csrf dependency to protect state-changing operations. Returns False for any verification failure (invalid signature, wrong subject).

Parameters:

Name Type Description Default
token str

CSRF token from X-CSRF-Token header.

required
sub str

Expected subject (username) from JWT.

required

Returns:

Name Type Description
bool bool

True if token is valid and subject matches, False otherwise.

Source code in app/security.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def verify_csrf(token: str, sub: str) -> bool:
    """Verify CSRF Token.

    Verifies a CSRF token matches the expected username. Used by the
    require_csrf dependency to protect state-changing operations. Returns
    False for any verification failure (invalid signature, wrong subject).

    Args:
        token: CSRF token from X-CSRF-Token header.
        sub: Expected subject (username) from JWT.

    Returns:
        bool: True if token is valid and subject matches, False otherwise.
    """
    try:
        data = _csrf.loads(token)
        return bool(data.get("sub") == sub)
    except Exception:
        return False

generate_totp_secret

generate_totp_secret()

Generate TOTP Secret.

Generates a new cryptographically random TOTP secret for two-factor authentication. The secret is Base32-encoded for compatibility with authenticator apps like Google Authenticator, Authy, etc.

Returns:

Name Type Description
str str

Base32-encoded secret (32 characters).

Source code in app/security.py
245
246
247
248
249
250
251
252
253
254
255
def generate_totp_secret() -> str:
    """Generate TOTP Secret.

    Generates a new cryptographically random TOTP secret for two-factor
    authentication. The secret is Base32-encoded for compatibility with
    authenticator apps like Google Authenticator, Authy, etc.

    Returns:
        str: Base32-encoded secret (32 characters).
    """
    return pyotp.random_base32()

generate_totp_provision_uri

generate_totp_provision_uri(username, secret, issuer='Quill')

Generate TOTP Provisioning URI.

Creates an otpauth:// URI for QR code generation, compatible with authenticator apps. The URI contains the secret, username, and issuer information. Users scan this QR code to add the account to their app.

Parameters:

Name Type Description Default
username str

User's username for labeling the TOTP entry.

required
secret str

Base32-encoded TOTP secret from generate_totp_secret().

required
issuer str

Application name displayed in authenticator app (default: "Quill").

'Quill'

Returns:

Name Type Description
str str

otpauth://totp/... URI for QR code generation.

Source code in app/security.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def generate_totp_provision_uri(
    username: str, secret: str, issuer: str = "Quill"
) -> str:
    """Generate TOTP Provisioning URI.

    Creates an otpauth:// URI for QR code generation, compatible with
    authenticator apps. The URI contains the secret, username, and issuer
    information. Users scan this QR code to add the account to their app.

    Args:
        username: User's username for labeling the TOTP entry.
        secret: Base32-encoded TOTP secret from generate_totp_secret().
        issuer: Application name displayed in authenticator app (default: "Quill").

    Returns:
        str: otpauth://totp/... URI for QR code generation.
    """
    totp = pyotp.TOTP(secret)
    return totp.provisioning_uri(name=username, issuer_name=issuer)

verify_totp_code

verify_totp_code(secret, code)

Verify TOTP Code.

Verifies a 6-digit TOTP code against the user's secret. Uses RFC 6238 time-based one-time password algorithm with 30-second time steps. Allows for clock drift of ±1 time step (default pyotp behavior).

Parameters:

Name Type Description Default
secret str

Base32-encoded TOTP secret from database.

required
code str

6-digit TOTP code from authenticator app.

required

Returns:

Name Type Description
bool bool

True if code is valid for current time window, False otherwise.

Source code in app/security.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def verify_totp_code(secret: str, code: str) -> bool:
    """Verify TOTP Code.

    Verifies a 6-digit TOTP code against the user's secret. Uses RFC 6238
    time-based one-time password algorithm with 30-second time steps.
    Allows for clock drift of ±1 time step (default pyotp behavior).

    Args:
        secret: Base32-encoded TOTP secret from database.
        code: 6-digit TOTP code from authenticator app.

    Returns:
        bool: True if code is valid for current time window, False otherwise.
    """
    try:
        totp = pyotp.TOTP(secret)
        return totp.verify(code)
    except Exception:
        return False

totp_provisioning_uri

totp_provisioning_uri(secret, username, issuer=None)

Return an otpauth:// URI which can be converted to QR code by the frontend.

Source code in app/security.py
300
301
302
303
304
305
306
307
308
309
def totp_provisioning_uri(
    secret: str, username: str, issuer: str | None = None
) -> str:
    """Return an otpauth:// URI which can be converted to QR code by
    the frontend.
    """
    totp = pyotp.totp.TOTP(secret)
    if issuer:
        return totp.provisioning_uri(name=username, issuer_name=issuer)
    return totp.provisioning_uri(name=username)

create_jwt_with_competencies

create_jwt_with_competencies(sub, roles, competencies, token_version=0)

Create JWT Access Token with CBAC Competencies.

Creates a short-lived JWT access token containing the user's identity, assigned roles, and resolved competencies. This extends create_access_token to include CBAC (Competency-Based Access Control) information in the token.

Parameters:

Name Type Description Default
sub str

Subject (username) for the token.

required
roles list[str]

List of role names assigned to the user (e.g., ["Clinician"]).

required
competencies list[str]

List of competency IDs user has (resolved from base profession).

required
token_version int

User's token version for session invalidation.

0

Returns:

Name Type Description
str str

Encoded JWT access token with competencies, valid for ACCESS_TTL_MIN minutes.

Raises:

Type Description
ValueError

If subject is empty.

Source code in app/security.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def create_jwt_with_competencies(
    sub: str,
    roles: list[str],
    competencies: list[str],
    token_version: int = 0,
) -> str:
    """Create JWT Access Token with CBAC Competencies.

    Creates a short-lived JWT access token containing the user's identity,
    assigned roles, and resolved competencies. This extends create_access_token
    to include CBAC (Competency-Based Access Control) information in the token.

    Args:
        sub: Subject (username) for the token.
        roles: List of role names assigned to the user (e.g., ["Clinician"]).
        competencies: List of competency IDs user has (resolved from base profession).
        token_version: User's token version for session invalidation.

    Returns:
        str: Encoded JWT access token with competencies, valid for ACCESS_TTL_MIN minutes.

    Raises:
        ValueError: If subject is empty.
    """
    if not sub or not sub.strip():
        raise ValueError("Subject (username) cannot be empty")
    payload: dict[str, Any] = {
        "sub": sub,
        "roles": roles,
        "competencies": competencies,
        "tv": token_version,
        "exp": _now() + timedelta(minutes=settings.ACCESS_TTL_MIN),
    }
    return jwt.encode(  # type: ignore[no-any-return]
        payload,
        settings.JWT_SECRET.get_secret_value(),
        algorithm=settings.JWT_ALG,
    )

decode_jwt_with_competencies

decode_jwt_with_competencies(tok)

Decode and Verify JWT Token with Competencies.

Decodes a JWT token and verifies its signature, extracting user identity, roles, and competencies. This is a wrapper around decode_token that documents the expected payload structure for CBAC tokens.

Parameters:

Name Type Description Default
tok str

JWT token string to decode.

required

Returns:

Name Type Description
dict dict[str, Any]

Decoded token payload containing 'sub' (username), 'roles', 'competencies', 'exp' (expiration), and other claims.

Raises:

Type Description
JWTError

If token signature is invalid.

ExpiredSignatureError

If token has expired.

JWTClaimsError

If token claims are invalid.

Source code in app/security.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def decode_jwt_with_competencies(tok: str) -> dict[str, Any]:
    """Decode and Verify JWT Token with Competencies.

    Decodes a JWT token and verifies its signature, extracting user identity,
    roles, and competencies. This is a wrapper around decode_token that
    documents the expected payload structure for CBAC tokens.

    Args:
        tok: JWT token string to decode.

    Returns:
        dict: Decoded token payload containing 'sub' (username), 'roles',
            'competencies', 'exp' (expiration), and other claims.

    Raises:
        jose.JWTError: If token signature is invalid.
        jose.ExpiredSignatureError: If token has expired.
        jose.JWTClaimsError: If token claims are invalid.
    """
    return decode_token(tok)

create_invite_token

create_invite_token(patient_id, email, user_type, *, ttl_days=7)

Create a JWT invite token for external user access.

Parameters:

Name Type Description Default
patient_id str

FHIR Patient resource ID.

required
email str

Invitee email address.

required
user_type str

external_hcp or patient_advocate.

required
ttl_days int

Token validity in days (default 7).

7

Returns:

Name Type Description
str str

Signed JWT invite token.

Source code in app/security.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def create_invite_token(
    patient_id: str,
    email: str,
    user_type: str,
    *,
    ttl_days: int = 7,
) -> str:
    """Create a JWT invite token for external user access.

    Args:
        patient_id: FHIR Patient resource ID.
        email: Invitee email address.
        user_type: ``external_hcp`` or ``patient_advocate``.
        ttl_days: Token validity in days (default 7).

    Returns:
        str: Signed JWT invite token.
    """
    payload: dict[str, Any] = {
        "type": "invite",
        "patient_id": patient_id,
        "email": email,
        "user_type": user_type,
        "exp": _now() + timedelta(days=ttl_days),
    }
    return jwt.encode(  # type: ignore[no-any-return]
        payload,
        settings.JWT_SECRET.get_secret_value(),
        algorithm=settings.JWT_ALG,
    )

decode_invite_token

decode_invite_token(tok)

Decode and verify an invite JWT.

Returns:

Name Type Description
dict dict[str, Any]

Payload with patient_id, email, user_type.

Raises:

Type Description
JWTError

Invalid or expired token.

Source code in app/security.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def decode_invite_token(tok: str) -> dict[str, Any]:
    """Decode and verify an invite JWT.

    Returns:
        dict: Payload with ``patient_id``, ``email``, ``user_type``.

    Raises:
        jose.JWTError: Invalid or expired token.
    """
    data: dict[str, Any] = jwt.decode(
        tok,
        settings.JWT_SECRET.get_secret_value(),
        algorithms=[settings.JWT_ALG],
    )
    if data.get("type") != "invite":
        raise jwt.JWTError("Not an invite token")
    return data

create_password_reset_token

create_password_reset_token(email)

Create a time-limited password reset token.

Generates a signed, time-limited token tied to the user's email. The token expires after PASSWORD_RESET_TTL_MIN minutes (default 30).

Parameters:

Name Type Description Default
email str

User's email address.

required

Returns:

Name Type Description
str str

URL-safe signed token.

Raises:

Type Description
ValueError

If email is empty.

Source code in app/security.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def create_password_reset_token(email: str) -> str:
    """Create a time-limited password reset token.

    Generates a signed, time-limited token tied to the user's email.
    The token expires after PASSWORD_RESET_TTL_MIN minutes (default 30).

    Args:
        email: User's email address.

    Returns:
        str: URL-safe signed token.

    Raises:
        ValueError: If email is empty.
    """
    if not email or not email.strip():
        raise ValueError("Email cannot be empty")
    return _password_reset.dumps({"email": email.strip().lower()})

verify_password_reset_token

verify_password_reset_token(token)

Verify a password reset token and return the email.

Checks the token signature and expiry. Returns the email if valid, None if the token is invalid or expired.

Parameters:

Name Type Description Default
token str

Password reset token from email link.

required

Returns:

Type Description
str | None

The email address if valid, None otherwise.

Source code in app/security.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
def verify_password_reset_token(token: str) -> str | None:
    """Verify a password reset token and return the email.

    Checks the token signature and expiry. Returns the email if valid,
    None if the token is invalid or expired.

    Args:
        token: Password reset token from email link.

    Returns:
        The email address if valid, None otherwise.
    """
    try:
        data: dict[str, str] = _password_reset.loads(
            token, max_age=settings.PASSWORD_RESET_TTL_MIN * 60
        )
        return data.get("email")
    except (SignatureExpired, BadSignature):
        return None