Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_ldap/schema.py

raw
1 # Copyright: (c) 2023, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # FOR INTERNAL COLLECTION USE ONLY
5 # The interfaces in this file are meant for use within this collection
6 # and may not remain stable to outside uses. Changes may be made in ANY release, even a bugfix release.
7 # See also: https://github.com/ansible/community/issues/539#issuecomment-780839686
8 # Please open an issue if you have questions about this.
9
10 import base64
11 import typing as t
12
13 try:
14 import sansldap
15 except Exception:
16 pass # Check is in __init__.py
17
18 from ...filter.ldap_converters import as_guid, as_sid
19 from .client import SyncLDAPClient
20
21
22 class LDAPSchema:
23 def __init__(
24 self,
25 attribute_types: t.Dict[str, "sansldap.schema.AttributeTypeDescription"],
26 ) -> None:
27 self.attribute_types = attribute_types
28
29 @classmethod
30 def load_schema(cls, client: SyncLDAPClient) -> "LDAPSchema":
31 root_dse = client.root_dse
32 attribute_types = list(
33 client.search(
34 filter=sansldap.FilterPresent("objectClass"),
35 attributes=["attributeTypes"],
36 search_base=root_dse.subschema_subentry,
37 search_scope=sansldap.SearchScope.BASE,
38 ).values()
39 )[0]["attributeTypes"]
40
41 attribute_info: t.Dict[str, sansldap.schema.AttributeTypeDescription] = {}
42 for info in attribute_types:
43 type_description = sansldap.schema.AttributeTypeDescription.from_string(info.decode("utf-8"))
44 if type_description.names:
45 attribute_info[type_description.names[0].lower()] = type_description
46
47 return LDAPSchema(attribute_info)
48
49 def cast_object(
50 self,
51 attribute: str,
52 values: t.List[bytes],
53 ) -> t.Any:
54 info = self.attribute_types.get(attribute.lower(), None)
55
56 caster: t.Callable[[bytes], t.Any]
57 if attribute == "objectSid":
58 caster = as_sid
59
60 elif attribute == "objectGuid":
61 caster = as_guid
62
63 elif not info or not info.syntax:
64 caster = _as_str
65
66 elif info.syntax == "1.3.6.1.4.1.1466.115.121.1.7":
67 caster = _as_bool
68
69 elif info.syntax in ["1.3.6.1.4.1.1466.115.121.1.27", "1.2.840.113556.1.4.906"]:
70 caster = _as_int
71
72 elif info.syntax in ["1.3.6.1.4.1.1466.115.121.1.40", "1.2.840.113556.1.4.907", "OctetString"]:
73 caster = _as_bytes
74
75 else:
76 caster = _as_str
77
78 casted_values: t.List = []
79 for v in values:
80 casted_values.append(caster(v))
81
82 if info and info.single_value:
83 return casted_values[0] if casted_values else None
84 else:
85 return casted_values
86
87
88 def _as_bool(value: bytes) -> bool:
89 return value == b"TRUE"
90
91
92 def _as_int(value: bytes) -> int:
93 return int(value)
94
95
96 def _as_bytes(value: bytes) -> str:
97 return base64.b64encode(value).decode()
98
99
100 def _as_str(value: bytes) -> str:
101 return value.decode("utf-8", errors="surrogateescape")