1 package org
.argeo
.osgi
.useradmin
;
3 import static org
.argeo
.util
.naming
.LdapAttrs
.objectClass
;
4 import static org
.argeo
.util
.naming
.LdapObjs
.extensibleObject
;
5 import static org
.argeo
.util
.naming
.LdapObjs
.inetOrgPerson
;
6 import static org
.argeo
.util
.naming
.LdapObjs
.organizationalPerson
;
7 import static org
.argeo
.util
.naming
.LdapObjs
.person
;
8 import static org
.argeo
.util
.naming
.LdapObjs
.top
;
12 import java
.net
.URISyntaxException
;
13 import java
.util
.ArrayList
;
14 import java
.util
.Arrays
;
15 import java
.util
.Dictionary
;
16 import java
.util
.Enumeration
;
17 import java
.util
.Hashtable
;
18 import java
.util
.Iterator
;
19 import java
.util
.List
;
20 import java
.util
.Optional
;
21 import java
.util
.StringJoiner
;
23 import javax
.naming
.InvalidNameException
;
24 import javax
.naming
.NameNotFoundException
;
25 import javax
.naming
.NamingEnumeration
;
26 import javax
.naming
.NamingException
;
27 import javax
.naming
.directory
.Attribute
;
28 import javax
.naming
.directory
.Attributes
;
29 import javax
.naming
.directory
.BasicAttribute
;
30 import javax
.naming
.directory
.BasicAttributes
;
31 import javax
.naming
.ldap
.LdapName
;
32 import javax
.naming
.ldap
.Rdn
;
34 import org
.argeo
.osgi
.transaction
.WorkControl
;
35 import org
.argeo
.util
.naming
.LdapAttrs
;
36 import org
.argeo
.util
.naming
.LdapObjs
;
37 import org
.osgi
.framework
.Filter
;
38 import org
.osgi
.framework
.FrameworkUtil
;
39 import org
.osgi
.framework
.InvalidSyntaxException
;
40 import org
.osgi
.service
.useradmin
.Authorization
;
41 import org
.osgi
.service
.useradmin
.Role
;
42 import org
.osgi
.service
.useradmin
.User
;
43 import org
.osgi
.service
.useradmin
.UserAdmin
;
45 /** Base class for a {@link UserDirectory}. */
46 abstract class AbstractUserDirectory
implements UserAdmin
, UserDirectory
{
47 static final String SHARED_STATE_USERNAME
= "javax.security.auth.login.name";
48 static final String SHARED_STATE_PASSWORD
= "javax.security.auth.login.password";
50 private final Hashtable
<String
, Object
> properties
;
51 private final LdapName baseDn
;
52 // private final LdapName userBaseDn, groupBaseDn;
53 private final Rdn userBaseRdn
, groupBaseRdn
, systemRoleBaseRdn
;
54 private final String userObjectClass
, groupObjectClass
;
56 private final boolean readOnly
;
57 private final boolean disabled
;
58 private final String uri
;
60 private UserAdmin externalRoles
;
61 // private List<String> indexedUserProperties = Arrays
62 // .asList(new String[] { LdapAttrs.uid.name(), LdapAttrs.mail.name(),
63 // LdapAttrs.cn.name() });
65 private final boolean scoped
;
67 private String memberAttributeId
= "member";
68 private List
<String
> credentialAttributeIds
= Arrays
69 .asList(new String
[] { LdapAttrs
.userPassword
.name(), LdapAttrs
.authPassword
.name() });
72 // private TransactionManager transactionManager;
73 private WorkControl transactionControl
;
74 private WcXaResource xaResource
= new WcXaResource(this);
76 private String forcedPassword
;
78 AbstractUserDirectory(URI uriArg
, Dictionary
<String
, ?
> props
, boolean scoped
) {
80 properties
= new Hashtable
<String
, Object
>();
81 for (Enumeration
<String
> keys
= props
.keys(); keys
.hasMoreElements();) {
82 String key
= keys
.nextElement();
83 properties
.put(key
, props
.get(key
));
87 uri
= uriArg
.toString();
88 // uri from properties is ignored
90 String uriStr
= UserAdminConf
.uri
.getValue(properties
);
97 forcedPassword
= UserAdminConf
.forcedPassword
.getValue(properties
);
99 userObjectClass
= UserAdminConf
.userObjectClass
.getValue(properties
);
100 String userBase
= UserAdminConf
.userBase
.getValue(properties
);
101 groupObjectClass
= UserAdminConf
.groupObjectClass
.getValue(properties
);
102 String groupBase
= UserAdminConf
.groupBase
.getValue(properties
);
103 String systemRoleBase
= UserAdminConf
.systemRoleBase
.getValue(properties
);
105 baseDn
= new LdapName(UserAdminConf
.baseDn
.getValue(properties
));
106 userBaseRdn
= new Rdn(userBase
);
107 // userBaseDn = new LdapName(userBase + "," + baseDn);
108 groupBaseRdn
= new Rdn(groupBase
);
109 // groupBaseDn = new LdapName(groupBase + "," + baseDn);
110 systemRoleBaseRdn
= new Rdn(systemRoleBase
);
111 } catch (InvalidNameException e
) {
112 throw new IllegalArgumentException("Badly formated base DN " + UserAdminConf
.baseDn
.getValue(properties
),
117 String readOnlyStr
= UserAdminConf
.readOnly
.getValue(properties
);
118 if (readOnlyStr
== null) {
119 readOnly
= readOnlyDefault(uri
);
120 properties
.put(UserAdminConf
.readOnly
.name(), Boolean
.toString(readOnly
));
122 readOnly
= Boolean
.parseBoolean(readOnlyStr
);
125 String disabledStr
= UserAdminConf
.disabled
.getValue(properties
);
126 if (disabledStr
!= null)
127 disabled
= Boolean
.parseBoolean(disabledStr
);
132 /** Returns the groups this user is a direct member of. */
133 protected abstract List
<LdapName
> getDirectGroups(LdapName dn
);
135 protected abstract Boolean
daoHasRole(LdapName dn
);
137 protected abstract DirectoryUser
daoGetRole(LdapName key
) throws NameNotFoundException
;
139 protected abstract List
<DirectoryUser
> doGetRoles(LdapName searchBase
, Filter f
, boolean deep
);
141 protected abstract AbstractUserDirectory
scope(User user
);
147 public void destroy() {
156 public String
getContext() {
157 return getBaseDn().toString();
161 public String
getName() {
162 return nameToSimple(getBaseDn(), ".");
166 public String
getRolePath(Role role
) {
167 return nameToRelativePath(((DirectoryUser
) role
).getDn());
171 public String
getRoleSimpleName(Role role
) {
172 LdapName dn
= LdapNameUtils
.toLdapName(role
.getName());
173 String name
= LdapNameUtils
.getLastRdnValue(dn
);
177 protected String
nameToRelativePath(LdapName dn
) {
178 LdapName name
= LdapNameUtils
.relativeName(getBaseDn(), dn
);
179 return nameToSimple(name
, "/");
182 protected String
nameToSimple(LdapName name
, String separator
) {
183 StringJoiner path
= new StringJoiner(separator
);
184 for (int i
= 0; i
< name
.size(); i
++) {
185 path
.add(name
.getRdn(i
).getValue().toString());
187 return path
.toString();
191 protected LdapName
pathToName(String path
) {
193 LdapName name
= (LdapName
) getBaseDn().clone();
194 String
[] segments
= path
.split("/");
195 Rdn parentRdn
= null;
196 for (String segment
: segments
) {
197 // TODO make attr names configurable ?
198 String attr
= LdapAttrs
.ou
.name();
199 if (parentRdn
!= null) {
200 if (getUserBaseRdn().equals(parentRdn
))
201 attr
= LdapAttrs
.uid
.name();
202 else if (getGroupBaseRdn().equals(parentRdn
))
203 attr
= LdapAttrs
.cn
.name();
204 else if (getSystemRoleBaseRdn().equals(parentRdn
))
205 attr
= LdapAttrs
.cn
.name();
207 Rdn rdn
= new Rdn(attr
, segment
);
212 } catch (InvalidNameException e
) {
213 throw new IllegalStateException("Cannot get role " + path
, e
);
219 public Role
getRoleByPath(String path
) {
220 return doGetRole(pathToName(path
));
224 public Optional
<String
> getRealm() {
225 Object realm
= getProperties().get(UserAdminConf
.realm
.name());
227 return Optional
.empty();
228 return Optional
.of(realm
.toString());
235 protected boolean isEditing() {
236 return xaResource
.wc() != null;
239 protected UserDirectoryWorkingCopy
getWorkingCopy() {
240 UserDirectoryWorkingCopy wc
= xaResource
.wc();
246 protected void checkEdit() {
247 if (xaResource
.wc() == null) {
249 transactionControl
.getWorkContext().registerXAResource(xaResource
, null);
250 } catch (Exception e
) {
251 throw new IllegalStateException("Cannot enlist " + xaResource
, e
);
257 protected List
<Role
> getAllRoles(DirectoryUser user
) {
258 List
<Role
> allRoles
= new ArrayList
<Role
>();
260 collectRoles(user
, allRoles
);
263 collectAnonymousRoles(allRoles
);
267 private void collectRoles(DirectoryUser user
, List
<Role
> allRoles
) {
268 Attributes attrs
= user
.getAttributes();
269 // TODO centralize attribute name
270 Attribute memberOf
= attrs
.get(LdapAttrs
.memberOf
.name());
271 // if user belongs to this directory, we only check meberOf
272 if (memberOf
!= null && user
.getDn().startsWith(getBaseDn())) {
274 NamingEnumeration
<?
> values
= memberOf
.getAll();
275 while (values
.hasMore()) {
276 Object value
= values
.next();
277 LdapName groupDn
= new LdapName(value
.toString());
278 DirectoryUser group
= doGetRole(groupDn
);
282 } catch (NamingException e
) {
283 throw new IllegalStateException("Cannot get memberOf groups for " + user
, e
);
286 for (LdapName groupDn
: getDirectGroups(user
.getDn())) {
287 // TODO check for loops
288 DirectoryUser group
= doGetRole(groupDn
);
291 collectRoles(group
, allRoles
);
297 private void collectAnonymousRoles(List
<Role
> allRoles
) {
298 // TODO gather anonymous roles
303 public Role
getRole(String name
) {
304 return doGetRole(toLdapName(name
));
307 protected DirectoryUser
doGetRole(LdapName dn
) {
308 UserDirectoryWorkingCopy wc
= getWorkingCopy();
311 user
= daoGetRole(dn
);
312 } catch (NameNotFoundException e
) {
316 if (user
== null && wc
.getNewUsers().containsKey(dn
))
317 user
= wc
.getNewUsers().get(dn
);
318 else if (wc
.getDeletedUsers().containsKey(dn
))
325 public Role
[] getRoles(String filter
) throws InvalidSyntaxException
{
326 List
<?
extends Role
> res
= getRoles(getBaseDn(), filter
, true);
327 return res
.toArray(new Role
[res
.size()]);
330 List
<DirectoryUser
> getRoles(LdapName searchBase
, String filter
, boolean deep
) throws InvalidSyntaxException
{
331 UserDirectoryWorkingCopy wc
= getWorkingCopy();
332 Filter f
= filter
!= null ? FrameworkUtil
.createFilter(filter
) : null;
333 List
<DirectoryUser
> res
= doGetRoles(searchBase
, f
, deep
);
335 for (Iterator
<DirectoryUser
> it
= res
.iterator(); it
.hasNext();) {
336 DirectoryUser user
= it
.next();
337 LdapName dn
= user
.getDn();
338 if (wc
.getDeletedUsers().containsKey(dn
))
341 for (DirectoryUser user
: wc
.getNewUsers().values()) {
342 if (f
== null || f
.match(user
.getProperties()))
345 // no need to check modified users,
346 // since doGetRoles was already based on the modified attributes
349 // if non deep we also search users and groups
352 // if (!(searchBase.endsWith(new LdapName(getUserBase()))
353 // || searchBase.endsWith(new LdapName(getGroupBase())))) {
354 // LdapName usersBase = (LdapName) ((LdapName) searchBase.clone()).add(getUserBase());
355 // res.addAll(getRoles(usersBase, filter, false));
356 // LdapName groupsBase = (LdapName) ((LdapName) searchBase.clone()).add(getGroupBase());
357 // res.addAll(getRoles(groupsBase, filter, false));
359 // } catch (InvalidNameException e) {
360 // throw new IllegalStateException("Cannot search users and groups", e);
367 public User
getUser(String key
, String value
) {
368 // TODO check value null or empty
369 List
<DirectoryUser
> collectedUsers
= new ArrayList
<DirectoryUser
>();
371 doGetUser(key
, value
, collectedUsers
);
373 throw new IllegalArgumentException("Key cannot be null");
376 if (collectedUsers
.size() == 1) {
377 return collectedUsers
.get(0);
378 } else if (collectedUsers
.size() > 1) {
379 // log.warn(collectedUsers.size() + " users for " + (key != null ? key + "=" :
385 protected void doGetUser(String key
, String value
, List
<DirectoryUser
> collectedUsers
) {
387 Filter f
= FrameworkUtil
.createFilter("(" + key
+ "=" + value
+ ")");
388 List
<DirectoryUser
> users
= doGetRoles(getBaseDn(), f
, true);
389 collectedUsers
.addAll(users
);
390 } catch (InvalidSyntaxException e
) {
391 throw new IllegalArgumentException("Cannot get user with " + key
+ "=" + value
, e
);
396 public Authorization
getAuthorization(User user
) {
397 if (user
== null || user
instanceof DirectoryUser
) {
398 return new LdifAuthorization(user
, getAllRoles((DirectoryUser
) user
));
401 AbstractUserDirectory scopedUserAdmin
= scope(user
);
403 DirectoryUser directoryUser
= (DirectoryUser
) scopedUserAdmin
.getRole(user
.getName());
404 if (directoryUser
== null)
405 throw new IllegalStateException("No scoped user found for " + user
);
406 LdifAuthorization authorization
= new LdifAuthorization(directoryUser
,
407 scopedUserAdmin
.getAllRoles(directoryUser
));
408 return authorization
;
410 scopedUserAdmin
.destroy();
416 public Role
createRole(String name
, int type
) {
418 UserDirectoryWorkingCopy wc
= getWorkingCopy();
419 LdapName dn
= toLdapName(name
);
420 if ((daoHasRole(dn
) && !wc
.getDeletedUsers().containsKey(dn
)) || wc
.getNewUsers().containsKey(dn
))
421 throw new IllegalArgumentException("Already a role " + name
);
422 BasicAttributes attrs
= new BasicAttributes(true);
423 // attrs.put(LdifName.dn.name(), dn.toString());
424 Rdn nameRdn
= dn
.getRdn(dn
.size() - 1);
425 // TODO deal with multiple attr RDN
426 attrs
.put(nameRdn
.getType(), nameRdn
.getValue());
427 if (wc
.getDeletedUsers().containsKey(dn
)) {
428 wc
.getDeletedUsers().remove(dn
);
429 wc
.getModifiedUsers().put(dn
, attrs
);
430 return getRole(name
);
432 wc
.getModifiedUsers().put(dn
, attrs
);
433 DirectoryUser newRole
= newRole(dn
, type
, attrs
);
434 wc
.getNewUsers().put(dn
, newRole
);
439 protected DirectoryUser
newRole(LdapName dn
, int type
, Attributes attrs
) {
440 DirectoryUser newRole
;
441 BasicAttribute objClass
= new BasicAttribute(objectClass
.name());
442 if (type
== Role
.USER
) {
443 String userObjClass
= newUserObjectClass(dn
);
444 objClass
.add(userObjClass
);
445 if (inetOrgPerson
.name().equals(userObjClass
)) {
446 objClass
.add(organizationalPerson
.name());
447 objClass
.add(person
.name());
448 } else if (organizationalPerson
.name().equals(userObjClass
)) {
449 objClass
.add(person
.name());
451 objClass
.add(top
.name());
452 objClass
.add(extensibleObject
.name());
454 newRole
= newUser(dn
, attrs
);
455 } else if (type
== Role
.GROUP
) {
456 String groupObjClass
= getGroupObjectClass();
457 objClass
.add(groupObjClass
);
458 // objClass.add(LdifName.extensibleObject.name());
459 objClass
.add(top
.name());
461 newRole
= newGroup(dn
, attrs
);
463 throw new IllegalArgumentException("Unsupported type " + type
);
468 public boolean removeRole(String name
) {
470 UserDirectoryWorkingCopy wc
= getWorkingCopy();
471 LdapName dn
= toLdapName(name
);
472 boolean actuallyDeleted
;
473 if (daoHasRole(dn
) || wc
.getNewUsers().containsKey(dn
)) {
474 DirectoryUser user
= (DirectoryUser
) getRole(name
);
475 wc
.getDeletedUsers().put(dn
, user
);
476 actuallyDeleted
= true;
477 } else {// just removing from groups (e.g. system roles)
478 actuallyDeleted
= false;
480 for (LdapName groupDn
: getDirectGroups(dn
)) {
481 DirectoryUser group
= doGetRole(groupDn
);
482 group
.getAttributes().get(getMemberAttributeId()).remove(dn
.toString());
484 return actuallyDeleted
;
488 protected void prepare(UserDirectoryWorkingCopy wc
) {
492 protected void commit(UserDirectoryWorkingCopy wc
) {
496 protected void rollback(UserDirectoryWorkingCopy wc
) {
504 // public int getHierarchyChildCount() {
509 // public HierarchyUnit getHierarchyChild(int i) {
510 // throw new IllegalArgumentException("No child hierarchy unit available");
514 // public HierarchyUnit getParent() {
519 // public int getHierarchyUnitType() {
524 // public String getHierarchyUnitName() {
525 // String name = LdapNameUtils.getLastRdnValue(baseDn);
526 // // TODO check ou, o, etc.
531 public HierarchyUnit
getHierarchyUnit(String path
) {
532 throw new UnsupportedOperationException();
536 public HierarchyUnit
getHierarchyUnit(Role role
) {
537 throw new UnsupportedOperationException();
541 // public List<? extends Role> getHierarchyUnitRoles(String filter, boolean deep) {
543 // return getRoles(getBaseDn(), filter, deep);
544 // } catch (InvalidSyntaxException e) {
545 // throw new IllegalArgumentException("Cannot filter " + filter + " " + getBaseDn(), e);
550 public Iterable
<HierarchyUnit
> getDirectHierarchyUnits(boolean functionalOnly
) {
551 throw new UnsupportedOperationException();
557 protected DirectoryUser
newUser(LdapName name
, Attributes attrs
) {
558 // TODO support devices, applications, etc.
559 return new LdifUser
.LdifPerson(this, name
, attrs
);
562 protected DirectoryGroup
newGroup(LdapName name
, Attributes attrs
) {
563 if (LdapNameUtils
.getParentRdn(name
).equals(getSystemRoleBaseRdn()))
564 return new LdifGroup
.LdifSystemPermissions(this, name
, attrs
);
566 if (hasObjectClass(attrs
, LdapObjs
.organization
))
567 return new LdifGroup
.LdifOrganization(this, name
, attrs
);
569 return new LdifGroup
.LdifFunctionalGroup(this, name
, attrs
);
573 private boolean hasObjectClass(Attributes attrs
, LdapObjs objectClass
) {
575 Attribute attr
= attrs
.get(LdapAttrs
.objectClass
.name());
576 NamingEnumeration
<?
> en
= attr
.getAll();
577 while (en
.hasMore()) {
578 String v
= en
.next().toString();
579 if (v
.equalsIgnoreCase(objectClass
.name()))
584 } catch (NamingException e
) {
585 throw new IllegalStateException("Cannot search for objectClass " + objectClass
.name(), e
);
590 protected String
getMemberAttributeId() {
591 return memberAttributeId
;
594 protected List
<String
> getCredentialAttributeIds() {
595 return credentialAttributeIds
;
598 protected String
getUri() {
602 private static boolean readOnlyDefault(String uriStr
) {
605 /// TODO make it more generic
608 uri
= new URI(uriStr
.split(" ")[0]);
609 } catch (URISyntaxException e
) {
610 throw new IllegalArgumentException(e
);
612 if (uri
.getScheme() == null)
613 return false;// assume relative file to be writable
614 if (uri
.getScheme().equals(UserAdminConf
.SCHEME_FILE
)) {
615 File file
= new File(uri
);
617 return !file
.canWrite();
619 return !file
.getParentFile().canWrite();
620 } else if (uri
.getScheme().equals(UserAdminConf
.SCHEME_LDAP
)) {
621 if (uri
.getAuthority() != null)// assume writable if authenticated
623 } else if (uri
.getScheme().equals(UserAdminConf
.SCHEME_OS
)) {
626 return true;// read only by default
629 public boolean isReadOnly() {
633 public boolean isDisabled() {
637 protected UserAdmin
getExternalRoles() {
638 return externalRoles
;
641 protected int roleType(LdapName dn
) {
642 Rdn technicalRdn
= LdapNameUtils
.getParentRdn(dn
);
643 if (getGroupBaseRdn().equals(technicalRdn
) || getSystemRoleBaseRdn().equals(technicalRdn
))
645 else if (userBaseRdn
.equals(technicalRdn
))
648 throw new IllegalArgumentException(
649 "Cannot dind role type, " + technicalRdn
+ " is not a technical RDN for " + dn
);
652 /** dn can be null, in that case a default should be returned. */
653 public String
getUserObjectClass() {
654 return userObjectClass
;
657 Rdn
getUserBaseRdn() {
661 protected String
newUserObjectClass(LdapName dn
) {
662 return getUserObjectClass();
665 public String
getGroupObjectClass() {
666 return groupObjectClass
;
669 Rdn
getGroupBaseRdn() {
673 Rdn
getSystemRoleBaseRdn() {
674 return systemRoleBaseRdn
;
677 LdapName
getBaseDn() {
678 return (LdapName
) baseDn
.clone();
681 public Dictionary
<String
, Object
> getProperties() {
685 public Dictionary
<String
, Object
> cloneProperties() {
686 return new Hashtable
<>(properties
);
689 public void setExternalRoles(UserAdmin externalRoles
) {
690 this.externalRoles
= externalRoles
;
693 // public void setTransactionManager(TransactionManager transactionManager) {
694 // this.transactionManager = transactionManager;
697 public String
getForcedPassword() {
698 return forcedPassword
;
701 public void setTransactionControl(WorkControl transactionControl
) {
702 this.transactionControl
= transactionControl
;
705 public WcXaResource
getXaResource() {
709 public boolean isScoped() {
714 public int hashCode() {
715 return baseDn
.hashCode();
719 public String
toString() {
720 return "User Directory " + baseDn
.toString();
726 static LdapName
toLdapName(String name
) {
728 return new LdapName(name
);
729 } catch (InvalidNameException e
) {
730 throw new IllegalArgumentException(name
+ " is not an LDAP name", e
);