Compare commits

..

15 Commits

Author SHA1 Message Date
renovate[bot]
26d7ffc4fa feat(deps): update python docker tag to v3.13 2025-01-20 12:04:53 +00:00
4e7f352a15 feat: added retention_days deletion 2025-01-20 13:04:18 +01:00
263d962912 feat: added retention_days for compliance 2025-01-20 11:37:23 +01:00
renovate[bot]
3d4e5e3f4b feat(deps): update dependency alembic to v1.14.1 (#16)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-01-20 09:31:02 +00:00
renovate[bot]
6cdae87f42 feat(deps): update dependency httpx to v0.28.1 2025-01-20 05:11:08 +00:00
renovate[bot]
de36e60710 feat(deps): update dependency anyio to v4.8.0 2025-01-20 01:16:18 +00:00
renovate[bot]
bcec3079d3 feat(deps): update dependency pytest to v8.3.4 2025-01-19 21:23:04 +00:00
renovate[bot]
cf033298ce feat(deps): update dependency psycopg-binary to v3.2.4 2025-01-19 17:13:09 +00:00
renovate[bot]
3738b6f0a7 feat(deps): update dependency psycopg to v3.2.4 2025-01-19 12:37:22 +00:00
renovate[bot]
b8ac7226be feat(deps): update dependency click to v8.1.8 2025-01-19 08:23:32 +00:00
dafdf34f71 feat: added automerge to renovate 2025-01-17 12:33:14 +01:00
e77fe115c6 fix: removed duplicate install 2024-11-24 17:16:23 +01:00
6ab1eafe1d fix: fixed security recommendation from codacy 2024-11-24 17:16:11 +01:00
256e2adbf7 fix: fixed a recommendation from codacy 2024-11-24 17:13:44 +01:00
7c0d0da511 fix: bumped security dependency 2024-11-24 17:13:33 +01:00
10 changed files with 185 additions and 65 deletions

View File

@@ -5,6 +5,7 @@ on:
branches:
- dev
- master
- renovate/**
paths-ignore:
- "**/.github/**"
- "**/.gitignore"

View File

@@ -1,9 +1,15 @@
FROM python:3.12-slim
ARG VERSION=unkown
FROM python:3.13-slim
ARG VERSION=unknown
# Create a non-root user and group
RUN groupadd -r appuser && useradd -r -g appuser appuser
WORKDIR /app
COPY . .
# Change ownership of the application directory
RUN chown -R appuser:appuser /app
# Python setup
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
@@ -12,13 +18,19 @@ ENV ENV=DEV
# Install dependencies
RUN pip install --no-cache-dir --upgrade -r requirements.txt
RUN pip install 'uvicorn[standard]'
# Switch to the non-root user
USER appuser
EXPOSE 9000
CMD ["uvicorn", "app.main:app", "--workers", "6" , "--host", "0.0.0.0", "--port", "9000"]
# Install curl
RUN apt-get update && apt-get install -y curl && apt-get clean
USER root
RUN apt-get update && apt-get install -y --no-install-recommends curl && apt-get clean
# Switch back to the non-root user
USER appuser
HEALTHCHECK --interval=30s --timeout=10s --retries=5 \
CMD curl --fail http://localhost:9000/openapi.json || exit 1

View File

@@ -0,0 +1,29 @@
"""empty message
Revision ID: 1e695b024786
Revises: 21dc1dc045b8
Create Date: 2025-01-20 11:36:14.692849
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "1e695b024786"
down_revision: Union[str, None] = "21dc1dc045b8"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
with op.batch_alter_table("application", schema=None) as batch_op:
batch_op.add_column(sa.Column("retention_days", sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table("application", schema=None) as batch_op:
batch_op.drop_column("retention_days")

View File

@@ -1,6 +1,7 @@
from creyPY.fastapi.models.base import Base
from sqlalchemy import Column, String
from sqlalchemy import Column, Integer, String
class Application(Base):
name = Column(String(512), nullable=False, unique=True)
retention_days = Column(Integer, nullable=True)

View File

@@ -1,9 +1,9 @@
from creyPY.fastapi.models.base import Base
from sqlalchemy import Column, String, ForeignKey, Enum, JSON
from sqlalchemy.dialects.postgresql import UUID
from enum import Enum as pyenum
from creyPY.fastapi.models.base import Base
from sqlalchemy import JSON, Column, Enum, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID
class TransactionType(pyenum):
CREATE = "create"

View File

@@ -1,8 +1,11 @@
from pydantic.json_schema import SkipJsonSchema
from app.schema.common import BaseSchemaModelIN, BaseSchemaModelOUT
class AppIN(BaseSchemaModelIN):
name: str
retention_days: int | SkipJsonSchema[None] = 30
class AppOUT(BaseSchemaModelOUT, AppIN):

View File

@@ -1,12 +1,32 @@
import os
from datetime import datetime, timedelta
from creyPY.fastapi.db.session import SQLALCHEMY_DATABASE_URL, name
from apscheduler.schedulers.background import BackgroundScheduler
from creyPY.fastapi.db.session import SQLALCHEMY_DATABASE_URL, get_db, name
from sqlalchemy.orm import Session
from alembic import command
from alembic.config import Config
from app.models.app import Application
from app.models.entry import LogEntry
from app.services.db.session import create_if_not_exists
def delete_old_logs(sess: Session | None = None):
session = sess or next(get_db())
for app in session.query(Application).filter(Application.retention_days.isnot(None)):
cutoff = datetime.now() - timedelta(days=app.retention_days)
print(
f"Deleting logs older than {app.retention_days} days (cutoff: {cutoff}) for {app.name}",
)
session.query(LogEntry).filter(
LogEntry.application == app.id, LogEntry.created_at < cutoff
).delete()
session.commit()
def setup(db_name=name):
# Create Database
create_if_not_exists(db_name)
@@ -18,3 +38,17 @@ def setup(db_name=name):
"script_location", os.path.join(os.path.dirname(os.path.dirname(__file__)), "alembic")
)
command.upgrade(config, "head")
# Start retention deletion
scheduler = BackgroundScheduler()
scheduler.add_job(
delete_old_logs,
"interval",
id="deletor",
days=1,
max_instances=1,
replace_existing=True,
next_run_time=datetime.now(),
)
scheduler.start()
print("Deletion scheduler started")

View File

@@ -1,3 +1,6 @@
import contextlib
from datetime import datetime, timedelta
from creyPY.fastapi.db.session import SQLALCHEMY_DATABASE_URL, get_db
from creyPY.fastapi.models.base import Base
from creyPY.fastapi.testing import GenericClient
@@ -5,16 +8,55 @@ from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import create_database, database_exists, drop_database
from app.models.entry import LogEntry
from app.services.auth import verify
import contextlib
from app.setup import delete_old_logs
from .main import app
CURRENT_USER = "api-key|testing"
ENTRY_EXAMPLES = [
{
"l_type": "info",
"t_type": "create",
"message": "User Max Mustermann created",
"environment": "dev",
},
{
"l_type": "info",
"t_type": "update",
"message": "User Max Mustermann updated",
"environment": "dev",
},
{
"l_type": "info",
"t_type": "create",
"author": "auth|max_muster",
"message": "User Max Mustermann created a Unit",
"object_reference": "1",
"environment": "dev",
},
{
"l_type": "info",
"t_type": "update",
"author": "auth|max_muster",
"message": "User Max Mustermann updated Unit 1",
"object_reference": "1",
"previous_object": {"name": "Unit 1"},
"environment": "prod",
},
{
"l_type": "warning",
"t_type": "delete",
"message": "User Max Mustermann deleted",
"environment": "prod",
},
]
@contextlib.contextmanager
def app_context(self, name: str = "Testing"):
app_id = self.create_app(name)
def app_context(self, name: str = "Testing", retention_days: int | None = None):
app_id = self.create_app(name, retention_days)
try:
yield app_id
finally:
@@ -23,45 +65,8 @@ def app_context(self, name: str = "Testing"):
@contextlib.contextmanager
def log_examples(self):
LOG_EXAMPLES = [
{
"l_type": "info",
"t_type": "create",
"message": "User Max Mustermann created",
"environment": "dev",
},
{
"l_type": "info",
"t_type": "update",
"message": "User Max Mustermann updated",
"environment": "dev",
},
{
"l_type": "info",
"t_type": "create",
"author": "auth|max_muster",
"message": "User Max Mustermann created a Unit",
"object_reference": "1",
"environment": "dev",
},
{
"l_type": "info",
"t_type": "update",
"author": "auth|max_muster",
"message": "User Max Mustermann updated Unit 1",
"object_reference": "1",
"previous_object": {"name": "Unit 1"},
"environment": "prod",
},
{
"l_type": "warning",
"t_type": "delete",
"message": "User Max Mustermann deleted",
"environment": "prod",
},
]
with app_context(self) as app_id:
for entry in LOG_EXAMPLES:
for entry in ENTRY_EXAMPLES:
self.log_message({"application": app_id, **entry})
yield app_id
@@ -86,6 +91,7 @@ class TestAPI:
global CURRENT_USER
return CURRENT_USER
self.db_instance = get_db_test()
app.dependency_overrides[get_db] = get_db_test
app.dependency_overrides[verify] = get_test_sub
self.c = GenericClient(app)
@@ -94,8 +100,8 @@ class TestAPI:
drop_database(self.engine.url)
# HELPERS
def create_app(self, name: str = "Testing"):
re = self.c.post("/app/", {"name": name})
def create_app(self, name: str = "Testing", retention_days: int | None = None):
re = self.c.post("/app/", {"name": name, "retention_days": retention_days})
return re["id"]
def destroy_app(self, app_id):
@@ -260,3 +266,29 @@ class TestAPI:
re = self.c.get("/log/?application=" + str(app_id))
assert re["total"] == 0
def test_retention_delete(self):
sess = next(self.db_instance)
with app_context(self, retention_days=2) as app_id:
for i in range(5):
sess.add(
LogEntry(
application=app_id,
created_at=datetime.now() - timedelta(days=i),
created_by_id=CURRENT_USER,
)
)
sess.commit()
assert sess.query(LogEntry).count() == 5
re = self.c.get("/log/?application=" + str(app_id))
assert re["total"] == 5
delete_old_logs(sess)
assert sess.query(LogEntry).count() == 2
# delete all logs
re = self.c.delete("/log/?application=" + str(app_id), r_code=200)

View File

@@ -1,7 +1,12 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended",
":semanticCommitTypeAll(feat)"
"extends": ["config:recommended", ":semanticCommitTypeAll(feat)"],
"packageRules": [
{
"automerge": true,
"description": "Automerge non-major updates",
"matchUpdateTypes": ["minor", "patch"],
"automergeType": "branch"
}
]
}

View File

@@ -1,36 +1,39 @@
annotated-types==0.7.0
anyio==4.6.2.post1
anyio==4.8.0
certifi==2024.8.30
creyPY==1.2.5
fastapi==0.115.0
fastapi==0.115.5
fastapi-pagination==0.12.31
h11==0.14.0
httpcore==1.0.6
httpx==0.27.2
httpx==0.28.1
idna==3.10
psycopg==3.2.3
psycopg-binary==3.2.3
psycopg==3.2.4
psycopg-binary==3.2.4
psycopg-pool==3.2.3
pydantic==2.9.2
pydantic_core==2.23.4
python-dotenv==1.0.1
sniffio==1.3.1
SQLAlchemy==2.0.35
starlette==0.38.6
starlette==0.40.0
typing_extensions==4.12.2
Mako==1.3.5 # Alembic
MarkupSafe==3.0.1 # Alembic
alembic==1.13.3 # Alembic
alembic==1.14.1 # Alembic
SQLAlchemy-Utils==0.41.2 # SQLAlchemy
click==8.1.7 # Uvicorn
click==8.1.8 # Uvicorn
uvicorn==0.31.1 # Uvicorn
iniconfig==2.0.0 # pytest
packaging==24.1 # pytest
pluggy==1.5.0 # pytest
pytest==8.3.3 # pytest
pytest==8.3.4 # pytest
fastapi-filters==0.2.9 # Filters
APScheduler==3.11.0 # Scheduler for deletion
tzlocal==5.2 # Scheduler for deletion