Skip to content

Commit

Permalink
[DOP-21268] - add SessionSettings
Browse files Browse the repository at this point in the history
  • Loading branch information
maxim-lixakov committed Nov 14, 2024
1 parent e1efdaa commit 0a41541
Show file tree
Hide file tree
Showing 12 changed files with 94 additions and 13 deletions.
4 changes: 4 additions & 0 deletions .env.docker
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ SYNCMASTER__LOGGING__SETUP=True
SYNCMASTER__LOGGING__PRESET=colored
SYNCMASTER__LOG_URL_TEMPLATE=https://grafana.example.com?correlation_id={{ correlation_id }}&run_id={{ run.id }}

# Session
SYNCMASTER__SERVER__SESSION__SECRET_KEY=session_secret_key

# Encrypt / Decrypt credentials data
SYNCMASTER__CRYPTO_KEY=UBgPTioFrtH2unlC4XFDiGf5sYfzbdSf_VgiUSaQc94=

Expand All @@ -30,6 +33,7 @@ SYNCMASTER__AUTH__KEYCLOAK_TOKEN_URL=http://keycloak:8080/realms/fastapi-realm/p
# Dummy Auth
SYNCMASTER__AUTH__PROVIDER=syncmaster.backend.providers.auth.dummy_provider.DummyAuthProvider
SYNCMASTER__AUTH__ACCESS_TOKEN__SECRET_KEY=bae1thahr8Iyaisai0kohvoh1aeg5quu
SYNCMASTER__AUTH__PROVIDER=syncmaster.backend.providers.auth.keycloak_provider.KeycloakAuthProvider

# RabbitMQ
SYNCMASTER__BROKER__URL=amqp://guest:guest@rabbitmq:5672/
Expand Down
3 changes: 3 additions & 0 deletions .env.local
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export SYNCMASTER__LOGGING__SETUP=True
export SYNCMASTER__LOGGING__PRESET=colored
export SYNCMASTER__LOG_URL_TEMPLATE="https://grafana.example.com?correlation_id={{ correlation_id }}&run_id={{ run.id }}"

# Session
export SYNCMASTER__SERVER__SESSION__SECRET_KEY=session_secret_key

# Encrypt / Decrypt credentials data
export SYNCMASTER__CRYPTO_KEY=UBgPTioFrtH2unlC4XFDiGf5sYfzbdSf_VgiUSaQc94=

Expand Down
2 changes: 1 addition & 1 deletion docs/backend/configuration/cors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ CORS settings

These settings used to control `CORS <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_ options.

.. autopydantic_model:: syncmaster.settings.server.cors.CORSSettings
.. autopydantic_model:: syncmaster.backend.settings.server.cors.CORSSettings
1 change: 1 addition & 0 deletions docs/backend/configuration/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Configuration
database
broker
logging
session
cors
debug
monitoring
Expand Down
2 changes: 1 addition & 1 deletion docs/backend/configuration/monitoring.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ REST API server provides the following endpoints with Prometheus compatible metr

These endpoints are enabled and configured using settings below:

.. autopydantic_model:: syncmaster.settings.server.monitoring.MonitoringSettings
.. autopydantic_model:: syncmaster.backend.settings.server.monitoring.MonitoringSettings
10 changes: 5 additions & 5 deletions docs/backend/configuration/openapi.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ OpenAPI settings

These settings used to control exposing OpenAPI.json and SwaggerUI/ReDoc endpoints.

.. autopydantic_model:: syncmaster.settings.server.openapi.OpenAPISettings
.. autopydantic_model:: syncmaster.settings.server.openapi.SwaggerSettings
.. autopydantic_model:: syncmaster.settings.server.openapi.RedocSettings
.. autopydantic_model:: syncmaster.settings.server.openapi.LogoSettings
.. autopydantic_model:: syncmaster.settings.server.openapi.FaviconSettings
.. autopydantic_model:: syncmaster.backend.settings.server.openapi.OpenAPISettings
.. autopydantic_model:: syncmaster.backend.settings.server.openapi.SwaggerSettings
.. autopydantic_model:: syncmaster.backend.settings.server.openapi.RedocSettings
.. autopydantic_model:: syncmaster.backend.settings.server.openapi.LogoSettings
.. autopydantic_model:: syncmaster.backend.settings.server.openapi.FaviconSettings
8 changes: 8 additions & 0 deletions docs/backend/configuration/session.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.. _backend-configuration-server-session:

Session settings
================

These settings used to control `Session <https://developer.mozilla.org/en-US/docs/Web/HTTP/Session>`_ options.

