Skip to content

Commit

Permalink
Merge pull request #443 from TeskaLabs/refactoring/session-to-models
Browse files Browse the repository at this point in the history
Rename SessionAdapter to Session and move to seacatauth.models
  • Loading branch information
byewokko authored Feb 25, 2025
2 parents fb116f6 + 00cdb95 commit 385824d
Show file tree
Hide file tree
Showing 16 changed files with 177 additions and 171 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## v25.05

### Pre-releases
- v25.05-alpha6
- v25.05-alpha5
- v25.05-alpha4
- v25.05-alpha3
Expand All @@ -18,6 +19,7 @@
- Provisioning service initialization uses system Session object (#439, v25.05-alpha2)

### Refactoring
- Rename SessionAdapter to Session and move to seacatauth.models (#443, v25.05-alpha6)
- Refactor communication module, merge message builders into communication providers (#442, v25.05-alpha5)
- Remove session adapter's dependency on session service (#441, v25.05-alpha4)

Expand Down
4 changes: 2 additions & 2 deletions seacatauth/authn/m2m.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from .. import AuditLogger, generic
from ..generic import nginx_introspection
from ..session import SessionAdapter
from ..models import Session

#

Expand Down Expand Up @@ -82,7 +82,7 @@ async def _authenticate_request(self, request, client_id):

# Find session object
try:
session = await self.SessionService.get_by(SessionAdapter.FN.Credentials.Id, credentials_id)
session = await self.SessionService.get_by(Session.FN.Credentials.Id, credentials_id)
except KeyError:
session = None

Expand Down
9 changes: 4 additions & 5 deletions seacatauth/authn/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@
from .. import exceptions, generic, AuditLogger
from ..last_activity import EventCode
from ..authz import build_credentials_authz

from ..models import Session
from ..session import (
credentials_session_builder,
authz_session_builder,
authentication_session_builder,
available_factors_session_builder,
SessionAdapter,
)

from ..events import EventTypes
Expand Down Expand Up @@ -327,7 +326,7 @@ async def authenticate(self, login_session, request_data):
break
return authenticated

async def login(self, login_session, root_session: SessionAdapter | None = None, from_info: list = None):
async def login(self, login_session, root_session: Session | None = None, from_info: list = None):
"""
Build and create a root session
"""
Expand Down Expand Up @@ -437,8 +436,8 @@ async def create_impersonated_session(self, impersonator_session, target_cid: st
},
)
session_builders.append((
(SessionAdapter.FN.Authentication.ImpersonatorCredentialsId, impersonator_cid),
(SessionAdapter.FN.Authentication.ImpersonatorSessionId, impersonator_session.SessionId),
(Session.FN.Authentication.ImpersonatorCredentialsId, impersonator_cid),
(Session.FN.Authentication.ImpersonatorSessionId, impersonator_session.SessionId),
))

session = await self.SessionService.create_session(
Expand Down
2 changes: 1 addition & 1 deletion seacatauth/batman/grafana.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import asab
import asab.config

from seacatauth.authz import build_credentials_authz
from ..authz import build_credentials_authz

#

Expand Down
8 changes: 5 additions & 3 deletions seacatauth/cookie/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
import asab.exceptions

from .. import exceptions
from ..session.adapter import SessionAdapter, CookieData
from ..models import Session

from ..models.session import CookieData
from ..session.builders import cookie_session_builder
from .. import AuditLogger

Expand Down Expand Up @@ -117,7 +119,7 @@ async def get_session_by_session_cookie_value(self, cookie_value: str):
"Cookie value is not base64", query={"cookie_value": cookie_value}) from e

try:
session = await self.SessionService.get_by(SessionAdapter.FN.Cookie.Id, cookie_value)
session = await self.SessionService.get_by(Session.FN.Cookie.Id, cookie_value)
except KeyError as e:
raise exceptions.SessionNotFoundError(
"Session not found", query={"cookie_value": cookie_value}) from e
Expand Down Expand Up @@ -204,7 +206,7 @@ async def create_anonymous_cookie_client_session(
return session


async def extend_session_expiration(self, session: SessionAdapter, client: dict = None):
async def extend_session_expiration(self, session: Session, client: dict = None):
expiration = client.get("session_expiration") if client else None
if expiration:
expiration = datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=expiration)
Expand Down
12 changes: 6 additions & 6 deletions seacatauth/credentials/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .policy import CredentialsPolicy
from .providers.abc import CredentialsProviderABC, EditableCredentialsProviderABC
from .. import AuditLogger, generic, exceptions
from ..session import SessionAdapter
from ..models import Session

#

Expand Down Expand Up @@ -239,7 +239,7 @@ async def _role_filter(self, credentials_id: str, role_ids: typing.Iterable):
return False


async def list(self, session: SessionAdapter, search_params: generic.SearchParams, try_global_search: bool = False):
async def list(self, session: Session, search_params: generic.SearchParams, try_global_search: bool = False):
"""
List credentials that are members of currently authorized tenants.
Global_search lists all credentials, regardless of tenants, but this requires superuser authorization.
Expand Down Expand Up @@ -346,7 +346,7 @@ def create_dict_provider(self, provider_id):
self.register_provider(provider)


async def create_credentials(self, provider_id: str, credentials_data: dict, session: SessionAdapter = None):
async def create_credentials(self, provider_id: str, credentials_data: dict, session: Session = None):
# Record the requester's ID for logging purposes
agent_cid = session.Credentials.Id if session is not None else None

Expand Down Expand Up @@ -409,7 +409,7 @@ async def create_credentials(self, provider_id: str, credentials_data: dict, ses


# TODO: Implement editing for M2M credentials
async def update_credentials(self, credentials_id: str, update_dict: dict, session: SessionAdapter = None):
async def update_credentials(self, credentials_id: str, update_dict: dict, session: Session = None):
"""
Validate the input data in the update dict according to active policies
and update credentials in the respective provider.
Expand Down Expand Up @@ -649,7 +649,7 @@ async def can_access_credentials(self, session, credentials_id: str) -> bool:


def _authorize_searched_tenants(
session: SessionAdapter,
session: Session,
search_params: generic.SearchParams,
try_global_search: bool = False
) -> typing.Optional[typing.Iterable[str]]:
Expand Down Expand Up @@ -685,7 +685,7 @@ def _authorize_searched_tenants(


def _authorize_searched_roles(
session: SessionAdapter,
session: Session,
search_params: generic.SearchParams
) -> typing.Optional[typing.Iterable[str]]:
"""
Expand Down
2 changes: 1 addition & 1 deletion seacatauth/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import aiohttp.web
import asab

from seacatauth import exceptions
from . import exceptions

#

Expand Down
5 changes: 5 additions & 0 deletions seacatauth/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from .session import Session

__all__ = [
"Session",
]
64 changes: 32 additions & 32 deletions seacatauth/session/adapter.py → seacatauth/models/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class BatmanData:
Token: typing.Optional[str]


class SessionAdapter:
class Session:
"""
Light object that represent a momentary view on the persisted session
"""
Expand Down Expand Up @@ -438,44 +438,44 @@ def _deserialize_batman_data(cls, session_dict):

def rest_get(session_dict):
data = {
"_id": session_dict.get(SessionAdapter.FN.SessionId),
"_c": session_dict.get(SessionAdapter.FN.CreatedAt),
"_m": session_dict.get(SessionAdapter.FN.ModifiedAt),
"_v": session_dict.get(SessionAdapter.FN.Version),
"type": session_dict.get(SessionAdapter.FN.Session.Type),
"expiration": session_dict.get(SessionAdapter.FN.Session.Expiration),
"max_expiration": session_dict.get(SessionAdapter.FN.Session.MaxExpiration),
"credentials_id": session_dict.get(SessionAdapter.FN.Credentials.Id),
"authn_time": session_dict.get(SessionAdapter.FN.Authentication.AuthnTime),
"login_descriptor": session_dict.get(SessionAdapter.FN.Authentication.LoginDescriptor),
"login_factors": session_dict.get(SessionAdapter.FN.Authentication.LoginFactors),
"tenants": session_dict.get(SessionAdapter.FN.Authorization.AssignedTenants),
"resources": session_dict.get(SessionAdapter.FN.Authorization.Authz),
"track_id": session_dict.get(SessionAdapter.FN.Session.TrackId),
"_id": session_dict.get(Session.FN.SessionId),
"_c": session_dict.get(Session.FN.CreatedAt),
"_m": session_dict.get(Session.FN.ModifiedAt),
"_v": session_dict.get(Session.FN.Version),
"type": session_dict.get(Session.FN.Session.Type),
"expiration": session_dict.get(Session.FN.Session.Expiration),
"max_expiration": session_dict.get(Session.FN.Session.MaxExpiration),
"credentials_id": session_dict.get(Session.FN.Credentials.Id),
"authn_time": session_dict.get(Session.FN.Authentication.AuthnTime),
"login_descriptor": session_dict.get(Session.FN.Authentication.LoginDescriptor),
"login_factors": session_dict.get(Session.FN.Authentication.LoginFactors),
"tenants": session_dict.get(Session.FN.Authorization.AssignedTenants),
"resources": session_dict.get(Session.FN.Authorization.Authz),
"track_id": session_dict.get(Session.FN.Session.TrackId),
}
psid = session_dict.get(SessionAdapter.FN.Session.ParentSessionId)
psid = session_dict.get(Session.FN.Session.ParentSessionId)
if psid is not None:
data["parent_session_id"] = psid

client_id = session_dict.get(SessionAdapter.FN.OAuth2.ClientId)
client_id = session_dict.get(Session.FN.OAuth2.ClientId)
if client_id is not None:
data["client_id"] = client_id
scope = session_dict.get(SessionAdapter.FN.OAuth2.Scope)
scope = session_dict.get(Session.FN.OAuth2.Scope)
if scope is not None:
data["scope"] = scope

if session_dict.get(SessionAdapter.FN.OAuth2.AccessToken) is not None:
if session_dict.get(Session.FN.OAuth2.AccessToken) is not None:
data["access_token"] = True
if session_dict.get(SessionAdapter.FN.Cookie.Id) is not None:
if session_dict.get(Session.FN.Cookie.Id) is not None:
data["cookie"] = True

if session_dict.get(SessionAdapter.FN.Authentication.IsAnonymous) is True:
if session_dict.get(Session.FN.Authentication.IsAnonymous) is True:
data["anonymous"] = True

impersonator_cid = session_dict.get(SessionAdapter.FN.Authentication.ImpersonatorCredentialsId)
impersonator_cid = session_dict.get(Session.FN.Authentication.ImpersonatorCredentialsId)
if impersonator_cid is not None:
data["impersonator_cid"] = impersonator_cid
impersonator_sid = session_dict.get(SessionAdapter.FN.Authentication.ImpersonatorSessionId)
impersonator_sid = session_dict.get(Session.FN.Authentication.ImpersonatorSessionId)
if impersonator_sid is not None:
data["impersonator_sid"] = impersonator_sid

Expand All @@ -484,15 +484,15 @@ def rest_get(session_dict):

# TODO: Use ASAB Authorization, this is a temporary solution.
def build_system_session(session_service, session_id):
session = SessionAdapter({
SessionAdapter.FN.SessionId: session_id,
SessionAdapter.FN.Version: 0,
SessionAdapter.FN.CreatedAt: datetime.datetime.now(datetime.UTC),
SessionAdapter.FN.ModifiedAt: None,
SessionAdapter.FN.Session.Type: "SYSTEM",
SessionAdapter.FN.Session.Expiration: datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=30),
SessionAdapter.FN.Authorization.Authz: {"*": ["authz:superuser"]},
SessionAdapter.FN.Credentials.Id: "SYSTEM",
session = Session({
Session.FN.SessionId: session_id,
Session.FN.Version: 0,
Session.FN.CreatedAt: datetime.datetime.now(datetime.UTC),
Session.FN.ModifiedAt: None,
Session.FN.Session.Type: "SYSTEM",
Session.FN.Session.Expiration: datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=30),
Session.FN.Authorization.Authz: {"*": ["authz:superuser"]},
Session.FN.Credentials.Id: "SYSTEM",
})
AuditLogger.log(asab.LOG_NOTICE, "Created new system session.", struct_data={"session_id": session.SessionId})
return session
16 changes: 8 additions & 8 deletions seacatauth/openidconnect/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import jwcrypto.jws

from ..generic import update_url_query_params
from ..session.adapter import SessionAdapter
from ..models import Session
from .. import exceptions
from . import pkce
from ..authz import build_credentials_authz
Expand Down Expand Up @@ -105,10 +105,10 @@ def __init__(self, app, service_name="seacatauth.OpenIdConnectService"):

async def refresh_session(
self,
session: SessionAdapter,
session: Session,
expires_at: typing.Optional[datetime.datetime] = None,
requested_scope: typing.Optional[typing.Iterable] = None,
) -> SessionAdapter:
) -> Session:
"""
Update/rebuild the session according to its authorization parameters
Expand Down Expand Up @@ -166,7 +166,7 @@ async def refresh_session(
)

if expires_at:
session_builders.append(((SessionAdapter.FN.Session.Expiration, expires_at),))
session_builders.append(((Session.FN.Session.Expiration, expires_at),))

session = await self.SessionService.update_session(session.SessionId, session_builders)

Expand Down Expand Up @@ -418,7 +418,7 @@ async def revoke_token(self, token, token_type_hint=None):
Invalidate a valid token. Currently only access_token type is supported.
"""
try:
session: SessionAdapter = await self.get_session_by_access_token(token)
session: Session = await self.get_session_by_access_token(token)
except exceptions.SessionNotFoundError:
return

Expand Down Expand Up @@ -480,7 +480,7 @@ async def calculate_token_expiration(


async def create_authorization_code(
self, session: SessionAdapter,
self, session: Session,
code_challenge: str | None = None,
code_challenge_method: str | None = None,
) -> str:
Expand Down Expand Up @@ -521,7 +521,7 @@ async def create_authorization_code(

async def create_access_token(
self,
session: SessionAdapter,
session: Session,
expires_at: datetime.datetime,
) -> str:
"""
Expand All @@ -546,7 +546,7 @@ async def create_access_token(

async def create_refresh_token(
self,
session: SessionAdapter,
session: Session,
expires_at: datetime.datetime,
) -> str:
"""
Expand Down
2 changes: 1 addition & 1 deletion seacatauth/provisioning/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from ..client.service import CLIENT_TEMPLATES
from ..generic import SessionContext
from ..session.adapter import build_system_session
from ..models import build_system_session

#

Expand Down
3 changes: 0 additions & 3 deletions seacatauth/session/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from .service import SessionService
from .handler import SessionHandler
from .adapter import SessionAdapter

from .builders import credentials_session_builder
from .builders import authz_session_builder
from .builders import cookie_session_builder
Expand All @@ -12,7 +10,6 @@
__all__ = [
"SessionService",
"SessionHandler",
"SessionAdapter",
"credentials_session_builder",
"authz_session_builder",
"cookie_session_builder",
Expand Down
Loading

0 comments on commit 385824d

Please sign in to comment.