Addressed SA-3 by encrypting the sqlite content with a .env secret
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
from backend.app.core.config import settings
|
||||
|
||||
|
||||
def _cipher() -> Fernet:
|
||||
if not settings.data_encryption_key:
|
||||
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY is required to access encrypted secrets')
|
||||
try:
|
||||
return Fernet(settings.data_encryption_key.encode('ascii'))
|
||||
except (ValueError, UnicodeEncodeError) as error:
|
||||
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY must be a valid Fernet key') from error
|
||||
|
||||
|
||||
def encrypt_secret(value: str) -> str:
|
||||
if not value:
|
||||
return value
|
||||
if value.startswith('enc:v1:'):
|
||||
return value
|
||||
return 'enc:v1:' + _cipher().encrypt(value.encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_secret(value: str) -> str:
|
||||
if not value or not value.startswith('enc:v1:'):
|
||||
return value
|
||||
try:
|
||||
return _cipher().decrypt(value[7:].encode('ascii')).decode('utf-8')
|
||||
except (InvalidToken, UnicodeEncodeError) as error:
|
||||
raise RuntimeError('Encrypted secret cannot be decrypted with LINKLOG_DATA_ENCRYPTION_KEY') from error
|
||||
Reference in New Issue
Block a user