Complete lab 7 security implementation

This commit is contained in:
2026-11-26 22:26:21 +03:00
parent 20afc2c790
commit df47ebd9f1
89 changed files with 9765 additions and 53 deletions
+75
View File
@@ -0,0 +1,75 @@
from __future__ import annotations
import os
from contextlib import contextmanager
from typing import Iterator
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
_pool: ConnectionPool | None = None
def _database_url() -> str:
url = os.environ.get("DATABASE_URL")
if not url:
raise RuntimeError("DATABASE_URL environment variable is required")
if "sslmode=" not in url:
sep = "&" if "?" in url else "?"
url = url + sep + "sslmode=verify-full&sslrootcert=/run/secrets/ca.crt"
return url
from psycopg_pool import ConnectionPool
def init_pool(min_size: int = 1, max_size: int = 10) -> None:
global _pool
if _pool is not None:
return
dsn = _database_url()
sep = "&" if "?" in dsn else "?"
dsn_with_opts = (
dsn
+ sep
+ "options="
+ "-c%20statement_timeout%3D5000"
+ "%20-c%20lock_timeout%3D3000"
+ "%20-c%20idle_in_transaction_session_timeout%3D10000"
)
_pool = ConnectionPool(
conninfo=dsn_with_opts,
min_size=min_size,
max_size=max_size,
kwargs={"row_factory": dict_row},
open=True,
timeout=5.0,
check=ConnectionPool.check_connection,
max_lifetime=120,
max_idle=60,
)
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
@contextmanager
def connection() -> Iterator[psycopg.Connection]:
if _pool is None:
raise RuntimeError("Connection pool is not initialized")
with _pool.connection() as conn:
yield conn
@contextmanager
def transaction() -> Iterator[psycopg.Connection]:
with connection() as conn:
with conn.transaction():
yield conn