File: //usr/lib/python3.9/site-packages/ipapython/__pycache__/dn.cpython-39.pyc
a
}�f*� � - @ s: d Z ddlmZ ddlZddlZddlZddlZzddlm Z W n& e
yf ddlmZm
Z
m Z Y n0 ddlmZm
Z
ejr�eZdZdd � Zd
d� Zdd
� Zdd� Zdd� Zdd� Zdd� Zdd� Zejr�dd� Zdd� Zndd� Zdd� ZejG dd� d��ZejG d d!� d!��Z ejG d"d#� d#��Z!ej"j#j$j%d$ej"j#j$j&d%ej"j#j$j'd&ej"j#j$j(d'ej"j#j$j)d(ej"j#j$j*d)ej"j#j$j+d*ej"j#j$j,d+ej"j#j$j-d,ej"j#j$j.d-ej"j#j$j/d.ej"j#j$j0d/ej"j#j$j1d0ej"j#j$j2d1ej"j#j$j3d2ej"j#j$j4d3ej"j#j$j5d4ej"j#j$j6d5ej"j#j$j7d6ej"�8d7�d8ej"�8d9�d:ej"�8d;�d<iZ9dS )=a�2
Goal
----
To allow a Python programmer the ability to operate on DN's
(Distinguished Names) in a simple intuitive manner supporting all the
Pythonic mechanisms for manipulating objects such that the simple
majority case remains simple with simple code, yet the corner cases
are fully supported. With the result both simple and complex cases are
100% correct.
This is achieved with a fair of amount of syntax sugar which is best
described as "Do What I Mean" (i.e. DWIM). The class implementations
take simple expressions and internally convert them to their more
complex full definitions hiding much of the complexity from the
programmer.
Anatomy of a DN
---------------
Some definitions:
AVA
An AVA is an Attribute Value Assertion. In more simple terms it's
an attribute value pair typically expressed as attr=value
(e.g. cn=Bob). Both the attr and value in an AVA when expressed in
a string representation are subject to encoding rules.
RDN
A RDN is a Relative Distinguished Name. A RDN is a non-empty set of
AVA's. In the common case a RDN is single valued consisting of 1
AVA (e.g. cn=Bob). But a RDN may be multi-valued consisting of
more than one AVA. Because the RDN is a set of AVA's the AVA's are
unordered when they appear in a multi-valued RDN. In the string
representation of a RDN AVA's are separated by the plus sign (+).
DN
A DN is a ordered sequence of 1 or more RDN's. In the string
representation of a DN each RDN is separated by a comma (,)
Thus a DN is:
Sequence of set of <encoded attr, encoded value> pairs
The following are valid DN's
# 1 RDN with 1 AVA (e.g. cn=Bob)
RDN(AVA)
# 2 RDN's each with 1 AVA (e.g. cn=Bob,dc=redhat.com)
RDN(AVA),RDN(AVA)
# 2 RDN's the first RDN is multi-valued with 2 AVA's
# the second RDN is singled valued with 1 AVA
# (e.g. cn=Bob+ou=people,dc=redhat.com
RDN({AVA,AVA}),RDN(AVA)
Common programming mistakes
---------------------------
DN's present a pernicious problem for programmers. They appear to have
a very simple string format in the majority case, a sequence of
attr=value pairs separated by commas. For example:
dn='cn=Bob,ou=people,dc=redhat,dc=com'
As such there is a tendency to believe you can form DN's by simple
string manipulations such as:
dn='%s=%s' % ('cn','Bob') + ',ou=people,dc=redhat,dc=com'
Or to extract a attr & value by searching the string, for example:
attr=dn[0 : dn.find('=')]
value=dn[dn.find('=')+1 : dn.find(',')]
Or compare a value returned by an LDAP query to a known value:
if value == 'Bob'
All of these simple coding assumptions are WRONG and will FAIL when a
DN is not one of the simple DN's (simple DN's are probably the 95% of
all DN's). This is what makes DN handling pernicious. What works in
95% of the cases and is simple, fails for the 5% of DN's which are not
simple.
Examples of where the simple assumptions fail are:
* A RDN may be multi-valued
* A multi-valued RDN has no ordering on it's components
* Attr's and values must be UTF-8 encoded
* String representations of AVA's, RDN's and DN's must be completely UTF-8
* An attr or value may have reserved characters which must be escaped.
* Whitespace needs special handling
To complicate matters a bit more the RFC for the string representation
of DN's (RFC 4514) permits a variety of different syntax's each of
which can evaluate to exactly the same DN but have different string
representations. For example, the attr "r,w" which contains a reserved
character (the comma) can be encoded as a string in these different
ways:
'r\,w' # backslash escape
'r\2cw' # hexadecimal ascii escape
'#722C77' # binary encoded
It should be clear a DN string may NOT be a simple string, rather a DN
string is ENCODED. For simple strings the encoding of the DN is
identical to the simple string value (this common case leads to
erroneous assumptions and bugs because it does not account for
encodings).
The openldap library we use at the client level uses the backslash
escape form. The LDAP server we use uses the hexadecimal ascii escape
form. Thus 'r,w' appears as 'r\,w' when sent from the client to the
LDAP server as part of a DN. But when it's returned as a DN from the
server in an LDAP search it's returned as 'r\2cw'. Any attempt to
compare 'r\,w' to 'r\2cw' for equality will fail despite the fact they
are indeed equal once decoded. Such a test fails because you're
comparing two different encodings of the same value. In MIME you
wouldn't expect the base64 encoding of a string to be equal to the
same string encoded as quoted-printable would you?
When you are comparing attrs or values which are part of a DN and
other string you MUST:
* Know if either of the strings have been encoded and make sure you're
comparing only decoded components component-wise.
* Extract the component from the DN and decode it. You CANNOT decode
the entire DN as a string and operate on it. Why? Consider a value
with a comma embedded in it. For example:
cn=r\2cw,cn=privilege
Is a DN with 2 RDN components: cn=r,w followed by "cn=privilege"
But if you decode the entire DN string as a whole you would get:
cn=r,w,cn=privilege
Which is a malformed DN with 3 RDN's, the 2nd RDN is invalid.
* Determine if a RDN is multi-valued, if so you must account
for the fact each AVA component in the multi-valued RDN can appear
in any order and still be equivalent. For example the following two
RDN's are equal:
cn=Bob+ou=people
ou=people+cn=Bob
In addition each AVA (cn=Bob & ou=people) needs to be
INDEPENDENTLY decoded prior to comparing the unordered set of AVA's
in the multi-valued RDN.
If you are trying to form a new DN or RDN from a raw string you cannot
simply do string concatenation or string formatting unless you ESCAPE
the components independently prior to concatenation, for example:
base = 'dc=redhat,dc=com'
value = 'r,w'
dn = 'cn=%s,%s' % (value, base)
Will result in the malformed DN 'cn=r,w,dc=redhat,dc=com'
Syntax Sugar
------------
The majority of DN's have a simple string form:
attr=value,attr=value
We want the programmer to be able to create DN's, compare them, and
operate on their components as simply and concisely as possible so
the classes are implemented to provide a lot of syntax sugar.
The classes automatically handle UTF-8 <-> Unicode conversions. Every
attr and value which is returned from a class will be Unicode. Every
attr and value assigned into an object will be promoted to
Unicode. All string representations in RFC 4514 format will be UTF-8
and properly escaped. Thus at the "user" or "API" level every string
is Unicode with the single exception that the str() method returns RFC
compliant escaped UTF-8.
RDN's are assumed to be single-valued. If you need a multi-valued RDN
(an exception) you must explicitly create a multi-valued RDN.
Thus DN's are assumed to be a sequence of attr, value pairs, which is
equivalent to a sequence of RDN's. The attr and value in the pair MUST
be strings.
The DN and RDN constructors take a sequence, the constructor parses
the sequence to find items it knows about.
The DN constructor will accept in it's sequence:
* tuple of 2 strings, converting it to an RDN
* list of 2 strings, converting it to an RDN
* a RDN object
* a DN syntax string (e.g. 'cn=Bob,dc=redhat.com')
Note DN syntax strings should be avoided if possible when passing to a
constructor because they run afoul of the problems outlined above
which the DN, RDN & AVA classes are meant to overcome. But sometimes a
DN syntax string is all you have to work with. DN strings which come
from a LDAP library or server will be properly formed and it's safe to
use those. However DN strings provided via user input should be
treated suspiciously as they may be improperly formed. You can test
for this by passing the string to the DN constructor and see if it
throws an exception.
The sequence passed to the DN constructor takes each item in order,
produces one or more RDN's from it and appends those RDN in order to
its internal RDN sequence.
For example:
DN(('cn', 'Bob'), ('dc', 'redhat.com'))
This is equivalent to the DN string:
cn=Bob,dc=redhat.com
And is exactly equal to:
DN(RDN(AVA('cn','Bob')),RDN(AVA('dc','redhat.com')))
The following are alternative syntax's which are all exactly
equivalent to the above example.
DN(['cn', 'Bob'], ['dc', 'redhat.com'])
DN(RDN('cn', 'Bob'), RDN('dc', 'redhat.com'))
You can provide a properly escaped string representation.
DN('cn=Bob,dc=redhat.com')
You can mix and match any of the forms in the constructor parameter
list.
DN(('cn', 'Bob'), 'dc=redhat.com')
DN(('cn', 'Bob'), RDN('dc', 'redhat.com'))
AVA's have an attr and value property, thus if you have an AVA
# Get the attr and value
ava.attr -> u'cn'
ava.value -> u'Bob'
# Set the attr and value
ava.attr = 'cn'
ava.value = 'Bob'
Since RDN's are assumed to be single valued, exactly the same
behavior applies to an RDN. If the RDN is multi-valued then the attr
property returns the attr of the first AVA, likewise for the value.
# Get the attr and value
rdn.attr -> u'cn'
rdn.value -> u'Bob'
# Set the attr and value
rdn.attr = 'cn'
rdn.value = 'Bob'
Also RDN's can be indexed by name or position (see the RDN class doc
for details).
rdn['cn'] -> u'Bob'
rdn[0] -> AVA('cn', 'Bob')
A DN is a sequence of RDN's, as such any of Python's container
operators can be applied to a DN in a intuitive way.
# How many RDN's in a DN?
len(dn)
# WARNING, this a count of RDN's not how characters there are in the
# string representation the dn, instead that would be:
len(str(dn))
# Iterate over each RDN in a DN
for rdn in dn:
# Get the first RDN in a DN
dn[0] -> RDN('cn', 'Bob')
# Get the value of the first RDN in a DN
dn[0].value -> u'Bob'
# Get the value of the first RDN by indexing by attr name
dn['cn'] -> u'Bob'
# WARNING, when a string is used as an index key the FIRST RDN's value
# in the sequence whose attr matches the key is returned. Thus if you
# have a DN like this "cn=foo,cn=bar" then dn['cn'] will always return
# 'foo' even though there is another attr with the name 'cn'. This is
# almost always what the programmer wants. See the class doc for how
# you can override this default behavior and get a list of every value
# whose attr matches the key.
# Set the first RDN in the DN (all are equivalent)
dn[0] = ('cn', 'Bob')
dn[0] = ['cn', 'Bob']
dn[0] = RDN('cn', 'Bob')
dn[0].attr = 'cn'
dn[0].value = 'Bob'
# Get the first two RDN's using slices
dn[0:2]
# Get the last two RDN's using slices
dn[-2:]
# Get a list of all RDN's using slices
dn[:]
# Set the 2nd and 3rd RDN using slices (all are equivalent)
dn[1:3] = ('cn', 'Bob), ('dc', 'redhat.com')
dn[1:3] = RDN('cn', 'Bob), RDN('dc', 'redhat.com')
String representations and escapes:
# To get an RFC compliant string representation of a DN, RDN or AVA
# simply call str() on it or evaluate it in a string context.
str(dn) -> 'cn=Bob,dc=redhat.com'
# When working with attr's and values you do not have to worry about
# escapes, simply use the raw unescaped string in a natural fashion.
rdn = RDN('cn', 'r,w')
# Thus:
rdn.value == 'r,w' -> True
# But:
str(rdn) == 'cn=r,w' -> False
# Because:
str(rdn) -> 'cn=r\2cw' or 'cn='r\,w' # depending on the underlying LDAP library
Equality and Comparing:
# All DN's, RDN's and AVA's support equality testing in an intuitive
# manner.
dn1 = DN(('cn', 'Bob'))
dn2 = DN(RDN('cn', 'Bob'))
dn1 == dn2 -> True
dn1[0] == dn2[0] -> True
dn1[0].value = 'Bobby'
dn1 == dn2 -> False
DN objects implement startswith(), endswith() and the "in" membership
operator. You may pass a DN or RDN object to these. Examples:
if dn.endswith(base_dn):
if dn.startswith(rdn1):
if container_dn in dn:
# See the class doc for how DN's, RDN's and AVA's compare
# (e.g. cmp()). The general rule is for objects supporting multiple
# values first their lengths are compared, then if the lengths match
# the respective components of each are pair-wise compared until one
# is discovered to be non-equal. The comparison is case insensitive.
Concatenation, In-Place Addition, Insertion:
# DN's and RDN's can be concatenated.
# Return a new DN by appending the RDN's of dn2 to dn1
dn3 = dn1 + dn2
# Append a RDN to DN's RDN sequence (all are equivalent)
dn += ('cn', 'Bob')
dn += RDN('cn', 'Bob')
# Append a DN to an existing DN
dn1 += dn2
# Prepend a RDN to an existing DN
dn1.insert(0, RDN('cn', 'Bob'))
Finally see the unittest for a more complete set of ways you can
manipulate these objects.
Immutability
------------
All the class types are immutable.
As with other immutable types (such as str and int), you must not rely on
the object identity operator ("is") for comparisons.
It is possible to "copy" an object by passing an object of the same type
to the constructor. The result may share underlying structure.
� )�print_functionN)�DECODING_ERROR)�str2dn�dn2strr )r r )�AVA�RDN�DNc C sN ||kr|}n|dk r*||7 }|dk r*d}| dk rF| |7 } | dk rFd} | |fS )z&helper to fixup start/end slice valuesr � )�start�end�lengthr r �0/usr/lib/python3.9/site-packages/ipapython/dn.py�_adjust_indices� s r c C sT t jrt| t�rtd| ��n2t| t�s6tt| ��} nt jrPt| t�rP| � d�} | S )Nzexpected str, got bytes: %r�utf-8)
�six�PY3�
isinstance�bytes� TypeError�str�
val_encode�PY2�unicode�encode)�valr r r
�_normalize_ava_input� s
r c C sR zt | �d��}W n ty0 td| ��Y n0 t|�dkrJtd| ��|d S )Nr zmalformed AVA string = "%s"� z multiple RDN's specified by "%s"r )r r r �
ValueError�len)�value�rdnsr r r
�str2rdn� s r! c G s� d}t | �}|dkr| }n�|dkr>t| d �t| d �dg}n�|dkr�| d }t|t�rb|�� }q�t|ttf�r�t |�dkr�td| ��t|d �t|d �dg}q�t|t�r�t |�}t |�dkr�t
d| ��t|d �}q�t
d|jj ��nt
d ��|S )
a�
Get AVA from args in open ldap format(raw). Optimized for construction
from openldap format.
Allowed formats of argument list:
1) three args - open ldap format (attr and value have to be utf-8 encoded):
a) ['attr', 'value', 0]
2) two args:
a) ['attr', 'value']
3) one arg:
a) [('attr', 'value')]
b) [['attr', 'value']]
c) [AVA(..)]
d) ['attr=value']
N� � r r z(tuple or list must be 2-valued, not "%s"z multiple AVA's specified by "%s"zMwith 1 argument, argument must be str, unicode, tuple or list, got %s insteadz(invalid number of arguments. 1-3 allowed)
r r r r �to_openldap�tuple�listr r r! r � __class__�__name__)�args�ava�l�arg�rdnr r r
�get_ava� s0
�r. c C s t | �dkrd S | jtd� d S )Nr )�key)r �sort�ava_key�r- r r r
� sort_avas
s r3 c C s | d � � | d � � fS �Nr r )�lower)r* r r r
r1 s r1 c C s0 t | �}t |�}||krdS ||k r(dS dS d S )Nr ���r )�rdn_key)�a�bZkey_aZkey_br r r
�cmp_rdns s r: c C s t | �ftdd� | D �� S )Nc s s | ]}t |�V qd S �N)r1 )�.0�kr r r
� <genexpr> � zrdn_key.<locals>.<genexpr>)r r% r2 r r r
r7 s r7 c C s
| � d�S �Nr )r ��sr r r
r % s r c C s
| � d�S r@ )�decoderA r r r
�
val_decode( s rD c C s t | t�rtd| ��| S )Nzexpected str, got bytes: %s)r r r rA r r r
r , s
c C s | S r; r rA r r r
rD 1 s c @ s� e Zd ZdZdd� Zdd� Zdd� Zee�Zdd � Z d
d� Z
ee �Zdd
� Zdd� Z
dd� Zdd� Zdd� Zdd� Zdd� Zdd� ZdS )r a
AVA(arg0, ...)
An AVA is an LDAP Attribute Value Assertion. It is convenient to think of
AVA's as a <attr,value> pair. AVA's are members of RDN's (Relative
Distinguished Name).
The AVA constructor is passed a sequence of args and a set of
keyword parameters used for configuration.
The arg sequence may be:
1) With 2 arguments, the first argument will be the attr, the 2nd
the value. Each argument must be scalar convertable to unicode.
2) With a sigle list or tuple argument containing exactly 2 items.
Each item must be scalar convertable to unicode.
3) With a single string (or unicode) argument, in this case the string will
be interpretted using the DN syntax described in RFC 4514 to yield a AVA
<attr,value> pair. The parsing recognizes the DN syntax escaping rules.
For example:
ava = AVA('cn', 'Bob') # case 1: two strings
ava = AVA(('cn', 'Bob')) # case 2: 2-valued tuple
ava = AVA(['cn', 'Bob']) # case 2: 2-valued list
ava = AVA('cn=Bob') # case 3: DN syntax
AVA object have two properties for accessing their data:
attr: the attribute name, cn in our exmaple
value: the attribute's value, Bob in our example
When attr and value are returned they will always be unicode. When
attr or value are set they will be promoted to unicode.
AVA objects support indexing by name, e.g.
ava['cn']
returns the value (Bob in our example). If the index does key does not match
the attr then a KeyError will be raised.
AVA objects support equality testing and comparsion (e.g. cmp()). When they
are compared the attr is compared first, if the 2 attr's are equal then the
values are compared. The comparison is case insensitive (because attr's map
to numeric OID's and their values derive from from the 'name' atribute type
(OID 2.5.4.41) whose EQUALITY MATCH RULE is caseIgnoreMatch.
The str method of an AVA returns the string representation in RFC 4514 DN
syntax with proper escaping.
c G s t |� | _d S r; )r. �_ava)�selfr) r r r
�__init__l s zAVA.__init__c C s t | jd �S )Nr �rD rE �rF r r r
� _get_attro s z
AVA._get_attrc
C sL zt |�| jd<