ldap-rest 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import t from"../../abstract/plugin.js";import{assertIdentityMode as e,identityFor as r}from"../auth/base.js";import{AmbiguousIdentityError as s,ForbiddenError as i}from"../errors.js";import{organizationLink as n,getParentDn as a,normalizeDn as o,escapeLdapFilter as h,isDnInBranch as c}from"../utils.js";import{authzFor as u,servesRequest as l}from"./composition.js";class AuthzBase extends t{constructor(t){super(t),this.roles=["authz"],this.resolutionCache=new Map,this.resolutionCacheFullWarned=!1,this.fallbackWarned=!1,this.hooks={ldaprenamedone:()=>{this.resolutionCache.clear()},ldapdeletedone:()=>{this.resolutionCache.clear()},ldapmodifyrequest:async([t,e,r,s])=>{if(this.shouldSkipAuthorization(s))return[t,e,r,s];const i=await this.resolveCaller(s);if(!i)return[t,e,r,s];const a=this.config.ldap_organization_link_attribute;if(a&&e.replace?.[a]){let r,o=this.extractBranchDn(t),h=!1;try{const e=(await this.server.ldap.search({paged:!1,scope:"base",attributes:[a]},t)).searchEntries[0];e&&(h=!0,r=n(e[a]),r&&(o=r))}catch{}const c=e.replace[a],u=Array.isArray(c)?String(c[0]):String(c),l=this.filtersAttachedEntries(),d=l&&h&&this.inTransit(r),f=l&&this.inTransit(u);if(!d){const t=f?"write":"read";if(!(await this.getUserPermissions(i,o))[t])throw new Error(`[authz-forbidden] User ${s.user} does not have ${t} permission for source branch ${o}`)}if(f){if(d){if(0===(await this.getAuthorizedBranches(i)).length)throw new Error(`[authz-forbidden] User ${s.user} administers no branch`)}}else{if(!(await this.getUserPermissions(i,u)).write)throw new Error(`[authz-forbidden] User ${s.user} does not have write permission for destination branch ${u}`)}}else{const e=await this.effectiveBranch(t);if(!(await this.getUserPermissions(i,e)).write)throw new Error(`[authz-forbidden] User ${s.user} does not have write permission for branch ${e}`)}return[t,e,r,s]},ldapaddrequest:async([t,e,r])=>{if(this.shouldSkipAuthorization(r))return[t,e,r];const s=await this.resolveCaller(r);if(!s)return[t,e,r];let i;const n=this.config.ldap_organization_link_attribute;if(n&&e[n]){const t=e[n];i=Array.isArray(t)?String(t[0]):String(t)}else i=this.extractBranchDn(t);if(!(await this.getUserPermissions(s,i)).write)throw new Error(`[authz-forbidden] User ${r.user} does not have write permission for branch ${i}`);return[t,e,r]},ldapsearchrequest:async([t,e,r])=>{if(this.shouldSkipAuthorization(r))return[t,e,r];const s=await this.resolveCaller(r);if(!s)return[t,e,r];if(t===this.config.ldap_top_organization&&"base"===e.scope)return[t,e,r];if(this.filtersAttachedEntries()){if(0===(await this.getAuthorizedBranches(s)).length)throw new Error(`[authz-forbidden] User ${r.user} administers no branch`);const i=this.config.ldap_organization_link_attribute;if(i&&!AuthzBase.wantsAttribute(e,i)){const t=e.attributes,r=Array.isArray(t)?t.map(String):[String(t)];e={...e,attributes:[...r,i]},AuthzBase.widenedForLink.add(e)}return[t,e,r]}if(!(await this.getUserPermissions(s,t)).read)throw new Error(`[authz-forbidden] User ${r.user} does not have read permission for branch ${t}`);return[t,e,r]},ldapsearchfilter:async([t,e,r])=>{const s=[t,e,r];if(!this.filtersAttachedEntries())return s;const i=this.config.ldap_organization_link_attribute;if(!i||this.shouldSkipAuthorization(e))return s;if(!t?.searchEntries?.length)return s;const n=await this.resolveCaller(e);if(!n)return s;const a=await this.getAuthorizedBranches(n);if(0===a.length)return s;const within=t=>a.some(e=>c(t,e)),o=this.transitKey();if(t.searchEntries=t.searchEntries.filter(t=>{const r=t[i];if(null==r)return!0;const s=(Array.isArray(r)?r:[r]).map(String);return 0===s.length||(!!s.some(within)||(!!s.some(t=>this.inTransit(t,o))||(this.logger.debug(`${this.name}: hiding ${String(t.dn)} from ${e.user}, attached to ${s[0]}`),!1)))}),r&&AuthzBase.widenedForLink.has(r))for(const e of t.searchEntries)delete e[i];return[t,e,r]},getOrganisationTop:async([t,e])=>{if(this.shouldSkipAuthorization(t))return[t,e];const r=await this.resolveCaller(t);if(!r)return[t,e];const s=await this.getAuthorizedBranches(r);if(s.length>0){const e=[];for(const r of s)try{const s=await this.server.ldap.search({paged:!1,scope:"base"},r,t);1===s.searchEntries.length&&e.push(s.searchEntries[0])}catch(t){this.logger.warn(`Failed to fetch authorized branch ${r}: ${t}`)}if(1===e.length)return[t,e[0]];if(e.length>1)return[t,e[0]]}return[t,e]},ldaprenamerequest:async([t,e,r])=>{if(this.shouldSkipAuthorization(r))return[t,e,r];const s=await this.resolveCaller(r);if(!s)return[t,e,r];const i=this.extractBranchDn(t),n=this.extractBranchDn(e);if(!(await this.getUserPermissions(s,i)).read)throw new Error(`[authz-forbidden] User ${r.user} does not have read permission for source branch ${i}`);if(!(await this.getUserPermissions(s,n)).write)throw new Error(`[authz-forbidden] User ${r.user} does not have write permission for destination branch ${n}`);return[t,e,r]},ldapdeleterequest:async([t,e])=>{if(this.shouldSkipAuthorization(e))return[t,e];const r=await this.resolveCaller(e);if(!r)return[t,e];const s=Array.isArray(t)?t:[t];for(const t of s){const s=await this.effectiveBranch(t);if(!(await this.getUserPermissions(r,s)).delete)throw new Error(`[authz-forbidden] User ${e.user} does not have delete permission for branch ${s}`)}return[t,e]}},e(this.config,this.constructor.name),u(this.config,this.constructor.name);const r=this.config.authz_unresolved_user??"deny";if(!AuthzBase.UNRESOLVED_POLICIES.includes(r))throw new Error(`${this.constructor.name}: unknown --authz-unresolved-user "${r}". Known: ${AuthzBase.UNRESOLVED_POLICIES.join(", ")}.`);this.config.authz_transit_branch&&!this.filtersAttachedEntries()&&this.logger.warn(`${this.constructor.name}: --authz-transit-branch is ignored, entries are not judged by their attachment here (--authz-filter-attached-entries)`)}static wantsAttribute(t,e){const r=t?.attributes;if(void 0===r)return!0;const s=(Array.isArray(r)?r:[r]).map(t=>String(t).toLowerCase());return 0===s.length||(!!s.includes("*")||s.includes(e.toLowerCase()))}extractBranchDn(t){return a(t)}filtersAttachedEntries(){return Boolean(this.config.authz_filter_attached_entries)}async effectiveBranch(t){const e=this.config.ldap_organization_link_attribute;if(!e||!this.filtersAttachedEntries())return this.extractBranchDn(t);try{const r=await this.server.ldap.search({paged:!1,scope:"base",attributes:[e]},t),s=n(r.searchEntries?.[0]?.[e]);if(s)return s}catch{}return this.extractBranchDn(t)}transitBranch(){if(!this.filtersAttachedEntries())return;const t=String(this.config.authz_transit_branch??"").trim();return t.length>0?t:void 0}inTransit(t,e=this.transitKey()){return void 0===t||void 0!==e&&o(t)===e}transitKey(){const t=this.transitBranch();return void 0===t?void 0:o(t)}async findUserDn(t){const e=`(${this.config.ldap_user_main_attribute||"uid"}=${h(t)})`,r=(await this.server.ldap.search({paged:!1,filter:e,attributes:["dn"],scope:"sub"},this.server.ldap.base)).searchEntries??[];if(r.length>1)throw new s(t,r.length);if(0===r.length)return null;const i=r[0].dn;return"string"==typeof i?i:String(i)}shouldSkipAuthorization(t){return!t?.user||!l(t,this.config)}async resolveCaller(t){const{value:e,fellBack:s}=r(t,this.config);s&&!this.fallbackWarned&&(this.fallbackWarned=!0,this.logger.warn(`${this.name}: --authz-identity asks for req.userName and the authenticator published none, so permissions are read for req.user instead. Rules written on logins will not match`));const n=e,a=Date.now(),o=this.resolutionCache.get(n);let h;if(o&&a-o.at<this.cacheTTL)h=o.user;else{if(h=await this.resolveUser(n),this.resolutionCache.size>=AuthzBase.RESOLUTION_CACHE_MAX)for(const[t,e]of this.resolutionCache)a-e.at>=this.cacheTTL&&this.resolutionCache.delete(t);this.resolutionCache.size<AuthzBase.RESOLUTION_CACHE_MAX?this.resolutionCache.set(n,{user:h,at:a}):this.resolutionCacheFullWarned||(this.resolutionCacheFullWarned=!0,this.logger.warn(`${this.name}: more than ${AuthzBase.RESOLUTION_CACHE_MAX} identities resolved within one cache window, so resolutions are no longer cached and each request costs a lookup`))}if(h)return h;if("allow"===this.config.authz_unresolved_user)return this.logger.warn(`User ${n} could not be resolved by ${this.name}; allowed by --authz-unresolved-user allow`),null;throw new i(`[authz-forbidden] User ${n} could not be resolved by ${this.name}, so no permission can be read for them`)}clearResolutionCache(){this.resolutionCache.clear()}}AuthzBase.widenedForLink=new WeakSet,AuthzBase.UNRESOLVED_POLICIES=["deny","allow"],AuthzBase.RESOLUTION_CACHE_MAX=1e4;export{AuthzBase as default};
1
+ import t from"../../abstract/plugin.js";import{roleAttribute as e}from"../../config/schema.js";import{assertIdentityMode as r,identityFor as s}from"../auth/base.js";import{AmbiguousIdentityError as i,ForbiddenError as n}from"../errors.js";import{organizationLink as a,getParentDn as o,normalizeDn as h,escapeLdapFilter as c,isDnInBranch as u}from"../utils.js";import{authzFor as l,servesRequest as d}from"./composition.js";class AuthzBase extends t{constructor(t){super(t),this.roles=["authz"],this.resolutionCache=new Map,this.resolutionCacheFullWarned=!1,this.fallbackWarned=!1,this.hooks={ldaprenamedone:()=>{this.resolutionCache.clear()},ldapdeletedone:()=>{this.resolutionCache.clear()},ldapmodifyrequest:async([t,e,r,s])=>{if(this.shouldSkipAuthorization(s))return[t,e,r,s];const i=await this.resolveCaller(s);if(!i)return[t,e,r,s];const n=this.config.ldap_organization_link_attribute;if(n&&e.replace?.[n]){let r,o=this.extractBranchDn(t),h=!1;try{const e=(await this.server.ldap.search({paged:!1,scope:"base",attributes:[n]},t)).searchEntries[0];e&&(h=!0,r=a(e[n]),r&&(o=r))}catch{}const c=e.replace[n],u=Array.isArray(c)?String(c[0]):String(c),l=this.filtersAttachedEntries(),d=l&&h&&this.inTransit(r),f=l&&this.inTransit(u);if(!d){const t=f?"write":"read";if(!(await this.getUserPermissions(i,o))[t])throw new Error(`[authz-forbidden] User ${s.user} does not have ${t} permission for source branch ${o}`)}if(f){if(d){if(0===(await this.getAuthorizedBranches(i)).length)throw new Error(`[authz-forbidden] User ${s.user} administers no branch`)}}else{if(!(await this.getUserPermissions(i,u)).write)throw new Error(`[authz-forbidden] User ${s.user} does not have write permission for destination branch ${u}`)}}else{const e=await this.effectiveBranch(t);if(!(await this.getUserPermissions(i,e)).write)throw new Error(`[authz-forbidden] User ${s.user} does not have write permission for branch ${e}`)}const o=this.domainLinkAttribute();return o&&await this.guardDomainLinks(i,s,t,[...AuthzBase.valuesOf(e.add,o),...AuthzBase.valuesOf(e.replace,o)],o,!1),[t,e,r,s]},ldapaddrequest:async([t,e,r])=>{if(this.shouldSkipAuthorization(r))return[t,e,r];const s=await this.resolveCaller(r);if(!s)return[t,e,r];let i;const n=this.config.ldap_organization_link_attribute;if(n&&e[n]){const t=e[n];i=Array.isArray(t)?String(t[0]):String(t)}else i=this.extractBranchDn(t);if(!(await this.getUserPermissions(s,i)).write)throw new Error(`[authz-forbidden] User ${r.user} does not have write permission for branch ${i}`);const a=this.domainLinkAttribute();return a&&await this.guardDomainLinks(s,r,t,AuthzBase.valuesOf(e,a),a,!0),[t,e,r]},ldapsearchrequest:async([t,e,r])=>{if(this.shouldSkipAuthorization(r))return[t,e,r];const s=await this.resolveCaller(r);if(!s)return[t,e,r];if(t===this.config.ldap_top_organization&&"base"===e.scope)return[t,e,r];if(this.filtersAttachedEntries()){if(0===(await this.getAuthorizedBranches(s)).length)throw new Error(`[authz-forbidden] User ${r.user} administers no branch`);const i=this.config.ldap_organization_link_attribute;if(i&&!AuthzBase.wantsAttribute(e,i)){const t=e.attributes,r=Array.isArray(t)?t.map(String):[String(t)];e={...e,attributes:[...r,i]},AuthzBase.widenedForLink.add(e)}return[t,e,r]}if(!(await this.getUserPermissions(s,t)).read)throw new Error(`[authz-forbidden] User ${r.user} does not have read permission for branch ${t}`);return[t,e,r]},ldapsearchfilter:async([t,e,r])=>{const s=[t,e,r];if(!this.filtersAttachedEntries())return s;const i=this.config.ldap_organization_link_attribute;if(!i||this.shouldSkipAuthorization(e))return s;if(!t?.searchEntries?.length)return s;const n=await this.resolveCaller(e);if(!n)return s;const a=await this.getAuthorizedBranches(n);if(0===a.length)return s;const within=t=>a.some(e=>u(t,e)),o=this.transitKey();if(t.searchEntries=t.searchEntries.filter(t=>{const r=t[i];if(null==r)return!0;const s=(Array.isArray(r)?r:[r]).map(String);return 0===s.length||(!!s.some(within)||(!!s.some(t=>this.inTransit(t,o))||(this.logger.debug(`${this.name}: hiding ${String(t.dn)} from ${e.user}, attached to ${s[0]}`),!1)))}),r&&AuthzBase.widenedForLink.has(r))for(const e of t.searchEntries)delete e[i];return[t,e,r]},getOrganisationTop:async([t,e])=>{if(this.shouldSkipAuthorization(t))return[t,e];const r=await this.resolveCaller(t);if(!r)return[t,e];const s=await this.getAuthorizedBranches(r);if(s.length>0){const e=[];for(const r of s)try{const s=await this.server.ldap.search({paged:!1,scope:"base"},r,t);1===s.searchEntries.length&&e.push(s.searchEntries[0])}catch(t){this.logger.warn(`Failed to fetch authorized branch ${r}: ${t}`)}if(1===e.length)return[t,e[0]];if(e.length>1)return[t,e[0]]}return[t,e]},ldaprenamerequest:async([t,e,r])=>{if(this.shouldSkipAuthorization(r))return[t,e,r];const s=await this.resolveCaller(r);if(!s)return[t,e,r];const i=this.extractBranchDn(t),n=this.extractBranchDn(e);if(!(await this.getUserPermissions(s,i)).read)throw new Error(`[authz-forbidden] User ${r.user} does not have read permission for source branch ${i}`);if(!(await this.getUserPermissions(s,n)).write)throw new Error(`[authz-forbidden] User ${r.user} does not have write permission for destination branch ${n}`);return[t,e,r]},ldapdeleterequest:async([t,e])=>{if(this.shouldSkipAuthorization(e))return[t,e];const r=await this.resolveCaller(e);if(!r)return[t,e];const s=Array.isArray(t)?t:[t];for(const t of s){const s=await this.effectiveBranch(t);if(!(await this.getUserPermissions(r,s)).delete)throw new Error(`[authz-forbidden] User ${e.user} does not have delete permission for branch ${s}`)}return[t,e]}},r(this.config,this.constructor.name),l(this.config,this.constructor.name);const e=this.config.authz_unresolved_user??"deny";if(!AuthzBase.UNRESOLVED_POLICIES.includes(e))throw new Error(`${this.constructor.name}: unknown --authz-unresolved-user "${e}". Known: ${AuthzBase.UNRESOLVED_POLICIES.join(", ")}.`);this.config.authz_transit_branch&&!this.filtersAttachedEntries()&&this.logger.warn(`${this.constructor.name}: --authz-transit-branch is ignored, entries are not judged by their attachment here (--authz-filter-attached-entries)`)}static wantsAttribute(t,e){const r=t?.attributes;if(void 0===r)return!0;const s=(Array.isArray(r)?r:[r]).map(t=>String(t).toLowerCase());return 0===s.length||(!!s.includes("*")||s.includes(e.toLowerCase()))}extractBranchDn(t){return o(t)}filtersAttachedEntries(){return Boolean(this.config.authz_filter_attached_entries)}async effectiveBranch(t){const e=this.config.ldap_organization_link_attribute;if(!e||!this.filtersAttachedEntries())return this.extractBranchDn(t);try{const r=await this.server.ldap.search({paged:!1,scope:"base",attributes:[e]},t),s=a(r.searchEntries?.[0]?.[e]);if(s)return s}catch{}return this.extractBranchDn(t)}transitBranch(){if(!this.filtersAttachedEntries())return;const t=String(this.config.authz_transit_branch??"").trim();return t.length>0?t:void 0}inTransit(t,e=this.transitKey()){return void 0===t||void 0!==e&&h(t)===e}transitKey(){const t=this.transitBranch();return void 0===t?void 0:h(t)}async findUserDn(t){const e=`(${this.config.ldap_user_main_attribute||"uid"}=${c(t)})`,r=(await this.server.ldap.search({paged:!1,filter:e,attributes:["dn"],scope:"sub"},this.server.ldap.base)).searchEntries??[];if(r.length>1)throw new i(t,r.length);if(0===r.length)return null;const s=r[0].dn;return"string"==typeof s?s:String(s)}shouldSkipAuthorization(t){return!t?.user||!d(t,this.config)}async resolveCaller(t){const{value:e,fellBack:r}=s(t,this.config);r&&!this.fallbackWarned&&(this.fallbackWarned=!0,this.logger.warn(`${this.name}: --authz-identity asks for req.userName and the authenticator published none, so permissions are read for req.user instead. Rules written on logins will not match`));const i=e,a=Date.now(),o=this.resolutionCache.get(i);let h;if(o&&a-o.at<this.cacheTTL)h=o.user;else{if(h=await this.resolveUser(i),this.resolutionCache.size>=AuthzBase.RESOLUTION_CACHE_MAX)for(const[t,e]of this.resolutionCache)a-e.at>=this.cacheTTL&&this.resolutionCache.delete(t);this.resolutionCache.size<AuthzBase.RESOLUTION_CACHE_MAX?this.resolutionCache.set(i,{user:h,at:a}):this.resolutionCacheFullWarned||(this.resolutionCacheFullWarned=!0,this.logger.warn(`${this.name}: more than ${AuthzBase.RESOLUTION_CACHE_MAX} identities resolved within one cache window, so resolutions are no longer cached and each request costs a lookup`))}if(h)return h;if("allow"===this.config.authz_unresolved_user)return this.logger.warn(`User ${i} could not be resolved by ${this.name}; allowed by --authz-unresolved-user allow`),null;throw new n(`[authz-forbidden] User ${i} could not be resolved by ${this.name}, so no permission can be read for them`)}domainLinkAttribute(){const t=this.server.loadedPlugins.ldapOrganizations;return e(t?.schema,"domainLink")||this.config.enterprise_domain_link_attribute||void 0}static valuesOf(t,e){if(!t)return[];const r=e.toLowerCase(),s=[];for(const[e,i]of Object.entries(t))if(e.split(";")[0].toLowerCase()===r&&null!=i)for(const t of Array.isArray(i)?i:[i])s.push(String(t));return s}async storedValues(t,e){try{const r=await this.server.ldap.search({paged:!1,scope:"base",attributes:[e]},t);return AuthzBase.valuesOf(r.searchEntries?.[0],e)}catch{return[]}}async guardDomainLinks(t,e,r,s,i,n){if(0===s.length)return;const a=new Set((n?[]:await this.storedValues(r,i)).map(h)),c=s.filter(t=>!a.has(h(t)));if(0===c.length)return;const l=this.config.ldap_top_organization,d=h(l||this.server.ldap.base),f=new Set;let g=o(r);const w=new Set;for(;g&&!w.has(h(g));){const t=h(g);if(w.add(t),t!==d&&!u(g,d))break;for(const t of await this.storedValues(g,i))f.add(h(t));if(t===d)break;const e=o(g);if(e===g)break;g=e}const p=c.filter(t=>!f.has(h(t)));if(!(0===p.length||l&&(await this.getUserPermissions(t,l)).write))throw new Error(`[authz-forbidden] User ${e.user} may not link ${r} to domain ${p[0]}: no organization above it is linked to it`)}clearResolutionCache(){this.resolutionCache.clear()}}AuthzBase.widenedForLink=new WeakSet,AuthzBase.UNRESOLVED_POLICIES=["deny","allow"],AuthzBase.RESOLUTION_CACHE_MAX=1e4;export{AuthzBase as default};
@@ -1 +1 @@
1
- import e from"../../abstract/plugin.js";import{wantJson as t,jsonBody as r,tryMethod as i,ok as s}from"../../lib/expressFormatedResponses.js";import{extractLdapCode as a}from"../../lib/ldapCodes.js";import{loadSchemaFileAsync as o,schemaUrl as n}from"../../lib/schemaFile.js";import{asyncHandler as h,isDummyMemberDn as c,escapeDnValue as d,validateDnValue as p,launchHooksChained as m,launchHooks as u,escapeLdapFilter as l,organizationLink as f,substringSearchFilter as g}from"../../lib/utils.js";import{NotFoundError as b,BadRequestError as w,HttpError as y}from"../../lib/errors.js";import{assertClientMaySet as $,modifiedAttributeNames as v,invalidValueMessage as _,missingRequiredAttribute as E,checkDnValues as A,matchesPattern as G}from"../../config/schema.js";class LdapGroups extends e{constructor(e){if(super(e),this.name="ldapGroups",this.roles=["api","configurable"],this.hooks={ldapdeletedone:async e=>{const t=Array.isArray(e)?e:[e];this.logger.debug(`User deletion detected, removing from groups: ${t.join(", ")}`),await Promise.all(t.map(e=>this.deleteMemberFromAll(e))).catch(e=>{this.logger.error("Failed to process user deletion in groups:",e)})}},this.ldap=e.ldap,this.base=this.config.ldap_group_base,this.cn=this.config.ldap_groups_main_attribute,this.base||(this.base=this.config.ldap_base,this.logger.warn(`LDAP group base is not defined, using "${this.base}"`)),!this.base)throw new Error("LDAP base is not defined, please set --ldap-group-base");if(this.config.ldap_group_base&&e.ldap.declareObjectClasses(this.base,this.config.group_class||[]),this.config.group_schema){const e=this.config.group_schema;o(e,{config:this.config}).then(e=>{this.schema=this.adaptSchema(e),this.logger.debug("Group schema loaded")}).catch(t=>this.logger.error(`Failed to load group schema from ${e}: ${t}`))}}adaptSchema(e){return e}api(e){e.get(`${this.config.api_prefix}/v1/ldap/groups`,h(async(e,r)=>{if(!t(e,r))return;const i={};if(e.query.match){if("string"!=typeof e.query.match)throw new w("Invalid match query");if("string"==typeof e.query.attribute&&e.query.attribute)i.filter=g(e.query.match,e.query.attribute);else if(/=/.test(e.query.match)){if(!/^[\w*=()&|, -]+$/.test(e.query.match))throw new w("Invalid match query: contains forbidden characters");i.filter=e.query.match}else{const t=l(e.query.match);i.filter=`(${this.cn}=${t})`}}e.query.attributes&&"string"==typeof e.query.attributes&&(i.attributes=e.query.attributes.split(","));const a=await this.listGroups({...i,req:e});return s(r,this.hideNeverReturn(a))})),e.get(`${this.config.api_prefix}/v1/ldap/groups/:cn`,h(async(e,t)=>this.apiGet(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups`,h(async(e,t)=>this.apiAdd(e,t,this.cn))),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn`,h(async(e,t)=>this.apiDelete(e,t))),e.put(`${this.config.api_prefix}/v1/ldap/groups/:cn`,h(async(e,t)=>this.apiModify(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/members`,h(async(e,t)=>{const s=decodeURIComponent(e.params.cn);if(!s)throw new w("cn is required");const a=r(e,t,"member");if(!a)return;if((Array.isArray(a.member)?a.member:[a.member]).some(e=>"string"!=typeof e))throw new w("member must be a string or string array");await i(t,this.addMember.bind(this),s,a.member)})),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn/members/:member`,h(async(e,r)=>{if(!t(e,r))return;const s=decodeURIComponent(e.params.cn),a=decodeURIComponent(e.params.member);if(!s||!a)throw new w("cn and member are required");await i(r,this.deleteMember.bind(this),s,a)})),this.config.ldap_organization_link_attribute&&this.config.ldap_organization_path_attribute&&e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/move`,h(async(e,s)=>{if(!t(e,s))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new w("cn is required");const o=r(e,s,"targetOrgDn");if(o){if("string"!=typeof o.targetOrgDn)throw new w("targetOrgDn must be a string");await i(s,this.moveGroup.bind(this),a,o.targetOrgDn,e)}})),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/rename`,h(async(e,s)=>{if(!t(e,s))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new w("cn is required");const o=r(e,s,"newCn");if(o){if("string"!=typeof o.newCn)throw new w("newCn must be a string");await i(s,this.renameGroup.bind(this),a,o.newCn,e)}}))}isDummyMember(e){return c(e,this.config.group_dummy_user)}withoutDummyMember(e){const t=e.member;if(void 0===t)return e;const r=Array.isArray(t)?t:[t];return{...e,member:r.filter(e=>!this.isDummyMember(e))}}async apiGet(e,r){if(!t(e,r))return;const i=decodeURIComponent(e.params.cn);try{const t=/,/.test(i)?i:`${this.cn}=${d(i)},${this.base}`,s=await this.ldap.search({paged:!1,scope:"base"},t,e);if(0===s.searchEntries.length)throw new b("Group not found");r.json(this.hideNeverReturn(this.withoutDummyMember(s.searchEntries[0])))}catch(e){if(e.code&&32===e.code)throw new b("Group not found");throw e}}async apiAdd(e,t,...s){const a=r(e,t,...s);if(!a)return;$(this.schema,Object.keys(a),this.cn);const o=a[this.cn],n=a.member?a.member:[],h=Object.fromEntries(Object.entries(a).filter(([e,t])=>e!==this.cn&&"member"!==e&&void 0!==t&&!(!0===this.schema?.attributes[e]?.fixed)));await i(t,this.addGroup.bind(this),o,n,h,e)}async apiDelete(e,r){if(!t(e,r))return;const s=decodeURIComponent(e.params.cn);if(!s)throw new w("cn is required");await i(r,this.deleteGroup.bind(this),s,e)}async apiModify(e,t){const s=r(e,t);if(!s)return;const a=this.fixDn(decodeURIComponent(e.params.cn));if(!a)throw new w("cn is required");$(this.schema,v(s));const o=Object.fromEntries(Object.entries(s).filter(([e,t])=>!(!0===this.schema?.attributes[e]?.fixed)));await i(t,this.modifyGroup.bind(this),a,o,e)}async addGroup(e,t=[],r={},i){let s;new RegExp(`^${this.cn}=`).test(e)?(s=e,e=e.replace(new RegExp(`^${this.cn}=((?:\\\\.|[^,])+)(?:,.*)?$`),"$1")):(p(e,this.cn),s=`${this.cn}=${d(e)},${this.base}`),await this.validateMembers(s,t),await this.validateNewGroup(s,{objectClass:this.config.group_class,cn:e,member:t,...r});const a=[...this.config.group_class];!(r.mail||r.twakeMailboxType||r.twakeDepartmentLink||r.twakeDepartmentPath)||a.includes("twakeGroup")||a.includes("twakeStaticGroup")||a.push("twakeGroup");let o,n={objectClass:a,...this.config.group_default_attributes,[this.cn]:e,member:[this.config.group_dummy_user],...r};t.length&&n.member.push(...t),[s,n]=await m(this.registeredHooks.ldapgroupadd,[s,n]);try{o=await this.ldap.add(s,n,i)}catch(e){if(e instanceof y)throw e;throw new Error(`Failed to add group ${s}: ${e}`)}return u(this.registeredHooks.ldapgroupadddone,[s,n]),o}async modifyGroup(e,t,r){let i=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;const s=this.opNumber();if([i,t]=await m(this.registeredHooks.ldapgroupmodify,[i,t,s]),t.add){if(t.add.member)throw new Error("Use dedicated API to add members");if(t.add[this.cn])throw new Error(`${this.cn} attribute iq unique, cannot add`)}if(t.delete){if(t.delete instanceof Object){if(t.delete.member)throw new Error("Use dedicated API to delete members");if(t.delete[this.cn])throw new Error(`Cannot delete ${this.cn} attribute`)}if(Array.isArray(t.delete)){if(t.delete.includes("member"))throw new Error("Use dedicated API to delete members");if(t.delete.includes(this.cn))throw new Error(`Cannot delete ${this.cn} attribute`)}}if(t.replace){if(t.replace.member)throw new Error("Use dedicated API to replace members");if(t.replace[this.cn])throw new Error(`Use dedicated API to change ${this.cn} attribute`)}await this.validateChanges(i,t);const a=await this.ldap.modify(i,t,r);return u(this.registeredHooks.ldapgroupmodifydone,[i,t,s]),a}async renameGroup(e,t,r){/,/.test(e)||p(e,this.cn),/,/.test(t)||p(t,this.cn);let i=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`,s=/,/.test(t)?t:`${this.cn}=${d(t)},${this.base}`;[i,s]=await m(this.registeredHooks.ldapgrouprename,[i,s]);const a=await this.ldap.rename(i,s,r);return u(this.registeredHooks.ldapgrouprenamedone,[i,s]),a}async deleteGroup(e,t){let r=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;r=await m(this.registeredHooks.ldapgroupdelete,r);const i=await this.ldap.delete(r,t);return u(this.registeredHooks.ldapgroupdeletedone,r),i}async addMember(e,t){const r=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;return Array.isArray(t)||(t=[t]),[e,t]=await m(this.registeredHooks.ldapgroupaddmember,[e,t]),await this.validateMembers(r,t),await this.ldap.modify(r,{add:{member:t}}).catch(e=>{if(e instanceof y)throw e;throw new Error(`Failed to add member(s) to ${r}: ${e}`)})}async deleteMember(e,t){const r=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;if([e,t]=await m(this.registeredHooks.ldapgroupdeletemember,[e,t]),this.isDummyMember(t))throw new w("Cannot delete dummy member from group");return await this.ldap.modify(r,{delete:{member:t}}).catch(e=>{if(e instanceof y)throw e;throw new Error(`Failed to delete member ${t} from ${r}: ${e}`)})}async deleteMemberFromAll(e){const t=await this.ldap.search({filter:`member=${l(e)}`,paged:!1,attributes:[this.cn]},this.base).catch(e=>{throw new Error(`Failed to search groups from ${this.base}: ${e}`)});await Promise.all(t.searchEntries.map(t=>this.ldap.modify(t.dn,{delete:{member:e}}).catch(r=>{if(65===a(r)&&this.config.group_dummy_user)return this.ldap.modify(t.dn,{add:{member:this.config.group_dummy_user},delete:{member:e}});throw r}).catch(r=>{const i=a(r);16!==i&&32!==i&&this.logger.error(`Failed to remove ${e} from group ${t.dn}:`,r)})))}async moveGroup(e,t,r){const i=this.config.ldap_organization_link_attribute,s=this.config.ldap_organization_path_attribute,a=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`,o=await this.ldap.search({paged:!1,scope:"base"},a);if(0===o.searchEntries.length)throw new Error(`Group ${a} not found`);const n=o.searchEntries[0],h=f(n[i]);if(!h)throw new Error(`Group ${a} does not have ${i} attribute and cannot be moved`);if(h===t)throw new Error("Group is already in the target organization");let c;try{c=await this.ldap.search({paged:!1,scope:"base",attributes:[s,"ou","o"]},t)}catch(e){throw new Error(`Target organization ${t} not found: ${e instanceof Error&&e.message?e.message:String(e)}`)}if(0===c.searchEntries.length)throw new Error(`Target organization ${t} not found`);const p=c.searchEntries[0][s];if(!p)throw new Error(`Target organization ${t} does not have ${s} attribute`);return await this.ldap.modify(a,{replace:{[i]:t,[s]:p}},r),this.logger.info(`Group ${a} moved from ${h} to ${t}`),{success:!0}}async listGroups({filter:e,attributes:t,req:r}={}){const i=await this.ldap.search({filter:e||"(objectClass=*)",attributes:t||[this.cn,"member"],paged:!0},this.base,r).catch(e=>{throw new Error(`Failed to list groups from ${this.base}: ${e}`)});let s={};for await(const e of i)for(const t of e.searchEntries){const e=t[this.cn];if(Array.isArray(e)&&0===e.length)continue;e&&(s[e]=this.withoutDummyMember(t))}return s=await m(this.registeredHooks._ldapgrouplist,s),s}async searchGroupsByName(e,t=!1,r=[this.cn,"member"],i){const s=l(e),a=t?`(${this.cn}=*${s}*)`:`(${this.cn}=${s})`;return await this.listGroups({filter:a,attributes:r,req:i})}fixDn(e){return!!e&&(/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`)}async validateMembers(e,t){if([e,t]=await m(this.server.hooks.ldapgroupvalidatemembers,[e,t]),!this.config.groups_allow_unexistent_members&&t&&t.length)try{await Promise.all(t.map(e=>this.server.ldap.queryLimit(async()=>{try{await this.ldap.search({paged:!1,scope:"base"},e)}catch(t){const r=a(t);if(32===r)throw new w(`Member ${e} not found`);if(34===r)throw new w(`Member ${e} is not a valid DN`);throw new Error(`Member ${e} not found: ${t}`)}})))}catch(e){if(e instanceof y)throw e;throw new Error(`Failed to find member(s): ${e}`)}}async validateNewGroup(e,t){if(!this.schema)return!0;[e,t]=await m(this.server.hooks.ldapgroupvalidatenew,[e,t]);for(const[e,r]of Object.entries(t))if(!await this._validateOneChange(e,r))throw new w(_(e,this.schema.attributes[e]));const r=E(this.schema,t,this.server.loadedPlugins);if(r)throw new w(`Attribute "${r}" is required`);return!0}async validateChanges(e,t){if(!this.schema)return!0;if([e,t]=await m(this.server.hooks.ldapgroupvalidatechanges,[e,t]),t.add)for(const[e,r]of Object.entries(t.add))if(!await this._validateOneChange(e,r))throw new w(_(e,this.schema.attributes[e]));if(t.replace)for(const[e,r]of Object.entries(t.replace))if(!await this._validateOneChange(e,r))throw new w(_(e,this.schema.attributes[e]));if(t.delete&&t.delete instanceof Object)for(const e of Array.isArray(t.delete)?t.delete:Object.keys(t.delete))await this._validateOneChange(e,null);return!0}async _validateOneChange(e,t){if(!this.schema)return!0;const r=this.schema.attributes[e];if(!r){if(this.schema.strict)throw new w(`Attribute "${e}" is not allowed`);return!0}if(null==t||Array.isArray(t)&&0===t.length){if(r.required)throw new w(`Attribute "${e}" is required`);return!0}if("array"===r.type){if(!Array.isArray(t))throw new w(`Attribute "${e}" must be an array`);if(!r.items)throw new Error(`Schema error: no item for array ${e}`);if("array"===r.items.type)throw new Error(`Schema error: array of array not supported for ${e}`);if(r.items.test&&"pointer"!==r.items.type)for(const i of t)if(typeof i!==r.items.type)throw new w(`Attribute "${e}" must be of type ${r.items.type}`)}else if("pointer"!==r.type&&typeof t!==r.type)return!1;if(await A(e,r,t,async e=>(await this.ldap.search({paged:!1,scope:"base",attributes:["dn"]},e)).searchEntries.length>0),!G(r,t))throw new w(_(e,r));return!0}getConfigApiData(){const e=this.config.api_prefix||"/api",t=this.server.loadedPlugins.static&&this.config.group_schema?n(this.config,this.config.group_schema):void 0;return{enabled:!0,base:this.base||"",mainAttribute:this.cn||"cn",objectClass:this.config.group_class||["top","groupOfNames"],schema:this.schema,schemaUrl:t,endpoints:{list:`${e}/v1/ldap/groups`,get:`${e}/v1/ldap/groups/:id`,create:`${e}/v1/ldap/groups`,update:`${e}/v1/ldap/groups/:id`,delete:`${e}/v1/ldap/groups/:id`,addMember:`${e}/v1/ldap/groups/:id/members`,removeMember:`${e}/v1/ldap/groups/:id/members/:memberId`,rename:`${e}/v1/ldap/groups/:id/rename`,move:`${e}/v1/ldap/groups/:id/move`}}}}export{LdapGroups as default};
1
+ import e from"../../abstract/plugin.js";import{wantJson as t,jsonBody as r,tryMethod as i,ok as s}from"../../lib/expressFormatedResponses.js";import{extractLdapCode as a}from"../../lib/ldapCodes.js";import{loadSchemaFileAsync as o,schemaUrl as n}from"../../lib/schemaFile.js";import{asyncHandler as h,isDummyMemberDn as c,escapeDnValue as d,validateDnValue as p,launchHooksChained as m,launchHooks as u,escapeLdapFilter as l,organizationLink as f,isAuthzRefusal as g,substringSearchFilter as b}from"../../lib/utils.js";import{NotFoundError as w,BadRequestError as y,HttpError as $}from"../../lib/errors.js";import{assertClientMaySet as v,modifiedAttributeNames as _,invalidValueMessage as E,missingRequiredAttribute as A,checkDnValues as G,matchesPattern as q}from"../../config/schema.js";class LdapGroups extends e{constructor(e){if(super(e),this.name="ldapGroups",this.roles=["api","configurable"],this.hooks={ldapdeletedone:async e=>{const t=Array.isArray(e)?e:[e];this.logger.debug(`User deletion detected, removing from groups: ${t.join(", ")}`),await Promise.all(t.map(e=>this.deleteMemberFromAll(e))).catch(e=>{this.logger.error("Failed to process user deletion in groups:",e)})}},this.ldap=e.ldap,this.base=this.config.ldap_group_base,this.cn=this.config.ldap_groups_main_attribute,this.base||(this.base=this.config.ldap_base,this.logger.warn(`LDAP group base is not defined, using "${this.base}"`)),!this.base)throw new Error("LDAP base is not defined, please set --ldap-group-base");if(this.config.ldap_group_base&&e.ldap.declareObjectClasses(this.base,this.config.group_class||[]),this.config.group_schema){const e=this.config.group_schema;o(e,{config:this.config}).then(e=>{this.schema=this.adaptSchema(e),this.logger.debug("Group schema loaded")}).catch(t=>this.logger.error(`Failed to load group schema from ${e}: ${t}`))}}adaptSchema(e){return e}api(e){e.get(`${this.config.api_prefix}/v1/ldap/groups`,h(async(e,r)=>{if(!t(e,r))return;const i={};if(e.query.match){if("string"!=typeof e.query.match)throw new y("Invalid match query");if("string"==typeof e.query.attribute&&e.query.attribute)i.filter=b(e.query.match,e.query.attribute);else if(/=/.test(e.query.match)){if(!/^[\w*=()&|, -]+$/.test(e.query.match))throw new y("Invalid match query: contains forbidden characters");i.filter=e.query.match}else{const t=l(e.query.match);i.filter=`(${this.cn}=${t})`}}e.query.attributes&&"string"==typeof e.query.attributes&&(i.attributes=e.query.attributes.split(","));const a=await this.listGroups({...i,req:e});return s(r,this.hideNeverReturn(a))})),e.get(`${this.config.api_prefix}/v1/ldap/groups/:cn`,h(async(e,t)=>this.apiGet(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups`,h(async(e,t)=>this.apiAdd(e,t,this.cn))),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn`,h(async(e,t)=>this.apiDelete(e,t))),e.put(`${this.config.api_prefix}/v1/ldap/groups/:cn`,h(async(e,t)=>this.apiModify(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/members`,h(async(e,t)=>{const s=decodeURIComponent(e.params.cn);if(!s)throw new y("cn is required");const a=r(e,t,"member");if(!a)return;if((Array.isArray(a.member)?a.member:[a.member]).some(e=>"string"!=typeof e))throw new y("member must be a string or string array");await i(t,this.addMember.bind(this),s,a.member,e)})),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn/members/:member`,h(async(e,r)=>{if(!t(e,r))return;const s=decodeURIComponent(e.params.cn),a=decodeURIComponent(e.params.member);if(!s||!a)throw new y("cn and member are required");await i(r,this.deleteMember.bind(this),s,a,e)})),this.config.ldap_organization_link_attribute&&this.config.ldap_organization_path_attribute&&e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/move`,h(async(e,s)=>{if(!t(e,s))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new y("cn is required");const o=r(e,s,"targetOrgDn");if(o){if("string"!=typeof o.targetOrgDn)throw new y("targetOrgDn must be a string");await i(s,this.moveGroup.bind(this),a,o.targetOrgDn,e)}})),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/rename`,h(async(e,s)=>{if(!t(e,s))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new y("cn is required");const o=r(e,s,"newCn");if(o){if("string"!=typeof o.newCn)throw new y("newCn must be a string");await i(s,this.renameGroup.bind(this),a,o.newCn,e)}}))}isDummyMember(e){return c(e,this.config.group_dummy_user)}withoutDummyMember(e){const t=e.member;if(void 0===t)return e;const r=Array.isArray(t)?t:[t];return{...e,member:r.filter(e=>!this.isDummyMember(e))}}async apiGet(e,r){if(!t(e,r))return;const i=decodeURIComponent(e.params.cn);try{const t=/,/.test(i)?i:`${this.cn}=${d(i)},${this.base}`,s=await this.ldap.search({paged:!1,scope:"base"},t,e);if(0===s.searchEntries.length)throw new w("Group not found");r.json(this.hideNeverReturn(this.withoutDummyMember(s.searchEntries[0])))}catch(e){if(e.code&&32===e.code)throw new w("Group not found");throw e}}async apiAdd(e,t,...s){const a=r(e,t,...s);if(!a)return;v(this.schema,Object.keys(a),this.cn);const o=a[this.cn],n=a.member?a.member:[],h=Object.fromEntries(Object.entries(a).filter(([e,t])=>e!==this.cn&&"member"!==e&&void 0!==t&&!(!0===this.schema?.attributes[e]?.fixed)));await i(t,this.addGroup.bind(this),o,n,h,e)}async apiDelete(e,r){if(!t(e,r))return;const s=decodeURIComponent(e.params.cn);if(!s)throw new y("cn is required");await i(r,this.deleteGroup.bind(this),s,e)}async apiModify(e,t){const s=r(e,t);if(!s)return;const a=this.fixDn(decodeURIComponent(e.params.cn));if(!a)throw new y("cn is required");v(this.schema,_(s));const o=Object.fromEntries(Object.entries(s).filter(([e,t])=>!(!0===this.schema?.attributes[e]?.fixed)));await i(t,this.modifyGroup.bind(this),a,o,e)}async addGroup(e,t=[],r={},i){let s;new RegExp(`^${this.cn}=`).test(e)?(s=e,e=e.replace(new RegExp(`^${this.cn}=((?:\\\\.|[^,])+)(?:,.*)?$`),"$1")):(p(e,this.cn),s=`${this.cn}=${d(e)},${this.base}`),await this.validateMembers(s,t,i),await this.validateNewGroup(s,{objectClass:this.config.group_class,cn:e,member:t,...r});const a=[...this.config.group_class];!(r.mail||r.twakeMailboxType||r.twakeDepartmentLink||r.twakeDepartmentPath)||a.includes("twakeGroup")||a.includes("twakeStaticGroup")||a.push("twakeGroup");let o,n={objectClass:a,...this.config.group_default_attributes,[this.cn]:e,member:[this.config.group_dummy_user],...r};t.length&&n.member.push(...t),[s,n]=await m(this.registeredHooks.ldapgroupadd,[s,n]);try{o=await this.ldap.add(s,n,i)}catch(e){if(e instanceof $)throw e;throw new Error(`Failed to add group ${s}: ${e}`)}return u(this.registeredHooks.ldapgroupadddone,[s,n]),o}async modifyGroup(e,t,r){let i=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;const s=this.opNumber();if([i,t]=await m(this.registeredHooks.ldapgroupmodify,[i,t,s]),t.add){if(t.add.member)throw new Error("Use dedicated API to add members");if(t.add[this.cn])throw new Error(`${this.cn} attribute iq unique, cannot add`)}if(t.delete){if(t.delete instanceof Object){if(t.delete.member)throw new Error("Use dedicated API to delete members");if(t.delete[this.cn])throw new Error(`Cannot delete ${this.cn} attribute`)}if(Array.isArray(t.delete)){if(t.delete.includes("member"))throw new Error("Use dedicated API to delete members");if(t.delete.includes(this.cn))throw new Error(`Cannot delete ${this.cn} attribute`)}}if(t.replace){if(t.replace.member)throw new Error("Use dedicated API to replace members");if(t.replace[this.cn])throw new Error(`Use dedicated API to change ${this.cn} attribute`)}await this.validateChanges(i,t);const a=await this.ldap.modify(i,t,r);return u(this.registeredHooks.ldapgroupmodifydone,[i,t,s]),a}async renameGroup(e,t,r){/,/.test(e)||p(e,this.cn),/,/.test(t)||p(t,this.cn);let i=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`,s=/,/.test(t)?t:`${this.cn}=${d(t)},${this.base}`;[i,s]=await m(this.registeredHooks.ldapgrouprename,[i,s]);const a=await this.ldap.rename(i,s,r);return u(this.registeredHooks.ldapgrouprenamedone,[i,s]),a}async deleteGroup(e,t){let r=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;r=await m(this.registeredHooks.ldapgroupdelete,r);const i=await this.ldap.delete(r,t);return u(this.registeredHooks.ldapgroupdeletedone,r),i}async addMember(e,t,r){const i=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;return Array.isArray(t)||(t=[t]),[e,t]=await m(this.registeredHooks.ldapgroupaddmember,[e,t]),await this.validateMembers(i,t,r),await this.ldap.modify(i,{add:{member:t}},r).catch(e=>{if(e instanceof $)throw e;throw new Error(`Failed to add member(s) to ${i}: ${e}`)})}async deleteMember(e,t,r){const i=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`;if([e,t]=await m(this.registeredHooks.ldapgroupdeletemember,[e,t]),this.isDummyMember(t))throw new y("Cannot delete dummy member from group");return await this.ldap.modify(i,{delete:{member:t}},r).catch(e=>{if(e instanceof $)throw e;throw new Error(`Failed to delete member ${t} from ${i}: ${e}`)})}async deleteMemberFromAll(e){const t=await this.ldap.search({filter:`member=${l(e)}`,paged:!1,attributes:[this.cn]},this.base).catch(e=>{throw new Error(`Failed to search groups from ${this.base}: ${e}`)});await Promise.all(t.searchEntries.map(t=>this.ldap.modify(t.dn,{delete:{member:e}}).catch(r=>{if(65===a(r)&&this.config.group_dummy_user)return this.ldap.modify(t.dn,{add:{member:this.config.group_dummy_user},delete:{member:e}});throw r}).catch(r=>{const i=a(r);16!==i&&32!==i&&this.logger.error(`Failed to remove ${e} from group ${t.dn}:`,r)})))}async moveGroup(e,t,r){const i=this.config.ldap_organization_link_attribute,s=this.config.ldap_organization_path_attribute,a=/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`,o=await this.ldap.search({paged:!1,scope:"base"},a);if(0===o.searchEntries.length)throw new Error(`Group ${a} not found`);const n=o.searchEntries[0],h=f(n[i]);if(!h)throw new Error(`Group ${a} does not have ${i} attribute and cannot be moved`);if(h===t)throw new Error("Group is already in the target organization");let c;try{c=await this.ldap.search({paged:!1,scope:"base",attributes:[s,"ou","o"]},t)}catch(e){throw new Error(`Target organization ${t} not found: ${e instanceof Error&&e.message?e.message:String(e)}`)}if(0===c.searchEntries.length)throw new Error(`Target organization ${t} not found`);const p=c.searchEntries[0][s];if(!p)throw new Error(`Target organization ${t} does not have ${s} attribute`);return await this.ldap.modify(a,{replace:{[i]:t,[s]:p}},r),this.logger.info(`Group ${a} moved from ${h} to ${t}`),{success:!0}}async listGroups({filter:e,attributes:t,req:r}={}){const i=await this.ldap.search({filter:e||"(objectClass=*)",attributes:t||[this.cn,"member"],paged:!0},this.base,r).catch(e=>{throw new Error(`Failed to list groups from ${this.base}: ${e}`)});let s={};for await(const e of i)for(const t of e.searchEntries){const e=t[this.cn];if(Array.isArray(e)&&0===e.length)continue;e&&(s[e]=this.withoutDummyMember(t))}return s=await m(this.registeredHooks._ldapgrouplist,s),s}async searchGroupsByName(e,t=!1,r=[this.cn,"member"],i){const s=l(e),a=t?`(${this.cn}=*${s}*)`:`(${this.cn}=${s})`;return await this.listGroups({filter:a,attributes:r,req:i})}fixDn(e){return!!e&&(/,/.test(e)?e:`${this.cn}=${d(e)},${this.base}`)}async validateMembers(e,t,r){[e,t]=await m(this.server.hooks.ldapgroupvalidatemembers,[e,t]);const i=Boolean(this.config.groups_allow_unexistent_members);if((!i||r)&&t&&t.length)try{await Promise.all(t.map(e=>this.server.ldap.queryLimit(async()=>{let t;try{t=await this.ldap.search({paged:!1,scope:"base"},e,r)}catch(t){if(g(t))throw t;if(i)return;const r=a(t);if(32===r)throw new y(`Member ${e} not found`);if(34===r)throw new y(`Member ${e} is not a valid DN`);throw new Error(`Member ${e} not found: ${t}`)}if(r&&!t.searchEntries?.length)throw new y(`Member ${e} not found`)})))}catch(e){if(e instanceof $||g(e))throw e;throw new Error(`Failed to find member(s): ${e}`)}}async validateNewGroup(e,t){if(!this.schema)return!0;[e,t]=await m(this.server.hooks.ldapgroupvalidatenew,[e,t]);for(const[e,r]of Object.entries(t))if(!await this._validateOneChange(e,r))throw new y(E(e,this.schema.attributes[e]));const r=A(this.schema,t,this.server.loadedPlugins);if(r)throw new y(`Attribute "${r}" is required`);return!0}async validateChanges(e,t){if(!this.schema)return!0;if([e,t]=await m(this.server.hooks.ldapgroupvalidatechanges,[e,t]),t.add)for(const[e,r]of Object.entries(t.add))if(!await this._validateOneChange(e,r))throw new y(E(e,this.schema.attributes[e]));if(t.replace)for(const[e,r]of Object.entries(t.replace))if(!await this._validateOneChange(e,r))throw new y(E(e,this.schema.attributes[e]));if(t.delete&&t.delete instanceof Object)for(const e of Array.isArray(t.delete)?t.delete:Object.keys(t.delete))await this._validateOneChange(e,null);return!0}async _validateOneChange(e,t){if(!this.schema)return!0;const r=this.schema.attributes[e];if(!r){if(this.schema.strict)throw new y(`Attribute "${e}" is not allowed`);return!0}if(null==t||Array.isArray(t)&&0===t.length){if(r.required)throw new y(`Attribute "${e}" is required`);return!0}if("array"===r.type){if(!Array.isArray(t))throw new y(`Attribute "${e}" must be an array`);if(!r.items)throw new Error(`Schema error: no item for array ${e}`);if("array"===r.items.type)throw new Error(`Schema error: array of array not supported for ${e}`);if(r.items.test&&"pointer"!==r.items.type)for(const i of t)if(typeof i!==r.items.type)throw new y(`Attribute "${e}" must be of type ${r.items.type}`)}else if("pointer"!==r.type&&typeof t!==r.type)return!1;if(await G(e,r,t,async e=>(await this.ldap.search({paged:!1,scope:"base",attributes:["dn"]},e)).searchEntries.length>0),!q(r,t))throw new y(E(e,r));return!0}getConfigApiData(){const e=this.config.api_prefix||"/api",t=this.server.loadedPlugins.static&&this.config.group_schema?n(this.config,this.config.group_schema):void 0;return{enabled:!0,base:this.base||"",mainAttribute:this.cn||"cn",objectClass:this.config.group_class||["top","groupOfNames"],schema:this.schema,schemaUrl:t,endpoints:{list:`${e}/v1/ldap/groups`,get:`${e}/v1/ldap/groups/:id`,create:`${e}/v1/ldap/groups`,update:`${e}/v1/ldap/groups/:id`,delete:`${e}/v1/ldap/groups/:id`,addMember:`${e}/v1/ldap/groups/:id/members`,removeMember:`${e}/v1/ldap/groups/:id/members/:memberId`,rename:`${e}/v1/ldap/groups/:id/rename`,move:`${e}/v1/ldap/groups/:id/move`}}}}export{LdapGroups as default};
@@ -1 +1 @@
1
- import e from"../../abstract/plugin.js";import{asyncHandler as i,escapeDnValue as s}from"../../lib/utils.js";import{NotFoundError as t,BadRequestError as a}from"../../lib/errors.js";const r=["pwdChangedTime","pwdAccountLockedTime","pwdFailureTime","pwdGraceUseTime","pwdReset","pwdPolicySubentry"],o=["pwdMaxAge","pwdMinAge","pwdInHistory","pwdCheckQuality","pwdMinLength","pwdMaxFailure","pwdLockout","pwdLockoutDuration","pwdGraceAuthNLimit","pwdExpireWarning","pwdMustChange","pwdAllowUserChange"],n=/[!@#$%^&*()_+\-=[\]{}|;:'",.<>?/]/;class PasswordPolicy extends e{constructor(){super(...arguments),this.name="ldapPasswordPolicy",this.roles=["api","configurable"],this.policyCache=null,this.policyCacheTime=0,this.POLICY_CACHE_TTL=6e4}api(e){const s=`${this.config.api_prefix}/v1`;e.get(`${s}/password-policy`,i(async(e,i)=>{const s=await this.readPolicyConfig();i.json(s)})),e.get(`${s}/users/:id/password-status`,i(async(e,i)=>{const s=Array.isArray(e.params.id)?e.params.id[0]:e.params.id,t=await this.getPasswordStatus(s);i.json(t)})),e.post(`${s}/users/:id/unlock`,i(async(e,i)=>{const s=Array.isArray(e.params.id)?e.params.id[0]:e.params.id;await this.unlockAccount(s),i.json({success:!0,message:"Account unlocked"})})),e.get(`${s}/password-policy/expiring-soon`,i(async(e,i)=>{const s=parseInt(e.query.days)||this.config.ppolicy_warn_days||14,t=await this.findExpiringPasswords(s);i.json({warningDays:s,users:t})})),e.get(`${s}/password-policy/locked-accounts`,i(async(e,i)=>{const s=await this.findLockedAccounts();i.json({accounts:s})})),this.config.ppolicy_validate_complexity&&e.post(`${s}/password/validate`,i(async(e,i)=>{const{password:s}=e.body;if(!s)throw new a("password required");const t=this.validateComplexity(s);i.json(t)}))}async getPasswordStatus(e){const i=this.resolveUserDn(e);try{const s=await this.server.ldap.search({filter:"(objectClass=*)",scope:"base",attributes:["*",...r],paged:!1},i);if(!s.searchEntries||0===s.searchEntries.length)throw new t(`User not found: ${e}`);const a=s.searchEntries[0],o=await this.readPolicyConfig();return this.calculateStatus(i,a,o)}catch(i){if(i instanceof Error&&("NoSuchObjectError"===i.name||i.message.includes("0x20")||i.message.includes("Code: 32")))throw new t(`User not found: ${e}`);throw i}}calculateStatus(e,i,s){const t=Date.now(),a=this.parseGeneralizedTime(i.pwdChangedTime);let r=null,o=!1,n=null;s.pwdMaxAge&&a&&(r=new Date(a.getTime()+1e3*s.pwdMaxAge),o=t>r.getTime(),n=Math.ceil((r.getTime()-t)/864e5));let c=!1;const p=this.config.ppolicy_warn_days||14;null!==n&&n>0&&(c=n<=p);const d=i.pwdAccountLockedTime;let l=!!d;if(l&&!("000001010000Z"===d)&&s.pwdLockoutDuration){const e=this.parseGeneralizedTime(d);if(e){t>new Date(e.getTime()+1e3*s.pwdLockoutDuration).getTime()&&(l=!1)}}const u=i.pwdFailureTime,h=Array.isArray(u)?u.length:0,w=i.pwdGraceUseTime,g=Array.isArray(w)?w.length:0,y="TRUE"===i.pwdReset;return{dn:e,passwordSet:!!i.userPassword,lastChanged:a?.toISOString()||null,expiresAt:r?.toISOString()||null,daysUntilExpiration:n,isExpired:o,isExpiringSoon:c,mustChange:y,isLocked:l,lockedAt:d&&this.parseGeneralizedTime(d)?.toISOString()||null,failureCount:h,graceLoginsUsed:g}}async unlockAccount(e){const i=this.resolveUserDn(e),s=await this.server.ldap.search({filter:"(objectClass=*)",scope:"base",attributes:["pwdAccountLockedTime","pwdFailureTime"],paged:!1},i);if(!s.searchEntries||0===s.searchEntries.length)throw new t(`User not found: ${e}`);const a=s.searchEntries[0],r={};a.pwdAccountLockedTime&&(r.pwdAccountLockedTime=[]),a.pwdFailureTime&&(r.pwdFailureTime=[]),Object.keys(r).length>0?(await this.server.ldap.modify(i,{delete:r}),this.logger.info(`Account unlocked: ${i}`)):this.logger.info(`Account was not locked: ${i}`)}async findExpiringPasswords(e){const i=await this.readPolicyConfig();if(!i.pwdMaxAge)return[];const s=this.config.ldap_users_base||this.config.ldap_base,t=await this.server.ldap.search({filter:"(pwdChangedTime=*)",scope:"sub",attributes:["uid","cn","displayName","mail","pwdChangedTime"],paged:!1},s),a=Date.now(),r=24*e*60*60*1e3,o=[];for(const e of t.searchEntries){const s=e,t=this.parseGeneralizedTime(s.pwdChangedTime);if(!t)continue;const n=new Date(t.getTime()+1e3*i.pwdMaxAge),c=n.getTime()-a;c>0&&c<r&&o.push({dn:s.dn,uid:s.uid,displayName:s.displayName||s.cn,mail:s.mail,expiresAt:n.toISOString(),daysUntilExpiration:Math.ceil(c/864e5)})}return o.sort((e,i)=>e.daysUntilExpiration-i.daysUntilExpiration)}async findLockedAccounts(){const e=this.config.ldap_users_base||this.config.ldap_base;return(await this.server.ldap.search({filter:"(pwdAccountLockedTime=*)",scope:"sub",attributes:["uid","cn","displayName","mail","pwdAccountLockedTime","pwdFailureTime"],paged:!1},e)).searchEntries.map(e=>{const i=e;return{dn:i.dn,uid:i.uid,displayName:i.displayName||i.cn,mail:i.mail,lockedAt:this.parseGeneralizedTime(i.pwdAccountLockedTime)?.toISOString(),failureCount:Array.isArray(i.pwdFailureTime)?i.pwdFailureTime.length:0}})}async readPolicyConfig(){if(this.policyCache&&Date.now()-this.policyCacheTime<this.POLICY_CACHE_TTL)return this.policyCache;const e=this.config.ppolicy_default_dn;if(e)try{const i=await this.server.ldap.search({filter:"(objectClass=*)",scope:"base",attributes:o,paged:!1},e);if(i.searchEntries.length>0)return this.policyCache=this.parsePolicyEntry(i.searchEntries[0],e),this.policyCacheTime=Date.now(),this.policyCache}catch(i){this.logger.warn(`Failed to read ppolicy from ${e}: ${i}`)}try{const e=await this.server.ldap.search({filter:"(objectClass=pwdPolicy)",scope:"sub",attributes:o,paged:!1},this.config.ldap_base);if(e.searchEntries.length>0){const i=e.searchEntries[0];return this.policyCache=this.parsePolicyEntry(i,i.dn),this.policyCacheTime=Date.now(),this.policyCache}}catch(e){this.logger.debug(`No ppolicy found: ${e}`)}return this.policyCache={},this.policyCacheTime=Date.now(),this.policyCache}parsePolicyEntry(e,i){return{dn:i,pwdMaxAge:this.parseNumber(e.pwdMaxAge),pwdMinAge:this.parseNumber(e.pwdMinAge),pwdInHistory:this.parseNumber(e.pwdInHistory),pwdCheckQuality:this.parseNumber(e.pwdCheckQuality),pwdMinLength:this.parseNumber(e.pwdMinLength),pwdMaxFailure:this.parseNumber(e.pwdMaxFailure),pwdLockout:"TRUE"===e.pwdLockout,pwdLockoutDuration:this.parseNumber(e.pwdLockoutDuration),pwdGraceAuthNLimit:this.parseNumber(e.pwdGraceAuthNLimit),pwdExpireWarning:this.parseNumber(e.pwdExpireWarning),pwdMustChange:"TRUE"===e.pwdMustChange,pwdAllowUserChange:void 0===e.pwdAllowUserChange||"TRUE"===e.pwdAllowUserChange}}parseNumber(e){if(void 0===e)return;const i=parseInt(e,10);return isNaN(i)?void 0:i}parseGeneralizedTime(e){if(!e)return null;const i=e.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/);if(!i)return null;const[,s,t,a,r,o,n]=i;return new Date(Date.UTC(+s,+t-1,+a,+r,+o,+n))}validateComplexity(e){const i=[],s=this.config,t=s.ppolicy_min_length||12;return e.length<t&&i.push(`Minimum ${t} characters required`),s.ppolicy_require_uppercase&&!/[A-Z]/.test(e)&&i.push("At least one uppercase letter required"),s.ppolicy_require_lowercase&&!/[a-z]/.test(e)&&i.push("At least one lowercase letter required"),s.ppolicy_require_digit&&!/\d/.test(e)&&i.push("At least one digit required"),s.ppolicy_require_special&&!n.test(e)&&i.push("At least one special character required"),{valid:0===i.length,errors:i}}resolveUserDn(e){if(e.includes("="))return e;const i=this.config.ldap_users_base||this.config.ldap_base;return`${this.config.ldap_user_main_attribute||"uid"}=${s(e)},${i}`}getConfigApiData(){const e=this.config.api_prefix||"/api",i=!!this.config.ppolicy_validate_complexity;return{name:this.name,enabled:!0,endpoints:{getPolicy:`${e}/v1/password-policy`,getUserStatus:`${e}/v1/users/:id/password-status`,unlockUser:`${e}/v1/users/:id/unlock`,getExpiringSoon:`${e}/v1/password-policy/expiring-soon`,getLockedAccounts:`${e}/v1/password-policy/locked-accounts`,validatePassword:i?`${e}/v1/password/validate`:void 0},config:{warnDays:this.config.ppolicy_warn_days||14,validateComplexity:i,...i&&{complexityRules:{minLength:this.config.ppolicy_min_length||12,requireUppercase:this.config.ppolicy_require_uppercase??!0,requireLowercase:this.config.ppolicy_require_lowercase??!0,requireDigit:this.config.ppolicy_require_digit??!0,requireSpecial:this.config.ppolicy_require_special??!0}}},ldapPolicy:this.policyCache||void 0}}}export{PasswordPolicy as default};
1
+ import e from"../../abstract/plugin.js";import{asyncHandler as i,escapeDnValue as s}from"../../lib/utils.js";import{NotFoundError as t,BadRequestError as a}from"../../lib/errors.js";const r=["pwdChangedTime","pwdAccountLockedTime","pwdFailureTime","pwdGraceUseTime","pwdReset","pwdPolicySubentry"],o=["pwdMaxAge","pwdMinAge","pwdInHistory","pwdCheckQuality","pwdMinLength","pwdMaxFailure","pwdLockout","pwdLockoutDuration","pwdGraceAuthNLimit","pwdExpireWarning","pwdMustChange","pwdAllowUserChange"],n=/[!@#$%^&*()_+\-=[\]{}|;:'",.<>?/]/;class PasswordPolicy extends e{constructor(){super(...arguments),this.name="ldapPasswordPolicy",this.roles=["api","configurable"],this.policyCache=null,this.policyCacheTime=0,this.POLICY_CACHE_TTL=6e4}api(e){const s=`${this.config.api_prefix}/v1`;e.get(`${s}/password-policy`,i(async(e,i)=>{const s=await this.readPolicyConfig();i.json(s)})),e.get(`${s}/users/:id/password-status`,i(async(e,i)=>{const s=Array.isArray(e.params.id)?e.params.id[0]:e.params.id,t=await this.getPasswordStatus(s,e);i.json(t)})),e.post(`${s}/users/:id/unlock`,i(async(e,i)=>{const s=Array.isArray(e.params.id)?e.params.id[0]:e.params.id;await this.unlockAccount(s,e),i.json({success:!0,message:"Account unlocked"})})),e.get(`${s}/password-policy/expiring-soon`,i(async(e,i)=>{const s=parseInt(e.query.days)||this.config.ppolicy_warn_days||14,t=await this.findExpiringPasswords(s,e);i.json({warningDays:s,users:t})})),e.get(`${s}/password-policy/locked-accounts`,i(async(e,i)=>{const s=await this.findLockedAccounts(e);i.json({accounts:s})})),this.config.ppolicy_validate_complexity&&e.post(`${s}/password/validate`,i(async(e,i)=>{const{password:s}=e.body;if(!s)throw new a("password required");const t=this.validateComplexity(s);i.json(t)}))}async getPasswordStatus(e,i){const s=this.resolveUserDn(e);try{const a=await this.server.ldap.search({filter:"(objectClass=*)",scope:"base",attributes:["*",...r],paged:!1},s,i);if(!a.searchEntries||0===a.searchEntries.length)throw new t(`User not found: ${e}`);const o=a.searchEntries[0],n=await this.readPolicyConfig();return this.calculateStatus(s,o,n)}catch(i){if(i instanceof Error&&("NoSuchObjectError"===i.name||i.message.includes("0x20")||i.message.includes("Code: 32")))throw new t(`User not found: ${e}`);throw i}}calculateStatus(e,i,s){const t=Date.now(),a=this.parseGeneralizedTime(i.pwdChangedTime);let r=null,o=!1,n=null;s.pwdMaxAge&&a&&(r=new Date(a.getTime()+1e3*s.pwdMaxAge),o=t>r.getTime(),n=Math.ceil((r.getTime()-t)/864e5));let c=!1;const p=this.config.ppolicy_warn_days||14;null!==n&&n>0&&(c=n<=p);const d=i.pwdAccountLockedTime;let l=!!d;if(l&&!("000001010000Z"===d)&&s.pwdLockoutDuration){const e=this.parseGeneralizedTime(d);if(e){t>new Date(e.getTime()+1e3*s.pwdLockoutDuration).getTime()&&(l=!1)}}const u=i.pwdFailureTime,h=Array.isArray(u)?u.length:0,w=i.pwdGraceUseTime,g=Array.isArray(w)?w.length:0,y="TRUE"===i.pwdReset;return{dn:e,passwordSet:!!i.userPassword,lastChanged:a?.toISOString()||null,expiresAt:r?.toISOString()||null,daysUntilExpiration:n,isExpired:o,isExpiringSoon:c,mustChange:y,isLocked:l,lockedAt:d&&this.parseGeneralizedTime(d)?.toISOString()||null,failureCount:h,graceLoginsUsed:g}}async unlockAccount(e,i){const s=this.resolveUserDn(e),a=await this.server.ldap.search({filter:"(objectClass=*)",scope:"base",attributes:["pwdAccountLockedTime","pwdFailureTime"],paged:!1},s,i);if(!a.searchEntries||0===a.searchEntries.length)throw new t(`User not found: ${e}`);const r=a.searchEntries[0],o={};r.pwdAccountLockedTime&&(o.pwdAccountLockedTime=[]),r.pwdFailureTime&&(o.pwdFailureTime=[]),Object.keys(o).length>0?(await this.server.ldap.modify(s,{delete:o},i),this.logger.info(`Account unlocked: ${s}`)):this.logger.info(`Account was not locked: ${s}`)}async findExpiringPasswords(e,i){const s=await this.readPolicyConfig();if(!s.pwdMaxAge)return[];const t=this.config.ldap_users_base||this.config.ldap_base,a=await this.server.ldap.search({filter:"(pwdChangedTime=*)",scope:"sub",attributes:["uid","cn","displayName","mail","pwdChangedTime"],paged:!1},t,i),r=Date.now(),o=24*e*60*60*1e3,n=[];for(const e of a.searchEntries){const i=e,t=this.parseGeneralizedTime(i.pwdChangedTime);if(!t)continue;const a=new Date(t.getTime()+1e3*s.pwdMaxAge),c=a.getTime()-r;c>0&&c<o&&n.push({dn:i.dn,uid:i.uid,displayName:i.displayName||i.cn,mail:i.mail,expiresAt:a.toISOString(),daysUntilExpiration:Math.ceil(c/864e5)})}return n.sort((e,i)=>e.daysUntilExpiration-i.daysUntilExpiration)}async findLockedAccounts(e){const i=this.config.ldap_users_base||this.config.ldap_base;return(await this.server.ldap.search({filter:"(pwdAccountLockedTime=*)",scope:"sub",attributes:["uid","cn","displayName","mail","pwdAccountLockedTime","pwdFailureTime"],paged:!1},i,e)).searchEntries.map(e=>{const i=e;return{dn:i.dn,uid:i.uid,displayName:i.displayName||i.cn,mail:i.mail,lockedAt:this.parseGeneralizedTime(i.pwdAccountLockedTime)?.toISOString(),failureCount:Array.isArray(i.pwdFailureTime)?i.pwdFailureTime.length:0}})}async readPolicyConfig(){if(this.policyCache&&Date.now()-this.policyCacheTime<this.POLICY_CACHE_TTL)return this.policyCache;const e=this.config.ppolicy_default_dn;if(e)try{const i=await this.server.ldap.search({filter:"(objectClass=*)",scope:"base",attributes:o,paged:!1},e);if(i.searchEntries.length>0)return this.policyCache=this.parsePolicyEntry(i.searchEntries[0],e),this.policyCacheTime=Date.now(),this.policyCache}catch(i){this.logger.warn(`Failed to read ppolicy from ${e}: ${i}`)}try{const e=await this.server.ldap.search({filter:"(objectClass=pwdPolicy)",scope:"sub",attributes:o,paged:!1},this.config.ldap_base);if(e.searchEntries.length>0){const i=e.searchEntries[0];return this.policyCache=this.parsePolicyEntry(i,i.dn),this.policyCacheTime=Date.now(),this.policyCache}}catch(e){this.logger.debug(`No ppolicy found: ${e}`)}return this.policyCache={},this.policyCacheTime=Date.now(),this.policyCache}parsePolicyEntry(e,i){return{dn:i,pwdMaxAge:this.parseNumber(e.pwdMaxAge),pwdMinAge:this.parseNumber(e.pwdMinAge),pwdInHistory:this.parseNumber(e.pwdInHistory),pwdCheckQuality:this.parseNumber(e.pwdCheckQuality),pwdMinLength:this.parseNumber(e.pwdMinLength),pwdMaxFailure:this.parseNumber(e.pwdMaxFailure),pwdLockout:"TRUE"===e.pwdLockout,pwdLockoutDuration:this.parseNumber(e.pwdLockoutDuration),pwdGraceAuthNLimit:this.parseNumber(e.pwdGraceAuthNLimit),pwdExpireWarning:this.parseNumber(e.pwdExpireWarning),pwdMustChange:"TRUE"===e.pwdMustChange,pwdAllowUserChange:void 0===e.pwdAllowUserChange||"TRUE"===e.pwdAllowUserChange}}parseNumber(e){if(void 0===e)return;const i=parseInt(e,10);return isNaN(i)?void 0:i}parseGeneralizedTime(e){if(!e)return null;const i=e.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/);if(!i)return null;const[,s,t,a,r,o,n]=i;return new Date(Date.UTC(+s,+t-1,+a,+r,+o,+n))}validateComplexity(e){const i=[],s=this.config,t=s.ppolicy_min_length||12;return e.length<t&&i.push(`Minimum ${t} characters required`),s.ppolicy_require_uppercase&&!/[A-Z]/.test(e)&&i.push("At least one uppercase letter required"),s.ppolicy_require_lowercase&&!/[a-z]/.test(e)&&i.push("At least one lowercase letter required"),s.ppolicy_require_digit&&!/\d/.test(e)&&i.push("At least one digit required"),s.ppolicy_require_special&&!n.test(e)&&i.push("At least one special character required"),{valid:0===i.length,errors:i}}resolveUserDn(e){if(e.includes("="))return e;const i=this.config.ldap_users_base||this.config.ldap_base;return`${this.config.ldap_user_main_attribute||"uid"}=${s(e)},${i}`}getConfigApiData(){const e=this.config.api_prefix||"/api",i=!!this.config.ppolicy_validate_complexity;return{name:this.name,enabled:!0,endpoints:{getPolicy:`${e}/v1/password-policy`,getUserStatus:`${e}/v1/users/:id/password-status`,unlockUser:`${e}/v1/users/:id/unlock`,getExpiringSoon:`${e}/v1/password-policy/expiring-soon`,getLockedAccounts:`${e}/v1/password-policy/locked-accounts`,validatePassword:i?`${e}/v1/password/validate`:void 0},config:{warnDays:this.config.ppolicy_warn_days||14,validateComplexity:i,...i&&{complexityRules:{minLength:this.config.ppolicy_min_length||12,requireUppercase:this.config.ppolicy_require_uppercase??!0,requireLowercase:this.config.ppolicy_require_lowercase??!0,requireDigit:this.config.ppolicy_require_digit??!0,requireSpecial:this.config.ppolicy_require_special??!0}}},ldapPolicy:this.policyCache||void 0}}}export{PasswordPolicy as default};
@@ -198,6 +198,48 @@ export default abstract class AuthzBase extends DmPlugin {
198
198
  /** Said once: a rule keyed on a value the authenticator did not publish. */
199
199
  private fallbackWarned;
200
200
  protected resolveCaller(req: DmRequest): Promise<string | null>;
201
+ /**
202
+ * The attribute linking an organization to the mail domains its entries
203
+ * may use: the organization schema's `domainLink` role, or
204
+ * `--enterprise-domain-link-attribute`, as `enterpriseRules` reads it.
205
+ *
206
+ * @returns the attribute name, or undefined when no domain is linked
207
+ */
208
+ protected domainLinkAttribute(): string | undefined;
209
+ /**
210
+ * The values a write gives an attribute, whatever case its name is
211
+ * spelled in.
212
+ */
213
+ private static valuesOf;
214
+ /**
215
+ * The values of an attribute on stored entries, read as the server, not
216
+ * as the caller.
217
+ */
218
+ private storedValues;
219
+ /**
220
+ * Refuse a delegated administrator a mail domain their branch was not
221
+ * given.
222
+ *
223
+ * The domains an organization's entries may use are those it links and
224
+ * those every organization above it links (`enterpriseRules`). Writing an
225
+ * organization only asks for write on its parent, so an administrator
226
+ * could create a sub-organization of their branch linked to any domain of
227
+ * the directory — another customer's — and create addresses in it (#325).
228
+ *
229
+ * A domain newly linked to an organization must therefore be one an
230
+ * organization above it already links. Only a caller holding write on the
231
+ * top organization — who creates the organizations domains are given to —
232
+ * links another. Removing a link narrows nothing above the caller's own
233
+ * branch and is judged as any other write.
234
+ *
235
+ * @param user the resolved caller
236
+ * @param req the request, for the refusal's wording
237
+ * @param dn the organization being written
238
+ * @param submitted the domain DNs the write gives it
239
+ * @param attr the domain link attribute
240
+ * @param creating whether the organization is being created, so holds none
241
+ */
242
+ private guardDomainLinks;
201
243
  /** Forget what was resolved, for a test that changes the directory. */
202
244
  protected clearResolutionCache(): void;
203
245
  /**
@@ -147,8 +147,29 @@ export default class LdapGroups extends DmPlugin {
147
147
  }, req?: Request): Promise<boolean>;
148
148
  renameGroup(cn: string, newCn: string, req?: Request): Promise<boolean>;
149
149
  deleteGroup(cn: string, req?: Request): Promise<boolean>;
150
- addMember(cn: string, member: string | string[]): Promise<boolean>;
151
- deleteMember(cn: string, member: string): Promise<boolean>;
150
+ /**
151
+ * Add members to a group.
152
+ *
153
+ * With `req`, the change is judged as a modification of the group, and
154
+ * each member must be an entry the caller can read: the routes used to
155
+ * call this without it, which every authorization plugin reads as an
156
+ * internal call and lets through — anyone authenticated could join any
157
+ * group, a team mailbox included (#325).
158
+ *
159
+ * @param cn group cn or DN
160
+ * @param member member DN(s)
161
+ * @param req the request, to authorize the change against its caller
162
+ */
163
+ addMember(cn: string, member: string | string[], req?: Request): Promise<boolean>;
164
+ /**
165
+ * Remove a member from a group; with `req`, judged as a modification of
166
+ * the group, as {@link addMember} is.
167
+ *
168
+ * @param cn group cn or DN
169
+ * @param member member DN
170
+ * @param req the request, to authorize the change against its caller
171
+ */
172
+ deleteMember(cn: string, member: string, req?: Request): Promise<boolean>;
152
173
  deleteMemberFromAll(memberDn: string): Promise<void>;
153
174
  /**
154
175
  * Move a group to a different organization by updating organization link and path attributes
@@ -189,11 +210,21 @@ export default class LdapGroups extends DmPlugin {
189
210
  * It calls ldapgroupvalidatemembers hook before validation
190
211
  * so that plugins can modify the members list and/or the group DN
191
212
  * and/or create missing members on the fly
213
+ *
214
+ * With `req`, each member is looked up as the caller sees the directory:
215
+ * an entry an authorization plugin hides from them is refused as one that
216
+ * does not exist, so that an administrator cannot put an account of
217
+ * another branch in a group of theirs. `--group-allow-unexistent-members`
218
+ * still accepts a member that does not exist, but not one that does and
219
+ * is hidden — which tells the caller it exists, a smaller leak than the
220
+ * membership it would otherwise grant.
221
+ *
192
222
  * @param dn Group DN (given to hooks)
193
223
  * @param members Array of member DNs to check
224
+ * @param req the request, whose caller must be able to read each member
194
225
  * @returns nothing, throw if error
195
226
  */
196
- validateMembers(dn: string, members: string[]): Promise<void>;
227
+ validateMembers(dn: string, members: string[], req?: Request): Promise<void>;
197
228
  validateNewGroup(dn: string, entry: AttributesList): Promise<boolean>;
198
229
  validateChanges(dn: string, changes: ModifyRequest): Promise<boolean>;
199
230
  _validateOneChange(field: string, value: AttributeValue | null): Promise<boolean>;
@@ -198,6 +198,11 @@ export default class PasswordPolicy extends DmPlugin {
198
198
  api(app: Express): void;
199
199
  /**
200
200
  * Get password status for a user
201
+ *
202
+ * Every lookup of this plugin carries the request, so an authorization
203
+ * plugin answers for the caller: without it, a route read as an internal
204
+ * call, and a delegated administrator could read or unlock any account of
205
+ * the directory (#325).
201
206
  */
202
207
  private getPasswordStatus;
203
208
  /**
@@ -96,6 +96,27 @@ to the transit branch follows the same rules through
96
96
  `POST /api/v1/ldap/groups/:cn/move`; that endpoint does not move a group
97
97
  attached to no organization.
98
98
 
99
+ ### Mail domains
100
+
101
+ The mail domains an organization's entries may use are those it links in
102
+ `twakeDomainLink` and those every organization above it links
103
+ (`ldap/enterpriseRules`). Creating or changing an organization only asks for
104
+ write on its parent, so the link itself is held to more:
105
+
106
+ - a domain newly linked to an organization must already be linked by an
107
+ organization above it, up to the top organization;
108
+ - a caller holding write on the top organization links any domain: they are
109
+ the one giving each organization its own;
110
+ - a domain the organization already links can be kept, and removing one is
111
+ judged as any other change.
112
+
113
+ So the administrator of `ou=Sales` can create `ou=Sales-EU` restricted to
114
+ Sales' domain, but cannot give it another customer's. The attribute is the
115
+ organization schema's `domainLink` role, or
116
+ `--enterprise-domain-link-attribute`; with neither, nothing is checked. The
117
+ rule belongs to the base of the authorization plugins, so `authzPerBranch`
118
+ applies it too.
119
+
99
120
  ## Configuration
100
121
 
101
122
  No configuration file needed - permissions are read from LDAP. Simply load the plugin:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ldap-rest",
3
- "version": "0.19.0",
3
+ "version": "0.19.1",
4
4
  "description": "Light directory manager",
5
5
  "keywords": [
6
6
  "Identity-Manager"