Debian Codegraph @

src/bonsai/ldapurl.py

raw symbols SCIP
1 from ipaddress import IPv6Address
2 from typing import Any, List, Union, Tuple, Optional
3
4 import re
5 import urllib.parse
6 from .ldapdn import LDAPDN
7
8
9 class LDAPURL:
10 """
11 LDAP URL object for handling LDAP connection informations, such as
12 hostname, port, LDAP bind DN, search attributes, scope (base,sub or
13 one) filter, and extensions. If `strurl` is None, then the default
14 url is `ldap://localhost:389`.
15
16 :param str strurl: string representation of a valid LDAP URL. Must \
17 be started with `ldap://`, `ldaps://` or `ldapi://`.
18
19 :raises ValueError: if the string parameter is not a valid LDAP URL.
20 """
21
22 __slots__ = ("__hostinfo", "__searchinfo", "__extensions", "__ipv6")
23
24 def __init__(self, strurl: Optional[str] = None) -> None:
25 """Init method."""
26 self.__hostinfo = ("ldap", "localhost", 389) # type: Tuple[str, str, int]
27 # Default values to the search parameters.
28 self.__searchinfo = (
29 LDAPDN(""),
30 [],
31 "",
32 "",
33 ) # type: Tuple[LDAPDN, List[str], str, str]
34 self.__extensions = [] # type: List[str]
35 self.__ipv6 = False
36 if strurl:
37 self.__str2url(strurl)
38
39 def __delattr__(self, attr: str) -> None:
40 """None of the attributes can be deleted."""
41 raise AttributeError("%s cannot be deleted." % attr)
42
43 def __str2url(self, strurl: str) -> None:
44 """Parsing string url to LDAPURL."""
45 # Form: [scheme]://[host]:[port]/[basedn]?[attrs]?[scope]?[filter]?[exts]
46 scheme, host, port = self.__hostinfo
47 binddn, attrlist, scope, filter_exp = self.__searchinfo
48 parsed_url = urllib.parse.urlparse(strurl)
49 scheme = parsed_url.scheme
50 if scheme not in ("ldap", "ldaps", "ldapi"):
51 raise ValueError(f"'{strurl}' is not a valid LDAP URL")
52 if scheme == "ldaps":
53 port = 636
54 elif scheme == "ldapi":
55 port = 0
56 if parsed_url.hostname:
57 host = parsed_url.hostname
58 if parsed_url.scheme != "ldapi":
59 valid, self.__ipv6 = self.is_valid_hostname(host)
60 if not valid:
61 raise ValueError(f"'{strurl}' has an invalid hostname")
62 if parsed_url.port:
63 port = parsed_url.port
64 binddn = LDAPDN(urllib.parse.unquote(parsed_url.path[1:]))
65 params = parsed_url.query.split("?")
66 # Attribute
67 if len(params) > 0 and len(params[0]) > 0:
68 attrlist = params[0].split(",")
69 # Scope (base/one/sub)
70 if len(params) > 1:
71 _scope = params[1].lower()
72 if _scope not in ("base", "one", "sub"):
73 raise ValueError("Invalid scope type.")
74 scope = _scope
75 # Filter
76 if len(params) > 2:
77 filter_exp = urllib.parse.unquote(params[2])
78 # Extensions
79 if len(params) > 3:
80 self.__extensions = params[3].split(",")
81 self.__hostinfo = (scheme, host, port)
82 self.__searchinfo = (binddn, attrlist, scope, filter_exp)
83
84 @staticmethod
85 def is_valid_hostname(hostname: str) -> Tuple[bool, bool]:
86 """Validate a hostname."""
87 hostname_regex = re.compile(
88 r"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]"
89 r"*[a-zA-Z0-9])\.)*([A-Za-z0-9]|"
90 r"[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"
91 )
92 try:
93 # Try parsing IPv6 address.
94 IPv6Address(hostname)
95 return (True, True)
96 except ValueError:
97 # Try IPv4 and standard hostname.
98 if hostname_regex.match(hostname):
99 return (True, False)
100 return (False, False)
101
102 @property
103 def host(self) -> str:
104 """The hostname."""
105 return self.__hostinfo[1]
106
107 @host.setter
108 def host(self, value: str) -> None:
109 """Setter for hostname."""
110 # RegExp for valid hostname.
111 valid, ipv6 = self.is_valid_hostname(value)
112 if not valid:
113 raise ValueError("'%s' is not a valid host name." % value)
114 else:
115 self.__hostinfo = (self.__hostinfo[0], value, self.__hostinfo[2])
116 self.__ipv6 = ipv6
117
118 @property
119 def port(self) -> int:
120 """The portnumber."""
121 return self.__hostinfo[2]
122
123 @port.setter
124 def port(self, value: int) -> None:
125 """Setter for portnumber."""
126 if isinstance(value, int) and (value > 0 and value < 65535):
127 self.__hostinfo = (self.__hostinfo[0], self.__hostinfo[1], value)
128 else:
129 raise ValueError("Port must be an int between 1 and 65535.")
130
131 @property
132 def scheme(self) -> str:
133 """The URL scheme."""
134 return self.__hostinfo[0]
135
136 @scheme.setter
137 def scheme(self, value: str) -> None:
138 """Setter for URL scheme."""
139 # It must be ldap, ldaps or ldapi
140 if isinstance(value, str) and value.lower() in ("ldap", "ldaps", "ldapi"):
141 self.__hostinfo = (value.lower(), self.__hostinfo[1], self.__hostinfo[2])
142 else:
143 raise ValueError("Scheme only be 'ldap', 'ldaps' or 'ldapi'.")
144
145 @property
146 def basedn(self) -> LDAPDN:
147 """The LDAP distinguished name for binding."""
148 return self.__searchinfo[0]
149
150 @basedn.setter
151 def basedn(self, value: Union[LDAPDN, str]) -> None:
152 """Setter for LDAP distinguished name for binding."""
153 self.__searchinfo = (
154 LDAPDN(str(value)),
155 self.__searchinfo[1],
156 self.__searchinfo[2],
157 self.__searchinfo[3],
158 )
159
160 @property
161 def attributes(self) -> List[str]:
162 """The searching attributes."""
163 return self.__searchinfo[1]
164
165 @property
166 def scope(self) -> str:
167 """The searching scope."""
168 return self.__searchinfo[2]
169
170 @scope.setter
171 def scope(self, value: str) -> None:
172 """Setter for searching scope."""
173 if isinstance(value, str):
174 if value.lower() in ("base", "one", "sub"):
175 self.__searchinfo = (
176 self.__searchinfo[0],
177 self.__searchinfo[1],
178 value,
179 self.__searchinfo[3],
180 )
181 else:
182 raise ValueError(
183 """Scope must be one of these:
184 'base', 'one', 'sub'."""
185 )
186 else:
187 raise TypeError("Scope must be a string.")
188
189 @property
190 def scope_num(self) -> int:
191 """Return the searching scope number."""
192 if self.scope == "base":
193 return 0
194 if self.scope == "one":
195 return 1
196 if self.scope == "sub":
197 return 2
198 else:
199 return -1
200
201 @property
202 def filter_exp(self) -> str:
203 """The searching filter expression."""
204 return self.__searchinfo[3]
205
206 def get_address(self) -> str:
207 """
208 Return the full address of the host.
209 """
210 if self.scheme == "ldapi":
211 return f"{self.__hostinfo[0]}://{self.__hostinfo[1]}"
212 if self.__ipv6:
213 return (
214 f"{self.__hostinfo[0]}://[{self.__hostinfo[1]}]:{self.__hostinfo[2]:d}"
215 )
216 else:
217 return f"{self.__hostinfo[0]}://{self.__hostinfo[1]}:{self.__hostinfo[2]:d}"
218
219 def __eq__(self, other: object) -> bool:
220 """
221 Check equality of two LDAPURL or an LDAPURL and a string.
222 """
223 if isinstance(other, LDAPURL):
224 return (
225 self.scheme == other.scheme
226 and self.host == other.host
227 and self.port == other.port
228 and self.basedn == other.basedn
229 and self.scope == other.scope
230 and self.filter_exp == other.filter_exp
231 and self.attributes == other.attributes
232 )
233 elif isinstance(other, str):
234 try:
235 other = LDAPURL(other)
236 except ValueError:
237 return False
238 return self == other
239 else:
240 return NotImplemented
241
242 def __str__(self) -> str:
243 """Returns the full format of LDAP URL."""
244 strurl = self.get_address()
245 strattrs = ""
246 strexts = ""
247 if self.__searchinfo[1]:
248 strattrs = ",".join(self.__searchinfo[1])
249 if self.__extensions:
250 strexts = ",".join(self.__extensions)
251 strbind = "?".join(
252 (
253 urllib.parse.quote(str(self.__searchinfo[0]), safe="=,"),
254 strattrs,
255 self.__searchinfo[2],
256 urllib.parse.quote(self.__searchinfo[3], safe="=,()*"),
257 strexts,
258 )
259 )
260 # Remove unnecessary question marks at the end of the string.
261 while strbind[-1] == "?":
262 strbind = strbind[:-1]
263 if not strbind:
264 break
265 if strbind:
266 strurl = "%s/%s" % (strurl, strbind)
267 return strurl
268
269 def __repr__(self) -> str:
270 """The LDAPURL representation."""
271 return "<LDAPURL %s>" % str(self)