.. autopydantic_model:: syncmaster.backend.settings.server.session.SessionSettings
2 changes: 1 addition & 1 deletion docs/backend/configuration/static_files.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ Serving static files

These settings used to control serving static files by a server.

.. autopydantic_model:: syncmaster.settings.server.static_files.StaticFilesSettings
.. autopydantic_model:: syncmaster.backend.settings.server.static_files.StaticFilesSettings
2 changes: 1 addition & 1 deletion syncmaster/backend/middlewares/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ def apply_middlewares(
apply_request_id_middleware(application, settings.server.request_id)
apply_openapi_middleware(application, settings.server.openapi)
apply_static_files(application, settings.server.static_files)
apply_session_middleware(application)
apply_session_middleware(application, settings.server.session)

return application
12 changes: 8 additions & 4 deletions syncmaster/backend/middlewares/session.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
# SPDX-FileCopyrightText: 2023-2024 MTS PJSC
# SPDX-License-Identifier: Apache-2.0
import secrets

from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware

from syncmaster.backend.settings.server.session import SessionSettings

def apply_session_middleware(app: FastAPI) -> FastAPI:

def apply_session_middleware(app: FastAPI, settings: SessionSettings) -> FastAPI:
"""Add SessionMiddleware middleware to the application."""
secret_key = secrets.token_urlsafe(32)
app.add_middleware(SessionMiddleware, secret_key=secret_key)

app.add_middleware(
SessionMiddleware,
**settings.dict(),
)
return app
5 changes: 5 additions & 0 deletions syncmaster/backend/settings/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from syncmaster.backend.settings.server.monitoring import MonitoringSettings
from syncmaster.backend.settings.server.openapi import OpenAPISettings
from syncmaster.backend.settings.server.request_id import RequestIDSettings
from syncmaster.backend.settings.server.session import SessionSettings
from syncmaster.backend.settings.server.static_files import StaticFilesSettings


Expand Down Expand Up @@ -36,6 +37,10 @@ class ServerSettings(BaseModel):
request_id: RequestIDSettings = Field(
default_factory=RequestIDSettings,
)
session: SessionSettings = Field(
default_factory=SessionSettings, # type: ignore[arg-type]
description=":ref:`Session settings <backend-configuration-server-session>`",
)
cors: CORSSettings = Field(
default_factory=CORSSettings,
description=":ref:`CORS settings <backend-configuration-server-cors>`",
Expand Down
56 changes: 56 additions & 0 deletions syncmaster/backend/settings/server/session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# SPDX-FileCopyrightText: 2023-2024 MTS PJSC
# SPDX-License-Identifier: Apache-2.0


from pydantic import BaseModel, Field


class SessionSettings(BaseModel):
"""Session Middleware Settings.
See `SessionMiddleware <https://www.starlette.io/middleware/#sessionmiddleware>`_ documentation.
.. note::
You can pass here any extra option supported by ``SessionMiddleware``,
even if it is not mentioned in documentation.
Examples
--------
For development environment:
.. code-block:: bash
SYNCMASTER__SERVER__SESSION__SECRET_KEY=secret
SYNCMASTER__SERVER__SESSION__SESSION_COOKIE=custom_cookie_name
SYNCMASTER__SERVER__SESSION__MAX_AGE=None # cookie will last as long as the browser session
SYNCMASTER__SERVER__SESSION__SAME_SITE=strict
SYNCMASTER__SERVER__SESSION__HTTPS_ONLY=True
SYNCMASTER__SERVER__SESSION__DOMAIN=example.com
For production environment:
.. code-block:: bash
SYNCMASTER__SERVER__SESSION__SECRET_KEY=secret
SYNCMASTER__SERVER__SESSION__HTTPS_ONLY=True
"""

secret_key: str = Field(description="A random string for signing cookies.")
session_cookie: str | None = Field(default="session", description="Name of the session cookie.")
max_age: int | None = Field(default=1209600, description="Session expiry time in seconds. Defaults to 2 weeks.")
same_site: str | None = Field(
default="lax",
description="Prevents cookie from being sent with cross-site requests.",
)
path: str | None = Field(default="/", description="Path to restrict session cookie access.")
https_only: bool = Field(default=False, description="Secure flag for HTTPS-only access.")
domain: str | None = Field(
default=None,
description="Domain for sharing cookies between subdomains or cross-domains.",
)

class Config:
extra = "allow"

0 comments on commit 0a41541

Please sign in to comment.