Created At: 2026-11-18T09:26:48Z Completed At: 2026-11-18T09:26:53Z Command exited with code 1. Command output: ============================= test session starts ============================== platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0 -- /root/telegram-saas/.venv/bin/python3 cachedir: .pytest_cache rootdir: /root/telegram-saas configfile: pyproject.toml plugins: anyio-4.16.0, asyncio-1.5.0 asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function collecting ... collected 6 items tests/unit/test_security_audit.py::test_secure_filename_and_path_traversal_neutralization FAILED [ 16%] tests/unit/test_security_audit.py::test_validate_file_content_magic_bytes_and_extensions PASSED [ 33%] tests/unit/test_security_audit.py::test_safe_template_rendering_zero_ssti_and_eval PASSED [ 50%] tests/unit/test_security_audit.py::test_in_app_rate_limiter_sliding_window PASSED [ 66%] tests/unit/test_security_audit.py::test_sql_injection_defense_via_parameterized_queries PASSED [ 83%] tests/unit/test_security_audit.py::test_audit_service_action_logging FAILED [100%] =================================== FAILURES =================================== ____________ test_secure_filename_and_path_traversal_neutralization ____________ @pytest.mark.unit def test_secure_filename_and_path_traversal_neutralization(): # 1. Directory traversal attacks > assert secure_filename("../../etc/passwd") == "etc_passwd" E AssertionError: assert 'passwd' == 'etc_passwd' E E - etc_passwd E ? ---- E + passwd tests/unit/test_security_audit.py:18: AssertionError ______________________ test_audit_service_action_logging _______________________ self = operation = 'INSERT INTO audit_logs (id, tenant_id, user_id, action, resource, ip_address, details, created_at, updated_at) VALUES...3::UUID, $4::VARCHAR, $5::VARCHAR, $6::VARCHAR, $7::JSONB, $8::TIMESTAMP WITH TIME ZONE, $9::TIMESTAMP WITH TIME ZONE)' parameters = (UUID('e9983bd0-208e-48ae-b199-928014f7ca48'), UUID('314b5413-3607-4868-a613-86cdaa320c85'), None, 'SECURITY_KEY_ROTATION', 'vault:token_v1', '192.0.2.1', ...) async def _prepare_and_execute(self, operation, parameters): adapt_connection = self._adapt_connection async with adapt_connection._execute_mutex: if adapt_connection._transaction is None: await adapt_connection._start_transaction() if parameters is None: parameters = () try: prepared_stmt, attributes = await adapt_connection._prepare( operation, self._invalidate_schema_cache_asof ) if attributes: self._description = [ ( attr.name, attr.type.oid, None, None, None, None, None, ) for attr in attributes ] else: self._description = None if self.server_side: self._cursor = await prepared_stmt.cursor(*parameters) self._rowcount = -1 else: > self._rows = deque(await prepared_stmt.fetch(*parameters)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:620: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.12/site-packages/asyncpg/prepared_stmt.py:177: in fetch data = await self.__bind_execute(args, 0, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/asyncpg/prepared_stmt.py:268: in __bind_execute data, status, _ = await self.__do_execute( .venv/lib/python3.12/site-packages/asyncpg/prepared_stmt.py:257: in __do_execute return await executor(protocol) ^^^^^^^^^^^^^^^^^^^^^^^^ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ > ??? E asyncpg.exceptions.ForeignKeyViolationError: insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey" E DETAIL: Key (tenant_id)=(314b5413-3607-4868-a613-86cdaa320c85) is not present in table "tenants". asyncpg/protocol/protocol.pyx:197: ForeignKeyViolationError The above exception was the direct cause of the following exception: self = dialect = context = statement = parameters = [(UUID('e9983bd0-208e-48ae-b199-928014f7ca48'), UUID('314b5413-3607-4868-a613-86cdaa320c85'), None, 'SECURITY_KEY_ROTATION', 'vault:token_v1', '192.0.2.1', ...)] def _exec_single_context( self, dialect: Dialect, context: ExecutionContext, statement: Union[str, Compiled], parameters: Optional[_AnyMultiExecuteParams], ) -> CursorResult[Unpack[TupleAny]]: """continue the _execute_context() method for a single DBAPI cursor.execute() or cursor.executemany() call. """ if dialect.bind_typing is BindTyping.SETINPUTSIZES: generic_setinputsizes = context._prepare_set_input_sizes() if generic_setinputsizes: try: dialect.do_set_input_sizes( context.cursor, generic_setinputsizes, context ) except BaseException as e: self._handle_dbapi_exception( e, str(statement), parameters, None, context ) cursor, str_statement, parameters = ( context.cursor, context.statement, context.parameters, ) effective_parameters: Optional[_AnyExecuteParams] if not context.executemany: effective_parameters = parameters[0] else: effective_parameters = parameters evt_handled: bool = False try: if self._has_events or self.engine._has_events: for fn in self.dispatch.before_cursor_execute: str_statement, effective_parameters = fn( self, cursor, str_statement, effective_parameters, context, context.executemany, ) if self._echo: self._log_info(str_statement) stats = context._get_cache_stats() self._log_parameters( effective_parameters, stats, ismulti=context.executemany ) if context.execute_style is ExecuteStyle.EXECUTEMANY: effective_parameters = cast( "_CoreMultiExecuteParams", effective_parameters ) if self.dialect._has_events: for fn in self.dialect.dispatch.do_executemany: if fn( cursor, str_statement, effective_parameters, context, ): evt_handled = True break if not evt_handled: self.dialect.do_executemany( cursor, str_statement, effective_parameters, context, ) elif not effective_parameters and context.no_parameters: if self.dialect._has_events: for fn in self.dialect.dispatch.do_execute_no_params: if fn(cursor, str_statement, context): evt_handled = True break if not evt_handled: self.dialect.do_execute_no_params( cursor, str_statement, context ) else: effective_parameters = cast( "_CoreSingleExecuteParams", effective_parameters ) if self.dialect._has_events: for fn in self.dialect.dispatch.do_execute: if fn( cursor, str_statement, effective_parameters, context, ): evt_handled = True break if not evt_handled: > self.dialect.do_execute( cursor, str_statement, effective_parameters, context ) .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1977: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py:1192: in do_execute cursor.execute(statement, parameters) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:671: in execute await_(self._prepare_and_execute(operation, parameters)) .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:171: in await_ return current.parent.switch(awaitable) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:209: in greenlet_spawn value = await result ^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:633: in _prepare_and_execute self._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:583: in _handle_exception self._adapt_connection._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:862: in _handle_exception super()._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/connectors/asyncio.py:412: in _handle_exception self._handle_exception_no_connection(self.dbapi, error) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cls = dbapi = error = ForeignKeyViolationError('insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey"') @classmethod def _handle_exception_no_connection( cls, dbapi: Any, error: Exception ) -> NoReturn: if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error): exception_mapping = dbapi._asyncpg_error_translate for super_ in type(error).__mro__: if super_ in exception_mapping: message = error.args[0] translated_error = exception_mapping[super_]( message, error ) > raise translated_error from error E sqlalchemy.dialects.postgresql.asyncpg.AsyncAdapt_asyncpg_dbapi.ForeignKeyViolationError: insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey" .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:855: ForeignKeyViolationError The above exception was the direct cause of the following exception: db_session = @pytest.mark.asyncio async def test_audit_service_action_logging(db_session: AsyncSession): tenant_id = uuid.uuid4() audit_service = AuditService(db_session) > log_entry = await audit_service.log_action( tenant_id=tenant_id, action="SECURITY_KEY_ROTATION", resource="vault:token_v1", ip_address="192.0.2.1", details={"key_version": 2, "actor": "admin"}, ) tests/unit/test_security_audit.py:112: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ modules/audit/service.py:29: in log_action await self.db.flush() .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py:1031: in flush await greenlet_spawn(self.sync_session.flush, objects=objects) .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:216: in greenlet_spawn result = context.switch(value) ^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:4626: in flush self._flush(objects) :2: in _flush return target(fn, self, objects=objects) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py:281: in warned return fn(*args, **kwargs) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:4769: in _flush with util.safe_reraise(): .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py:166: in __exit__ raise exc_value.with_traceback(exc_tb) .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:4730: in _flush flush_context.execute() .venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py:467: in execute rec.execute(self) .venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py:643: in execute util.preloaded.orm_persistence._save_obj( .venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py:92: in _save_obj _emit_insert_statements( .venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py:1250: in _emit_insert_statements result = connection.execute( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1494: in execute return meth( .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py:534: in _execute_on_connection return connection._execute_clauseelement( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1714: in _execute_clauseelement ret = self._execute_context( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1868: in _execute_context return self._exec_single_context( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1996: in _exec_single_context self._handle_dbapi_exception( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:2351: in _handle_dbapi_exception raise sqlalchemy_exception.with_traceback(exc_info[2]) from e .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1977: in _exec_single_context self.dialect.do_execute( .venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py:1192: in do_execute cursor.execute(statement, parameters) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:671: in execute await_(self._prepare_and_execute(operation, parameters)) .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:171: in await_ return current.parent.switch(awaitable) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:209: in greenlet_spawn value = await result ^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:633: in _prepare_and_execute self._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:583: in _handle_exception self._adapt_connection._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:862: in _handle_exception super()._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/connectors/asyncio.py:412: in _handle_exception self._handle_exception_no_connection(self.dbapi, error) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cls = dbapi = error = ForeignKeyViolationError('insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey"') @classmethod def _handle_exception_no_connection( cls, dbapi: Any, error: Exception ) -> NoReturn: if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error): exception_mapping = dbapi._asyncpg_error_translate for super_ in type(error).__mro__: if super_ in exception_mapping: message = error.args[0] translated_error = exception_mapping[super_]( message, error ) > raise translated_error from error E sqlalchemy.exc.IntegrityError: (sqlalchemy.dialects.postgresql.asyncpg.ForeignKeyViolationError) insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey" E [SQL: INSERT INTO audit_logs (id, tenant_id, user_id, action, resource, ip_address, details, created_at, updated_at) VALUES ($1::UUID, $2::UUID, $3::UUID, $4::VARCHAR, $5::VARCHAR, $6::VARCHAR, $7::JSONB, $8::TIMESTAMP WITH TIME ZONE, $9::TIMESTAMP WITH TIME ZONE)] E [parameters: (UUID('e9983bd0-208e-48ae-b199-928014f7ca48'), UUID('314b5413-3607-4868-a613-86cdaa320c85'), None, 'SECURITY_KEY_ROTATION', 'vault:token_v1', '192.0.2.1', '{"key_version": 2, "actor": "admin"}', datetime.datetime(2026, 11, 18, 9, 26, 52, 665251, tzinfo=datetime.timezone.utc), datetime.datetime(2026, 11, 18, 9, 26, 52, 665254, tzinfo=datetime.timezone.utc))] E (Background on this error at: https://sqlalche.me/e/21/gkpj) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:855: IntegrityError =============================== warnings summary =============================== tests/unit/test_security_audit.py:15 /root/telegram-saas/tests/unit/test_security_audit.py:15: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit tests/unit/test_security_audit.py:25 /root/telegram-saas/tests/unit/test_security_audit.py:25: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit tests/unit/test_security_audit.py:50 /root/telegram-saas/tests/unit/test_security_audit.py:50: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit tests/unit/test_security_audit.py:72 /root/telegram-saas/tests/unit/test_security_audit.py:72: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html =========================== short test summary info ============================ FAILED tests/unit/test_security_audit.py::test_secure_filename_and_path_traversal_neutralization FAILED tests/unit/test_security_audit.py::test_audit_service_action_logging =================== 2 failed, 4 passed, 4 warnings in 0.47s ====================