2009-06-10 07:24:35 -05:00
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2009 Red Hat
# see file 'COPYING' for use and warranty information
#
2010-12-09 06:59:11 -06:00
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
2009-06-10 07:24:35 -05:00
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
2010-12-09 06:59:11 -06:00
# along with this program. If not, see <http://www.gnu.org/licenses/>.
2009-06-10 07:24:35 -05:00
"""
Directory Server Access Control Instructions ( ACIs )
2009-09-28 09:13:06 -05:00
2010-08-24 22:40:32 -05:00
ACIs are used to allow or deny access to information . This module is
currently designed to allow , not deny , access .
2009-09-28 09:13:06 -05:00
2010-08-24 22:40:32 -05:00
The aci commands are designed to grant permissions that allow updating
existing entries or adding or deleting new ones . The goal of the ACIs
that ship with IPA is to provide a set of low - level permissions that
grant access to special groups called taskgroups . These low - level
permissions can be combined into roles that grant broader access . These
2010-12-01 10:23:52 -06:00
roles are another type of group , roles .
2009-09-28 09:13:06 -05:00
For example , if you have taskgroups that allow adding and modifying users you
2010-12-01 10:23:52 -06:00
could create a role , useradmin . You would assign users to the useradmin
role to allow them to do the operations defined by the taskgroups .
2009-09-28 09:13:06 -05:00
2010-08-24 22:40:32 -05:00
You can create ACIs that delegate permission so users in group A can write
attributes on group B .
2009-09-28 09:13:06 -05:00
The type option is a map that applies to all entries in the users , groups or
host location . It is primarily designed to be used when granting add
permissions ( to write new entries ) .
2010-08-24 22:40:32 -05:00
An ACI consists of three parts :
1. target
2. permissions
3. bind rules
The target is a set of rules that define which LDAP objects are being
2010-12-02 12:25:00 -06:00
targeted . This can include a list of attributes , an area of that LDAP
2010-08-24 22:40:32 -05:00
tree or an LDAP filter .
2010-12-02 12:25:00 -06:00
The targets include :
- attrs : list of attributes affected
- type : an object type ( user , group , host , service , etc )
- memberof : members of a group
- targetgroup : grant access to modify a specific group . This is primarily
designed to enable users to add or remove members of a specific group .
- filter : A legal LDAP filter used to narrow the scope of the target .
- subtree : Used to apply a rule across an entire set of objects . For example ,
to allow adding users you need to grant " add " permission to the subtree
ldap : / / uid = * , cn = users , cn = accounts , dc = example , dc = com . The subtree option
is a fail - safe for objects that may not be covered by the type option .
2011-09-05 09:30:05 -05:00
The permissions define what the ACI is allowed to do , and are one or
2010-12-02 12:25:00 -06:00
more of :
2010-08-24 22:40:32 -05:00
1. write - write one or more attributes
2. read - read one or more attributes
3. add - add a new entry to the tree
4. delete - delete an existing entry
5. all - all permissions are granted
Note the distinction between attributes and entries . The permissions are
independent , so being able to add a user does not mean that the user will
2011-05-04 03:26:18 -05:00
be editable .
2010-08-24 22:40:32 -05:00
The bind rule defines who this ACI grants permissions to . The LDAP server
allows this to be any valid LDAP entry but we encourage the use of
2010-12-01 10:23:52 -06:00
taskgroups so that the rights can be easily shared through roles .
2010-08-24 22:40:32 -05:00
2009-09-28 09:13:06 -05:00
For a more thorough description of access controls see
http : / / www . redhat . com / docs / manuals / dir - server / ag / 8.0 / Managing_Access_Control . html
EXAMPLES :
2011-05-04 03:26:18 -05:00
NOTE : ACIs are now added via the permission plugin . These examples are to
2010-12-02 12:25:00 -06:00
demonstrate how the various options work but this is done via the permission
command - line now ( see last example ) .
2010-08-24 22:40:32 -05:00
Add an ACI so that the group " secretaries " can update the address on any user :
2010-12-02 12:25:00 -06:00
ipa group - add - - desc = " Office secretaries " secretaries
2011-01-21 02:20:01 -06:00
ipa aci - add - - attrs = streetAddress - - memberof = ipausers - - group = secretaries - - permissions = write - - prefix = none " Secretaries write addresses "
2009-09-28 09:13:06 -05:00
Show the new ACI :
2011-01-21 02:20:01 -06:00
ipa aci - show - - prefix = none " Secretaries write addresses "
2009-09-28 09:13:06 -05:00
2010-12-02 12:25:00 -06:00
Add an ACI that allows members of the " addusers " permission to add new users :
2011-01-21 02:20:01 -06:00
ipa aci - add - - type = user - - permission = addusers - - permissions = add - - prefix = none " Add new users "
2009-09-28 09:13:06 -05:00
2010-12-02 12:25:00 -06:00
Add an ACI that allows members of the editors manage members of the admins group :
2011-01-21 02:20:01 -06:00
ipa aci - add - - permissions = write - - attrs = member - - targetgroup = admins - - group = editors - - prefix = none " Editors manage admins "
2010-12-01 10:23:52 -06:00
2011-09-05 09:30:05 -05:00
Add an ACI that allows members of the admins group to manage the street and zip code of those in the editors group :
2013-02-22 07:48:50 -06:00
ipa aci - add - - permissions = write - - memberof = editors - - group = admins - - attrs = street - - attrs = postalcode - - prefix = none " admins edit the address of editors "
2010-12-02 12:25:00 -06:00
Add an ACI that allows the admins group manage the street and zipcode of those who work for the boss :
2013-02-22 07:48:50 -06:00
ipa aci - add - - permissions = write - - group = admins - - attrs = street - - attrs = postalcode - - filter = " (manager=uid=boss,cn=users,cn=accounts,dc=example,dc=com) " - - prefix = none " Edit the address of those who work for the boss "
2010-12-02 12:25:00 -06:00
Add an entirely new kind of record to IPA that isn ' t covered by any of the --type options, creating a permission:
ipa permission - add - - permissions = add - - subtree = " cn=*,cn=orange,cn=accounts,dc=example,dc=com " - - desc = " Add Orange Entries " add_orange
2010-08-24 22:40:32 -05:00
The show command shows the raw 389 - ds ACI .
2009-09-28 09:13:06 -05:00
2010-08-10 12:22:50 -05:00
IMPORTANT : When modifying the target attributes of an existing ACI you
must include all existing attributes as well . When doing an aci - mod the
targetattr REPLACES the current attributes , it does not add to them .
2009-06-10 07:24:35 -05:00
"""
2012-01-06 06:58:01 -06:00
from copy import deepcopy
2009-06-10 07:24:35 -05:00
2015-09-11 06:43:28 -05:00
import six
2009-06-10 07:24:35 -05:00
from ipalib import api , crud , errors
2013-11-29 05:57:30 -06:00
from ipalib import Object
from ipalib import Flag , Str , StrEnum , DNParam
2009-06-10 07:24:35 -05:00
from ipalib . aci import ACI
2009-12-11 16:35:06 -06:00
from ipalib import output
from ipalib import _ , ngettext
2013-09-12 03:43:44 -05:00
from ipalib . plugable import Registry
2016-04-20 08:41:34 -05:00
from . baseldap import gen_pkey_only_option , pkey_to_value
2015-12-16 12:04:20 -06:00
from ipapython . ipa_log_manager import root_logger
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
from ipapython . dn import DN
2009-06-10 07:24:35 -05:00
2015-09-11 06:43:28 -05:00
if six . PY3 :
unicode = str
2013-09-12 03:43:44 -05:00
register = Registry ( )
2011-01-21 02:20:01 -06:00
ACI_NAME_PREFIX_SEP = " : "
2009-06-10 07:24:35 -05:00
_type_map = {
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
' user ' : ' ldap:/// ' + str ( DN ( ( ' uid ' , ' * ' ) , api . env . container_user , api . env . basedn ) ) ,
' group ' : ' ldap:/// ' + str ( DN ( ( ' cn ' , ' * ' ) , api . env . container_group , api . env . basedn ) ) ,
' host ' : ' ldap:/// ' + str ( DN ( ( ' fqdn ' , ' * ' ) , api . env . container_host , api . env . basedn ) ) ,
' hostgroup ' : ' ldap:/// ' + str ( DN ( ( ' cn ' , ' * ' ) , api . env . container_hostgroup , api . env . basedn ) ) ,
' service ' : ' ldap:/// ' + str ( DN ( ( ' krbprincipalname ' , ' * ' ) , api . env . container_service , api . env . basedn ) ) ,
' netgroup ' : ' ldap:/// ' + str ( DN ( ( ' ipauniqueid ' , ' * ' ) , api . env . container_netgroup , api . env . basedn ) ) ,
' dnsrecord ' : ' ldap:/// ' + str ( DN ( ( ' idnsname ' , ' * ' ) , api . env . container_dns , api . env . basedn ) ) ,
2009-06-10 07:24:35 -05:00
}
_valid_permissions_values = [
2010-08-24 22:40:32 -05:00
u ' read ' , u ' write ' , u ' add ' , u ' delete ' , u ' all '
2009-06-10 07:24:35 -05:00
]
2011-01-21 02:20:01 -06:00
_valid_prefix_values = (
u ' permission ' , u ' delegation ' , u ' selfservice ' , u ' none '
)
2009-12-11 16:35:06 -06:00
class ListOfACI ( output . Output ) :
type = ( list , tuple )
2010-03-05 15:11:21 -06:00
doc = _ ( ' A list of ACI values ' )
2009-12-11 16:35:06 -06:00
def validate ( self , cmd , entries ) :
assert isinstance ( entries , self . type )
for ( i , entry ) in enumerate ( entries ) :
if not isinstance ( entry , unicode ) :
raise TypeError ( output . emsg %
( cmd . name , self . __class__ . __name__ ,
self . name , i , unicode , type ( entry ) , entry )
)
aci_output = (
output . Output ( ' result ' , unicode , ' A string representing the ACI ' ) ,
output . value ,
output . summary ,
)
2011-01-21 02:20:01 -06:00
def _make_aci_name ( aciprefix , aciname ) :
"""
Given a name and a prefix construct an ACI name .
"""
if aciprefix == u " none " :
return aciname
return aciprefix + ACI_NAME_PREFIX_SEP + aciname
def _parse_aci_name ( aciname ) :
"""
Parse the raw ACI name and return a tuple containing the ACI prefix
and the actual ACI name .
"""
aciparts = aciname . partition ( ACI_NAME_PREFIX_SEP )
if not aciparts [ 2 ] : # no prefix/name separator found
return ( u " none " , aciparts [ 0 ] )
return ( aciparts [ 0 ] , aciparts [ 2 ] )
2009-06-10 07:24:35 -05:00
2011-01-31 12:10:37 -06:00
def _group_from_memberof ( memberof ) :
"""
Pull the group name out of a memberOf filter
"""
st = memberof . find ( ' memberOf= ' )
if st == - 1 :
# We have a raw group name, use that
return api . Object [ ' group ' ] . get_dn ( memberof )
en = memberof . find ( ' ) ' , st )
return memberof [ st + 9 : en ]
2011-01-20 15:35:34 -06:00
def _make_aci ( ldap , current , aciname , kw ) :
2010-08-10 12:22:50 -05:00
"""
Given a name and a set of keywords construct an ACI .
"""
# Do some quick and dirty validation.
2012-02-07 06:07:09 -06:00
checked_args = [ ' type ' , ' filter ' , ' subtree ' , ' targetgroup ' , ' attrs ' , ' memberof ' ]
valid = { }
for arg in checked_args :
if arg in kw :
valid [ arg ] = kw [ arg ] is not None
else :
valid [ arg ] = False
if valid [ ' type ' ] + valid [ ' filter ' ] + valid [ ' subtree ' ] + valid [ ' targetgroup ' ] > 1 :
2009-12-11 16:35:06 -06:00
raise errors . ValidationError ( name = ' target ' , error = _ ( ' type, filter, subtree and targetgroup are mutually exclusive ' ) )
2009-09-28 09:13:06 -05:00
2011-01-21 02:20:01 -06:00
if ' aciprefix ' not in kw :
raise errors . ValidationError ( name = ' aciprefix ' , error = _ ( ' ACI prefix is required ' ) )
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
if sum ( valid . values ( ) ) == 0 :
2009-12-11 16:35:06 -06:00
raise errors . ValidationError ( name = ' target ' , error = _ ( ' at least one of: type, filter, subtree, targetgroup, attrs or memberof are required ' ) )
2009-09-28 09:13:06 -05:00
2012-02-07 06:07:09 -06:00
if valid [ ' filter ' ] + valid [ ' memberof ' ] > 1 :
2011-01-31 12:10:37 -06:00
raise errors . ValidationError ( name = ' target ' , error = _ ( ' filter and memberof are mutually exclusive ' ) )
2009-09-28 09:13:06 -05:00
group = ' group ' in kw
2010-12-01 10:23:52 -06:00
permission = ' permission ' in kw
2010-08-10 12:22:50 -05:00
selfaci = ' selfaci ' in kw and kw [ ' selfaci ' ] == True
2010-12-01 10:23:52 -06:00
if group + permission + selfaci > 1 :
raise errors . ValidationError ( name = ' target ' , error = _ ( ' group, permission and self are mutually exclusive ' ) )
elif group + permission + selfaci == 0 :
raise errors . ValidationError ( name = ' target ' , error = _ ( ' One of group, permission or self is required ' ) )
2009-09-28 09:13:06 -05:00
# Grab the dn of the group we're granting access to. This group may be a
2010-12-01 10:23:52 -06:00
# permission or a user group.
2009-12-11 16:35:06 -06:00
entry_attrs = [ ]
2010-12-01 10:23:52 -06:00
if permission :
# This will raise NotFound if the permission doesn't exist
2009-09-28 09:13:06 -05:00
try :
2010-12-01 10:23:52 -06:00
entry_attrs = api . Command [ ' permission_show ' ] ( kw [ ' permission ' ] ) [ ' result ' ]
2015-07-30 09:49:29 -05:00
except errors . NotFound as e :
2010-12-01 10:23:52 -06:00
if ' test ' in kw and not kw . get ( ' test ' ) :
raise e
else :
2013-02-04 02:47:00 -06:00
entry_attrs = {
' dn ' : DN ( ( ' cn ' , kw [ ' permission ' ] ) ,
api . env . container_permission , api . env . basedn ) ,
}
2009-09-28 09:13:06 -05:00
elif group :
# Not so friendly with groups. This will raise
try :
2013-06-25 07:58:37 -05:00
group_dn = api . Object [ ' group ' ] . get_dn_if_exists ( kw [ ' group ' ] )
entry_attrs = { ' dn ' : group_dn }
2009-09-28 09:13:06 -05:00
except errors . NotFound :
2009-12-11 16:35:06 -06:00
raise errors . NotFound ( reason = _ ( " Group ' %s ' does not exist " ) % kw [ ' group ' ] )
2009-06-10 07:24:35 -05:00
2010-12-21 21:39:55 -06:00
try :
a = ACI ( current )
2011-01-21 02:20:01 -06:00
a . name = _make_aci_name ( kw [ ' aciprefix ' ] , aciname )
2010-12-21 21:39:55 -06:00
a . permissions = kw [ ' permissions ' ]
if ' selfaci ' in kw and kw [ ' selfaci ' ] :
a . set_bindrule ( ' userdn = " ldap:///self " ' )
else :
dn = entry_attrs [ ' dn ' ]
a . set_bindrule ( ' groupdn = " ldap:/// %s " ' % dn )
2012-02-07 06:07:09 -06:00
if valid [ ' attrs ' ] :
2010-12-21 21:39:55 -06:00
a . set_target_attr ( kw [ ' attrs ' ] )
2012-02-07 06:07:09 -06:00
if valid [ ' memberof ' ] :
try :
2013-06-25 07:58:37 -05:00
api . Object [ ' group ' ] . get_dn_if_exists ( kw [ ' memberof ' ] )
2012-02-07 06:07:09 -06:00
except errors . NotFound :
api . Object [ ' group ' ] . handle_not_found ( kw [ ' memberof ' ] )
2011-01-31 12:10:37 -06:00
groupdn = _group_from_memberof ( kw [ ' memberof ' ] )
a . set_target_filter ( ' memberOf= %s ' % groupdn )
2012-02-07 06:07:09 -06:00
if valid [ ' filter ' ] :
2011-01-20 15:35:34 -06:00
# Test the filter by performing a simple search on it. The
# filter is considered valid if either it returns some entries
# or it returns no entries, otherwise we let whatever exception
# happened be raised.
if kw [ ' filter ' ] in ( ' ' , None , u ' ' ) :
raise errors . BadSearchFilter ( info = _ ( ' empty filter ' ) )
try :
entries = ldap . find_entries ( filter = kw [ ' filter ' ] )
except errors . NotFound :
pass
2010-12-21 21:39:55 -06:00
a . set_target_filter ( kw [ ' filter ' ] )
2012-02-07 06:07:09 -06:00
if valid [ ' type ' ] :
2010-12-21 21:39:55 -06:00
target = _type_map [ kw [ ' type ' ] ]
a . set_target ( target )
2012-02-07 06:07:09 -06:00
if valid [ ' targetgroup ' ] :
2010-12-21 21:39:55 -06:00
# Purposely no try here so we'll raise a NotFound
2013-06-25 07:58:37 -05:00
group_dn = api . Object [ ' group ' ] . get_dn_if_exists ( kw [ ' targetgroup ' ] )
target = ' ldap:/// %s ' % group_dn
2010-12-21 21:39:55 -06:00
a . set_target ( target )
2012-02-07 06:07:09 -06:00
if valid [ ' subtree ' ] :
2010-12-21 21:39:55 -06:00
# See if the subtree is a full URI
target = kw [ ' subtree ' ]
if not target . startswith ( ' ldap:/// ' ) :
target = ' ldap:/// %s ' % target
a . set_target ( target )
2015-07-30 09:49:29 -05:00
except SyntaxError as e :
2010-12-21 21:39:55 -06:00
raise errors . ValidationError ( name = ' target ' , error = _ ( ' Syntax Error: %(error)s ' ) % dict ( error = str ( e ) ) )
2009-06-10 07:24:35 -05:00
return a
2012-01-16 04:14:59 -06:00
def _aci_to_kw ( ldap , a , test = False , pkey_only = False ) :
2010-06-11 11:11:24 -05:00
""" Convert an ACI into its equivalent keywords.
This is used for the modify operation so we can merge the
incoming kw and existing ACI and pass the result to
_make_aci ( ) .
"""
kw = { }
2011-01-21 02:20:01 -06:00
kw [ ' aciprefix ' ] , kw [ ' aciname ' ] = _parse_aci_name ( a . name )
2012-01-16 04:14:59 -06:00
if pkey_only :
return kw
2010-06-11 11:11:24 -05:00
kw [ ' permissions ' ] = tuple ( a . permissions )
if ' targetattr ' in a . target :
2015-08-12 08:23:56 -05:00
kw [ ' attrs ' ] = tuple ( unicode ( e )
for e in a . target [ ' targetattr ' ] [ ' expression ' ] )
2010-06-11 11:11:24 -05:00
if ' targetfilter ' in a . target :
target = a . target [ ' targetfilter ' ] [ ' expression ' ]
2011-12-06 17:15:41 -06:00
if target . startswith ( ' (memberOf= ' ) or target . startswith ( ' memberOf= ' ) :
( junk , memberof ) = target . split ( ' memberOf= ' , 1 )
memberof = DN ( memberof )
kw [ ' memberof ' ] = memberof [ ' cn ' ]
2010-06-11 11:11:24 -05:00
else :
2010-11-03 10:30:03 -05:00
kw [ ' filter ' ] = unicode ( target )
2010-06-11 11:11:24 -05:00
if ' target ' in a . target :
target = a . target [ ' target ' ] [ ' expression ' ]
found = False
for k in _type_map . keys ( ) :
if _type_map [ k ] == target :
kw [ ' type ' ] = unicode ( k )
found = True
2016-03-20 15:32:27 -05:00
break
2010-06-11 11:11:24 -05:00
if not found :
if target . startswith ( ' ( ' ) :
2010-11-03 10:30:03 -05:00
kw [ ' filter ' ] = unicode ( target )
2010-06-11 11:11:24 -05:00
else :
# See if the target is a group. If so we set the
# targetgroup attr, otherwise we consider it a subtree
2013-01-03 07:40:40 -06:00
try :
targetdn = DN ( target . replace ( ' ldap:/// ' , ' ' ) )
except ValueError as e :
raise errors . ValidationError ( name = ' subtree ' , error = _ ( " invalid DN ( %s ) " ) % e . message )
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
if targetdn . endswith ( DN ( api . env . container_group , api . env . basedn ) ) :
kw [ ' targetgroup ' ] = targetdn [ 0 ] [ ' cn ' ]
2010-06-11 11:11:24 -05:00
else :
2010-11-03 10:30:03 -05:00
kw [ ' subtree ' ] = unicode ( target )
2010-06-11 11:11:24 -05:00
groupdn = a . bindrule [ ' expression ' ]
groupdn = groupdn . replace ( ' ldap:/// ' , ' ' )
2010-08-10 12:22:50 -05:00
if groupdn == ' self ' :
kw [ ' selfaci ' ] = True
2010-11-03 10:30:03 -05:00
elif groupdn == ' anyone ' :
pass
2010-06-11 11:11:24 -05:00
else :
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
groupdn = DN ( groupdn )
if len ( groupdn ) and groupdn [ 0 ] . attr == ' cn ' :
dn = DN ( )
2013-10-31 11:54:21 -05:00
entry = ldap . make_entry ( dn )
2010-12-01 10:23:52 -06:00
try :
2013-10-21 06:24:05 -05:00
entry = ldap . get_entry ( groupdn , [ ' cn ' ] )
2015-07-30 09:49:29 -05:00
except errors . NotFound as e :
2010-12-01 10:23:52 -06:00
# FIXME, use real name here
if test :
2013-02-04 02:47:00 -06:00
dn = DN ( ( ' cn ' , ' test ' ) , api . env . container_permission ,
api . env . basedn )
2013-10-31 11:54:21 -05:00
entry = ldap . make_entry ( dn , { ' cn ' : [ u ' test ' ] } )
if api . env . container_permission in entry . dn :
2013-10-21 06:24:05 -05:00
kw [ ' permission ' ] = entry [ ' cn ' ] [ 0 ]
2010-11-03 10:30:03 -05:00
else :
2013-10-21 06:24:05 -05:00
if ' cn ' in entry :
kw [ ' group ' ] = entry [ ' cn ' ] [ 0 ]
2010-06-11 11:11:24 -05:00
return kw
2009-06-10 07:24:35 -05:00
def _convert_strings_to_acis ( acistrs ) :
acis = [ ]
for a in acistrs :
try :
acis . append ( ACI ( a ) )
2015-07-30 09:49:29 -05:00
except SyntaxError as e :
2011-11-15 13:39:31 -06:00
root_logger . warning ( " Failed to parse: %s " % a )
2009-06-10 07:24:35 -05:00
return acis
2011-01-21 02:20:01 -06:00
def _find_aci_by_name ( acis , aciprefix , aciname ) :
name = _make_aci_name ( aciprefix , aciname ) . lower ( )
2009-06-10 07:24:35 -05:00
for a in acis :
2011-01-21 02:20:01 -06:00
if a . name . lower ( ) == name :
2009-06-10 07:24:35 -05:00
return a
2009-12-11 16:35:06 -06:00
raise errors . NotFound ( reason = _ ( ' ACI with name " %s " not found ' ) % aciname )
2009-06-10 07:24:35 -05:00
2010-11-03 10:30:03 -05:00
2013-02-14 06:23:06 -06:00
def validate_permissions ( ugettext , perm ) :
perm = perm . strip ( ) . lower ( )
if perm not in _valid_permissions_values :
return ' " %s " is not a valid permission ' % perm
def _normalize_permissions ( perm ) :
2009-06-10 07:24:35 -05:00
valid_permissions = [ ]
2013-02-14 06:23:06 -06:00
perm = perm . strip ( ) . lower ( )
if perm not in valid_permissions :
valid_permissions . append ( perm )
2009-06-10 07:24:35 -05:00
return ' , ' . join ( valid_permissions )
2011-01-21 02:20:01 -06:00
_prefix_option = StrEnum ( ' aciprefix ' ,
cli_name = ' prefix ' ,
label = _ ( ' ACI prefix ' ) ,
doc = _ ( ' Prefix used to distinguish ACI types ' \
' (permission, delegation, selfservice, none) ' ) ,
values = _valid_prefix_values ,
)
2009-06-10 07:24:35 -05:00
2013-09-12 03:43:44 -05:00
@register ( )
2009-06-16 07:38:27 -05:00
class aci ( Object ) :
2009-06-10 07:24:35 -05:00
"""
ACI object .
"""
2011-01-20 14:07:43 -06:00
NO_CLI = True
2010-02-08 06:03:28 -06:00
label = _ ( ' ACIs ' )
2009-06-10 07:24:35 -05:00
takes_params = (
Str ( ' aciname ' ,
cli_name = ' name ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' ACI name ' ) ,
2009-06-10 07:24:35 -05:00
primary_key = True ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
2010-12-01 10:23:52 -06:00
Str ( ' permission? ' ,
cli_name = ' permission ' ,
label = _ ( ' Permission ' ) ,
doc = _ ( ' Permission ACI grants access to ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
2009-09-28 09:13:06 -05:00
Str ( ' group? ' ,
cli_name = ' group ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' User group ' ) ,
doc = _ ( ' User group ACI grants access to ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-09-28 09:13:06 -05:00
) ,
2011-11-21 09:50:27 -06:00
Str ( ' permissions+ ' , validate_permissions ,
2009-06-10 07:24:35 -05:00
cli_name = ' permissions ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' Permissions ' ) ,
2013-02-14 11:01:16 -06:00
doc = _ ( ' Permissions to grant ' \
2010-08-24 22:40:32 -05:00
' (read, write, add, delete, all) ' ) ,
2009-06-10 07:24:35 -05:00
normalizer = _normalize_permissions ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
2011-11-21 09:50:27 -06:00
Str ( ' attrs* ' ,
2009-06-10 07:24:35 -05:00
cli_name = ' attrs ' ,
2013-02-14 11:01:16 -06:00
label = _ ( ' Attributes to which the permission applies ' ) ,
doc = _ ( ' Attributes ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
StrEnum ( ' type? ' ,
cli_name = ' type ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' Type ' ) ,
2010-11-03 10:30:03 -05:00
doc = _ ( ' type of IPA object (user, group, host, hostgroup, service, netgroup) ' ) ,
2011-01-13 10:32:57 -06:00
values = ( u ' user ' , u ' group ' , u ' host ' , u ' service ' , u ' hostgroup ' , u ' netgroup ' , u ' dnsrecord ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
Str ( ' memberof? ' ,
cli_name = ' memberof ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' Member of ' ) , # FIXME: Does this label make sense?
doc = _ ( ' Member of a group ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
Str ( ' filter? ' ,
cli_name = ' filter ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' Filter ' ) ,
doc = _ ( ' Legal LDAP filter (e.g. ou=Engineering) ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
Str ( ' subtree? ' ,
cli_name = ' subtree ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' Subtree ' ) ,
doc = _ ( ' Subtree to apply ACI to ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
Str ( ' targetgroup? ' ,
cli_name = ' targetgroup ' ,
2010-02-19 10:08:16 -06:00
label = _ ( ' Target group ' ) ,
doc = _ ( ' Group to apply ACI to ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2009-06-10 07:24:35 -05:00
) ,
2010-08-10 12:22:50 -05:00
Flag ( ' selfaci? ' ,
cli_name = ' self ' ,
label = _ ( ' Target your own entry (self) ' ) ,
doc = _ ( ' Apply ACI to your own entry (self) ' ) ,
2011-11-14 10:03:44 -06:00
flags = ( ' virtual_attribute ' , ) ,
2010-08-10 12:22:50 -05:00
) ,
2009-06-10 07:24:35 -05:00
)
2013-09-12 03:43:44 -05:00
@register ( )
2009-06-16 09:51:44 -05:00
class aci_add ( crud . Create ) :
2009-06-10 07:24:35 -05:00
"""
Create new ACI .
"""
2011-01-20 14:07:43 -06:00
NO_CLI = True
2009-12-11 16:35:06 -06:00
msg_summary = _ ( ' Created ACI " %(value)s " ' )
2010-12-01 10:23:52 -06:00
takes_options = (
2011-01-21 02:20:01 -06:00
_prefix_option ,
2010-12-01 10:23:52 -06:00
Flag ( ' test? ' ,
doc = _ ( ' Test the ACI syntax but don \' t write anything ' ) ,
default = False ,
) ,
)
2009-06-10 07:24:35 -05:00
def execute ( self , aciname , * * kw ) :
"""
Execute the aci - create operation .
Returns the entry as it will be created in LDAP .
: param aciname : The name of the ACI being added .
: param kw : Keyword arguments for the other LDAP attributes .
"""
assert ' aciname ' not in kw
ldap = self . api . Backend . ldap2
2011-01-20 15:35:34 -06:00
newaci = _make_aci ( ldap , None , aciname , kw )
2009-06-10 07:24:35 -05:00
2013-10-21 06:24:05 -05:00
entry = ldap . get_entry ( self . api . env . basedn , [ ' aci ' ] )
2009-06-10 07:24:35 -05:00
2013-10-21 06:24:05 -05:00
acis = _convert_strings_to_acis ( entry . get ( ' aci ' , [ ] ) )
2009-06-10 07:24:35 -05:00
for a in acis :
2010-12-01 10:23:52 -06:00
# FIXME: add check for permission_group = permission_group
if a . isequal ( newaci ) or newaci . name == a . name :
2009-06-10 07:24:35 -05:00
raise errors . DuplicateEntry ( )
2009-12-11 16:35:06 -06:00
newaci_str = unicode ( newaci )
2014-05-27 09:41:43 -05:00
entry . setdefault ( ' aci ' , [ ] ) . append ( newaci_str )
2009-06-10 07:24:35 -05:00
2010-12-01 10:23:52 -06:00
if not kw . get ( ' test ' , False ) :
2013-10-21 06:24:05 -05:00
ldap . update_entry ( entry )
2009-06-10 07:24:35 -05:00
2010-11-03 10:30:03 -05:00
if kw . get ( ' raw ' , False ) :
result = dict ( aci = unicode ( newaci_str ) )
else :
2010-12-01 10:23:52 -06:00
result = _aci_to_kw ( ldap , newaci , kw . get ( ' test ' , False ) )
2009-12-11 16:35:06 -06:00
return dict (
2010-11-03 10:30:03 -05:00
result = result ,
2014-03-27 08:04:00 -05:00
value = pkey_to_value ( aciname , kw ) ,
2009-12-11 16:35:06 -06:00
)
2009-06-10 07:24:35 -05:00
2013-09-12 03:43:44 -05:00
@register ( )
2009-06-16 09:51:44 -05:00
class aci_del ( crud . Delete ) :
2009-06-10 07:24:35 -05:00
"""
Delete ACI .
"""
2011-01-20 14:07:43 -06:00
NO_CLI = True
2011-01-07 10:17:55 -06:00
has_output = output . standard_boolean
2009-12-11 16:35:06 -06:00
msg_summary = _ ( ' Deleted ACI " %(value)s " ' )
2011-01-21 02:20:01 -06:00
takes_options = ( _prefix_option , )
2012-06-21 07:20:26 -05:00
def execute ( self , aciname , aciprefix , * * options ) :
2009-06-10 07:24:35 -05:00
"""
Execute the aci - delete operation .
2011-11-10 18:53:21 -06:00
: param aciname : The name of the ACI being deleted .
2012-04-17 11:48:33 -05:00
: param aciprefix : The ACI prefix .
2009-06-10 07:24:35 -05:00
"""
ldap = self . api . Backend . ldap2
2013-10-21 06:24:05 -05:00
entry = ldap . get_entry ( self . api . env . basedn , [ ' aci ' ] )
2009-06-10 07:24:35 -05:00
2013-10-21 06:24:05 -05:00
acistrs = entry . get ( ' aci ' , [ ] )
2009-06-10 07:24:35 -05:00
acis = _convert_strings_to_acis ( acistrs )
2012-04-17 11:48:33 -05:00
aci = _find_aci_by_name ( acis , aciprefix , aciname )
2009-06-10 07:24:35 -05:00
for a in acistrs :
2009-09-28 09:13:06 -05:00
candidate = ACI ( a )
if aci . isequal ( candidate ) :
2009-06-10 07:24:35 -05:00
acistrs . remove ( a )
break
2013-10-21 06:24:05 -05:00
entry [ ' aci ' ] = acistrs
2009-06-10 07:24:35 -05:00
2013-10-21 06:24:05 -05:00
ldap . update_entry ( entry )
2009-06-10 07:24:35 -05:00
2009-12-11 16:35:06 -06:00
return dict (
result = True ,
2014-03-27 08:04:00 -05:00
value = pkey_to_value ( aciname , options ) ,
2009-12-11 16:35:06 -06:00
)
2009-06-10 07:24:35 -05:00
2013-09-12 03:43:44 -05:00
@register ( )
2009-06-16 07:38:27 -05:00
class aci_mod ( crud . Update ) :
2009-06-10 07:24:35 -05:00
"""
Modify ACI .
"""
2011-01-20 14:07:43 -06:00
NO_CLI = True
2010-11-03 10:30:03 -05:00
has_output_params = (
Str ( ' aci ' ,
label = _ ( ' ACI ' ) ,
) ,
)
2011-01-21 02:20:01 -06:00
takes_options = ( _prefix_option , )
2012-04-17 11:42:35 -05:00
internal_options = [ ' rename ' ]
2009-12-11 16:35:06 -06:00
msg_summary = _ ( ' Modified ACI " %(value)s " ' )
2009-06-10 07:24:35 -05:00
def execute ( self , aciname , * * kw ) :
2012-04-17 11:48:33 -05:00
aciprefix = kw [ ' aciprefix ' ]
2009-06-10 07:24:35 -05:00
ldap = self . api . Backend . ldap2
2009-09-28 09:13:06 -05:00
2013-10-21 06:24:05 -05:00
entry = ldap . get_entry ( self . api . env . basedn , [ ' aci ' ] )
2009-06-10 07:24:35 -05:00
2013-10-21 06:24:05 -05:00
acis = _convert_strings_to_acis ( entry . get ( ' aci ' , [ ] ) )
2012-04-17 11:48:33 -05:00
aci = _find_aci_by_name ( acis , aciprefix , aciname )
2009-06-10 07:24:35 -05:00
2010-06-11 11:11:24 -05:00
# The strategy here is to convert the ACI we're updating back into
# a series of keywords. Then we replace any keywords that have been
# updated and convert that back into an ACI and write it out.
2012-01-06 06:58:01 -06:00
oldkw = _aci_to_kw ( ldap , aci )
newkw = deepcopy ( oldkw )
2012-04-17 11:48:33 -05:00
if newkw . get ( ' selfaci ' , False ) :
2010-08-10 12:22:50 -05:00
# selfaci is set in aci_to_kw to True only if the target is self
kw [ ' selfaci ' ] = True
2012-04-17 11:48:33 -05:00
newkw . update ( kw )
2012-01-06 06:58:01 -06:00
for acikw in ( oldkw , newkw ) :
2012-04-17 11:48:33 -05:00
acikw . pop ( ' aciname ' , None )
2009-06-10 07:24:35 -05:00
2010-08-10 12:22:50 -05:00
# _make_aci is what is run in aci_add and validates the input.
# Do this before we delete the existing ACI.
2011-01-20 15:35:34 -06:00
newaci = _make_aci ( ldap , None , aciname , newkw )
2010-12-01 10:23:52 -06:00
if aci . isequal ( newaci ) :
raise errors . EmptyModlist ( )
2010-08-10 12:22:50 -05:00
2012-04-17 11:48:33 -05:00
self . api . Command [ ' aci_del ' ] ( aciname , aciprefix = aciprefix )
2009-06-10 07:24:35 -05:00
2012-01-06 06:58:01 -06:00
try :
result = self . api . Command [ ' aci_add ' ] ( aciname , * * newkw ) [ ' result ' ]
2015-07-30 09:49:29 -05:00
except Exception as e :
2012-01-06 06:58:01 -06:00
# ACI could not be added, try to restore the old deleted ACI and
# report the ADD error back to user
try :
self . api . Command [ ' aci_add ' ] ( aciname , * * oldkw )
2012-04-17 11:48:33 -05:00
except Exception :
2012-01-06 06:58:01 -06:00
pass
raise e
2010-06-11 11:11:24 -05:00
2010-11-03 10:30:03 -05:00
if kw . get ( ' raw ' , False ) :
result = dict ( aci = unicode ( newaci ) )
else :
result = _aci_to_kw ( ldap , newaci )
2010-06-11 11:11:24 -05:00
return dict (
result = result ,
2014-03-27 08:04:00 -05:00
value = pkey_to_value ( aciname , kw ) ,
2010-06-11 11:11:24 -05:00
)
2009-06-10 07:24:35 -05:00
2013-09-12 03:43:44 -05:00
@register ( )
2009-06-16 07:38:27 -05:00
class aci_find ( crud . Search ) :
2009-06-10 07:24:35 -05:00
"""
Search for ACIs .
2009-09-28 09:13:06 -05:00
Returns a list of ACIs
EXAMPLES :
To find all ACIs that apply directly to members of the group ipausers :
ipa aci - find - - memberof = ipausers
To find all ACIs that grant add access :
ipa aci - find - - permissions = add
Note that the find command only looks for the given text in the set of
ACIs , it does not evaluate the ACIs to see if something would apply .
For example , searching on memberof = ipausers will find all ACIs that
have ipausers as a memberof . There may be other ACIs that apply to
members of that group indirectly .
2009-06-10 07:24:35 -05:00
"""
2011-01-20 14:07:43 -06:00
NO_CLI = True
2009-12-11 16:35:06 -06:00
msg_summary = ngettext ( ' %(count)d ACI matched ' , ' %(count)d ACIs matched ' , 0 )
2012-01-16 04:14:59 -06:00
takes_options = ( _prefix_option . clone_rename ( " aciprefix? " , required = False ) ,
gen_pkey_only_option ( " name " ) , )
2011-01-21 02:20:01 -06:00
2016-05-19 07:19:07 -05:00
def execute ( self , term = None , * * kw ) :
2009-06-10 07:24:35 -05:00
ldap = self . api . Backend . ldap2
2013-10-21 06:24:05 -05:00
entry = ldap . get_entry ( self . api . env . basedn , [ ' aci ' ] )
2009-06-10 07:24:35 -05:00
2013-10-21 06:24:05 -05:00
acis = _convert_strings_to_acis ( entry . get ( ' aci ' , [ ] ) )
2009-06-10 07:24:35 -05:00
results = [ ]
if term :
term = term . lower ( )
for a in acis :
if a . name . lower ( ) . find ( term ) != - 1 and a not in results :
results . append ( a )
acis = list ( results )
else :
results = list ( acis )
2012-01-06 05:44:59 -06:00
if kw . get ( ' aciname ' ) :
2009-06-10 07:24:35 -05:00
for a in acis :
2011-01-21 02:20:01 -06:00
prefix , name = _parse_aci_name ( a . name )
if name != kw [ ' aciname ' ] :
results . remove ( a )
acis = list ( results )
2012-01-06 05:44:59 -06:00
if kw . get ( ' aciprefix ' ) :
2011-01-21 02:20:01 -06:00
for a in acis :
prefix , name = _parse_aci_name ( a . name )
if prefix != kw [ ' aciprefix ' ] :
2009-06-10 07:24:35 -05:00
results . remove ( a )
acis = list ( results )
2012-01-06 05:44:59 -06:00
if kw . get ( ' attrs ' ) :
2009-06-10 07:24:35 -05:00
for a in acis :
2010-11-03 10:30:03 -05:00
if not ' targetattr ' in a . target :
results . remove ( a )
continue
2009-06-10 07:24:35 -05:00
alist1 = sorted (
[ t . lower ( ) for t in a . target [ ' targetattr ' ] [ ' expression ' ] ]
)
alist2 = sorted ( [ t . lower ( ) for t in kw [ ' attrs ' ] ] )
2010-11-03 10:30:03 -05:00
if len ( set ( alist1 ) & set ( alist2 ) ) != len ( alist2 ) :
2009-06-10 07:24:35 -05:00
results . remove ( a )
acis = list ( results )
2012-01-06 05:44:59 -06:00
if kw . get ( ' permission ' ) :
2009-06-10 07:24:35 -05:00
try :
2010-12-01 10:23:52 -06:00
self . api . Command [ ' permission_show ' ] (
kw [ ' permission ' ]
2010-06-11 11:11:24 -05:00
)
2009-06-10 07:24:35 -05:00
except errors . NotFound :
pass
else :
for a in acis :
2013-10-31 11:54:21 -05:00
uri = ' ldap:/// %s ' % entry . dn
if a . bindrule [ ' expression ' ] != uri :
2009-06-10 07:24:35 -05:00
results . remove ( a )
acis = list ( results )
2012-01-06 05:44:59 -06:00
if kw . get ( ' permissions ' ) :
2009-06-10 07:24:35 -05:00
for a in acis :
alist1 = sorted ( a . permissions )
alist2 = sorted ( kw [ ' permissions ' ] )
2010-11-03 10:30:03 -05:00
if len ( set ( alist1 ) & set ( alist2 ) ) != len ( alist2 ) :
2009-06-10 07:24:35 -05:00
results . remove ( a )
2010-11-03 10:30:03 -05:00
acis = list ( results )
2009-06-10 07:24:35 -05:00
2012-01-06 05:44:59 -06:00
if kw . get ( ' memberof ' ) :
2009-06-10 07:24:35 -05:00
try :
2011-01-31 12:10:37 -06:00
dn = _group_from_memberof ( kw [ ' memberof ' ] )
2009-06-10 07:24:35 -05:00
except errors . NotFound :
pass
else :
memberof_filter = ' (memberOf= %s ) ' % dn
for a in acis :
if ' targetfilter ' in a . target :
2009-09-28 09:13:06 -05:00
targetfilter = a . target [ ' targetfilter ' ] [ ' expression ' ]
if targetfilter != memberof_filter :
2009-06-10 07:24:35 -05:00
results . remove ( a )
else :
results . remove ( a )
2012-01-06 05:44:59 -06:00
if kw . get ( ' type ' ) :
2010-12-10 12:31:58 -06:00
for a in acis :
2010-12-08 12:33:40 -06:00
if ' target ' in a . target :
target = a . target [ ' target ' ] [ ' expression ' ]
else :
2010-12-01 10:23:52 -06:00
results . remove ( a )
2010-12-08 12:33:40 -06:00
continue
found = False
for k in _type_map . keys ( ) :
if _type_map [ k ] == target and kw [ ' type ' ] == k :
found = True
2016-03-20 15:32:27 -05:00
break
2010-12-08 12:33:40 -06:00
if not found :
try :
results . remove ( a )
except ValueError :
pass
2012-01-06 05:44:59 -06:00
if kw . get ( ' selfaci ' , False ) is True :
2010-12-08 12:33:40 -06:00
for a in acis :
if a . bindrule [ ' expression ' ] != u ' ldap:///self ' :
try :
results . remove ( a )
except ValueError :
pass
2010-12-01 10:23:52 -06:00
2012-01-06 05:44:59 -06:00
if kw . get ( ' group ' ) :
2010-12-10 12:31:58 -06:00
for a in acis :
groupdn = a . bindrule [ ' expression ' ]
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
groupdn = DN ( groupdn . replace ( ' ldap:/// ' , ' ' ) )
try :
2012-12-19 08:38:52 -06:00
cn = groupdn [ 0 ] [ ' cn ' ]
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
except ( IndexError , KeyError ) :
cn = None
2010-12-10 12:31:58 -06:00
if cn is None or cn != kw [ ' group ' ] :
try :
results . remove ( a )
except ValueError :
pass
2012-01-06 05:44:59 -06:00
if kw . get ( ' targetgroup ' ) :
2010-12-10 12:31:58 -06:00
for a in acis :
found = False
if ' target ' in a . target :
target = a . target [ ' target ' ] [ ' expression ' ]
2013-01-10 05:13:39 -06:00
targetdn = DN ( target . replace ( ' ldap:/// ' , ' ' ) )
group_container_dn = DN ( api . env . container_group , api . env . basedn )
if targetdn . endswith ( group_container_dn ) :
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
try :
cn = targetdn [ 0 ] [ ' cn ' ]
except ( IndexError , KeyError ) :
cn = None
2010-12-10 12:31:58 -06:00
if cn == kw [ ' targetgroup ' ] :
found = True
if not found :
try :
results . remove ( a )
except ValueError :
pass
2012-01-06 05:44:59 -06:00
if kw . get ( ' filter ' ) :
2011-01-27 04:11:28 -06:00
if not kw [ ' filter ' ] . startswith ( ' ( ' ) :
kw [ ' filter ' ] = unicode ( ' ( ' + kw [ ' filter ' ] + ' ) ' )
for a in acis :
if ' targetfilter ' not in a . target or \
not a . target [ ' targetfilter ' ] [ ' expression ' ] or \
a . target [ ' targetfilter ' ] [ ' expression ' ] != kw [ ' filter ' ] :
results . remove ( a )
2012-05-11 15:15:58 -05:00
if kw . get ( ' subtree ' ) :
for a in acis :
if ' target ' in a . target :
target = a . target [ ' target ' ] [ ' expression ' ]
else :
results . remove ( a )
continue
if kw [ ' subtree ' ] . lower ( ) != target . lower ( ) :
try :
results . remove ( a )
except ValueError :
pass
2009-06-10 07:24:35 -05:00
2010-11-03 10:30:03 -05:00
acis = [ ]
for result in results :
if kw . get ( ' raw ' , False ) :
aci = dict ( aci = unicode ( result ) )
else :
2012-01-16 04:14:59 -06:00
aci = _aci_to_kw ( ldap , result ,
pkey_only = kw . get ( ' pkey_only ' , False ) )
2010-11-03 10:30:03 -05:00
acis . append ( aci )
2009-06-10 07:24:35 -05:00
2010-11-03 10:30:03 -05:00
return dict (
result = acis ,
count = len ( acis ) ,
truncated = False ,
2009-06-10 07:24:35 -05:00
)
2013-09-12 03:43:44 -05:00
@register ( )
2009-06-16 07:38:27 -05:00
class aci_show ( crud . Retrieve ) :
2009-06-10 07:24:35 -05:00
"""
2009-09-28 09:13:06 -05:00
Display a single ACI given an ACI name .
2009-06-10 07:24:35 -05:00
"""
2011-01-20 14:07:43 -06:00
NO_CLI = True
2010-11-03 10:30:03 -05:00
has_output_params = (
Str ( ' aci ' ,
label = _ ( ' ACI ' ) ,
) ,
2009-12-11 16:35:06 -06:00
)
2013-11-29 05:57:30 -06:00
takes_options = (
_prefix_option ,
DNParam ( ' location? ' ,
label = _ ( ' Location of the ACI ' ) ,
)
)
2011-01-21 02:20:01 -06:00
2009-06-10 07:24:35 -05:00
def execute ( self , aciname , * * kw ) :
"""
Execute the aci - show operation .
Returns the entry
: param uid : The login name of the user to retrieve .
: param kw : unused
"""
ldap = self . api . Backend . ldap2
2013-11-29 05:57:30 -06:00
dn = kw . get ( ' location ' , self . api . env . basedn )
entry = ldap . get_entry ( dn , [ ' aci ' ] )
2009-06-10 07:24:35 -05:00
2013-10-21 06:24:05 -05:00
acis = _convert_strings_to_acis ( entry . get ( ' aci ' , [ ] ) )
2009-06-10 07:24:35 -05:00
2011-01-21 02:20:01 -06:00
aci = _find_aci_by_name ( acis , kw [ ' aciprefix ' ] , aciname )
2010-11-03 10:30:03 -05:00
if kw . get ( ' raw ' , False ) :
result = dict ( aci = unicode ( aci ) )
else :
result = _aci_to_kw ( ldap , aci )
2009-12-11 16:35:06 -06:00
return dict (
2010-11-03 10:30:03 -05:00
result = result ,
2014-03-27 08:04:00 -05:00
value = pkey_to_value ( aciname , kw ) ,
2009-12-11 16:35:06 -06:00
)
2009-06-10 07:24:35 -05:00
2010-12-01 10:23:52 -06:00
2013-09-12 03:43:44 -05:00
@register ( )
2010-12-01 10:23:52 -06:00
class aci_rename ( crud . Update ) :
"""
Rename an ACI .
"""
2011-01-20 14:07:43 -06:00
NO_CLI = True
2010-12-01 10:23:52 -06:00
has_output_params = (
Str ( ' aci ' ,
label = _ ( ' ACI ' ) ,
) ,
)
takes_options = (
2011-01-21 02:20:01 -06:00
_prefix_option ,
2010-12-01 10:23:52 -06:00
Str ( ' newname ' ,
doc = _ ( ' New ACI name ' ) ,
) ,
)
2011-01-21 02:20:01 -06:00
msg_summary = _ ( ' Renamed ACI to " %(value)s " ' )
2010-12-01 10:23:52 -06:00
def execute ( self , aciname , * * kw ) :
ldap = self . api . Backend . ldap2
2013-10-21 06:24:05 -05:00
entry = ldap . get_entry ( self . api . env . basedn , [ ' aci ' ] )
2010-12-01 10:23:52 -06:00
2013-10-21 06:24:05 -05:00
acis = _convert_strings_to_acis ( entry . get ( ' aci ' , [ ] ) )
2011-01-21 02:20:01 -06:00
aci = _find_aci_by_name ( acis , kw [ ' aciprefix ' ] , aciname )
2010-12-01 10:23:52 -06:00
for a in acis :
2011-01-21 02:20:01 -06:00
prefix , name = _parse_aci_name ( a . name )
if _make_aci_name ( prefix , kw [ ' newname ' ] ) == a . name :
2010-12-01 10:23:52 -06:00
raise errors . DuplicateEntry ( )
# The strategy here is to convert the ACI we're updating back into
# a series of keywords. Then we replace any keywords that have been
# updated and convert that back into an ACI and write it out.
newkw = _aci_to_kw ( ldap , aci )
if ' selfaci ' in newkw and newkw [ ' selfaci ' ] == True :
# selfaci is set in aci_to_kw to True only if the target is self
kw [ ' selfaci ' ] = True
if ' aciname ' in newkw :
del newkw [ ' aciname ' ]
# _make_aci is what is run in aci_add and validates the input.
# Do this before we delete the existing ACI.
2011-01-20 15:35:34 -06:00
newaci = _make_aci ( ldap , None , kw [ ' newname ' ] , newkw )
2010-12-01 10:23:52 -06:00
2012-04-17 11:48:33 -05:00
self . api . Command [ ' aci_del ' ] ( aciname , aciprefix = kw [ ' aciprefix ' ] )
2010-12-01 10:23:52 -06:00
result = self . api . Command [ ' aci_add ' ] ( kw [ ' newname ' ] , * * newkw ) [ ' result ' ]
if kw . get ( ' raw ' , False ) :
result = dict ( aci = unicode ( newaci ) )
else :
result = _aci_to_kw ( ldap , newaci )
return dict (
result = result ,
2014-03-27 08:04:00 -05:00
value = pkey_to_value ( kw [ ' newname ' ] , kw ) ,
2010-12-01 10:23:52 -06:00
)