Complete SSO role mapping and offline StateCorp release tooling
Some checks failed
State Corp Backend CI/CD / Quality gate (push) Failing after 9m34s
State Corp Backend CI/CD / Build linux/amd64 images once (push) Has been skipped
State Corp Backend CI/CD / Release dev (push) Has been skipped
State Corp Backend CI/CD / Refresh and release internal main (push) Has been skipped
State Corp Backend CI/CD / Release customer main (push) Has been skipped
Some checks failed
State Corp Backend CI/CD / Quality gate (push) Failing after 9m34s
State Corp Backend CI/CD / Build linux/amd64 images once (push) Has been skipped
State Corp Backend CI/CD / Release dev (push) Has been skipped
State Corp Backend CI/CD / Refresh and release internal main (push) Has been skipped
State Corp Backend CI/CD / Release customer main (push) Has been skipped
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("user", "0009_ssoidentity")]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="ssoidentity",
|
||||
name="external_groups",
|
||||
field=models.JSONField(default=list, verbose_name="external groups"),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="ssoidentity",
|
||||
name="okpo",
|
||||
field=models.CharField(blank=True, max_length=32, verbose_name="OKPO"),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="ssoidentity",
|
||||
name="user_type_code",
|
||||
field=models.CharField(blank=True, max_length=64, verbose_name="user type code"),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="ssoidentity",
|
||||
name="default_organisation",
|
||||
field=models.JSONField(blank=True, null=True, verbose_name="default organisation"),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="ssoidentity",
|
||||
name="is_integrated_structure",
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="ssoidentity",
|
||||
name="ex_loop",
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="ssoidentity",
|
||||
name="role_managed_by_sso",
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
@@ -122,6 +122,15 @@ class SsoIdentity(models.Model):
|
||||
)
|
||||
issuer = models.CharField(_("issuer"), max_length=64)
|
||||
subject = models.CharField(_("external user id"), max_length=255)
|
||||
external_groups = models.JSONField(_("external groups"), default=list)
|
||||
okpo = models.CharField(_("OKPO"), max_length=32, blank=True)
|
||||
user_type_code = models.CharField(_("user type code"), max_length=64, blank=True)
|
||||
default_organisation = models.JSONField(
|
||||
_("default organisation"), null=True, blank=True
|
||||
)
|
||||
is_integrated_structure = models.BooleanField(default=False)
|
||||
ex_loop = models.BooleanField(default=False)
|
||||
role_managed_by_sso = models.BooleanField(default=False)
|
||||
last_authenticated_at = models.DateTimeField(_("last authenticated at"))
|
||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
||||
updated_at = models.DateTimeField(_("updated at"), auto_now=True)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
@@ -17,6 +18,7 @@ from django.utils import timezone
|
||||
from jwt import InvalidTokenError
|
||||
|
||||
from .models import SsoIdentity
|
||||
from .services import UserService
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
@@ -36,6 +38,50 @@ class SsoClaims:
|
||||
last_name: str
|
||||
jti: str
|
||||
expires_at: int
|
||||
groups: tuple[str, ...]
|
||||
okpo: str
|
||||
user_type_code: str
|
||||
default_organisation: str | dict | None
|
||||
is_integrated_structure: bool
|
||||
ex_loop: bool
|
||||
|
||||
|
||||
def _optional_text(payload: dict, key: str, *, max_length: int) -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return ""
|
||||
if not isinstance(value, str) or len(value) > max_length:
|
||||
raise SsoAuthenticationError("Некорректные данные SSO-пользователя.")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _optional_boolean(payload: dict, key: str) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return False
|
||||
if not isinstance(value, bool):
|
||||
raise SsoAuthenticationError("Некорректные данные SSO-пользователя.")
|
||||
return value
|
||||
|
||||
|
||||
def _role_for_groups(groups: tuple[str, ...]) -> str:
|
||||
try:
|
||||
mapping = json.loads(settings.SSO_GROUP_ROLE_MAP_JSON)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise SsoAuthenticationError("Некорректная конфигурация ролей SSO.") from exc
|
||||
if not isinstance(mapping, dict) or any(
|
||||
not isinstance(group, str)
|
||||
or not group.strip()
|
||||
or role not in (UserService.ROLE_USER, UserService.ROLE_ADMIN)
|
||||
for group, role in mapping.items()
|
||||
):
|
||||
raise SsoAuthenticationError("Некорректная конфигурация ролей SSO.")
|
||||
mapped = {mapping[group] for group in groups if group in mapping}
|
||||
return (
|
||||
UserService.ROLE_ADMIN
|
||||
if UserService.ROLE_ADMIN in mapped
|
||||
else UserService.ROLE_USER
|
||||
)
|
||||
|
||||
|
||||
def _load_public_key():
|
||||
@@ -102,6 +148,27 @@ def _validate_token_lifetime(payload: dict) -> tuple[int, int]:
|
||||
return issued_at, expires_at
|
||||
|
||||
|
||||
def _normalized_groups(payload: dict) -> tuple[str, ...]:
|
||||
groups = payload.get("groups", [])
|
||||
if not isinstance(groups, list) or len(groups) > 100 or any(
|
||||
not isinstance(group, str) or not group.strip() or len(group) > 255
|
||||
for group in groups
|
||||
):
|
||||
raise SsoAuthenticationError("Некорректные группы SSO-пользователя.")
|
||||
return tuple(dict.fromkeys(group.strip() for group in groups))
|
||||
|
||||
|
||||
def _default_organisation(payload: dict) -> str | dict | None:
|
||||
organisation = payload.get("default_organisation")
|
||||
if organisation is not None and not isinstance(organisation, str | dict):
|
||||
raise SsoAuthenticationError("Некорректная организация SSO-пользователя.")
|
||||
if isinstance(organisation, str) and len(organisation) > 255:
|
||||
raise SsoAuthenticationError("Некорректная организация SSO-пользователя.")
|
||||
if isinstance(organisation, dict) and len(json.dumps(organisation)) > 4096:
|
||||
raise SsoAuthenticationError("Некорректная организация SSO-пользователя.")
|
||||
return organisation
|
||||
|
||||
|
||||
def verify_sso_token(encoded_token: str) -> SsoClaims:
|
||||
"""Проверяет ES256 SSO JWT и возвращает только нужные локальному сервису claims."""
|
||||
payload = _decode_sso_payload(encoded_token)
|
||||
@@ -146,6 +213,12 @@ def verify_sso_token(encoded_token: str) -> SsoClaims:
|
||||
last_name=str(payload.get("last_name") or ""),
|
||||
jti=jti,
|
||||
expires_at=expires_at,
|
||||
groups=_normalized_groups(payload),
|
||||
okpo=_optional_text(payload, "okpo", max_length=32),
|
||||
user_type_code=_optional_text(payload, "user_type_code", max_length=64),
|
||||
default_organisation=_default_organisation(payload),
|
||||
is_integrated_structure=_optional_boolean(payload, "is_integrated_structure"),
|
||||
ex_loop=_optional_boolean(payload, "ex_loop"),
|
||||
)
|
||||
|
||||
|
||||
@@ -179,6 +252,7 @@ def provision_sso_user(claims: SsoClaims):
|
||||
.first()
|
||||
)
|
||||
|
||||
is_new_user = False
|
||||
if identity is not None:
|
||||
user = identity.user
|
||||
if not user.is_active:
|
||||
@@ -203,12 +277,14 @@ def provision_sso_user(claims: SsoClaims):
|
||||
user = User(username=claims.username, email=claims.email, is_verified=True)
|
||||
user.set_unusable_password()
|
||||
user.save()
|
||||
is_new_user = True
|
||||
|
||||
identity = SsoIdentity.objects.create(
|
||||
user=user,
|
||||
issuer=claims.issuer,
|
||||
subject=claims.subject,
|
||||
last_authenticated_at=timezone.now(),
|
||||
role_managed_by_sso=is_new_user or settings.SSO_MANAGE_LINKED_USER_ROLES,
|
||||
)
|
||||
|
||||
user.username = claims.username
|
||||
@@ -221,5 +297,21 @@ def provision_sso_user(claims: SsoClaims):
|
||||
profile.last_name = claims.last_name
|
||||
profile.save(update_fields=["first_name", "mid_name", "last_name", "updated_at"])
|
||||
identity.last_authenticated_at = timezone.now()
|
||||
identity.save(update_fields=["last_authenticated_at", "updated_at"])
|
||||
identity.external_groups = list(claims.groups)
|
||||
identity.okpo = claims.okpo
|
||||
identity.user_type_code = claims.user_type_code
|
||||
identity.default_organisation = claims.default_organisation
|
||||
identity.is_integrated_structure = claims.is_integrated_structure
|
||||
identity.ex_loop = claims.ex_loop
|
||||
if settings.SSO_MANAGE_LINKED_USER_ROLES:
|
||||
identity.role_managed_by_sso = True
|
||||
identity.save(
|
||||
update_fields=[
|
||||
"last_authenticated_at", "external_groups", "okpo", "user_type_code",
|
||||
"default_organisation", "is_integrated_structure", "ex_loop",
|
||||
"role_managed_by_sso", "updated_at",
|
||||
]
|
||||
)
|
||||
if identity.role_managed_by_sso:
|
||||
UserService.assign_role(user, _role_for_groups(claims.groups))
|
||||
return user
|
||||
|
||||
Reference in New Issue
Block a user