authentik.lib.sync.outgoing.base
Basic outgoing sync Client
1"""Basic outgoing sync Client""" 2 3from collections.abc import Generator 4from contextlib import contextmanager 5from datetime import timedelta 6from enum import StrEnum 7from typing import TYPE_CHECKING 8 9import pglock 10from deepmerge import always_merger 11from django.db import DatabaseError, connection 12from structlog.stdlib import get_logger 13 14from authentik.core.expression.exceptions import ( 15 PropertyMappingExpressionException, 16) 17from authentik.events.models import Event, EventAction 18from authentik.lib.config import advisory_lock_db_alias 19from authentik.lib.expression.exceptions import ControlFlowException 20from authentik.lib.sync.mapper import PropertyMappingManager 21from authentik.lib.sync.outgoing.exceptions import ( 22 NotFoundSyncException, 23 ObjectLockTimeout, 24 StopSync, 25) 26 27if TYPE_CHECKING: 28 from django.db.models import Model 29 30 from authentik.lib.sync.outgoing.models import OutgoingSyncProvider 31 32 33class Direction(StrEnum): 34 add = "add" 35 remove = "remove" 36 37 38SAFE_METHODS = [ 39 "GET", 40 "HEAD", 41 "OPTIONS", 42 "TRACE", 43] 44 45OBJECT_LOCK_TIMEOUT = timedelta(seconds=30) 46 47 48class BaseOutgoingSyncClient[ 49 TModel: "Model", 50 TConnection: "Model", 51 TSchema: dict, 52 TProvider: "OutgoingSyncProvider", 53]: 54 """Basic Outgoing sync client Client""" 55 56 provider: TProvider 57 connection_type: type[TConnection] 58 connection_type_query: str 59 mapper: PropertyMappingManager 60 61 can_discover = False 62 63 def __init__(self, provider: TProvider): 64 self.logger = get_logger().bind(provider=provider.name) 65 self.provider = provider 66 67 def create(self, obj: TModel) -> TConnection: 68 """Create object in remote destination""" 69 raise NotImplementedError() 70 71 def update(self, obj: TModel, connection: TConnection): 72 """Update object in remote destination""" 73 raise NotImplementedError() 74 75 @contextmanager 76 def object_lock(self, obj: TModel) -> Generator[None]: 77 """Serialize remote operations for one object and provider.""" 78 lock_id = ( 79 f"goauthentik.io/{connection.schema_name}/providers/outgoing-sync/" 80 f"{self.provider._meta.label_lower}/{self.provider.pk}/" 81 f"{obj._meta.label_lower}/{obj.pk}" 82 ) 83 with pglock.advisory( 84 lock_id=lock_id, 85 timeout=OBJECT_LOCK_TIMEOUT, 86 side_effect=pglock.Return, 87 using=advisory_lock_db_alias(), 88 ) as lock_acquired: 89 if not lock_acquired: 90 raise ObjectLockTimeout(lock_id) 91 yield 92 93 def write_locked(self, obj: TModel) -> tuple[TConnection, bool]: 94 """Write an object to the destination while holding its object lock.""" 95 with self.object_lock(obj): 96 return self.write(obj) 97 98 def write(self, obj: TModel) -> tuple[TConnection, bool]: 99 """Write an object while the caller holds its object lock.""" 100 connection = self.connection_type.objects.filter( 101 provider=self.provider, **{self.connection_type_query: obj} 102 ).first() 103 try: 104 if not connection: 105 connection = self.create(obj) 106 return connection, True 107 try: 108 self.update(obj, connection) 109 return connection, False 110 except NotFoundSyncException: 111 connection.delete() 112 connection = self.create(obj) 113 return connection, True 114 except DatabaseError as exc: 115 self.logger.warning("Failed to write object", obj=obj, exc=exc) 116 if connection: 117 connection.delete() 118 return None, False 119 120 def sync_group_membership(self, obj: TModel, action: Direction, users_set: set[int]) -> None: 121 """Update group membership while holding the same lock used by writes.""" 122 with self.object_lock(obj): 123 self.update_group(obj, action, users_set) 124 125 def update_group(self, obj: TModel, action: Direction, users_set: set[int]) -> None: 126 """Update group membership in the remote destination.""" 127 raise NotImplementedError() 128 129 def delete(self, identifier: str): 130 """Delete object from destination""" 131 raise NotImplementedError() 132 133 def to_schema(self, obj: TModel, connection: TConnection | None, **defaults) -> TSchema: 134 """Convert object to destination schema""" 135 raw_final_object = {} 136 try: 137 eval_kwargs = { 138 "request": None, 139 "provider": self.provider, 140 "connection": connection, 141 obj._meta.model_name: obj, 142 } 143 eval_kwargs.setdefault("user", None) 144 for value in self.mapper.iter_eval(**eval_kwargs): 145 always_merger.merge(raw_final_object, value) 146 except ControlFlowException as exc: 147 raise exc from exc 148 except PropertyMappingExpressionException as exc: 149 # Value error can be raised when assigning invalid data to an attribute 150 Event.new( 151 EventAction.CONFIGURATION_ERROR, 152 message="Failed to evaluate property-mapping", 153 mapping=exc.mapping, 154 ).with_exception(exc).save() 155 raise StopSync(exc, obj, exc.mapping) from exc 156 if not raw_final_object: 157 raise StopSync(ValueError("No mappings configured"), obj) 158 for key, value in defaults.items(): 159 raw_final_object.setdefault(key, value) 160 return raw_final_object 161 162 def discover(self): 163 """Optional method. Can be used to implement a "discovery" where 164 upon creation of this provider, this function will be called and can 165 pre-link any users/groups in the remote system with the respective 166 object in authentik based on a common identifier""" 167 raise NotImplementedError() 168 169 def update_single_attribute(self, connection: TConnection): 170 """Update connection attributes on a connection object, when the connection 171 is manually created""" 172 raise NotImplementedError
49class BaseOutgoingSyncClient[ 50 TModel: "Model", 51 TConnection: "Model", 52 TSchema: dict, 53 TProvider: "OutgoingSyncProvider", 54]: 55 """Basic Outgoing sync client Client""" 56 57 provider: TProvider 58 connection_type: type[TConnection] 59 connection_type_query: str 60 mapper: PropertyMappingManager 61 62 can_discover = False 63 64 def __init__(self, provider: TProvider): 65 self.logger = get_logger().bind(provider=provider.name) 66 self.provider = provider 67 68 def create(self, obj: TModel) -> TConnection: 69 """Create object in remote destination""" 70 raise NotImplementedError() 71 72 def update(self, obj: TModel, connection: TConnection): 73 """Update object in remote destination""" 74 raise NotImplementedError() 75 76 @contextmanager 77 def object_lock(self, obj: TModel) -> Generator[None]: 78 """Serialize remote operations for one object and provider.""" 79 lock_id = ( 80 f"goauthentik.io/{connection.schema_name}/providers/outgoing-sync/" 81 f"{self.provider._meta.label_lower}/{self.provider.pk}/" 82 f"{obj._meta.label_lower}/{obj.pk}" 83 ) 84 with pglock.advisory( 85 lock_id=lock_id, 86 timeout=OBJECT_LOCK_TIMEOUT, 87 side_effect=pglock.Return, 88 using=advisory_lock_db_alias(), 89 ) as lock_acquired: 90 if not lock_acquired: 91 raise ObjectLockTimeout(lock_id) 92 yield 93 94 def write_locked(self, obj: TModel) -> tuple[TConnection, bool]: 95 """Write an object to the destination while holding its object lock.""" 96 with self.object_lock(obj): 97 return self.write(obj) 98 99 def write(self, obj: TModel) -> tuple[TConnection, bool]: 100 """Write an object while the caller holds its object lock.""" 101 connection = self.connection_type.objects.filter( 102 provider=self.provider, **{self.connection_type_query: obj} 103 ).first() 104 try: 105 if not connection: 106 connection = self.create(obj) 107 return connection, True 108 try: 109 self.update(obj, connection) 110 return connection, False 111 except NotFoundSyncException: 112 connection.delete() 113 connection = self.create(obj) 114 return connection, True 115 except DatabaseError as exc: 116 self.logger.warning("Failed to write object", obj=obj, exc=exc) 117 if connection: 118 connection.delete() 119 return None, False 120 121 def sync_group_membership(self, obj: TModel, action: Direction, users_set: set[int]) -> None: 122 """Update group membership while holding the same lock used by writes.""" 123 with self.object_lock(obj): 124 self.update_group(obj, action, users_set) 125 126 def update_group(self, obj: TModel, action: Direction, users_set: set[int]) -> None: 127 """Update group membership in the remote destination.""" 128 raise NotImplementedError() 129 130 def delete(self, identifier: str): 131 """Delete object from destination""" 132 raise NotImplementedError() 133 134 def to_schema(self, obj: TModel, connection: TConnection | None, **defaults) -> TSchema: 135 """Convert object to destination schema""" 136 raw_final_object = {} 137 try: 138 eval_kwargs = { 139 "request": None, 140 "provider": self.provider, 141 "connection": connection, 142 obj._meta.model_name: obj, 143 } 144 eval_kwargs.setdefault("user", None) 145 for value in self.mapper.iter_eval(**eval_kwargs): 146 always_merger.merge(raw_final_object, value) 147 except ControlFlowException as exc: 148 raise exc from exc 149 except PropertyMappingExpressionException as exc: 150 # Value error can be raised when assigning invalid data to an attribute 151 Event.new( 152 EventAction.CONFIGURATION_ERROR, 153 message="Failed to evaluate property-mapping", 154 mapping=exc.mapping, 155 ).with_exception(exc).save() 156 raise StopSync(exc, obj, exc.mapping) from exc 157 if not raw_final_object: 158 raise StopSync(ValueError("No mappings configured"), obj) 159 for key, value in defaults.items(): 160 raw_final_object.setdefault(key, value) 161 return raw_final_object 162 163 def discover(self): 164 """Optional method. Can be used to implement a "discovery" where 165 upon creation of this provider, this function will be called and can 166 pre-link any users/groups in the remote system with the respective 167 object in authentik based on a common identifier""" 168 raise NotImplementedError() 169 170 def update_single_attribute(self, connection: TConnection): 171 """Update connection attributes on a connection object, when the connection 172 is manually created""" 173 raise NotImplementedError
Basic Outgoing sync client Client
68 def create(self, obj: TModel) -> TConnection: 69 """Create object in remote destination""" 70 raise NotImplementedError()
Create object in remote destination
72 def update(self, obj: TModel, connection: TConnection): 73 """Update object in remote destination""" 74 raise NotImplementedError()
Update object in remote destination
76 @contextmanager 77 def object_lock(self, obj: TModel) -> Generator[None]: 78 """Serialize remote operations for one object and provider.""" 79 lock_id = ( 80 f"goauthentik.io/{connection.schema_name}/providers/outgoing-sync/" 81 f"{self.provider._meta.label_lower}/{self.provider.pk}/" 82 f"{obj._meta.label_lower}/{obj.pk}" 83 ) 84 with pglock.advisory( 85 lock_id=lock_id, 86 timeout=OBJECT_LOCK_TIMEOUT, 87 side_effect=pglock.Return, 88 using=advisory_lock_db_alias(), 89 ) as lock_acquired: 90 if not lock_acquired: 91 raise ObjectLockTimeout(lock_id) 92 yield
Serialize remote operations for one object and provider.
94 def write_locked(self, obj: TModel) -> tuple[TConnection, bool]: 95 """Write an object to the destination while holding its object lock.""" 96 with self.object_lock(obj): 97 return self.write(obj)
Write an object to the destination while holding its object lock.
99 def write(self, obj: TModel) -> tuple[TConnection, bool]: 100 """Write an object while the caller holds its object lock.""" 101 connection = self.connection_type.objects.filter( 102 provider=self.provider, **{self.connection_type_query: obj} 103 ).first() 104 try: 105 if not connection: 106 connection = self.create(obj) 107 return connection, True 108 try: 109 self.update(obj, connection) 110 return connection, False 111 except NotFoundSyncException: 112 connection.delete() 113 connection = self.create(obj) 114 return connection, True 115 except DatabaseError as exc: 116 self.logger.warning("Failed to write object", obj=obj, exc=exc) 117 if connection: 118 connection.delete() 119 return None, False
Write an object while the caller holds its object lock.
121 def sync_group_membership(self, obj: TModel, action: Direction, users_set: set[int]) -> None: 122 """Update group membership while holding the same lock used by writes.""" 123 with self.object_lock(obj): 124 self.update_group(obj, action, users_set)
Update group membership while holding the same lock used by writes.
126 def update_group(self, obj: TModel, action: Direction, users_set: set[int]) -> None: 127 """Update group membership in the remote destination.""" 128 raise NotImplementedError()
Update group membership in the remote destination.
130 def delete(self, identifier: str): 131 """Delete object from destination""" 132 raise NotImplementedError()
Delete object from destination
134 def to_schema(self, obj: TModel, connection: TConnection | None, **defaults) -> TSchema: 135 """Convert object to destination schema""" 136 raw_final_object = {} 137 try: 138 eval_kwargs = { 139 "request": None, 140 "provider": self.provider, 141 "connection": connection, 142 obj._meta.model_name: obj, 143 } 144 eval_kwargs.setdefault("user", None) 145 for value in self.mapper.iter_eval(**eval_kwargs): 146 always_merger.merge(raw_final_object, value) 147 except ControlFlowException as exc: 148 raise exc from exc 149 except PropertyMappingExpressionException as exc: 150 # Value error can be raised when assigning invalid data to an attribute 151 Event.new( 152 EventAction.CONFIGURATION_ERROR, 153 message="Failed to evaluate property-mapping", 154 mapping=exc.mapping, 155 ).with_exception(exc).save() 156 raise StopSync(exc, obj, exc.mapping) from exc 157 if not raw_final_object: 158 raise StopSync(ValueError("No mappings configured"), obj) 159 for key, value in defaults.items(): 160 raw_final_object.setdefault(key, value) 161 return raw_final_object
Convert object to destination schema
163 def discover(self): 164 """Optional method. Can be used to implement a "discovery" where 165 upon creation of this provider, this function will be called and can 166 pre-link any users/groups in the remote system with the respective 167 object in authentik based on a common identifier""" 168 raise NotImplementedError()
Optional method. Can be used to implement a "discovery" where upon creation of this provider, this function will be called and can pre-link any users/groups in the remote system with the respective object in authentik based on a common identifier
170 def update_single_attribute(self, connection: TConnection): 171 """Update connection attributes on a connection object, when the connection 172 is manually created""" 173 raise NotImplementedError
Update connection attributes on a connection object, when the connection is manually created