scim2-sqlalchemy 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ from .generation import generate_mappings
2
+ from .mapping import Attribute
3
+ from .mapping import Hashed
4
+ from .mapping import Link
5
+ from .mapping import Many
6
+ from .mapping import ResourceMapping
7
+ from .storage import AsyncSqlAlchemyStorage
8
+ from .storage import SqlAlchemyStorage
9
+
10
+ __all__ = [
11
+ "AsyncSqlAlchemyStorage",
12
+ "Attribute",
13
+ "Hashed",
14
+ "Many",
15
+ "Link",
16
+ "ResourceMapping",
17
+ "SqlAlchemyStorage",
18
+ "generate_mappings",
19
+ ]
@@ -0,0 +1,173 @@
1
+ import unicodedata
2
+ import warnings
3
+ from collections.abc import Iterable
4
+ from typing import Any
5
+
6
+ from scim2_models import AttributeBinding
7
+ from scim2_models import ScimPolicy
8
+ from scim2_models import default_comparison_key
9
+ from scim2_models.path import CompareOperator
10
+ from sqlalchemy import ColumnElement
11
+ from sqlalchemy import String
12
+ from sqlalchemy import func
13
+ from sqlalchemy import literal
14
+ from sqlalchemy import literal_column
15
+
16
+ from .mapping import ResourceMapping
17
+ from .mapping import _Column
18
+
19
+ _ESCAPE = "/"
20
+
21
+ _SUBSTRINGS = {
22
+ CompareOperator.co: "contains",
23
+ CompareOperator.sw: "startswith",
24
+ CompareOperator.ew: "endswith",
25
+ }
26
+
27
+ _KEY_FUNCTION = "scim2_key"
28
+
29
+
30
+ def _escape(value: str) -> str:
31
+ """Escape the LIKE wildcards of a value, so that they match themselves."""
32
+ for character in (_ESCAPE, "%", "_"):
33
+ value = value.replace(character, _ESCAPE + character)
34
+ return value
35
+
36
+
37
+ class _Comparator:
38
+ """How a database compares the strings of a policy.
39
+
40
+ The default lowers both sides with the lower() of the database, which
41
+ approaches the default comparison key, and only lowers ASCII letters on
42
+ some databases.
43
+ """
44
+
45
+ def __init__(self, policy: ScimPolicy) -> None:
46
+ self.policy = policy
47
+
48
+ def prepare(self, connection: Any) -> None:
49
+ """Make a DBAPI connection ready to compare strings."""
50
+
51
+ async def prepare_async(self, connection: Any) -> None:
52
+ """Make an asyncio DBAPI connection ready to compare strings."""
53
+
54
+ def column(self, column: _Column) -> ColumnElement[Any]:
55
+ """Return a string column in the form it is compared under."""
56
+ if column.casefolded:
57
+ return func.lower(column.compared)
58
+ return column.compared
59
+
60
+ def operand(self, column: _Column, value: str) -> Any:
61
+ """Return a string compared with a column, in the form it is compared under."""
62
+ if column.casefolded:
63
+ return func.lower(literal(value))
64
+ return value
65
+
66
+ def substring(
67
+ self, op: CompareOperator, column: _Column, value: str
68
+ ) -> ColumnElement[bool]:
69
+ """Return whether a string column contains, starts or ends with a value."""
70
+ pattern = self.operand(column, _escape(value))
71
+ method = getattr(self.column(column), _SUBSTRINGS[op])
72
+ return method(pattern, escape=_ESCAPE) # type: ignore[no-any-return]
73
+
74
+
75
+ class _Normalizer(_Comparator):
76
+ """Compare strings in PostgreSQL, normalized to NFC on both sides.
77
+
78
+ The lower() of PostgreSQL follows the locale of the database, so the
79
+ comparison approaches the default comparison key without reaching it. The
80
+ C collation orders the strings by code point, as scim2-models does.
81
+ """
82
+
83
+ def _form(self, column: _Column, expression: Any) -> ColumnElement[Any]:
84
+ """Normalize a string expression to NFC, lowered if the column ignores the case, under the C collation."""
85
+ normalized = func.normalize(expression, literal_column("NFC"), type_=String)
86
+ if column.casefolded:
87
+ normalized = func.normalize(
88
+ func.lower(normalized), literal_column("NFC"), type_=String
89
+ )
90
+ return normalized.collate("C")
91
+
92
+ def column(self, column: _Column) -> ColumnElement[Any]:
93
+ """Return a string column normalized to NFC."""
94
+ return self._form(column, column.compared)
95
+
96
+ def operand(self, column: _Column, value: str) -> Any:
97
+ """Return a string normalized to NFC, in Python then in the database."""
98
+ return self._form(column, literal(unicodedata.normalize("NFC", value)))
99
+
100
+
101
+ class _KeyFunction(_Comparator):
102
+ """Compare strings in SQLite with the comparison key of the policy itself.
103
+
104
+ The key is a SQL function of the connection, which takes the URN of the
105
+ attribute and the value, and returns NULL for a value the key refuses.
106
+ LIKE is not used, as SQLite ignores the case of ASCII letters in it.
107
+ """
108
+
109
+ def __init__(self, policy: ScimPolicy, mappings: Iterable[ResourceMapping]):
110
+ super().__init__(policy)
111
+ self.bindings: dict[str, AttributeBinding] = {
112
+ column.binding.urn: column.binding
113
+ for mapping in mappings
114
+ for column in mapping._string_columns()
115
+ }
116
+
117
+ def prepare(self, connection: Any) -> None:
118
+ """Register the comparison key as a SQL function of a DBAPI connection."""
119
+ connection.create_function(_KEY_FUNCTION, 2, self.key, deterministic=True)
120
+
121
+ async def prepare_async(self, connection: Any) -> None:
122
+ """Register the comparison key as a SQL function of an asyncio DBAPI connection."""
123
+ await connection.create_function(_KEY_FUNCTION, 2, self.key, deterministic=True)
124
+
125
+ def key(self, urn: str, value: Any) -> Any:
126
+ """Return the comparison key of a stored value, or None if the key refuses it."""
127
+ if value is None:
128
+ return None
129
+ try:
130
+ return self.bindings[urn].comparable(value, self.policy)
131
+ except ValueError:
132
+ return None
133
+
134
+ def column(self, column: _Column) -> ColumnElement[Any]:
135
+ """Return the comparison key of a string column, computed by the SQL function."""
136
+ key: ColumnElement[Any] = getattr(func, _KEY_FUNCTION)(
137
+ literal(column.binding.urn), column.compared, type_=String
138
+ )
139
+ return key
140
+
141
+ def operand(self, column: _Column, value: str) -> Any:
142
+ """Return the comparison key of a string, computed in Python."""
143
+ return column.binding.comparable(value, self.policy)
144
+
145
+ def substring(
146
+ self, op: CompareOperator, column: _Column, value: str
147
+ ) -> ColumnElement[bool]:
148
+ """Return whether a string column contains, starts or ends with a value, compared by their keys."""
149
+ left = self.column(column)
150
+ right = literal(self.operand(column, value))
151
+ if op == CompareOperator.co:
152
+ return func.instr(left, right) > 0
153
+ if op == CompareOperator.sw:
154
+ return func.substr(left, 1, func.length(right)) == right
155
+ start = func.length(left) - func.length(right) + 1
156
+ return func.substr(left, start) == right
157
+
158
+
159
+ def _comparator(
160
+ dialect: str, policy: ScimPolicy, mappings: Iterable[ResourceMapping]
161
+ ) -> _Comparator:
162
+ """Return how a database compares strings, warning when it cannot follow the policy."""
163
+ if dialect == "sqlite":
164
+ return _KeyFunction(policy, mappings)
165
+ if policy.comparison_key is not default_comparison_key:
166
+ warnings.warn(
167
+ f"The {dialect} storage cannot compare strings with the comparison key "
168
+ "of the policy: filters and uniqueness checks only approach it",
169
+ stacklevel=2,
170
+ )
171
+ if dialect == "postgresql":
172
+ return _Normalizer(policy)
173
+ return _Comparator(policy)
@@ -0,0 +1,305 @@
1
+ import base64
2
+ import datetime
3
+ from collections.abc import Iterable
4
+ from collections.abc import Mapping
5
+ from enum import Enum
6
+ from inspect import isclass
7
+ from typing import Any
8
+
9
+ from pydantic import BaseModel
10
+ from scim2_models import AttributeBinding
11
+ from scim2_models import InvalidValueException
12
+ from scim2_models import Meta
13
+ from scim2_models import Mutability
14
+ from scim2_models import MutabilityException
15
+ from scim2_models import Path
16
+ from scim2_models import Resource
17
+
18
+ from .mapping import ResourceMapping
19
+ from .mapping import _Collection
20
+ from .mapping import _Column
21
+ from .mapping import _Storage
22
+
23
+
24
+ def _as_scim(value: Any) -> Any:
25
+ """Return a value read from the database in the form SCIM holds it.
26
+
27
+ A date without a time zone is taken as UTC, since SQLite drops the zone.
28
+ Binary values are encoded in base64, the form the models decode them from.
29
+ """
30
+ if isinstance(value, datetime.datetime) and value.tzinfo is None:
31
+ return value.replace(tzinfo=datetime.UTC)
32
+ if isinstance(value, bytes):
33
+ return base64.b64encode(value).decode()
34
+ return value
35
+
36
+
37
+ def _as_stored(value: Any) -> Any:
38
+ """Return a SCIM value in the form a column holds it."""
39
+ if isinstance(value, Enum):
40
+ return value.value
41
+ if isinstance(value, datetime.datetime) and value.tzinfo is not None:
42
+ return value.astimezone(datetime.UTC)
43
+ return value
44
+
45
+
46
+ def _read(column: _Column, record: Any) -> Any:
47
+ """Return the SCIM value of a column of a record, or None if the column is not read."""
48
+ value = getattr(record, column.key)
49
+ if value is None or not column.readable:
50
+ return None
51
+ if isinstance(value, Enum) and column.enumeration is not None:
52
+ return column.stored_string(column.enumeration, value)
53
+ return _as_scim(value)
54
+
55
+
56
+ def _version(mapping: ResourceMapping, record: Any) -> str:
57
+ """Return the weak ETag of the version of a record."""
58
+ return f'W/"{getattr(record, mapping._version.key)}"'
59
+
60
+
61
+ def _to_scim(
62
+ mapping: ResourceMapping,
63
+ record: Any,
64
+ resource_type: str,
65
+ model: type[Resource[Any]],
66
+ endpoints: Mapping[str, str],
67
+ collections: Iterable[_Collection],
68
+ ) -> Resource[Any]:
69
+ """Build the resource a record stores, as an instance of model.
70
+
71
+ Only the given collections are read: the others may not be loaded.
72
+
73
+ The attributes are found by their URN, so model may be another model of
74
+ the same schemas than the model of the mapping, such as a model a provider
75
+ built from the schemas. endpoints gives the endpoint of each resource type
76
+ by name: a link to one of them gets a $ref relative to the SCIM root, when
77
+ model declares it, which the server makes absolute (RFC 7643 §2.3.7).
78
+ """
79
+ resource = model()
80
+ special = (mapping._id, mapping._created, mapping._last_modified)
81
+ for column in mapping._columns.values():
82
+ if column in special:
83
+ continue
84
+ value = _read(column, record)
85
+ if value is not None:
86
+ Path[model](column.binding.urn).set(resource, value) # type: ignore[valid-type]
87
+
88
+ read: dict[str, tuple[bool, list[dict[str, Any]]]] = {}
89
+ for collection in collections:
90
+ endpoint = None
91
+ if Path[model](f"{collection.binding.urn}.$ref").resolve() is not None: # type: ignore[valid-type]
92
+ endpoint = endpoints.get(collection.resource_type) # type: ignore[arg-type]
93
+ _, entries = read.setdefault(collection.binding.urn, (collection.single, []))
94
+ for related in _related(collection, record):
95
+ entry = _read_entry(collection, related, endpoint)
96
+ if entry is not None:
97
+ entries.append(entry)
98
+ for urn, (single, entries) in read.items():
99
+ if entries:
100
+ Path[model](urn).set(resource, entries[0] if single else entries) # type: ignore[valid-type]
101
+
102
+ resource.id = str(_read(mapping._id, record))
103
+ resource.meta = Meta(
104
+ resource_type=resource_type,
105
+ created=_read(mapping._created, record),
106
+ last_modified=_read(mapping._last_modified, record),
107
+ version=_version(mapping, record),
108
+ )
109
+ return model.model_validate(resource.model_dump())
110
+
111
+
112
+ def _related(collection: _Collection, record: Any) -> list[Any]:
113
+ """Return the records a collection of a record holds, as a list even for a single one."""
114
+ related = getattr(record, collection.relationship.key)
115
+ if collection.single:
116
+ return [] if related is None else [related]
117
+ return list(related)
118
+
119
+
120
+ def _entries(collection: _Collection, resource: Resource[Any]) -> list[Any]:
121
+ """Return the entries a resource holds for a collection, as a list even for a single one."""
122
+ value = Path(collection.binding.urn).get(resource, strict=False)
123
+ if collection.single:
124
+ return [] if value is None else [value]
125
+ return list(value or [])
126
+
127
+
128
+ def _read_entry(collection: _Collection, entry: Any, endpoint: str | None) -> Any:
129
+ """Return the values of an entry, by sub-attribute name, or the value of an entry of a simple collection.
130
+
131
+ A link gets a $ref when the endpoint of the resources it links to is known.
132
+ """
133
+ if collection.simple:
134
+ return _read(collection.columns[None], entry)
135
+ values = {}
136
+ for sub_field_name, column in collection.columns.items():
137
+ value = _read(column, entry)
138
+ if value is not None and sub_field_name == "value" and not collection.owned:
139
+ value = str(value)
140
+ if endpoint is not None:
141
+ values["$ref"] = f"{endpoint}/{value}"
142
+ values[column.binding.urn.rsplit(".", 1)[-1]] = value
143
+ if collection.link_type is not None:
144
+ values["type"] = collection.link_type
145
+ return values
146
+
147
+
148
+ def _from_scim(
149
+ mapping: ResourceMapping,
150
+ resource: Resource[Any],
151
+ record: Any,
152
+ links: dict[_Collection, list[Any]],
153
+ creating: bool,
154
+ ) -> None:
155
+ """Write a resource into a record.
156
+
157
+ Read-only attributes are left as they are, and so is a write-only attribute
158
+ the resource has no value for, since a resource never carries it back.
159
+ When creating the record, a missing value is not written, so that the
160
+ column keeps its default. links holds the records each Link of the
161
+ resource links to.
162
+ """
163
+ for column in mapping._columns.values():
164
+ if not column.writable:
165
+ continue
166
+ value = Path(column.binding.urn).get(resource, strict=False)
167
+ if value is None and (creating or not column.readable):
168
+ continue
169
+ setattr(record, column.key, None if value is None else _as_stored(value))
170
+
171
+ for collection in mapping._all_collections():
172
+ if not collection.writable:
173
+ continue
174
+ if collection.owned:
175
+ entries = Path(collection.binding.urn).get(resource, strict=False) or []
176
+ value = [_write_entry(collection, entry) for entry in entries]
177
+ elif collection.single:
178
+ value = next(iter(links[collection]), None)
179
+ else:
180
+ value = links[collection]
181
+ setattr(record, collection.relationship.key, value)
182
+
183
+
184
+ def _write_entry(collection: _Collection, entry: Any) -> Any:
185
+ """Build the record storing an entry of a multi-valued attribute."""
186
+ record = collection.entry_class()
187
+ if collection.simple:
188
+ setattr(record, collection.columns[None].key, _as_stored(entry))
189
+ return record
190
+ for column in collection.columns.values():
191
+ if not column.writable:
192
+ continue
193
+ value = getattr(entry, column.binding.target_field_name, None)
194
+ if value is not None:
195
+ setattr(record, column.key, _as_stored(value))
196
+ return record
197
+
198
+
199
+ def _link_entries(
200
+ mapping: ResourceMapping, resource: Resource[Any]
201
+ ) -> list[tuple[list[_Collection], list[Any]]]:
202
+ """Return the entries of each written attribute of a resource linking to other resources, with the collections of its Links.
203
+
204
+ A link is stored by its value, so an entry without one, such as an entry
205
+ with a $ref only, raises InvalidValueException rather than being lost.
206
+ """
207
+ links = []
208
+ for collections in mapping._collections.values():
209
+ collection = collections[0]
210
+ if collection.owned or not collection.writable:
211
+ continue
212
+ entries = _entries(collection, resource)
213
+ if any(entry.value is None for entry in entries):
214
+ raise InvalidValueException(
215
+ detail=f"'{collection.binding.urn}' holds an entry without value"
216
+ )
217
+ links.append((collections, entries))
218
+ return links
219
+
220
+
221
+ def _check_storable(
222
+ mapping: ResourceMapping,
223
+ resource: Resource[Any],
224
+ stored: Resource[Any] | None,
225
+ ) -> None:
226
+ """Refuse a change of a resource that the mapping cannot store.
227
+
228
+ Each attribute of the resource is compared with the stored resource, None
229
+ for a new one. A value equal to the stored one changes nothing, so a
230
+ resource read and sent back is accepted. A missing value changes nothing
231
+ either, except for a stored value whose column cannot hold none: removing it
232
+ raises MutabilityException. The read-only attributes of the model of the resource are skipped,
233
+ as RFC 7644 §3.5.1 has them ignored, and so are the derived ones.
234
+ """
235
+ model = type(resource)
236
+ for path in Path[model].iter_paths(): # type: ignore[valid-type]
237
+ binding = path.resolve()
238
+ if binding is None:
239
+ continue
240
+ target = binding.target_type
241
+ if isclass(target) and issubclass(target, BaseModel):
242
+ continue
243
+ if Mutability.read_only in (
244
+ binding.model.get_field_annotation(binding.field_name, Mutability),
245
+ binding.get_annotation(Mutability),
246
+ ):
247
+ continue
248
+ storage = mapping._storage(binding.urn)
249
+ value = _comparable(path.get(resource, strict=False))
250
+ current = None
251
+ if stored is not None:
252
+ current = _comparable(Path(binding.urn).get(stored, strict=False))
253
+ if storage == _Storage.written:
254
+ _check_enumerated(mapping, binding, value)
255
+ if (
256
+ value is None
257
+ and current is not None
258
+ and not mapping._nullable(binding.urn)
259
+ ):
260
+ raise MutabilityException(
261
+ attribute=binding.urn,
262
+ detail=f"'{binding.urn}' cannot be removed on this server",
263
+ )
264
+ continue
265
+ if storage in (_Storage.derived, _Storage.ref, _Storage.link_type) or value in (
266
+ None,
267
+ current,
268
+ ):
269
+ continue
270
+ if storage == _Storage.read_only:
271
+ raise MutabilityException(
272
+ attribute=binding.urn,
273
+ mutability="readOnly",
274
+ detail=f"'{binding.urn}' is read-only on this server",
275
+ )
276
+ raise InvalidValueException(
277
+ detail=f"'{binding.urn}' is not stored by this server"
278
+ )
279
+
280
+
281
+ def _check_enumerated(
282
+ mapping: ResourceMapping, binding: AttributeBinding, value: Any
283
+ ) -> None:
284
+ """Refuse a string that an Enum column does not store, rather than failing in the database."""
285
+ _, column = mapping._lookup(binding)[0]
286
+ if column is None or column.enumeration is None:
287
+ return
288
+ stored = column.enumeration.enums
289
+ for item in value if isinstance(value, list) else [value]:
290
+ if item is not None and item not in stored:
291
+ raise InvalidValueException(
292
+ detail=f"'{binding.urn}' cannot hold {item!r} on this server"
293
+ )
294
+
295
+
296
+ def _comparable(value: Any) -> Any:
297
+ """Return a value in a form two resources compare in.
298
+
299
+ A list of missing values, as a path through the entries of a multi-valued
300
+ attribute gives, is no value.
301
+ """
302
+ if isinstance(value, list):
303
+ values = [_as_stored(item) for item in value]
304
+ return None if all(item is None for item in values) else values
305
+ return _as_stored(value)