ldap-rest 1.1.0 → 1.2.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.
- package/bin/index.mjs +8 -7
- package/dist/abstract/ldapFlat.js +1 -1
- package/dist/abstract/plugin.js +1 -1
- package/dist/abstract/twakePlugin.js +1 -1
- package/dist/bin/index.js +1 -1
- package/dist/config/args.js +1 -1
- package/dist/config/schema.js +1 -1
- package/dist/lib/changeContext.js +1 -1
- package/dist/lib/entitySchema/validator.js +1 -0
- package/dist/lib/expressFormatedResponses.js +1 -1
- package/dist/lib/health.js +1 -0
- package/dist/lib/instanceProviders.js +1 -1
- package/dist/lib/ldapActions.js +1 -1
- package/dist/lib/ldapSchema.js +1 -1
- package/dist/lib/metrics.js +1 -0
- package/dist/lib/requestContext.js +1 -1
- package/dist/lib/shutdown.js +1 -0
- package/dist/lib/staticFiles.js +1 -0
- package/dist/lib/storage/store.js +1 -1
- package/dist/lib/utils.js +1 -1
- package/dist/logger/winston.js +1 -1
- package/dist/plugins/auth/crowdsec.js +1 -1
- package/dist/plugins/auth/openidconnect.js +1 -1
- package/dist/plugins/demo/helloworld.js +1 -1
- package/dist/plugins/ldap/bulkImport.js +1 -1
- package/dist/plugins/ldap/departmentSync.js +1 -1
- package/dist/plugins/ldap/flatGeneric.js +1 -1
- package/dist/plugins/ldap/groups.js +1 -1
- package/dist/plugins/ldap/organizations.js +1 -1
- package/dist/plugins/metrics.js +1 -0
- package/dist/plugins/rabbitmq.js +1 -1
- package/dist/plugins/scim/baseResolver.js +1 -1
- package/dist/plugins/scim/bulk.js +1 -1
- package/dist/plugins/scim/errors.js +1 -1
- package/dist/plugins/scim/filter.js +1 -1
- package/dist/plugins/scim/groups.js +1 -1
- package/dist/plugins/scim/mapping.js +1 -1
- package/dist/plugins/scim/patch.js +1 -1
- package/dist/plugins/scim/projection.js +1 -1
- package/dist/plugins/scim/scim.js +1 -1
- package/dist/plugins/scim/users.js +1 -1
- package/dist/plugins/static.js +1 -1
- package/dist/plugins/storage/file.js +1 -1
- package/dist/plugins/storage/postgres.js +1 -1
- package/dist/plugins/storage/valkey.js +1 -1
- package/dist/plugins/storage.js +1 -1
- package/dist/plugins/twake/calendar.js +1 -1
- package/dist/plugins/twake/clouderyProvision.js +1 -1
- package/dist/plugins/twake/cozyProvision.js +1 -1
- package/dist/plugins/twake/drive.js +1 -1
- package/dist/plugins/twake/groups.js +1 -1
- package/dist/plugins/twake/james.js +1 -1
- package/dist/plugins/twake/migrationProxy.js +1 -0
- package/dist/plugins/twake/spaces.js +1 -1
- package/dist/plugins/weblogs.js +1 -1
- package/dist/src/abstract/ldapFlat.d.ts +3 -13
- package/dist/src/abstract/plugin.d.ts +20 -0
- package/dist/src/abstract/twakePlugin.d.ts +23 -1
- package/dist/src/bin/index.d.ts +46 -1
- package/dist/src/config/args.d.ts +12 -1
- package/dist/src/lib/changeContext.d.ts +11 -0
- package/dist/src/lib/entitySchema/validator.d.ts +64 -0
- package/dist/src/lib/expressFormatedResponses.d.ts +19 -0
- package/dist/src/lib/health.d.ts +63 -0
- package/dist/src/lib/instanceProviders.d.ts +4 -0
- package/dist/src/lib/ldapActions.d.ts +32 -2
- package/dist/src/lib/metrics.d.ts +44 -0
- package/dist/src/lib/requestContext.d.ts +40 -0
- package/dist/src/lib/shutdown.d.ts +20 -0
- package/dist/src/lib/staticFiles.d.ts +33 -0
- package/dist/src/lib/storage/store.d.ts +8 -0
- package/dist/src/lib/utils.d.ts +15 -0
- package/dist/src/logger/winston.d.ts +4 -0
- package/dist/src/plugins/ldap/groups.d.ts +18 -3
- package/dist/src/plugins/ldap/organizations.d.ts +3 -5
- package/dist/src/plugins/metrics.d.ts +17 -0
- package/dist/src/plugins/rabbitmq.d.ts +37 -1
- package/dist/src/plugins/scim/errors.d.ts +2 -0
- package/dist/src/plugins/scim/types.d.ts +2 -1
- package/dist/src/plugins/static.d.ts +12 -0
- package/dist/src/plugins/storage/file.d.ts +4 -0
- package/dist/src/plugins/storage/postgres.d.ts +7 -14
- package/dist/src/plugins/storage/valkey.d.ts +2 -15
- package/dist/src/plugins/storage.d.ts +8 -0
- package/dist/src/plugins/twake/drive.d.ts +8 -0
- package/dist/src/plugins/twake/groups.d.ts +1 -2
- package/dist/src/plugins/twake/james.d.ts +2 -0
- package/dist/src/plugins/twake/migrationProxy.d.ts +71 -0
- package/docs/client-development/api/reference.md +5 -9
- package/docs/client-development/api/rest-api.md +4 -10
- package/docs/client-development/schemas/README.md +60 -21
- package/docs/plugin-development/README.md +15 -13
- package/docs/plugin-development/dependencies.md +8 -0
- package/docs/plugin-development/hooks.md +1 -1
- package/docs/usage/README.md +1 -0
- package/docs/usage/configuration.md +62 -24
- package/docs/usage/operations.md +193 -0
- package/docs/usage/plugins/README.md +2 -0
- package/docs/usage/plugins/auth/authz-per-branch.md +2 -1
- package/docs/usage/plugins/integrations/README.md +8 -4
- package/docs/usage/plugins/integrations/groups.md +2 -2
- package/docs/usage/plugins/integrations/mail-migration.md +102 -0
- package/docs/usage/plugins/integrations/scim.md +16 -3
- package/docs/usage/plugins/integrations/spaces.md +1 -1
- package/docs/usage/plugins/ldap/bulk-import.md +3 -1
- package/docs/usage/plugins/ldap/flat-generic.md +5 -2
- package/docs/usage/plugins/ldap/on-change.md +2 -1
- package/docs/usage/plugins/ldap/organizations.md +7 -7
- package/docs/usage/plugins/utilities/metrics.md +21 -0
- package/docs/usage/plugins/utilities/static.md +16 -8
- package/docs/usage/plugins/utilities/storage.md +7 -0
- package/docs/usage/plugins/utilities/weblogs.md +51 -30
- package/docs/usage/upgrading.md +84 -0
- package/package.json +11 -2
- package/static/schemas/example/README.md +1 -0
package/dist/lib/ldapSchema.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const t=new Set(["1.3.6.1.4.1.1466.115.121.1.5","1.3.6.1.4.1.1466.115.121.1.8","1.3.6.1.4.1.1466.115.121.1.9","1.3.6.1.4.1.1466.115.121.1.10","1.3.6.1.4.1.1466.115.121.1.28","1.3.6.1.4.1.1466.115.121.1.40","1.3.6.1.4.1.1466.115.121.1.49","1.3.6.1.1.16.1"]),e=new Set(["userpassword","jpegphoto","usercertificate","cacertificate","certificaterevocationlist","authoritiyrevocationlist","crosscertificatepair","photo","personalsignature","audio","thumbnailphoto","thumbnaillogo","objectguid","objectsid"]);function readList(t,e){if("("!==t[e])return{values:[t[e]],next:e+1};const s=[];let n=e+1;for(;n<t.length&&")"!==t[n];)"$"!==t[n]&&s.push(t[n]),n++;return{values:s,next:n+1}}function parseDefinition(t,e){const s=function(t){const e=[];let s=0;for(;s<t.length;){const n=t[s];if(
|
|
1
|
+
const t=new Set(["1.3.6.1.4.1.1466.115.121.1.5","1.3.6.1.4.1.1466.115.121.1.8","1.3.6.1.4.1.1466.115.121.1.9","1.3.6.1.4.1.1466.115.121.1.10","1.3.6.1.4.1.1466.115.121.1.28","1.3.6.1.4.1.1466.115.121.1.40","1.3.6.1.4.1.1466.115.121.1.49","1.3.6.1.1.16.1"]),e=new Set(["userpassword","jpegphoto","usercertificate","cacertificate","certificaterevocationlist","authoritiyrevocationlist","crosscertificatepair","photo","personalsignature","audio","thumbnailphoto","thumbnaillogo","objectguid","objectsid"]);function readList(t,e){if(e>=t.length||")"===t[e])return{values:[],next:e};if("("!==t[e])return{values:[t[e]],next:e+1};const s=[];let n=e+1;for(;n<t.length&&")"!==t[n];)"$"!==t[n]&&s.push(t[n]),n++;return{values:s,next:n+1}}function parseDefinition(t,e){const s=function(t){const e=[];let s=0;for(;s<t.length;){const n=t[s];if(/\s/.test(n))s++;else if("("===n||")"===n)e.push(n),s++;else if("'"===n){let n="";for(s++;s<t.length&&"'"!==t[s];){if("\\"===t[s]&&s+2<t.length){const e=t.substring(s+1,s+3);if(/^[0-9a-fA-F]{2}$/.test(e)){n+=String.fromCharCode(parseInt(e,16)),s+=3;continue}}n+=t[s],s++}s++,e.push(n)}else{let n="";for(;s<t.length&&!/[\s()']/.test(t[s]);)n+=t[s],s++;e.push(n)}}return e}(t);if(s.length<2||"("!==s[0])return null;const n=s[1],i={};let o=2;for(;o<s.length&&")"!==s[o];){const t=s[o];if(o++,e.has(t)){const{values:e,next:n}=readList(s,o);i[t]=e,o=n}else if(t.startsWith("X-")){const{next:e}=readList(s,o);i[t]=[],o=e}else i[t]=[]}return{oid:n,fields:i}}const s=new Set(["NAME","DESC","SUP","EQUALITY","ORDERING","SUBSTR","SYNTAX","USAGE"]),n=new Set(["NAME","DESC","SUP","MUST","MAY"]),i=new Set(["DESC"]),o=new Set(["NAME","DESC","SUP","SYNTAX"]);function parseAttributeType(t){const e=parseDefinition(t,s);if(!e)return null;const{oid:n,fields:i}=e;let o,a=i.SYNTAX?.[0];if(a){const t=/^(.*?)\{(\d+)\}$/.exec(a);t&&(a=t[1],o=parseInt(t[2],10))}return{oid:n,names:i.NAME||[],desc:i.DESC?.[0],obsolete:"OBSOLETE"in i,sup:i.SUP?.[0],equality:i.EQUALITY?.[0],ordering:i.ORDERING?.[0],substr:i.SUBSTR?.[0],syntax:a,syntaxLength:o,singleValue:"SINGLE-VALUE"in i,collective:"COLLECTIVE"in i,noUserModification:"NO-USER-MODIFICATION"in i,usage:i.USAGE?.[0]||"userApplications"}}function parseObjectClass(t){const e=parseDefinition(t,n);if(!e)return null;const{oid:s,fields:i}=e,o="ABSTRACT"in i?"ABSTRACT":"AUXILIARY"in i?"AUXILIARY":"STRUCTURAL";return{oid:s,names:i.NAME||[],desc:i.DESC?.[0],obsolete:"OBSOLETE"in i,sup:i.SUP||[],kind:o,must:i.MUST||[],may:i.MAY||[]}}function parseSyntax(e){const s=parseDefinition(e,i);return s?{oid:s.oid,desc:s.fields.DESC?.[0],binary:t.has(s.oid)}:null}function parseMatchingRule(t){const e=parseDefinition(t,o);return e?{oid:e.oid,names:e.fields.NAME||[],desc:e.fields.DESC?.[0],syntax:e.fields.SYNTAX?.[0]}:null}function parseSchema(t){const parseAll=(t,e)=>(t||[]).map(e).filter(t=>null!==t);return{attributeTypes:parseAll(t.attributeTypes,parseAttributeType),objectClasses:parseAll(t.objectClasses,parseObjectClass),syntaxes:parseAll(t.ldapSyntaxes,parseSyntax),matchingRules:parseAll(t.matchingRules,parseMatchingRule)}}class SchemaIndex{constructor(t){this.objectClassesByName=new Map,this.attributeTypesByName=new Map,this.syntaxesByOid=new Map,this.schema=t;for(const e of t.objectClasses){this.objectClassesByName.set(e.oid.toLowerCase(),e);for(const t of e.names)this.objectClassesByName.set(t.toLowerCase(),e)}for(const e of t.attributeTypes){this.attributeTypesByName.set(e.oid.toLowerCase(),e);for(const t of e.names)this.attributeTypesByName.set(t.toLowerCase(),e)}for(const e of t.syntaxes)this.syntaxesByOid.set(e.oid,e)}getObjectClass(t){return this.objectClassesByName.get(t.toLowerCase())}getAttributeType(t){const e=t.split(";")[0];return this.attributeTypesByName.get(e.toLowerCase())}getAttributeSyntax(t){const e=new Set;let s=this.getAttributeType(t);for(;s&&!e.has(s.oid);){if(s.syntax)return s.syntax;e.add(s.oid),s=s.sup?this.getAttributeType(s.sup):void 0}}isBinaryAttribute(s){const n=s.split(";")[0].toLowerCase();if(s.split(";").slice(1).some(t=>"binary"===t.toLowerCase()))return!0;if(e.has(n))return!0;const i=this.getAttributeSyntax(n);return!!i&&t.has(i)}resolveAttributes(t){const e=new Set,s=new Set,n=new Set,walk=t=>{const i=t.toLowerCase();if(n.has(i))return;n.add(i);const o=this.getObjectClass(t);o&&(o.must.forEach(t=>e.add(t)),o.may.forEach(t=>s.add(t)),o.sup.forEach(walk))};t.forEach(walk);for(const t of e)for(const e of s)e.toLowerCase()===t.toLowerCase()&&s.delete(e);return{must:[...e],may:[...s]}}missingClasses(t,e){const s=new Set(e.map(t=>this.getObjectClass(t)?.oid??t.toLowerCase())),n=[],i=[];for(const e of t){const t=this.getObjectClass(e);t&&!s.has(t.oid)&&(s.add(t.oid),"AUXILIARY"===t.kind?n.push(t):"STRUCTURAL"===t.kind&&i.push(t.names[0]??e))}return{auxiliary:n,structural:i}}}export{SchemaIndex,parseAttributeType,parseMatchingRule,parseObjectClass,parseSchema,parseSyntax};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Registry as e,Histogram as t,Counter as r}from"prom-client";import{extractLdapCode as s}from"./ldapCodes.js";const o=new e,a=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],n=new t({name:"ldap_rest_http_request_duration_seconds",help:"Time to answer a request, by method, route template and status",labelNames:["method","route","status"],buckets:a,registers:[o]}),i=new t({name:"ldap_rest_ldap_operation_duration_seconds",help:"Time the directory takes to answer, by operation and result: ok, the LDAP result code of a refusal, or error when it did not answer",labelNames:["operation","result"],buckets:a,registers:[o]}),l=new t({name:"ldap_rest_ldap_pool_wait_seconds",help:"Time to get a pooled directory connection, opening one included",buckets:a,registers:[o]}),d=new r({name:"ldap_rest_ldap_search_cache_total",help:"Cacheable searches, served by the cache or sent to the directory",labelNames:["result"],registers:[o]}),c=new r({name:"ldap_rest_hook_failures_total",help:"Notification hooks that threw, by hook and plugin",labelNames:["hook","plugin"],registers:[o]}),u=new t({name:"ldap_rest_outbound_request_duration_seconds",help:"Time a service the server calls takes to answer, by target and status: the HTTP status, or error when it did not answer",labelNames:["target","status"],buckets:a,registers:[o]}),p=new r({name:"ldap_rest_unhandled_rejections_total",help:"Promise rejections nothing handled",registers:[o]}),ldapResult=e=>{const t=s(e);return void 0===t?"error":String(t)},secondsSince=e=>Number(process.hrtime.bigint()-e)/1e9;async function timedLdap(e,t){const r=process.hrtime.bigint();let s="ok";try{return await t()}catch(e){throw s=ldapResult(e),e}finally{i.observe({operation:e,result:s},secondsSince(r))}}async function timedOutbound(e,t){const r=process.hrtime.bigint();let s="error";try{const e=await t();return s=String(e.status),e}finally{u.observe({target:e,status:s},secondsSince(r))}}const routeTemplate=e=>{const t=e.route,r=t?.path,one=e=>"string"==typeof e?e:e instanceof RegExp?e.source:"other";if(void 0===r)return"none";const s=Array.isArray(r)?r.map(one).join("|"):one(r);return`${e.baseUrl?"*":""}${s}`};export{c as hookFailures,n as httpRequestDuration,i as ldapOperationDuration,l as ldapPoolWait,ldapResult,d as ldapSearchCache,u as outboundRequestDuration,o as registry,routeTemplate,secondsSince,timedLdap,timedOutbound,p as unhandledRejections};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage as
|
|
1
|
+
import{AsyncLocalStorage as t}from"async_hooks";const n=new t;function runForRequest(t,e){return n.run(t,e)}function outsideRequest(t){return n.exit(t)}function currentRequest(){return n.getStore()}const e=new t;function outsideAnyRequest(t){return n.exit(()=>e.exit(t))}function runWithLogContext(t,n){return e.run(t,n)}function runAsPlugin(t,n,u){return e.run({...e.getStore(),plugin:t,op:n},u)}function currentLogContext(){return e.getStore()}export{currentLogContext,currentRequest,outsideAnyRequest,outsideRequest,runAsPlugin,runForRequest,runWithLogContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{constants as e}from"os";const s=["SIGTERM","SIGINT"],o={ms:2e4},t=[],r=new Map;let c=[],n=!1;const settle=e=>Promise.resolve().then(e).catch(()=>{});function registerProcessShutdown(e){if(n)c.push(settle(e));else if(t.push(e),!(r.size>0))for(const e of s){const listener=()=>fanOut(e);r.set(e,listener),process.prependListener(e,listener)}}function fanOut(s){const i=process.listenerCount(s)-1;n=!0;for(const[e,s]of r)process.removeListener(e,s);r.clear(),c=t.splice(0).map(settle);const p=(async()=>{for(;c.length>0;)await Promise.allSettled(c.splice(0))})();let l;const a=new Promise(e=>{l=setTimeout(e,o.ms)}),f=128+e.signals[s];Promise.race([p,a]).then(()=>{clearTimeout(l),i>0||(process.kill(process.pid,s),process.exit(f))}).catch(()=>process.exit(f))}export{registerProcessShutdown,o as shutdownTimeout};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const isStaticFiles=t=>"function"==typeof t.schemaUrlOf&&"function"==typeof t.servedPath;function staticPlugins(t){const s=[],e=[];for(const n of Object.values(t.loadedPlugins)){if(!isStaticFiles(n))continue;const t=n.servedPath().toLowerCase();s.some(s=>(t+"/").startsWith(s+"/")||(s+"/").startsWith(t+"/"))||(s.push(t),e.push(n))}return e.sort((t,s)=>Number("static"===s.name)-Number("static"===t.name))}function staticSchemaUrl(t,s){for(const e of staticPlugins(t)){const t=e.schemaUrlOf(s);if(t)return t}}export{isStaticFiles,staticPlugins,staticSchemaUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
class Store{constructor(e){this.logger=e}static scoped(e,t){return`${e}\0${t}`}static readable(e){return e.replace("\0",":")}static encodeRecord(e,t){return`${t.deadline} ${Store.readable(e)}\n${t.value}`}static decodeRecord(e){const t=String(e),s=t.indexOf("\n"),r=s<0?t:t.slice(0,s),
|
|
1
|
+
class Store{constructor(e){this.closed=!1,this.logger=e}health(){return Promise.resolve("ok")}static scoped(e,t){return`${e}\0${t}`}static readable(e){return e.replace("\0",":")}static encodeRecord(e,t){return`${t.deadline} ${Store.readable(e)}\n${t.value}`}static decodeRecord(e){const t=String(e),s=t.indexOf("\n"),r=s<0?t:t.slice(0,s),i=parseInt(r.split(" ")[0],10);return Number.isFinite(i)?{deadline:i,value:s<0?"":t.slice(s+1)}:null}async open(){}close(){return this.closed=!0,this.stopSweeping(),Promise.resolve()}async get(e,t){const s=Store.scoped(e,t),r=await this.load(s);return null===r?null:r.deadline<=Date.now()?(this.drop(s).catch(()=>{}),null):r.value}async set(e,t,s,r){await this.save(Store.scoped(e,t),{value:s,deadline:r})}async delete(e,t){await this.drop(Store.scoped(e,t))}startSweeping(e){if(this.sweeper||e<=0)return;const run=()=>{this.sweep().then(e=>{e>0&&this.logger.debug(`${this.name}: swept ${e} record(s)`)}).catch(e=>{this.logger.warn(`${this.name}: sweep failed: ${e instanceof Error?e.message:JSON.stringify(e)}`)})};this.sweeper=setInterval(run,1e3*e),this.sweeper.unref?.(),run()}stopSweeping(){this.sweeper&&clearInterval(this.sweeper),this.sweeper=void 0}}export{Store as default};
|
package/dist/lib/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BadRequestError as e}from"./errors.js";import{getLogger as n}from"./expressFormatedResponses.js";import{
|
|
1
|
+
import{BadRequestError as e}from"./errors.js";import{getLogger as n}from"./expressFormatedResponses.js";import{hookFailures as t}from"./metrics.js";import{runAsPlugin as r,outsideRequest as o}from"./requestContext.js";const i=new Map;function getCompiledRegex(e,n){const t=n?`${e}:${n}`:e;let r=i.get(t);return r||(r=new RegExp(e,n),i.set(t,r)),r}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const describeThrown=e=>{try{return JSON.stringify(e)??String(e)}catch{return String(e)}},hookLabel=e=>{const n=hookOwner(e);return n?` in ${n.plugin} (${n.hook})`:e.name?` in ${e.name}`:""},runAsHookOwner=(e,n)=>{const t=hookOwner(e);return r(t?.plugin,t?.hook,n)},launchHooks=async(e,...r)=>{if(e)for(const i of e)i&&await runAsHookOwner(i,async()=>{try{await o(()=>i(...r))}catch(e){const r=hookLabel(i),o=hookOwner(i);t.inc({hook:o?.hook??(i.name||"anonymous"),plugin:o?.plugin??"none"}),e instanceof Error?n()?.error(`Hook error${r}`,e):n()?.error(`Hook error${r}: ${describeThrown(e)}`)}})},s=new WeakMap,recordHookOwner=(e,n,t)=>{s.set(e,{plugin:n,hook:t})},hookOwner=e=>s.get(e),isAuthzRefusal=e=>/\[authz-forbidden\]/.test(String(e?.message??"")),isRefusal=e=>403===e?.statusCode||isAuthzRefusal(e),launchHooksChained=async(e,t)=>{if(e)for(const r of e)r&&(t=await runAsHookOwner(r,async()=>{try{return await o(()=>r(t))}catch(e){if(isRefusal(e)){const t=hookOwner(r);n()?.warn(`${t?`${t.plugin} refused ${t.hook}`:`a hook no plugin registered (${r.name||"anonymous"}) refused`}: ${e.message}`)}throw e}}));return t},transformSchemas=(e,n)=>e.toString().replace(/__(\S+)__/g,(e,t)=>{if(!t||"string"!=typeof t)return e;const r=t.trim().toLowerCase();return n[r]?"object"!=typeof n[r]?n[r]:JSON.stringify(n[r]):e});function escapeLdapFilter(e){return e.replace(/\\/g,"\\5c").replace(/\*/g,"\\2a").replace(/\(/g,"\\28").replace(/\)/g,"\\29").replace(/\0/g,"\\00")}function substringSearchFilter(n,t){const r=/^[a-zA-Z][a-zA-Z0-9-]*$/,o=t.split(",").map(e=>e.trim()).filter(Boolean);if(0===o.length||!o.every(e=>r.test(e)))throw new e("Invalid LDAP attribute name");const i=escapeLdapFilter(n),s=o.map(e=>`(${e}=*${i}*)`);return 1===s.length?s[0]:`(|${s.join("")})`}function fillPattern(e,n,t){return e.split(n).join(t)}function escapeDnValue(e){let n=e.replace(/[\\,+"<>;=]/g,e=>`\\${e}`).replace(/[\0-\x1f\x7f]/g,e=>`\\${hexByte(e.charCodeAt(0))}`);return e.startsWith(" ")&&(n=`\\${n}`),e.length>1&&e.endsWith(" ")&&(n=`${n.slice(0,-1)}\\ `),e.startsWith("#")&&(n=`\\${n}`),n}const a=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});function unescapeDnValue(n){if("string"!=typeof n)throw new e("DN value must be a string");let t="",r=0,o=[];const flushBytes=()=>{if(o.length){for(const e of utf8Chars(o))t+="number"==typeof e?String.fromCharCode(e):e;o=[]}};for(;r<n.length;)if("\\"===n[r]&&r+1<n.length){const e=n[r+1];if(/[0-9a-fA-F]/.test(e)&&r+2<n.length){const e=n.substring(r+1,r+3);if(/^[0-9a-fA-F]{2}$/.test(e)){o.push(parseInt(e,16)),r+=3;continue}}flushBytes(),t+=e,r+=2}else flushBytes(),t+=n[r],r++;return flushBytes(),t}function validateDnValue(e,n){if(null==e||"string"!=typeof e)throw new Error(`${n} must be a string`);if(0===e.trim().length)throw new Error(`${n} must be a non-empty string`);if(/[\x00-\x1F\x7F]/.test(e))throw new Error(`${n} contains invalid control characters`);if(/[\u200B-\u200F\uFEFF]/.test(e))throw new Error(`${n} contains invalid invisible characters`)}function asciiSpace(e){return" "===e||e>="\t"&&e<="\r"}function trimUnescaped(e){let n=0,t=e.length;for(;n<t&&asciiSpace(e[n]);)n++;for(;t>n&&asciiSpace(e[t-1]);)t--;if(t<e.length){let r=0;for(let o=t-1;o>=n&&"\\"===e[o];o--)r++;r%2==1&&t++}return e.slice(n,t)}function parseDn(n){if("string"!=typeof n)throw new e("DN must be a string");const t=[];let r="",o=!1,i=!1;for(let e=0;e<n.length;e++){const s=n[e];o?(r+=s,o=!1):"\\"===s?(r+=s,o=!0):'"'===s&&(i||opensValue(r))?(r+=s,i=!i):i||","!==s&&";"!==s?r+=s:(t.push(trimUnescaped(r)),r="")}if(i)throw new e("DN has an unbalanced quote");return r&&t.push(trimUnescaped(r)),t}function opensValue(e){const n=e.trimEnd();if(!n.endsWith("="))return!1;let t=0;for(let e=n.length-2;e>=0&&"\\"===n[e];e--)t++;return t%2==0}function isDnSyntax(e){let n;try{n=parseDn(e)}catch{return!1}if(0===n.length)return!1;const t=/^\s*(?:[A-Za-z][A-Za-z0-9-]*|(?:OID\.)?\d+(?:\.\d+)+)\s*=/i;return n.every(e=>{if(!e)return!1;const n=[];let r="",o=!1;for(const t of e){if(o)o=!1;else if("\\"===t)o=!0;else if("+"===t){n.push(r),r="";continue}r+=t}return n.push(r),n.every(e=>t.test(e))})}function getParentDn(e){const n=parseDn(e);return n.length<=1?e:n.slice(1).join(",")}function getRdn(e){return parseDn(e)[0]||""}function rdnValue(e){const[n]=parseDn(e),t=n?n.indexOf("="):-1;if(t<=0)return"";let r=t+1;for(;r<n.length&&asciiSpace(n[r]);)r++;return unescapeDnValue(n.slice(r))}function isChildOf(e,n){try{return isDnInBranch(e,n)&&!isDnInBranch(n,e)}catch{return!1}}const c=/((?:\\[0-9a-fA-F]{2})+)|\\([^])/g;function hexByte(e){return e.toString(16).padStart(2,"0")}function utf8Chars(e){const n=[],t=Uint8Array.from(e);for(let r=0;r<e.length;){const o=utf8Length(e[r]);let i;if(o&&r+o<=e.length)try{i=a.decode(t.subarray(r,r+o))}catch{}void 0===i?n.push(e[r++]):(n.push(...i),r+=o)}return n}function utf8Length(e){return e<128?1:e>>5==6?2:e>>4==14?3:e>>3==30?4:0}const u=new Map,l=new Map;function registerAttributeTypes(e){for(const{oid:n,names:t}of e){const e=(t[0]??n).toLowerCase();for(const r of[n,...t])u.set(r.toLowerCase(),e),l.set(r.toLowerCase(),t[0]??n)}}function knownAttributeName(e){return l.get(e.toLowerCase().replace(/^oid\./,""))}function rdnTypes(e){return splitRdn(parseDn(e)[0]??"").map(e=>{const n=e.indexOf("=");return-1===n?"":canonicalType(e.slice(0,n).trim())})}function canonicalType(e){const n=e.toLowerCase().replace(/^oid\./,"");return u.get(n)??n}function splitRdn(e){const n=[];let t="",r=!1,o=!1;for(const i of e){if(r)r=!1;else if("\\"===i)r=!0;else if('"'===i&&(o||opensValue(t)))o=!o;else if("+"===i&&!o){n.push(t),t="";continue}t+=i}return n.push(t),n}function normalizeDn(e){return normalizedRdns(e).join(",")}function normalizedRdns(e){return parseDn(e).map(e=>splitRdn(e).map(e=>{const n=e.indexOf("=");return-1===n?e.trim().toLowerCase():`${canonicalType(e.slice(0,n).trim())}=${function(e){const n=trimUnescaped(e);if(/^#(?:[0-9a-fA-F]{2})+$/.test(n))return n;let t=0;for(let e=n.length-2;e>0&&"\\"===n[e];e--)t++;e=n.length>=2&&n.startsWith('"')&&n.endsWith('"')&&t%2==0?n.slice(1,-1):n;const r=[];let o=0;const plain=e=>{for(const n of e)r.push(n)};for(const n of e.matchAll(c)){plain(e.slice(o,n.index)),o=n.index+n[0].length;const[,t,i]=n;if(void 0!==i){r.push(i);continue}const s=t.split("\\").filter(Boolean).map(e=>parseInt(e,16));for(const e of utf8Chars(s))"number"==typeof e?r.push(`\\${hexByte(e)}`):plain(e)}o<e.length&&plain(e.slice(o));const kept=e=>3===e.length&&"\\"===e[0],i=[];let s="";for(const e of r)kept(e)?(i.push(...s.toLowerCase().normalize("NFKC"),e),s=""):s+=e;i.push(...s.toLowerCase().normalize("NFKC"));const a=i.filter((e,n)=>" "!==e||n>0&&" "!==i[n-1]);let u=0,l=a.length;for(;u<l&&" "===a[u];)u++;for(;l>u&&" "===a[l-1];)l--;let f="";for(let e=u;e<l;e++){const n=a[e];kept(n)?f+=n:n.charCodeAt(0)<32||127===n.charCodeAt(0)?f+=`\\${hexByte(n.charCodeAt(0))}`:',+"\\<>;='.includes(n)||e===u&&"#"===n?f+=`\\${n}`:f+=n}return f}(e.slice(n+1)).toLowerCase()}`}).sort().join("+")).filter(e=>e.length>0)}function isDummyMemberDn(e,n){if(!n||"string"!=typeof e)return!1;if(e===n)return!0;try{return normalizeDn(e)===normalizeDn(n)}catch{return!1}}function organizationLink(e){for(const n of Array.isArray(e)?e:[e]){if(null==n)continue;const e=String(n).trim();if(e.length>0)return e}}function isDnInBranch(e,n){const t=normalizedRdns(n);if(0===t.length)return!1;const r=normalizedRdns(e);if(r.length<t.length)return!1;return r.slice(r.length-t.length).every((e,n)=>e===t[n])}function movedToTrash(e,n,t){return!!e&&isDnInBranch(t,e)&&!isDnInBranch(n,e)}registerAttributeTypes([{oid:"2.5.4.0",names:["objectClass"]},{oid:"2.5.4.3",names:["cn","commonName"]},{oid:"2.5.4.4",names:["sn","surname"]},{oid:"2.5.4.5",names:["serialNumber"]},{oid:"2.5.4.6",names:["c","countryName"]},{oid:"2.5.4.7",names:["l","localityName"]},{oid:"2.5.4.8",names:["st","stateOrProvinceName"]},{oid:"2.5.4.9",names:["street","streetAddress"]},{oid:"2.5.4.10",names:["o","organizationName"]},{oid:"2.5.4.11",names:["ou","organizationalUnitName"]},{oid:"2.5.4.12",names:["title"]},{oid:"2.5.4.42",names:["givenName","gn"]},{oid:"2.5.4.43",names:["initials"]},{oid:"2.5.4.46",names:["dnQualifier"]},{oid:"2.5.4.65",names:["pseudonym"]},{oid:"0.9.2342.19200300.100.1.1",names:["uid","userid"]},{oid:"0.9.2342.19200300.100.1.3",names:["mail","rfc822Mailbox"]},{oid:"0.9.2342.19200300.100.1.25",names:["dc","domainComponent"]},{oid:"2.16.840.1.113730.3.1.241",names:["displayName"]},{oid:"2.16.840.1.113730.3.1.3",names:["employeeNumber"]},{oid:"1.3.6.1.1.1.1.0",names:["uidNumber"]},{oid:"1.3.6.1.1.1.1.1",names:["gidNumber"]}]);const asyncHandler=e=>(n,t,r)=>{Promise.resolve(e(n,t,r)).catch(r)};export{asyncHandler,escapeDnValue,escapeLdapFilter,escapeRegex,fillPattern,getCompiledRegex,getParentDn,getRdn,hookOwner,isAuthzRefusal,isChildOf,isDnInBranch,isDnSyntax,isDummyMemberDn,knownAttributeName,launchHooks,launchHooksChained,movedToTrash,normalizeDn,organizationLink,parseDn,rdnTypes,rdnValue,recordHookOwner,registerAttributeTypes,runAsHookOwner,substringSearchFilter,transformSchemas,unescapeDnValue,validateDnValue};
|
package/dist/logger/winston.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"winston";const
|
|
1
|
+
import{inspect as e}from"util";import r from"winston";import{currentLogContext as o}from"../lib/requestContext.js";const t={levels:{error:0,warn:1,notice:2,info:3,debug:4}},n=["console","file"],l=r.format(e=>{const r=o();return r?(r.requestId&&(e.requestId=r.requestId),!r.plugin||void 0!==e.plugin&&e.plugin!==r.plugin||(e.plugin=r.plugin,e.op??(e.op=r.op)),e):e}),buildLogger=o=>{const i=o.logger||"console";if(!n.includes(i))throw new Error(`Unknown logger "${String(i)}": --logger takes ${n.join(" or ")}`);if("file"===i&&!o.log_file)throw new Error("--logger file needs a file: set --log-file (or DM_LOG_FILE)");return r.createLogger({levels:t.levels,level:o.log_level,format:r.format.combine(r.format.timestamp(),l(),r.format.printf(({timestamp:r,level:o,message:t,requestId:n,plugin:l,op:i,error:s})=>`${r} [${o}]${"string"==typeof n?` [${n}]`:""}${"string"==typeof l?` [${l}${"string"==typeof i?` ${i}`:""}]`:""}: ${t}${void 0===s?"":` (${"string"==typeof s?s:s instanceof Error?String(s):e(s,{breakLength:1/0})})`}`)),transports:["console"===i?new r.transports.Console({stderrLevels:["error","warn"],format:r.format.json()}):new r.transports.File({filename:o.log_file})]})};export{buildLogger};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"
|
|
1
|
+
import e from"../../abstract/plugin.js";class CrowdSec extends e{constructor(...e){if(super(...e),this.name="crowdsec",this.roles=["protect"],this.cache=new Map,this.apiUrl=this.config.crowdsec_url||"http://localhost:8080/v1/decisions",this.apiKey=this.config.crowdsec_api_key,this.cacheTtl=this.config.crowdsec_cache_ttl||60,!this.apiKey)throw new Error("CrowdSec plugin requires crowdsec_api_key configuration");this.logger.info(`CrowdSec integration enabled with API at ${this.apiUrl} (cache TTL: ${this.cacheTtl}s)`)}api(e){e.use(async(e,r,t)=>{const s=this.getClientIp(e);try{if(await this.checkIpBanned(s))return this.logger.warn(`Blocked request from CrowdSec-banned IP: ${s}`),r.status(403).json({error:"Access denied",reason:"IP address is banned by security policies"});t()}catch(e){this.logger.error(`CrowdSec API error for IP ${s}: ${e instanceof Error?e.message:String(e)}`),t()}})}async checkIpBanned(e){const r=this.cache.get(e),t=Date.now();if(r&&t<r.expiresAt)return this.logger.debug(`CrowdSec cache hit for IP ${e}: ${r.isBanned}`),r.isBanned;const s=`${this.apiUrl}?ip=${encodeURIComponent(e)}`;this.logger.debug(`Querying CrowdSec API: ${s}`);const i=await this.fetch(s,{headers:{"X-Api-Key":this.apiKey}});if(!i.ok)throw new Error(`CrowdSec API returned status ${i.status}: ${i.statusText}`);let o;try{const e=await i.text();o="null"===e||""===e?null:JSON.parse(e)}catch(e){throw this.logger.error(`Failed to parse CrowdSec API response: ${e instanceof Error?e.message:String(e)}`),new Error("Invalid JSON response from CrowdSec API")}let c=!1;return null!==o&&Array.isArray(o)&&(c=o.some(e=>"ban"===e.type)),this.cache.set(e,{isBanned:c,expiresAt:t+1e3*this.cacheTtl}),this.logger.debug(`CrowdSec decision for IP ${e}: ${c?"BANNED":"ALLOWED"}`),c}getClientIp(e){const r=e.headers["x-forwarded-for"];if(r){return(Array.isArray(r)?r[0]:r).split(",")[0].trim()}return e.socket.remoteAddress||"unknown"}}export{CrowdSec as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"crypto";import o from"express-openid-connect";import s from"../../lib/auth/base.js";import{launchHooksChained as t}from"../../lib/utils.js";import{serverError as
|
|
1
|
+
import{randomUUID as e}from"crypto";import o from"express-openid-connect";import s from"../../lib/auth/base.js";import{launchHooksChained as t,runAsHookOwner as i}from"../../lib/utils.js";import{serverError as n,unauthorized as r}from"../../lib/expressFormatedResponses.js";const{auth:a,requiresAuth:c}=o,d=["/login","/logout","/callback","/backchannel-logout"],h=/^end_session_endpoint must be configured/,u=/^\/logout\/?$/i,l="dmSession",sessionClaims=e=>{const{oidc:o,appSession:s}=e,t=o?.idTokenClaims;if(!t)return;const i=s?.[l];return"string"==typeof i?{...t,session:i}:t},subjectOf=e=>{try{const o=JSON.parse(Buffer.from(String(e).split(".")[1],"base64url").toString());return"string"==typeof o.sub?o.sub:void 0}catch{return}},walkSubscribers=async(e,o)=>{let s;for(const t of e??[])if(t)try{await i(t,()=>t(o))}catch(e){s??(s=e instanceof Error?e:new Error(String(e)))}if(s)throw s};class OpenIDConnect extends s{constructor(e){super(e),this.name="openidconnect",this.configApiKey="openidconnect",this.roles=["auth","configurable"],this.warnedNoEndSession=!1,this.warnedNoRecord=!1,this.warnedUnnamed=!1;for(const e of["oidc_server","oidc_client_id","oidc_client_secret","base_url"])if(!this.config[e])throw new Error(`Missing config parameter ${e}`)}buildConfig(){return{authRequired:!1,issuerBaseURL:this.config.oidc_server,clientID:this.config.oidc_client_id,secret:this.config.oidc_client_secret,baseURL:this.config.base_url,clientSecret:this.config.oidc_client_secret,authorizationParams:{response_type:"code",scope:"openid profile email"},idpLogout:!0,routes:{logout:!1},afterCallback:async(e,o,s)=>({...s,[l]:await this.sessionId(e,subjectOf(s.id_token))}),backchannelLogout:{onLogoutToken:async e=>{this.server.hooks.oidclogouttoken?await walkSubscribers(this.server.hooks.oidclogouttoken,e):this.logger.warn("openidconnect: a logout token arrived but no Back-Channel Logout plugin is loaded, so nothing records it")},onLogin:async e=>{if(!this.server.hooks.oidclogin)return;const o=e.oidc?.idTokenClaims;if(o)try{await walkSubscribers(this.server.hooks.oidclogin,o)}catch(o){const s=e.appSession;if(s)for(const e of Object.keys(s))delete s[e];throw o}},isLoggedOut:e=>this.loggedOut(e)}}}identitySource(){const e=this.config.oidc_username_claim||"sub";return`req.user: the OIDC sub, an opaque provider identifier; req.userName: the "${e}" claim`+("sub"===e?" — the same value, until --oidc-username-claim names another":"")}getConfigApiData(){return{enabled:!0,endpoints:{logout:"/logout"}}}get pathPrefixes(){const e=super.pathPrefixes;return 0===e.length?e:[...e,...d]}api(e){this.router=a(this.buildConfig()),super.api(e)}authMethod(e,o,s){if(!this.router)return n(o,new Error(`${this.name}: api() has not built the router`));this.router(e,o,t=>{if(t&&u.test(e.path)&&this.noEndSession(t))return o.redirect(this.config.base_url);if(t)return n(o,t);if(("GET"===e.method||"HEAD"===e.method)&&u.test(e.path))return void this.endHere(e).then(()=>o.oidc.logout({logoutParams:{post_logout_redirect_uri:void 0}}));const guard=()=>{c()(e,o,t=>{if(t)return r(o);const i=e.oidc.user,n=this.config.oidc_username_claim||"sub",a=i[n];"sub"!==n&&"string"!=typeof a&&this.logger.warn(`${this.name}: no "${n}" claim on this session, so req.userName falls back to the sub. Check --oidc-username-claim against the scopes the provider is asked for`),this.publishIdentity(e,String(i.sub),"string"==typeof a?a:String(i.sub)),s()})},i=this.renewExpired(e);i?i.then(guard):guard()})}renewExpired(e){const o=e.oidc,s=o.accessToken;if(!s?.isExpired())return;const end=()=>{e.appSession=void 0};if(o.refreshToken)return s.refresh().then(()=>{},e=>{this.logger.info(`${this.name}: the provider refused to renew an access token, so the session ends: ${String(e)}`),end()});end()}async loggedOut(e){if(!this.server.hooks.oidcsessionvalid)return!1;const o=sessionClaims(e),[,s]=await t(this.server.hooks.oidcsessionvalid,[o,!0]);return!s}async sessionId(o,s){const{oidc:t,appSession:i}=o,n=i?.[l];return"string"==typeof n&&void 0!==s&&t?.isAuthenticated()&&t.idTokenClaims?.sub===s&&!await this.loggedOut(o).catch(()=>!0)?n:e()}async endHere(e){if(!e.oidc?.isAuthenticated())return;const o=sessionClaims(e);if(!o)return;const{iss:s,sid:t,session:i}=o,n=i?{iss:s,session:i}:t?{iss:s,sid:t}:void 0;if(n)if(this.server.hooks.oidclogouttoken)try{await walkSubscribers(this.server.hooks.oidclogouttoken,n)}catch(e){this.logger.error(`${this.name}: /logout could not record the session it ends, so a copy of its cookie stays valid until its tokens expire: ${String(e)}`)}else this.warnedNoRecord||(this.warnedNoRecord=!0,this.logger.warn(`${this.name}: no Back-Channel Logout plugin is loaded, so /logout drops the browser's cookie and nothing else: a copy of it stays valid until its tokens expire. Load core/bcl to end the session here as well`));else this.warnedUnnamed||(this.warnedUnnamed=!0,this.logger.warn(`${this.name}: /logout ended a session nothing names — one established before this version, from a provider that sends no sid — so a copy of its cookie stays valid until its tokens expire`))}noEndSession(e){return!!(e instanceof Error&&h.test(e.message))&&(this.warnedNoEndSession||(this.warnedNoEndSession=!0,this.logger.warn(`${this.name}: the provider publishes no end_session_endpoint, so /logout ends the session here only, and the provider may log the caller back in`)),!0)}}export{OpenIDConnect as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"../../abstract/plugin.js";import{asyncHandler as s}from"../../lib/utils.js";class HelloWorld extends o{constructor(){super(...arguments),this.name="hello",this.roles=["demo"]}api(o){o.get(`${this.config.api_prefix}/hello`,s(async(o,s)=>{const
|
|
1
|
+
import o from"../../abstract/plugin.js";import{asyncHandler as s,runAsHookOwner as e}from"../../lib/utils.js";class HelloWorld extends o{constructor(){super(...arguments),this.name="hello",this.roles=["demo"]}api(o){o.get(`${this.config.api_prefix}/hello`,s(async(o,s)=>{const l={message:"Hello",hookResults:[]};if(this.server.hooks&&this.server.hooks.hello)for(const o of this.server.hooks.hello){const s=o;l.hookResults.push(await e(o,()=>s()))}s.json(l)}))}}export{HelloWorld as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"multer";import{parse as e}from"csv-parse/sync";import r from"../../abstract/plugin.js";import{badRequest as i,serverError as s}from"../../lib/expressFormatedResponses.js";import{errorBody as o,AUTHZ_REFUSED as a,HttpError as n}from"../../lib/errors.js";import{loadSchemaFile as c}from"../../lib/schemaFile.js";import{isAuthzRefusal as l,validateDnValue as
|
|
1
|
+
import t from"multer";import{parse as e}from"csv-parse/sync";import r from"../../abstract/plugin.js";import{badRequest as i,serverError as s}from"../../lib/expressFormatedResponses.js";import{errorBody as o,AUTHZ_REFUSED as a,HttpError as n}from"../../lib/errors.js";import{loadSchemaFile as c}from"../../lib/schemaFile.js";import{isAuthzRefusal as l,validateDnValue as d,escapeDnValue as p}from"../../lib/utils.js";const u=/^([A-Za-z][A-Za-z0-9-]*|\d+(\.\d+)+)(;[A-Za-z0-9-]+)*$/;class LdapBulkImport extends r{constructor(e){super(e),this.name="ldapBulkImport",this.roles=["configurable"],this.resources=new Map;const r=parseInt(this.config.bulk_import_max_file_size,10)||10485760;this.upload=t({storage:t.memoryStorage(),limits:{fileSize:r},fileFilter:(t,e,r)=>{"text/csv"===e.mimetype||e.originalname.endsWith(".csv")?r(null,!0):r(new Error("Only CSV files are allowed"))}});const i=this.config.bulk_import_schemas;if(!i)return void this.logger.warn("No bulk import schemas configured");const s=i.split(",").map(t=>t.trim());for(const t of s){const[e,r]=t.split(":").map(t=>t.trim());if(e&&r)try{const t=c(r,{config:this.config});this.resources.set(e,{name:e,schema:t,base:t.base||this.config.ldap_base,mainAttribute:t.mainAttribute||"cn"}),this.logger.info(`Loaded bulk import resource: ${e} from ${r}`)}catch(t){this.logger.error(`Failed to load schema for ${e}: ${t.message}`)}else this.logger.warn(`Invalid schema entry: ${t}`)}}api(t){for(const[e,r]of this.resources)t.get(`${this.config.api_prefix}/v1/ldap/bulk-import/${e}/template.csv`,(t,e)=>this.getTemplate(t,e,r)),t.post(`${this.config.api_prefix}/v1/ldap/bulk-import/${e}`,this.upload.single("file"),async(t,e)=>this.bulkImport(t,e,r))}getTemplate(t,e,r){const i=this.getEditableAttributes(r.schema);i.push("organizationDn"),e.setHeader("Content-Type","text/csv; charset=utf-8"),e.setHeader("Content-Disposition",`attachment; filename="${r.name}-template.csv"`),e.send(i.join(",")+"\n")}async bulkImport(t,r,c){if(!t.file)return i(r,"No file uploaded");const d="true"===t.body.dryRun||!0===t.body.dryRun,p="true"===t.body.updateExisting||!0===t.body.updateExisting,u="false"!==t.body.continueOnError&&!1!==t.body.continueOnError,h=Date.now(),f={success:!0,total:0,created:0,updated:0,skipped:0,failed:0,errors:[],details:{duration:"",linesProcessed:0}};try{const i=t.file.buffer.toString("utf-8"),s=e(i,{columns:!0,skip_empty_lines:!0,trim:!0});f.total=s.length;for(let e=0;e<s.length;e++){const r=e+2,i=s[e];try{const{dn:e,entry:r,orgDn:s}=this.buildRecord(i,c);await this.authorizeRow(e,r,t),await this.completeRecord(r,s,c);const o=await this.entryExists(e);if(o&&!p){f.skipped++;continue}if(d){o||await this.server.ldap.authorize("ldapaddrequest",[e,r,t]),o&&await this.server.ldap.authorize("ldapmodifyrequest",[e,{replace:r},this.opNumber(),t]),o?f.updated++:f.created++;continue}o&&p?(await this.server.ldap.modify(e,{replace:r},t),f.updated++):(await this.server.ldap.add(e,r,t),f.created++)}catch(t){if(f.failed++,f.errors.push({line:r,identifier:i[c.mainAttribute],...l(t)?o(t,a):{error:t.message,...t instanceof n?t.refusal:void 0}}),!u)throw t}}f.details.linesProcessed=s.length,f.details.duration=`${((Date.now()-h)/1e3).toFixed(1)}s`,r.json(f)}catch(t){return s(r,t)}}async authorizeRow(t,e,r){try{await this.server.ldap.authorize("ldapaddrequest",[t,e,r])}catch(i){if(!l(i))throw i;try{await this.server.ldap.authorize("ldapmodifyrequest",[t,{replace:e},this.opNumber(),r])}catch{throw i}}}buildRecord(t,e){const r={},i=e.schema,s=t.organizationDn;delete t.organizationDn;const o=new Set;for(const[t,e]of Object.entries(i.properties||{}))if(!0===e.fixed){const i=e.default||e.const;void 0!==i&&(r[t]=i,o.add(t.toLowerCase()))}for(const[e,i]of Object.entries(t))if(i&&""!==i.trim()){if(!u.test(e))throw new Error(`Invalid column name: ${e}`);if(o.has(e.split(";")[0].toLowerCase()))throw new Error(`Attribute "${e}" is fixed and cannot be imported`);r[e]=i.includes(";")?i.split(";").map(t=>t.trim()):i}if(s){const t=this.findAttributeByRole(i,"organizationLink");t&&(r[t]=s)}const a=e.mainAttribute,n=r[a];if(!n)throw new Error(`Missing main attribute: ${a}`);const c=Array.isArray(n)?String(n[0]):String(n);d(c,a);return{dn:`${a}=${p(c)},${e.base}`,entry:r,orgDn:s}}async completeRecord(t,e,r){const i=r.schema;if(e){const r=this.findAttributeByRole(i,"organizationPath");if(r){const i=(await this.fetchOrganization(e))[r];t[r]=Array.isArray(i)?i[0]:i}}for(const[e,r]of Object.entries(i.properties||{}))if(!0===r.required&&!t[e])throw new Error(`Missing required attribute: ${e}`)}getEditableAttributes(t){const e=[];for(const[r,i]of Object.entries(t.properties||{}))!0!==i.fixed&&(i.role?.includes("organizationLink")||i.role?.includes("organizationPath")||e.push(r));return e}findAttributeByRole(t,e){for(const[r,i]of Object.entries(t.properties||{}))if(i.role?.includes(e))return r;return null}async fetchOrganization(t){const e=await this.server.ldap.system.search({paged:!1,scope:"base"},t);if(0===e.searchEntries.length)throw new Error(`Organization not found: ${t}`);return e.searchEntries[0]}async entryExists(t){try{return(await this.server.ldap.system.search({paged:!1,scope:"base"},t)).searchEntries.length>0}catch(t){return!1}}getConfigApiData(){const t=this.config.api_prefix||"/api",e=[];return this.resources.forEach((r,i)=>{e.push({name:i,mainAttribute:r.mainAttribute,base:r.base,maxFileSize:parseInt(this.config.bulk_import_max_file_size,10)||10485760,batchSize:parseInt(this.config.bulk_import_batch_size,10)||100,endpoints:{template:`${t}/v1/ldap/bulk-import/${i}/template.csv`,import:`${t}/v1/ldap/bulk-import/${i}`}})}),{enabled:!0,resources:e}}}export{LdapBulkImport as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"../../abstract/plugin.js";import{roleAttribute as e}from"../../config/schema.js";import{isDnInBranch as a,parseDn as r,normalizeDn as n,getParentDn as i,rdnValue as s,escapeLdapFilter as o}from"../../lib/utils.js";class LdapDepartmentSync extends t{constructor(t){super(t),this.name="ldapDepartmentSync",this.roles=["consistency"],this.hooks={ldaprenamedone:async([t,e])=>{if(/^ou=/.test(t)){this.logger.info(`Organization renamed from ${t} to ${e}, synchronizing linked resources...`);try{const a=this.config.ldap_top_organization.replace(/^ou=[^,]+,/,"");await this.updateOrganizationPaths(e);for(const r of this.linkedAttributes())await this.updateLinkedResources(t,e,a,r),await this.updateDescendantReferences(t,e,a,r)}catch(t){this.logger.error(`Error synchronizing department links after rename: ${t}`)}}}},this.linkAttr=this.config.ldap_organization_link_attribute||"twakeDepartmentLink",this.pathAttr=this.config.ldap_organization_path_attribute||"twakeDepartmentPath"}organizationPathAttribute(){const t=this.server.loadedPlugins.ldapOrganizations;return e(t?.schema,"organizationPath")||this.pathAttr}linkedAttributes(){const t=[],a=this.server.loadedPlugins.ldapFlatGeneric;for(const e of a?.instances||[])t.push(e.schema);const r=this.server.loadedPlugins.ldapGroups;t.push(r?.schema);const n=[];for(const a of t){const t=e(a,"organizationLink");t&&n.push({link:t,path:e(a,"organizationPath")||this.pathAttr})}n.push({link:this.linkAttr,path:this.pathAttr});const i=new Set;return n.filter(({link:t,path:e})=>{const a=`${t.toLowerCase()} ${e.toLowerCase()}`;return!i.has(a)&&(i.add(a),!0)})}async updateOrganizationPaths(t){const e=this.organizationPathAttribute(),o=this.config.ldap_top_organization;if(!o||!a(t,o))return;const h=this.config.ldap_organization_path_separator||" / ",c=await this.server.ldap.system.search({paged:!0,scope:"sub",filter:`(${e}=*)`,attributes:[e]},t),d=[];for await(const t of c)for(const a of t.searchEntries){const t=String(a.dn);if(!/^ou=/i.test(t))continue;const r=a[e];d.push({dn:t,path:String(Array.isArray(r)?r[0]:r)})}d.sort((t,e)=>r(t.dn).length-r(e.dn).length);const l=n(o),g=new Map;let p=0;for(const{dn:t,path:a}of d){const r=i(t),o=n(r);let c;if(o!==l&&(c=g.get(o)??await this.readPath(r)??void 0,void 0===c)){this.logger.warn(`Organization ${r} has no ${e}: the path of ${t} is left as it is`);continue}const d=s(t),u=c?`${c}${h}${d}`:d;if(g.set(n(t),u),u!==a)try{await this.server.ldap.system.modify(t,{replace:{[e]:u}}),p++}catch(e){this.logger.error(`Failed to update the path of ${t} after organization rename: ${e}`)}}this.logger.info(`Updated the path of ${p} organizations below ${t}`)}async readPath(t){const e=this.organizationPathAttribute();try{const a=await this.server.ldap.system.search({paged:!1,scope:"base",attributes:[e]},t),r=a.searchEntries[0]?.[e];return void 0===r?null:String(Array.isArray(r)?r[0]:r)}catch{return null}}async updateLinkedResources(t,e,a,r){const n=`(${r.link}=${o(t)})`;this.logger.debug(`Searching for resources directly linked to ${t}: ${n}`);const i=await this.server.ldap.system.search({paged:!0,filter:n,attributes:[r.link,r.path]},a);let s=0;for await(const t of i)for(const a of t.searchEntries){const t=String(a.dn);try{const a=await this.getDepartmentPath(e);await this.server.ldap.system.modify(t,{replace:{[r.link]:e,[r.path]:a}}),s++,this.logger.debug(`Updated ${t}: ${r.link}=${e}, ${r.path}=${a}`)}catch(e){this.logger.error(`Failed to update ${t} after organization rename: ${e}`)}}this.logger.info(`Updated ${s} resources directly linked to the renamed organization`)}async updateDescendantReferences(t,e,a,r){const n=`(${r.link}=*)`;this.logger.debug(`Searching for resources linked to descendants of ${t}: ${n}`);const i=await this.server.ldap.system.search({paged:!0,filter:n,attributes:[r.link,r.path]},a);let s=0;for await(const a of i)for(const n of a.searchEntries){const a=String(n.dn),i=n[r.link],o=Array.isArray(i)?String(i[0]):String(i);if(o!==t&&o.endsWith(`,${t}`))try{const n=o.replace(`,${t}
|
|
1
|
+
import t from"../../abstract/plugin.js";import{roleAttribute as e}from"../../config/schema.js";import{isDnInBranch as a,parseDn as r,normalizeDn as n,getParentDn as i,rdnValue as s,escapeLdapFilter as o}from"../../lib/utils.js";class LdapDepartmentSync extends t{constructor(t){super(t),this.name="ldapDepartmentSync",this.roles=["consistency"],this.hooks={ldaprenamedone:async([t,e])=>{if(/^ou=/.test(t)){this.logger.info(`Organization renamed from ${t} to ${e}, synchronizing linked resources...`);try{const a=this.config.ldap_top_organization.replace(/^ou=[^,]+,/,"");await this.updateOrganizationPaths(e);for(const r of this.linkedAttributes())await this.updateLinkedResources(t,e,a,r),await this.updateDescendantReferences(t,e,a,r)}catch(t){this.logger.error(`Error synchronizing department links after rename: ${t}`)}}}},this.linkAttr=this.config.ldap_organization_link_attribute||"twakeDepartmentLink",this.pathAttr=this.config.ldap_organization_path_attribute||"twakeDepartmentPath"}organizationPathAttribute(){const t=this.server.loadedPlugins.ldapOrganizations;return e(t?.schema,"organizationPath")||this.pathAttr}linkedAttributes(){const t=[],a=this.server.loadedPlugins.ldapFlatGeneric;for(const e of a?.instances||[])t.push(e.schema);const r=this.server.loadedPlugins.ldapGroups;t.push(r?.schema);const n=[];for(const a of t){const t=e(a,"organizationLink");t&&n.push({link:t,path:e(a,"organizationPath")||this.pathAttr})}n.push({link:this.linkAttr,path:this.pathAttr});const i=new Set;return n.filter(({link:t,path:e})=>{const a=`${t.toLowerCase()} ${e.toLowerCase()}`;return!i.has(a)&&(i.add(a),!0)})}async updateOrganizationPaths(t){const e=this.organizationPathAttribute(),o=this.config.ldap_top_organization;if(!o||!a(t,o))return;const h=this.config.ldap_organization_path_separator||" / ",c=await this.server.ldap.system.search({paged:!0,scope:"sub",filter:`(${e}=*)`,attributes:[e]},t),d=[];for await(const t of c)for(const a of t.searchEntries){const t=String(a.dn);if(!/^ou=/i.test(t))continue;const r=a[e];d.push({dn:t,path:String(Array.isArray(r)?r[0]:r)})}d.sort((t,e)=>r(t.dn).length-r(e.dn).length);const l=n(o),g=new Map;let p=0;for(const{dn:t,path:a}of d){const r=i(t),o=n(r);let c;if(o!==l&&(c=g.get(o)??await this.readPath(r)??void 0,void 0===c)){this.logger.warn(`Organization ${r} has no ${e}: the path of ${t} is left as it is`);continue}const d=s(t),u=c?`${c}${h}${d}`:d;if(g.set(n(t),u),u!==a)try{await this.server.ldap.system.modify(t,{replace:{[e]:u}}),p++}catch(e){this.logger.error(`Failed to update the path of ${t} after organization rename: ${e}`)}}this.logger.info(`Updated the path of ${p} organizations below ${t}`)}async readPath(t){const e=this.organizationPathAttribute();try{const a=await this.server.ldap.system.search({paged:!1,scope:"base",attributes:[e]},t),r=a.searchEntries[0]?.[e];return void 0===r?null:String(Array.isArray(r)?r[0]:r)}catch{return null}}async updateLinkedResources(t,e,a,r){const n=`(${r.link}=${o(t)})`;this.logger.debug(`Searching for resources directly linked to ${t}: ${n}`);const i=await this.server.ldap.system.search({paged:!0,filter:n,attributes:[r.link,r.path]},a);let s=0;for await(const t of i)for(const a of t.searchEntries){const t=String(a.dn);try{const a=await this.getDepartmentPath(e);await this.server.ldap.system.modify(t,{replace:{[r.link]:e,[r.path]:a}}),s++,this.logger.debug(`Updated ${t}: ${r.link}=${e}, ${r.path}=${a}`)}catch(e){this.logger.error(`Failed to update ${t} after organization rename: ${e}`)}}this.logger.info(`Updated ${s} resources directly linked to the renamed organization`)}async updateDescendantReferences(t,e,a,r){const n=`(${r.link}=*)`;this.logger.debug(`Searching for resources linked to descendants of ${t}: ${n}`);const i=await this.server.ldap.system.search({paged:!0,filter:n,attributes:[r.link,r.path]},a);let s=0;for await(const a of i)for(const n of a.searchEntries){const a=String(n.dn),i=n[r.link],o=Array.isArray(i)?String(i[0]):String(i);if(o!==t&&o.endsWith(`,${t}`))try{const n=o.replace(`,${t}`,()=>`,${e}`),i=await this.getDepartmentPath(n);await this.server.ldap.system.modify(a,{replace:{[r.link]:n,[r.path]:i}}),s++,this.logger.debug(`Updated descendant link ${a}: ${r.link}=${n}, ${r.path}=${i}`)}catch(t){this.logger.error(`Failed to update descendant reference ${a}: ${t}`)}}this.logger.info(`Updated ${s} resources linked to descendants of the renamed organization`)}async getDepartmentPath(t){const e=this.organizationPathAttribute();try{const a=await this.server.ldap.system.search({paged:!1,scope:"base",attributes:[e,"ou","o"]},t);if(!a.searchEntries||0===a.searchEntries.length)throw new Error(`Organization ${t} not found`);const r=a.searchEntries[0];if(r[e]){const t=r[e];return Array.isArray(t)?String(t[0]):String(t)}const n=r.ou||r.o;if(n){return`/${Array.isArray(n)?String(n[0]):String(n)}`}return this.logger.warn(`Organization ${t} has no ${e} attribute, using DN`),t}catch(e){throw new Error(`Failed to fetch organization ${t}: ${e}`)}}}export{LdapDepartmentSync as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"../../abstract/plugin.js";import
|
|
1
|
+
import e from"../../abstract/plugin.js";import t from"../../abstract/ldapFlat.js";import{loadSchemaFile as a}from"../../lib/schemaFile.js";import{staticSchemaUrl as l}from"../../lib/staticFiles.js";const i=[{plugin:"ldapGroups",modules:["ldap/groups"],collection:"groups"},{plugin:"ldapOrganizations",modules:["ldap/organizations","ldap/organization"],collection:"organizations"},{plugin:"ldapRaw",modules:["ldap/raw"],collection:"raw"},{plugin:"ldapBulkImport",modules:["ldap/bulkImport"],collection:"bulk-import"}];function pluginModule(e){return e.split(":")[0].replace(/\.[cm]?js$/,"").split("/").slice(-2).join("/")}class LdapFlatInstance extends t{constructor(e,t){super(e,t),this.name="ldapFlatInstance",this.roles=["api"],this.dependencies={departmentSync:"core/ldap/departmentSync"}}}class LdapFlatGeneric extends e{constructor(e){super(e),this.name="ldapFlatGeneric",this.roles=["configurable"],this.instances=[],this.schemaPaths=[];const t=this.config.ldap_flat_schema||[],l=new Map,n=new Map;if(0===t.length)return void this.logger.warn("No schemas provided for ldapFlatGeneric plugin");const s=(this.config.plugin||[]).map(pluginModule),r=new Map;for(const{plugin:e,modules:t,collection:a}of i)(this.server.loadedPlugins[e]||t.some(e=>s.includes(e)))&&r.set(a,`plugin ${e}`);t.forEach(t=>{try{const i=a(t,{config:this.config});if(!i.entity)throw new Error(`Schema ${t} is missing "entity" metadata section`);const s=["name","mainAttribute","objectClass","singularName","pluralName","base"];for(const e of s)if(!i.entity[e])throw new Error(`Schema ${t} is missing entity.${e}`);const o=l.get(i.entity.name);if(o)throw new Error(`entity "${i.entity.name}" is already declared by ${o}`);const p=n.get(i.entity.pluralName)||r.get(i.entity.pluralName);if(p)throw new Error(`entity "${i.entity.name}" wants the URL of "${i.entity.pluralName}", already served by ${p}`);let c=i.entity.base;c=c.replace(/\{([^}]+)\}/g,(e,t)=>{const a=t,l=this.config[a];return"string"==typeof l?l:e});const u=new LdapFlatInstance(e,{base:c,mainAttribute:i.entity.mainAttribute,objectClass:i.entity.objectClass,defaultAttributes:i.entity.defaultAttributes||{},schemaPath:t,singularName:i.entity.singularName,pluralName:i.entity.pluralName,hookPrefix:`ldap${i.entity.name}`});u.label=i.entity.label,u.singularLabel=i.entity.singularLabel,u.valueLabels=i.entity.valueLabels,u.name=`ldapFlat:${i.entity.name}`,this.instances.push(u),this.schemaPaths.push(t),l.set(i.entity.name,t),n.set(i.entity.pluralName,t),this.logger.info(`Created ldapFlat instance for "${i.entity.name}" (${i.entity.pluralName})`)}catch(e){this.logger.error(`Failed to load schema ${t}: ${e}`)}})}api(e){this.instances.forEach(t=>{t.api(e)})}getConfigApiData(){const e=this.config.api_prefix||"/api";return{flatResources:this.instances.map((t,a)=>{const i=this.schemaPaths[a]?l(this.server,this.schemaPaths[a]):void 0;return{name:t.name.replace("ldapFlat:",""),singularName:t.singularName,pluralName:t.pluralName,label:t.label,singularLabel:t.singularLabel,valueLabels:t.valueLabels,mainAttribute:t.mainAttribute,objectClass:t.objectClass,base:t.base,schema:t.schema||{strict:!1,attributes:{}},schemaUrl:i,endpoints:{list:`${e}/v1/ldap/${t.pluralName}`,get:`${e}/v1/ldap/${t.pluralName}/:id`,create:`${e}/v1/ldap/${t.pluralName}`,update:`${e}/v1/ldap/${t.pluralName}/:id`,delete:`${e}/v1/ldap/${t.pluralName}/:id`,rename:`${e}/v1/ldap/${t.pluralName}/:id/rename`}}})}}}export{LdapFlatGeneric as default,i as ldapPluginCollections};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"../../abstract/plugin.js";import{assertModifyRequest as t}from"../../lib/ldapActions.js";import{wantJson as r,jsonBody as i,tryMethod as s,ok as a}from"../../lib/expressFormatedResponses.js";import{extractLdapCode as o}from"../../lib/ldapCodes.js";import{loadSchemaFileAsync as n,schemaUrl as h}from"../../lib/schemaFile.js";import{movedToTrash as d,asyncHandler as c,isDummyMemberDn as p,validateDnValue as u,escapeDnValue as m,launchHooksChained as l,launchHooks as f,escapeLdapFilter as g,organizationLink as w,isDnSyntax as b,normalizeDn as y,isDnInBranch as $,getRdn as v,isAuthzRefusal as G,substringSearchFilter as _}from"../../lib/utils.js";import{NotFoundError as A,BadRequestError as D,HttpError as q,ConflictError as C}from"../../lib/errors.js";import{assertClientMaySet as j,schemaAttribute as k,modifiedAttributeNames as E,toDirectoryEntry as M,invalidValueMessage as O,missingRequiredAttribute as x,toDirectoryChanges as N,checkDnValues as z,matchesPattern as F}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)})},ldaprenamedone:async([e,t])=>{d(this.config.trash_base,e,t)&&await this.deleteMemberFromAll(e).catch(e=>{this.logger.error("Failed to process a move to the trash 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;n(e,{config:this.config}).then(e=>{this.schema=this.adaptSchema(e),this.server.ldap.knowAttributeNames(Object.keys(this.schema.attributes)),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`,c(async(e,t)=>{if(!r(e,t))return;const i={};if(e.query.match){if("string"!=typeof e.query.match)throw new D("Invalid match query");if("string"==typeof e.query.attribute&&e.query.attribute)i.filter=_(e.query.match,e.query.attribute);else if(/=/.test(e.query.match)){if(!/^[\w*=()&|, .@'-]+$/.test(e.query.match))throw new D("Invalid match query: contains forbidden characters");i.filter=e.query.match}else{const t=g(e.query.match);i.filter=`(${this.cn}=${t})`}}e.query.attributes&&"string"==typeof e.query.attributes&&(i.attributes=e.query.attributes.split(","));const s=await this.listGroups({...i,req:e});return a(t,this.hideNeverReturn(s))})),e.get(`${this.config.api_prefix}/v1/ldap/groups/:cn`,c(async(e,t)=>this.apiGet(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups`,c(async(e,t)=>this.apiAdd(e,t,this.cn))),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn`,c(async(e,t)=>this.apiDelete(e,t))),e.put(`${this.config.api_prefix}/v1/ldap/groups/:cn`,c(async(e,t)=>this.apiModify(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/members`,c(async(e,t)=>{const r=decodeURIComponent(e.params.cn);if(!r)throw new D("cn is required");const a=this.routeGroupDn(r),o=i(e,t,"member");if(!o)return;const n=Array.isArray(o.member)?o.member:[o.member];if(n.some(e=>"string"!=typeof e))throw new D("member must be a string or string array");await this.judgedGroup(a,()=>this.ldap.authorize("ldapmodifyrequest",[a,{add:{member:n}},this.opNumber(),e])),await s(t,this.addMember.bind(this),r,o.member,e)})),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn/members/:member`,c(async(e,t)=>{if(!r(e,t))return;const i=decodeURIComponent(e.params.cn),a=decodeURIComponent(e.params.member);if(!i||!a)throw new D("cn and member are required");const o=this.routeGroupDn(i);await this.judgedGroup(o,()=>this.ldap.authorize("ldapmodifyrequest",[o,{delete:{member:[a]}},this.opNumber(),e])),await s(t,this.deleteMember.bind(this),i,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`,c(async(e,t)=>{if(!r(e,t))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new D("cn is required");const o=this.routeGroupDn(a),n=i(e,t,"targetOrgDn");if(!n)return;if("string"!=typeof n.targetOrgDn)throw new D("targetOrgDn must be a string");const h=this.config.ldap_organization_link_attribute;await this.judgedGroup(o,()=>this.ldap.authorize("ldapmodifyrequest",[o,{replace:{[h]:n.targetOrgDn}},this.opNumber(),e])),await s(t,this.moveGroup.bind(this),a,n.targetOrgDn,e)})),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/rename`,c(async(e,t)=>{if(!r(e,t))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new D("cn is required");const o=this.routeGroupDn(a),n=i(e,t,"newCn");if(!n)return;if("string"!=typeof n.newCn)throw new D("newCn must be a string");const h=/,/.test(n.newCn)?this.routeGroupDn(n.newCn):this.toGroupDn(n.newCn);await this.judgedGroup(o,()=>this.ldap.authorize("ldaprenamerequest",[o,h,e])),await s(t,this.renameGroup.bind(this),a,n.newCn,e)}))}isDummyMember(e){return p(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,t){if(!r(e,t))return;const i=decodeURIComponent(e.params.cn),s=this.routeGroupDn(i);try{const r=await this.ldap.search({paged:!1,scope:"base",filter:this.groupFilter()},s,e);if(0===r.searchEntries.length)throw new A("Group not found");t.json(this.hideNeverReturn(this.withoutDummyMember(r.searchEntries[0])))}catch(e){if(e.code&&32===e.code)throw new A("Group not found");if(34===o(e))throw new D(`${i} is not a valid DN`);throw e}}async apiAdd(e,t,...r){const a=i(e,t,...r);if(!a)return;await this.server.ldap.canonicalAttributes(a),j(this.schema,Object.keys(a),this.cn);const o=a[this.cn];"string"==typeof o&&(/,/.test(o)||new RegExp(`^${this.cn}=`,"i").test(o))&&this.routeGroupDn(/,/.test(o)?o:`${o},${this.base}`);const n=a.member?a.member:[],h=Object.fromEntries(Object.entries(a).filter(([e,t])=>e!==this.cn&&"member"!==e&&void 0!==t&&!(!0===k(this.schema,e)?.[1]?.fixed)));await s(t,this.addGroup.bind(this),o,n,h,e)}async apiDelete(e,t){if(!r(e,t))return;const i=decodeURIComponent(e.params.cn);if(!i)throw new D("cn is required");const a=this.routeGroupDn(i);await this.judgedGroup(a,()=>this.ldap.authorize("ldapdeleterequest",[a,e])),await s(t,this.deleteGroup.bind(this),i,e)}async apiModify(e,r){const a=i(e,r);if(!a)return;t(a);const o=decodeURIComponent(e.params.cn);if(!o)throw new D("cn is required");const n=this.routeGroupDn(o);await this.server.ldap.canonicalChanges(a),j(this.schema,E(a));const fixed=e=>!0===k(this.schema,e)?.[1]?.fixed,keep=e=>e&&Object.fromEntries(Object.entries(e).filter(([e])=>!fixed(e))),h={...a.add?{add:keep(a.add)}:{},...a.replace?{replace:keep(a.replace)}:{},...a.delete?{delete:Array.isArray(a.delete)?a.delete.filter(e=>!fixed(e)):keep(a.delete)}:{}};await this.judgedGroup(n,()=>this.ldap.authorize("ldapmodifyrequest",[n,h,this.opNumber(),e])),await s(r,this.modifyGroup.bind(this),n,h,e)}async addGroup(e,t=[],r={},i){let s;await this.server.ldap.canonicalAttributes(r),new RegExp(`^${this.cn}=`,"i").test(e)?(s=/,/.test(e)?e:`${e},${this.base}`,e=e.replace(new RegExp(`^${this.cn}=((?:\\\\.|[^,])+)(?:,.*)?$`,"i"),"$1")):(u(e,this.cn),s=`${this.cn}=${m(e)},${this.base}`);let a,o=this.candidateGroup(e,t,r);await this.ldap.authorize("ldapaddrequest",[s,{...o},i]),await this.validateMembers(s,t,i),await this.validateNewGroup(s,{objectClass:this.config.group_class,cn:e,member:t,...r}),M(this.schema,o),[s,o]=await l(this.registeredHooks.ldapgroupadd,[s,o]);try{a=await this.ldap.add(s,o,i)}catch(e){if(e instanceof q)throw e;throw new Error(`Failed to add group ${s}: ${e}`)}return f(this.registeredHooks.ldapgroupadddone,[s,o]),a}candidateGroup(e,t,r){const i=[...this.config.group_class];!(r.mail||r.twakeMailboxType||r.twakeDepartmentLink||r.twakeDepartmentPath)||i.includes("twakeGroup")||i.includes("twakeStaticGroup")||i.push("twakeGroup");const s={objectClass:i,...this.config.group_default_attributes,[this.cn]:e,member:[this.config.group_dummy_user],...r};return t.length&&s.member.push(...t),s}async modifyGroup(e,t,r){await this.server.ldap.canonicalChanges(t);let i=this.toGroupDn(e);const s=this.opNumber();if([i,t]=await l(this.registeredHooks.ldapgroupmodify,[i,t,s]),t.add){if(t.add.member)throw new D("Use dedicated API to add members");if(t.add[this.cn])throw new D(`${this.cn} attribute is unique, cannot add`)}if(t.delete){if(t.delete instanceof Object){if(t.delete.member)throw new D("Use dedicated API to delete members");if(t.delete[this.cn])throw new D(`Cannot delete ${this.cn} attribute`)}if(Array.isArray(t.delete)){if(t.delete.includes("member"))throw new D("Use dedicated API to delete members");if(t.delete.includes(this.cn))throw new D(`Cannot delete ${this.cn} attribute`)}}if(t.replace){if(t.replace.member)throw new D("Use dedicated API to replace members");if(t.replace[this.cn])throw new D(`Use dedicated API to change ${this.cn} attribute`)}await this.ldap.authorize("ldapmodifyrequest",[i,t,s,r]),await this.validateChanges(i,t);const a=await this.ldap.modify(i,t,r);return f(this.registeredHooks.ldapgroupmodifydone,[i,t,s]),a}async renameGroup(e,t,r){/,/.test(e)||u(e,this.cn),/,/.test(t)||u(t,this.cn);let i=this.toGroupDn(e),s=this.toGroupDn(t);[i,s]=await l(this.registeredHooks.ldapgrouprename,[i,s]);const a=await this.ldap.rename(i,s,r);return f(this.registeredHooks.ldapgrouprenamedone,[i,s]),a}async deleteGroup(e,t){let r=this.toGroupDn(e);r=await l(this.registeredHooks.ldapgroupdelete,r);const i=await this.ldap.delete(r,t);return f(this.registeredHooks.ldapgroupdeletedone,r),i}async addMember(e,t,r){const i=this.toGroupDn(e);return Array.isArray(t)||(t=[t]),[e,t]=await l(this.registeredHooks.ldapgroupaddmember,[e,t]),await this.ldap.authorize("ldapmodifyrequest",[i,{add:{member:t}},this.opNumber(),r]),await this.validateMembers(i,t,r),await this.ldap.modify(i,{add:{member:t}},r).catch(e=>{if(e instanceof q)throw e;throw new Error(`Failed to add member(s) to ${i}: ${e}`)})}async deleteMember(e,t,r){const i=this.toGroupDn(e);if([e,t]=await l(this.registeredHooks.ldapgroupdeletemember,[e,t]),this.isDummyMember(t))throw new D("Cannot delete dummy member from group");return await this.removeMember(i,t,r).catch(e=>{if(16===o(e))throw new A(`${t} is not a member of ${i}`);if(e instanceof q)throw e;throw new Error(`Failed to delete member ${t} from ${i}: ${e}`)})}async removeMember(e,t,r){return await this.ldap.modify(e,{delete:{member:t}},r).catch(i=>{if(65!==o(i))throw i;const s=this.config.group_dummy_user;if(!s)throw new C(`Cannot remove ${t}, the last member of ${e}: a group needs at least one member`);return this.ldap.modify(e,{add:{member:s},delete:{member:t}},r)})}async deleteMemberFromAll(e){const t=await this.ldap.system.search({filter:`member=${g(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.removeMember(t.dn,e).catch(r=>{const i=o(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=this.toGroupDn(e);let n;await this.ldap.authorize("ldapmodifyrequest",[a,{replace:{[i]:t}},this.opNumber(),r]);try{n=await this.ldap.system.search({paged:!1,scope:"base"},a)}catch(e){if(32===o(e))throw new A(`Group ${a} not found`);throw e}if(0===n.searchEntries.length)throw new A(`Group ${a} not found`);const h=n.searchEntries[0],d=w(h[i]);if(!d)throw new D(`Group ${a} does not have ${i} attribute and cannot be moved`);if(d===t)throw new D("Group is already in the target organization");let c;try{c=await this.ldap.system.search({paged:!1,scope:"base",attributes:[s,"ou","o"]},t)}catch(e){const r=o(e);if(32===r)throw new A(`Target organization ${t} not found`);if(34===r)throw new D(`${t} is not a valid DN`);throw new Error(`Target organization ${t} not found: ${e instanceof Error&&e.message?e.message:String(e)}`)}if(0===c.searchEntries.length)throw new A(`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 ${d} 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 l(this.registeredHooks._ldapgrouplist,s),s}async searchGroupsByName(e,t=!1,r=[this.cn,"member"],i){const s=g(e),a=t?`(${this.cn}=*${s}*)`:`(${this.cn}=${s})`;return await this.listGroups({filter:a,attributes:r,req:i})}toGroupDn(e){if(!/,/.test(e))return`${this.cn}=${m(e)},${this.base}`;if(!b(e))throw new D(`${e} is not a valid DN`);return e}routeGroupDn(e){const t=this.toGroupDn(e),r=this.base,i=y(`${this.cn}=x`).split("=")[0];if(!$(t,r)||y(t)===y(r)||!y(v(t)).split(/(?<!\\)\+/).some(e=>e.startsWith(`${i}=`)))throw new A("Group not found");return t}groupFilter(){return`(|${[...new Set([...this.config.group_class??[],"groupOfNames","groupOfUniqueNames","groupOfURLs","posixGroup"].filter(e=>e&&"top"!==e.toLowerCase()))].map(e=>`(objectClass=${g(e)})`).join("")})`}async judgedGroup(e,t){let r;await t();try{r=await this.ldap.system.search({paged:!1,scope:"base",filter:this.groupFilter(),attributes:["1.1"]},e)}catch(t){const r=o(t);if(32===r)throw new A("Group not found");if(34===r)throw new D(`${e} is not a valid DN`);throw t}if(!r.searchEntries?.length)throw new A("Group not found")}async validateMembers(e,t,r){[e,t]=await l(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=o(t);if(32===r)throw new D(`Member ${e} not found`);if(34===r)throw new D(`Member ${e} is not a valid DN`);throw new Error(`Member ${e} not found: ${t}`)}if(r&&!t.searchEntries?.length)throw new D(`Member ${e} not found`)})))}catch(e){if(e instanceof q||G(e))throw e;throw new Error(`Failed to find member(s): ${e}`)}}async validateNewGroup(e,t){if(!this.schema)return M(void 0,t),!0;[e,t]=await l(this.server.hooks.ldapgroupvalidatenew,[e,t]);for(const[e,r]of Object.entries(t))if(!await this._validateOneChange(e,r))throw new D(O(e,k(this.schema,e)?.[1]));const r=x(this.schema,t,this.server.loadedPlugins);if(r)throw new D(`Attribute "${r}" is required`);return M(this.schema,t),!0}async validateChanges(e,t){if(!this.schema)return N(void 0,t),!0;if([e,t]=await l(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 D(O(e,k(this.schema,e)?.[1]));if(t.replace)for(const[e,r]of Object.entries(t.replace))if(!await this._validateOneChange(e,r))throw new D(O(e,k(this.schema,e)?.[1]));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 N(this.schema,t),!0}async _validateOneChange(e,t){if(!this.schema)return!0;const r=k(this.schema,e)?.[1];if(!r){if(this.schema.strict)throw new D(`Attribute "${e}" is not allowed`);return!0}if(null==t||Array.isArray(t)&&0===t.length){if(r.required)throw new D(`Attribute "${e}" is required`);return!0}if("array"===r.type){if(!Array.isArray(t))throw new D(`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 D(`Attribute "${e}" must be of type ${r.items.type}`)}else if("pointer"!==r.type&&typeof t!==r.type)return!1;if(await z(e,r,t,async e=>(await this.ldap.system.search({paged:!1,scope:"base",attributes:["dn"]},e)).searchEntries.length>0),!F(r,t))throw new D(O(e,r));return!0}getConfigApiData(){const e=this.config.api_prefix||"/api",t=this.server.loadedPlugins.static&&this.config.group_schema?h(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{assertModifyRequest as t}from"../../lib/ldapActions.js";import{wantJson as r,jsonBody as i,tryMethod as s,ok as a}from"../../lib/expressFormatedResponses.js";import{extractLdapCode as o}from"../../lib/ldapCodes.js";import{loadSchemaFileAsync as n}from"../../lib/schemaFile.js";import{staticSchemaUrl as h}from"../../lib/staticFiles.js";import{movedToTrash as d,asyncHandler as p,isDummyMemberDn as c,validateDnValue as u,escapeDnValue as m,launchHooksChained as l,launchHooks as g,escapeLdapFilter as f,organizationLink as w,isDnSyntax as b,normalizeDn as y,isDnInBranch as $,getRdn as v,isAuthzRefusal as G,substringSearchFilter as _}from"../../lib/utils.js";import{NotFoundError as D,BadRequestError as q,HttpError as C,ConflictError as j}from"../../lib/errors.js";import{assertClientMaySet as A,modifiedAttributeNames as k,toDirectoryEntry as M}from"../../config/schema.js";import{applyFixedDefaults as E,EntityValidator as N}from"../../lib/entitySchema/validator.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)})},ldaprenamedone:async([e,t])=>{d(this.config.trash_base,e,t)&&await this.deleteMemberFromAll(e).catch(e=>{this.logger.error("Failed to process a move to the trash 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;n(e,{config:this.config}).then(e=>{this.schema=this.adaptSchema(e),this.server.ldap.knowAttributeNames(Object.keys(this.schema.attributes)),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`,p(async(e,t)=>{if(!r(e,t))return;const i={};if(e.query.match){if("string"!=typeof e.query.match)throw new q("Invalid match query");if("string"==typeof e.query.attribute&&e.query.attribute)i.filter=_(e.query.match,e.query.attribute);else if(/=/.test(e.query.match)){if(!/^[\w*=()&|, .@'-]+$/.test(e.query.match))throw new q("Invalid match query: contains forbidden characters");i.filter=e.query.match}else{const t=f(e.query.match);i.filter=`(${this.cn}=${t})`}}e.query.attributes&&"string"==typeof e.query.attributes&&(i.attributes=e.query.attributes.split(","));const s=await this.listGroups({...i,req:e});return a(t,this.hideNeverReturn(s))})),e.get(`${this.config.api_prefix}/v1/ldap/groups/:cn`,p(async(e,t)=>this.apiGet(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups`,p(async(e,t)=>this.apiAdd(e,t,this.cn))),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn`,p(async(e,t)=>this.apiDelete(e,t))),e.put(`${this.config.api_prefix}/v1/ldap/groups/:cn`,p(async(e,t)=>this.apiModify(e,t))),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/members`,p(async(e,t)=>{const r=decodeURIComponent(e.params.cn);if(!r)throw new q("cn is required");const a=this.routeGroupDn(r),o=i(e,t,"member");if(!o)return;const n=Array.isArray(o.member)?o.member:[o.member];if(n.some(e=>"string"!=typeof e))throw new q("member must be a string or string array");await this.judgedGroup(a,()=>this.ldap.authorize("ldapmodifyrequest",[a,{add:{member:n}},this.opNumber(),e])),await s(t,this.addMember.bind(this),r,o.member,e)})),e.delete(`${this.config.api_prefix}/v1/ldap/groups/:cn/members/:member`,p(async(e,t)=>{if(!r(e,t))return;const i=decodeURIComponent(e.params.cn),a=decodeURIComponent(e.params.member);if(!i||!a)throw new q("cn and member are required");const o=this.routeGroupDn(i);await this.judgedGroup(o,()=>this.ldap.authorize("ldapmodifyrequest",[o,{delete:{member:[a]}},this.opNumber(),e])),await s(t,this.deleteMember.bind(this),i,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`,p(async(e,t)=>{if(!r(e,t))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new q("cn is required");const o=this.routeGroupDn(a),n=i(e,t,"targetOrgDn");if(!n)return;if("string"!=typeof n.targetOrgDn)throw new q("targetOrgDn must be a string");const h=this.config.ldap_organization_link_attribute;await this.judgedGroup(o,()=>this.ldap.authorize("ldapmodifyrequest",[o,{replace:{[h]:n.targetOrgDn}},this.opNumber(),e])),await s(t,this.moveGroup.bind(this),a,n.targetOrgDn,e)})),e.post(`${this.config.api_prefix}/v1/ldap/groups/:cn/rename`,p(async(e,t)=>{if(!r(e,t))return;const a=decodeURIComponent(e.params.cn);if(!a)throw new q("cn is required");const o=this.routeGroupDn(a),n=i(e,t,"newCn");if(!n)return;if("string"!=typeof n.newCn)throw new q("newCn must be a string");const h=/,/.test(n.newCn)?this.routeGroupDn(n.newCn):this.toGroupDn(n.newCn);await this.judgedGroup(o,()=>this.ldap.authorize("ldaprenamerequest",[o,h,e])),await s(t,this.renameGroup.bind(this),a,n.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,t){if(!r(e,t))return;const i=decodeURIComponent(e.params.cn),s=this.routeGroupDn(i);try{const r=await this.ldap.search({paged:!1,scope:"base",filter:this.groupFilter()},s,e);if(0===r.searchEntries.length)throw new D("Group not found");t.json(this.hideNeverReturn(this.withoutDummyMember(r.searchEntries[0])))}catch(e){if(e.code&&32===e.code)throw new D("Group not found");if(34===o(e))throw new q(`${i} is not a valid DN`);throw e}}async apiAdd(e,t,...r){const a=i(e,t,...r);if(!a)return;await this.server.ldap.canonicalAttributes(a),A(this.schema,Object.keys(a),this.cn);const o=a[this.cn];"string"==typeof o&&(/,/.test(o)||new RegExp(`^${this.cn}=`,"i").test(o))&&this.routeGroupDn(/,/.test(o)?o:`${o},${this.base}`);const n=a.member?Array.isArray(a.member)?a.member:[a.member]:[],h=Object.fromEntries(Object.entries(a).filter(([e,t])=>e!==this.cn&&"member"!==e&&"objectClass"!==e&&void 0!==t));await s(t,this.addGroup.bind(this),o,n,h,e)}async apiDelete(e,t){if(!r(e,t))return;const i=decodeURIComponent(e.params.cn);if(!i)throw new q("cn is required");const a=this.routeGroupDn(i);await this.judgedGroup(a,()=>this.ldap.authorize("ldapdeleterequest",[a,e])),await s(t,this.deleteGroup.bind(this),i,e)}async apiModify(e,r){const a=i(e,r);if(!a)return;t(a);const o=decodeURIComponent(e.params.cn);if(!o)throw new q("cn is required");const n=this.routeGroupDn(o);await this.server.ldap.canonicalChanges(a),A(this.schema,k(a)),await this.judgedGroup(n,()=>this.ldap.authorize("ldapmodifyrequest",[n,a,this.opNumber(),e])),await s(r,this.modifyGroup.bind(this),n,a,e)}async addGroup(e,t=[],r={},i){let s;await this.server.ldap.canonicalAttributes(r),new RegExp(`^${this.cn}=`,"i").test(e)?(s=/,/.test(e)?e:`${e},${this.base}`,e=e.replace(new RegExp(`^${this.cn}=((?:\\\\.|[^,])+)(?:,.*)?$`,"i"),"$1")):(u(e,this.cn),s=`${this.cn}=${m(e)},${this.base}`);let a=this.candidateGroup(e,t,r);await this.ldap.authorize("ldapaddrequest",[s,{...a},i]),await this.validateMembers(s,t,i);const o=await this.validateNewGroup(s,{objectClass:a.objectClass,[this.cn]:e,member:t,...r});let n;delete o.member,Object.assign(a,o),M(this.schema,a),[s,a]=await l(this.registeredHooks.ldapgroupadd,[s,a]);try{n=await this.ldap.add(s,a,i)}catch(e){if(e instanceof C)throw e;throw new Error(`Failed to add group ${s}: ${e}`)}return g(this.registeredHooks.ldapgroupadddone,[s,a]),n}candidateGroup(e,t,r){const i=[...this.config.group_class];!(r.mail||r.twakeMailboxType||r.twakeDepartmentLink||r.twakeDepartmentPath)||i.includes("twakeGroup")||i.includes("twakeStaticGroup")||i.push("twakeGroup");const s={objectClass:i,...this.config.group_default_attributes,[this.cn]:e,member:[this.config.group_dummy_user],...r};return t.length&&s.member.push(...t),E(this.schema,s),s}async modifyGroup(e,t,r){await this.server.ldap.canonicalChanges(t);let i=this.toGroupDn(e);const s=this.opNumber();if([i,t]=await l(this.registeredHooks.ldapgroupmodify,[i,t,s]),t.add){if(t.add.member)throw new q("Use dedicated API to add members");if(t.add[this.cn])throw new q(`${this.cn} attribute is unique, cannot add`)}if(t.delete){if(t.delete instanceof Object){if(t.delete.member)throw new q("Use dedicated API to delete members");if(t.delete[this.cn])throw new q(`Cannot delete ${this.cn} attribute`)}if(Array.isArray(t.delete)){if(t.delete.includes("member"))throw new q("Use dedicated API to delete members");if(t.delete.includes(this.cn))throw new q(`Cannot delete ${this.cn} attribute`)}}if(t.replace){if(t.replace.member)throw new q("Use dedicated API to replace members");if(t.replace[this.cn])throw new q(`Use dedicated API to change ${this.cn} attribute`)}await this.ldap.authorize("ldapmodifyrequest",[i,t,s,r]),t=await this.validateChanges(i,t);const a=await this.ldap.modify(i,t,r);return g(this.registeredHooks.ldapgroupmodifydone,[i,t,s]),a}async renameGroup(e,t,r){/,/.test(e)||u(e,this.cn),/,/.test(t)||u(t,this.cn);let i=this.toGroupDn(e),s=this.toGroupDn(t);[i,s]=await l(this.registeredHooks.ldapgrouprename,[i,s]);const a=await this.ldap.rename(i,s,r);return g(this.registeredHooks.ldapgrouprenamedone,[i,s]),a}async deleteGroup(e,t){let r=this.toGroupDn(e);r=await l(this.registeredHooks.ldapgroupdelete,r);const i=await this.ldap.delete(r,t);return g(this.registeredHooks.ldapgroupdeletedone,r),i}async addMember(e,t,r){const i=this.toGroupDn(e);return Array.isArray(t)||(t=[t]),[e,t]=await l(this.registeredHooks.ldapgroupaddmember,[e,t]),await this.ldap.authorize("ldapmodifyrequest",[i,{add:{member:t}},this.opNumber(),r]),await this.validateMembers(i,t,r),await this.ldap.modify(i,{add:{member:t}},r).catch(e=>{if(e instanceof C)throw e;throw new Error(`Failed to add member(s) to ${i}: ${e}`)})}async deleteMember(e,t,r){const i=this.toGroupDn(e);if([e,t]=await l(this.registeredHooks.ldapgroupdeletemember,[e,t]),this.isDummyMember(t))throw new q("Cannot delete dummy member from group");return await this.removeMember(i,t,r).catch(e=>{if(16===o(e))throw new D(`${t} is not a member of ${i}`);if(e instanceof C)throw e;throw new Error(`Failed to delete member ${t} from ${i}: ${e}`)})}async removeMember(e,t,r){return await this.ldap.modify(e,{delete:{member:t}},r).catch(i=>{if(65!==o(i))throw i;const s=this.config.group_dummy_user;if(!s)throw new j(`Cannot remove ${t}, the last member of ${e}: a group needs at least one member`);return this.ldap.modify(e,{add:{member:s},delete:{member:t}},r)})}async deleteMemberFromAll(e){const t=await this.ldap.system.search({filter:`member=${f(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.removeMember(t.dn,e).catch(r=>{const i=o(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=this.toGroupDn(e);let n;await this.ldap.authorize("ldapmodifyrequest",[a,{replace:{[i]:t}},this.opNumber(),r]);try{n=await this.ldap.system.search({paged:!1,scope:"base"},a)}catch(e){if(32===o(e))throw new D(`Group ${a} not found`);throw e}if(0===n.searchEntries.length)throw new D(`Group ${a} not found`);const h=n.searchEntries[0],d=w(h[i]);if(!d)throw new q(`Group ${a} does not have ${i} attribute and cannot be moved`);if(d===t)throw new q("Group is already in the target organization");let p;try{p=await this.ldap.system.search({paged:!1,scope:"base",attributes:[s,"ou","o"]},t)}catch(e){const r=o(e);if(32===r)throw new D(`Target organization ${t} not found`);if(34===r)throw new q(`${t} is not a valid DN`);throw new Error(`Target organization ${t} not found: ${e instanceof Error&&e.message?e.message:String(e)}`)}if(0===p.searchEntries.length)throw new D(`Target organization ${t} not found`);const c=p.searchEntries[0][s];if(!c)throw new Error(`Target organization ${t} does not have ${s} attribute`);return await this.ldap.modify(a,{replace:{[i]:t,[s]:c}},r),this.logger.info(`Group ${a} moved from ${d} 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 l(this.registeredHooks._ldapgrouplist,s),s}async searchGroupsByName(e,t=!1,r=[this.cn,"member"],i){const s=f(e),a=t?`(${this.cn}=*${s}*)`:`(${this.cn}=${s})`;return await this.listGroups({filter:a,attributes:r,req:i})}toGroupDn(e){if(!/,/.test(e))return`${this.cn}=${m(e)},${this.base}`;if(!b(e))throw new q(`${e} is not a valid DN`);return e}routeGroupDn(e){const t=this.toGroupDn(e),r=this.base,i=y(`${this.cn}=x`).split("=")[0];if(!$(t,r)||y(t)===y(r)||!y(v(t)).split(/(?<!\\)\+/).some(e=>e.startsWith(`${i}=`)))throw new D("Group not found");return t}groupFilter(){return`(|${[...new Set([...this.config.group_class??[],"groupOfNames","groupOfUniqueNames","groupOfURLs","posixGroup"].filter(e=>e&&"top"!==e.toLowerCase()))].map(e=>`(objectClass=${f(e)})`).join("")})`}async judgedGroup(e,t){let r;await t();try{r=await this.ldap.system.search({paged:!1,scope:"base",filter:this.groupFilter(),attributes:["1.1"]},e)}catch(t){const r=o(t);if(32===r)throw new D("Group not found");if(34===r)throw new q(`${e} is not a valid DN`);throw t}if(!r.searchEntries?.length)throw new D("Group not found")}async validateMembers(e,t,r){[e,t]=await l(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=o(t);if(32===r)throw new q(`Member ${e} not found`);if(34===r)throw new q(`Member ${e} is not a valid DN`);throw new Error(`Member ${e} not found: ${t}`)}if(r&&!t.searchEntries?.length)throw new q(`Member ${e} not found`)})))}catch(e){if(e instanceof C||G(e))throw e;throw new Error(`Failed to find member(s): ${e}`)}}async validateNewGroup(e,t){return[e,t]=await l(this.server.hooks.ldapgroupvalidatenew,[e,t]),await this.validator().validateNew(t),t}async validateChanges(e,t){return[e,t]=await l(this.server.hooks.ldapgroupvalidatechanges,[e,t]),await this.validator().validateChanges(t),t}validator(){return new N(this.schema,{entryExists:async e=>{try{return(await this.ldap.system.search({paged:!1,scope:"base",attributes:["dn"]},e)).searchEntries.length>0}catch{return!1}},loadedPlugins:this.server.loadedPlugins,singularName:"group"})}getConfigApiData(){const e=this.config.api_prefix||"/api",t=this.config.group_schema?h(this.server,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 t from"../../abstract/plugin.js";import{assertModifyRequest as i}from"../../lib/ldapActions.js";import{tryMethodData as a,jsonBody as e,tryMethod as n,wantJson as s}from"../../lib/expressFormatedResponses.js";import{asyncHandler as r,validateDnValue as o,escapeDnValue as h,getRdn as c,isDnInBranch as d,rdnValue as l,normalizeDn as g,getParentDn as p,escapeLdapFilter as u,launchHooksChained as f,isAuthzRefusal as w,isChildOf as m,substringSearchFilter as z}from"../../lib/utils.js";import{BadRequestError as y,NotFoundError as b,ConflictError as $,HttpError as v}from"../../lib/errors.js";import{extractLdapCode as _}from"../../lib/ldapCodes.js";import{loadSchemaFileAsync as O,schemaUrl as A}from"../../lib/schemaFile.js";import{assertClientMaySet as C,modifiedAttributeNames as E,toDirectoryEntry as L,missingRequiredAttribute as k,invalidValueMessage as j,schemaAttribute as S,toDirectoryChanges as q,checkDnValues as x,matchesPattern as D}from"../../config/schema.js";class LdapOrganizations extends t{constructor(t){if(super(t),this.name="ldapOrganizations",this.roles=["api","consistency","configurable"],this.hooks={ldapaddrequest:async([t,i,a])=>(this.isOu(i)||await this.checkDeptLink(i),this.isOu(i)&&await this.checkDeptPath(i,t),void 0!==a?[t,i,a]:[t,i]),ldapmodifyrequest:async([t,i,a,e])=>{let n,s={},r={};const checkIsOu=async()=>{if(void 0!==n)return n;if(i.replace?.objectClass)n=this.isOu({objectClass:i.replace.objectClass});else if(i.add?.objectClass)n=this.isOu({objectClass:i.add.objectClass});else{const i=await this.server.ldap.system.search({paged:!1,scope:"base"},t);n=i.searchEntries.length>0&&this.isOu(i.searchEntries[0])}return n};if(i.delete){const t=(Array.isArray(i.delete)?i.delete.map(String):Object.keys(i.delete)).map(t=>t.split(";")[0].toLowerCase()),a=t.includes(this.linkAttr.toLowerCase()),e=t.includes(this.pathAttr.toLowerCase());if(a||e){if(!await checkIsOu()&&a)throw new y("An organization link cannot be deleted");if(e)throw new y("An organization path cannot be deleted")}}if(i.replace&&(i.replace[this.linkAttr]&&(s={...i.replace}),i.replace[this.pathAttr]&&(r={...i.replace})),i.add&&(i.add[this.linkAttr]&&(s={...s,...i.add}),i.add[this.pathAttr]&&(r={...r,...i.add})),Object.keys(s).length>0){await checkIsOu()||await this.checkDeptLink(s)}if(Object.keys(r).length>0){await checkIsOu()&&await this.checkDeptPath(r,t)}return[t,i,a,e]},ldapdeleterequest:async([t,i])=>{const a=Array.isArray(t)?t:[t];for(const t of a)/^\s*ou\s*=/i.test(t)&&await this.isEmptyOrganization(t);return[t,i]},ldaprenamerequest:([t,i,a])=>[t,i,a]},this.sizeLimitWarned=new Set,!this.config.ldap_top_organization)throw new Error("Missing --ldap-top-organization");if(this.pathAttr=this.config.ldap_organization_path_attribute,this.linkAttr=this.config.ldap_organization_link_attribute,t.ldap.declareObjectClasses(this.config.ldap_top_organization,this.config.ldap_organization_class||[],!0),this.config.organization_schema){const t=this.config.organization_schema;O(t,{config:this.config}).then(t=>{this.schema=t,this.server.ldap.knowAttributeNames(Object.keys(t.attributes)),this.logger.debug("Organization schema loaded")}).catch(i=>this.logger.error(`Failed to load organization schema from ${t}: ${i}`))}}api(t){t.get(`${this.config.api_prefix}/v1/ldap/organizations/top`,async(t,i)=>{await a(i,async()=>this.hideNeverReturn(await this.getOrganisationTop(t)))}),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn`,async(t,i)=>{const e=decodeURIComponent(t.params.dn);await a(i,async()=>this.hideNeverReturn(await this.getOrganisationByDn(e,t)))}),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn/subnodes`,async(t,i)=>{const e=decodeURIComponent(t.params.dn);await a(i,async()=>this.hideNeverReturn(await this.getOrganisationSubnodes(e,t)))}),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn/subnodes/search`,r(async(t,i)=>{const e=decodeURIComponent(t.params.dn),n=t.query.q;if(!n)throw new y('query parameter "q" is required');await a(i,async()=>this.hideNeverReturn(await this.searchOrganisationSubnodes(e,n,t)))})),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn/search`,r(async(t,i)=>{const e=decodeURIComponent(t.params.dn),n=t.query.q;if(!n)throw new y('query parameter "q" is required');await a(i,async()=>this.hideNeverReturn(await this.searchOrganisationTree(e,n,t)))})),t.post(`${this.config.api_prefix}/v1/ldap/organizations`,r(async(t,i)=>this.apiAdd(t,i))),t.put(`${this.config.api_prefix}/v1/ldap/organizations/:dn`,r(async(t,i)=>this.apiModify(t,i))),t.delete(`${this.config.api_prefix}/v1/ldap/organizations/:dn`,r(async(t,i)=>this.apiDelete(t,i))),t.post(`${this.config.api_prefix}/v1/ldap/organizations/:dn/move`,r(async(t,i)=>this.apiMove(t,i)))}async apiAdd(t,i){const a=e(t,i,"ou");if(!a)return;C(this.schema,Object.keys(a),"ou"),o(a.ou,"ou");const s=a.parentDn||this.config.ldap_top_organization,r=`ou=${h(a.ou)},${s}`,c={objectClass:this.config.ldap_organization_class,ou:a.ou,...Object.fromEntries(Object.entries(a).filter(([t])=>"ou"!==t&&"parentDn"!==t))};await n(i,this.addOrganization.bind(this),r,c,t)}async apiModify(t,a){const s=e(t,a);if(!s)return;i(s);const r=decodeURIComponent(t.params.dn);if(!r)throw new y("dn is required");C(this.schema,E(s)),await n(a,this.modifyOrganization.bind(this),r,s,t)}async apiDelete(t,i){if(!s(t,i))return;const a=decodeURIComponent(t.params.dn);if(!a)throw new y("dn is required");await n(i,this.deleteOrganization.bind(this),a,t)}async apiMove(t,i){if(!s(t,i))return;const n=e(t,i,"targetOrgDn");if(!n)return;const r=decodeURIComponent(t.params.dn);if(!r)throw new y("dn is required");const{targetOrgDn:o}=n;if(!o||"string"!=typeof o)throw new y("Missing or invalid targetOrgDn in request body");await a(i,this.moveOrganization.bind(this),r,o,t)}async checkDeptLink(t){if(t[this.linkAttr]){const i=t[this.linkAttr],a=Array.isArray(i)?i[0]:i,e=await this.server.ldap.system.search({paged:!1,scope:"base"},a);if(0===e.searchEntries.length)throw new b(`Organization ${a} does not exist`);if(!new RegExp(`(.*,)?${this.config.ldap_top_organization}`).test(e.searchEntries[0].dn))throw new y(`Entry ${a} isn't in top organization branch`)}}async checkDeptPath(t,i){if(t[this.pathAttr]){const a=t[this.pathAttr],e=Array.isArray(a)?a[0]:a,n=this.config.ldap_organization_path_separator||" / ",s=this.config.ldap_top_organization||"",r=i&&s&&/^ou=/i.test(c(i))&&d(i,s)?l(i):void 0,o=t.ou,h=(Array.isArray(o)?o[0]:o)||r;let f=e;if((this.isOu(t)||void 0!==r)&&h){const t=s?l(s):"";if(t&&e.startsWith(h+n)&&e.endsWith(n+t))return;if(e===h){const t=s?g(s):"";if(!i||!t||!d(i,s)||g(i)===t||g(p(i))===t)return;throw new y(`Organization path "${e}" names no parent, but ${i} is not directly under ${s}`)}if(!e.endsWith(n+h))throw new y(`Organization path must end with its own name, preceded by separator "${n}"`);f=e.slice(0,e.length-n.length-h.length)}const w=await this.server.ldap.system.search({paged:!1,scope:"sub",filter:`(${this.pathAttr}=${u(f)})`,attributes:["dn"]},this.config.ldap_top_organization);if(!w.searchEntries||0===w.searchEntries.length)throw new y(`Invalid organization path ${e}: no organization holds "${f}"`)}}async isEmptyOrganization(t){if((await this.server.ldap.system.search({paged:!1,filter:`(${this.config.ldap_organization_link_attribute}=${u(t)})`})).searchEntries.length>0)throw new $(`Organization ${t} is not empty`)}isOu(t){if(!t.objectClass)return!1;const i=[].concat(t.objectClass).map(t=>String(t).toLowerCase());return this.config.ldap_organization_class.filter(t=>"top"!==t.toLowerCase()).some(t=>i.includes(t.toLowerCase()))}async getOrganisationTop(t){if(!this.config.ldap_top_organization)throw new y("No top organization configured");const i=await this.server.ldap.search({paged:!1,scope:"base"},this.config.ldap_top_organization,t);if(1!==i.searchEntries.length)throw new b("Top organization not found");const[,a]=await f(this.registeredHooks.getOrganisationTop,[t,i.searchEntries[0]]);return a}async getOrganisationByDn(t,i){let a;try{a=await this.server.ldap.search({paged:!1,scope:"base",filter:"(objectClass=organizationalUnit)"},t,i)}catch(i){const a=_(i);if(32===a)throw new b(`Organization ${t} not found`);if(34===a)throw new y(`${t} is not a valid DN`);throw i}if(1!==a.searchEntries.length)throw new b(`Organization ${t} not found`);return a.searchEntries[0]}async getOrganisationSubnodes(t,i){const a=[],e=this.config.ldap_organization_max_subnodes||50,n=i?.query?.objectClass;n&&"organizationalUnit"!==n||a.push(...await this.childOrganizations(t,"(objectClass=organizationalUnit)",e,i));const s=this.config.ldap_top_organization,r=p(s);let o=`(${this.config.ldap_organization_link_attribute}=${u(t)})`;return n&&(o=`(&${o}(objectClass=${u(n)}))`),this.server.logger.debug(`Searching for linked entities with filter: ${o} in ${r}`),a.push(...await this.linkedEntities(r,o,e,t,i)),a}warnSizeLimit(t,i){this.sizeLimitWarned.has(t)?this.server.logger.debug(i):(this.sizeLimitWarned.size<LdapOrganizations.SIZE_LIMIT_WARNED_MAX&&this.sizeLimitWarned.add(t),this.server.logger.warn(i))}static moreIndicator(t,i,a,e){return{dn:t,cn:[i],objectClass:["moreIndicator"],_isMoreIndicator:"true",...void 0===e?{}:{_totalCount:e.toString()},_displayedCount:a.toString()}}async childOrganizations(t,i,a,e){try{const a=await this.server.ldap.search({paged:!0,scope:"one",filter:i},t,e),n=[];for await(const t of a)n.push(...t.searchEntries);return this.server.logger.debug(`Found ${n.length} sub-OUs for ${t}`),n}catch(i){const a=_(i);if(32===a)return this.server.logger.debug(`No sub-OUs for ${t}: the node holds none`),[];if(34===a)throw new y(`${t} is not a valid DN`);if(4!==a)throw i}const n=(await this.server.ldap.search({paged:!1,scope:"one",filter:i,sizeLimit:a+1},t,e)).searchEntries.slice(0,a);return this.warnSizeLimit(`children:${t}`,`Organization ${t} holds more child organizations than the directory will list in one answer, so ${n.length} are returned and the rest are hidden. Raise the size limit for the account ldap-rest binds as (olcLimits, or olcSizeLimit) to list them all.`),[...n,LdapOrganizations.moreIndicator(`more-organizations-${t}`,"... more organizations than the directory will list",n.length)]}async linkedEntities(t,i,a,e,n){const s=[];let r=0;try{const e=await this.server.ldap.search({paged:!0,filter:i},t,n);for await(const t of e){r+=t.searchEntries.length;const i=a-s.length;i>0&&s.push(...t.searchEntries.slice(0,i))}}catch(s){if(t!==e&&(w(s)||403===s?.statusCode))return this.linkedEntities(e,i,a,e,n);if(4!==_(s))throw s;const r=await this.server.ldap.search({paged:!1,filter:i,sizeLimit:a+1},t,n);this.warnSizeLimit(`linked:${e}`,`More entries are attached to ${e} than the directory will list in one answer. Raise the size limit for the account ldap-rest binds as (olcLimits, or olcSizeLimit) to count them all.`);const o=r.searchEntries.slice(0,a);return[...o,LdapOrganizations.moreIndicator(`more-${e}`,"... more elements than the directory will list",o.length)]}return this.server.logger.debug(`Found ${r} linked entities for ${e}, returning ${s.length}`),r<=a?s:[...s,LdapOrganizations.moreIndicator(`more-${e}`,`... ${r-a} more ${r-a===1?"element":"elements"}`,a,r)]}async addOrganization(t,i,a){return await this.server.ldap.authorize("ldapaddrequest",[t,i,a]),await this.validateNewOrganization(t,i),await this.server.ldap.add(t,i,a)}async modifyOrganization(t,i,a){return await this.server.ldap.authorize("ldapmodifyrequest",[t,i,this.opNumber(),a]),await this.validateChanges(t,i),await this.server.ldap.modify(t,i,a)}async validateNewOrganization(t,i){if(!this.schema)return L(void 0,i),!0;for(const[t,a]of Object.entries(i))if(!await this._validateOneChange(t,a))throw new y(this.invalidValueMessage(t));const a=k(this.schema,i,this.server.loadedPlugins);if(a)throw new y(`Attribute "${a}" is required`);return L(this.schema,i),!0}invalidValueMessage(t){return j(t,S(this.schema,t)?.[1])}async validateChanges(t,i){if(!this.schema)return q(void 0,i),!0;if(i.add)for(const[t,a]of Object.entries(i.add))if(!await this._validateOneChange(t,a))throw new y(this.invalidValueMessage(t));if(i.replace)for(const[t,a]of Object.entries(i.replace))if(!await this._validateOneChange(t,a))throw new y(this.invalidValueMessage(t));return q(this.schema,i),!0}async _validateOneChange(t,i){if(!this.schema)return!0;const a=S(this.schema,t)?.[1];if(!a){if(this.schema.strict)throw new y(`Attribute "${t}" is not allowed`);return!0}if(null==i||Array.isArray(i)&&0===i.length){if(a.required)throw new y(`Attribute "${t}" is required`);return!0}if("string"===a.type&&Array.isArray(i))throw new y(`Attribute "${t}" must be a single value`);return await x(t,a,i,t=>this.entryExists(t)),D(a,i)}async entryExists(t){try{return(await this.server.ldap.system.search({paged:!1,scope:"base",attributes:["dn"]},t)).searchEntries.length>0}catch{return!1}}async moveOrganization(t,i,a){const e=`${c(t)},${i}`;let n,s;await this.server.ldap.authorize("ldaprenamerequest",[t,e,a]);try{n=await this.server.ldap.system.search({paged:!1,scope:"base"},i)}catch(t){throw new b(`Target organization ${i} not found: ${t instanceof Error?t.message:String(t)}`)}if(!n.searchEntries||0===n.searchEntries.length)throw new b(`Target organization ${i} not found`);if(!this.isOu(n.searchEntries[0]))throw new y(`Target ${i} is not an organizational unit`);try{s=await this.server.ldap.system.search({paged:!1,scope:"base"},t)}catch(t){throw new b(`Source organization not found: ${t}`)}if(!s.searchEntries||0===s.searchEntries.length)throw new b(`Source organization ${t} not found`);if(e===t)throw new y("Cannot move organization to its current location");if(i.toLowerCase()===t.toLowerCase()||m(i,t))throw new y("Cannot move organization into itself or its descendant");try{await this.server.ldap.rename(t,e,a),this.logger.info(`Moved organization from ${t} to ${e}`)}catch(t){if(t instanceof v)throw t;throw new Error(`Failed to move organization: ${t}`)}return{newDn:e}}async deleteOrganization(t,i){try{return await this.server.ldap.delete(t,i)}catch(i){if(32===_(i))throw new b(`Organization ${t} not found`);throw i}}async searchOrganisationSubnodes(t,i,a){const e=[],n=this.config.ldap_organization_max_subnodes||50;e.push(...await this.childOrganizations(t,`(&(objectClass=organizationalUnit)${z(i,"ou,description")})`,n,a));const s=this.config.ldap_top_organization,r=p(s),o=u(t),h=this.config.display_name_attribute||"displayName",c=`(&(${this.config.ldap_organization_link_attribute}=${o})${z(i,`uid,cn,mail,sn,givenName,${h}`)})`;return this.server.logger.debug(`Searching for linked entities with filter: ${c} in ${r}`),e.push(...await this.linkedEntities(r,c,n,t,a)),e}async searchOrganisationTree(t,i,a){const e=this.config.ldap_organization_max_subnodes||50,n=this.pathAttr?`ou,description,${this.pathAttr}`:"ou,description",s=`(&(objectClass=organizationalUnit)${z(i,n)})`,r=[];let o=0;try{const i=await this.server.ldap.search({paged:!0,scope:"sub",filter:s},t,a);for await(const t of i){o+=t.searchEntries.length;const i=e-r.length;i>0&&r.push(...t.searchEntries.slice(0,i))}}catch(i){const n=_(i);if(32===n)return this.server.logger.debug(`No organizations under ${t}: no such node`),[];if(34===n)throw new y(`${t} is not a valid DN`);if(4!==n)throw i;const r=(await this.server.ldap.search({paged:!1,scope:"sub",filter:s,sizeLimit:e+1},t,a)).searchEntries.slice(0,e);return this.warnSizeLimit(`search:${t}`,`A search under ${t} matched more organizations than the directory will list in one answer, so ${r.length} are returned and the rest are hidden. Raise the size limit for the account ldap-rest binds as (olcLimits, or olcSizeLimit) to search them all.`),[...r,LdapOrganizations.moreIndicator(`more-organizations-${t}`,"... more organizations than the directory will list",r.length)]}if(o<=e)return r;const h=o-e;return[...r,LdapOrganizations.moreIndicator(`more-organizations-${t}`,`... ${h} more ${1===h?"organization":"organizations"}, narrow the search`,e,o)]}getConfigApiData(){const t=this.config.api_prefix||"/api",i=this.server.loadedPlugins.static&&this.config.organization_schema?A(this.config,this.config.organization_schema):void 0;return{enabled:!0,topOrganization:this.config.ldap_top_organization||"",organizationClass:this.config.ldap_organization_class||["top","organizationalUnit"],linkAttribute:this.linkAttr||"",pathAttribute:this.pathAttr||"",pathSeparator:this.config.ldap_organization_path_separator||" / ",maxSubnodes:this.config.ldap_organization_max_subnodes||50,schema:this.schema,schemaUrl:i,endpoints:{getTop:`${t}/v1/ldap/organizations/top`,get:`${t}/v1/ldap/organizations/:dn`,getSubnodes:`${t}/v1/ldap/organizations/:dn/subnodes`,searchSubnodes:`${t}/v1/ldap/organizations/:dn/subnodes/search`,search:`${t}/v1/ldap/organizations/:dn/search`,create:`${t}/v1/ldap/organizations`,update:`${t}/v1/ldap/organizations/:dn`,move:`${t}/v1/ldap/organizations/:dn/move`,delete:`${t}/v1/ldap/organizations/:dn`}}}}LdapOrganizations.SIZE_LIMIT_WARNED_MAX=500;export{LdapOrganizations as default};
|
|
1
|
+
import t from"../../abstract/plugin.js";import{assertModifyRequest as i}from"../../lib/ldapActions.js";import{tryMethodData as a,jsonBody as e,tryMethod as n,wantJson as s}from"../../lib/expressFormatedResponses.js";import{asyncHandler as r,validateDnValue as o,escapeDnValue as h,getRdn as c,isDnInBranch as d,rdnValue as l,normalizeDn as g,getParentDn as p,escapeLdapFilter as u,launchHooksChained as f,isAuthzRefusal as w,isChildOf as m,substringSearchFilter as z}from"../../lib/utils.js";import{BadRequestError as y,NotFoundError as b,ConflictError as $,HttpError as _}from"../../lib/errors.js";import{extractLdapCode as v}from"../../lib/ldapCodes.js";import{loadSchemaFileAsync as O}from"../../lib/schemaFile.js";import{staticSchemaUrl as E}from"../../lib/staticFiles.js";import{assertClientMaySet as A,modifiedAttributeNames as C}from"../../config/schema.js";import{applyFixedDefaults as L,EntityValidator as k}from"../../lib/entitySchema/validator.js";class LdapOrganizations extends t{constructor(t){if(super(t),this.name="ldapOrganizations",this.roles=["api","consistency","configurable"],this.hooks={ldapaddrequest:async([t,i,a])=>(this.isOu(i)||await this.checkDeptLink(i),this.isOu(i)&&await this.checkDeptPath(i,t),void 0!==a?[t,i,a]:[t,i]),ldapmodifyrequest:async([t,i,a,e])=>{let n,s={},r={};const checkIsOu=async()=>{if(void 0!==n)return n;if(i.replace?.objectClass)n=this.isOu({objectClass:i.replace.objectClass});else if(i.add?.objectClass)n=this.isOu({objectClass:i.add.objectClass});else{const i=await this.server.ldap.system.search({paged:!1,scope:"base"},t);n=i.searchEntries.length>0&&this.isOu(i.searchEntries[0])}return n};if(i.delete){const t=(Array.isArray(i.delete)?i.delete.map(String):Object.keys(i.delete)).map(t=>t.split(";")[0].toLowerCase()),a=t.includes(this.linkAttr.toLowerCase()),e=t.includes(this.pathAttr.toLowerCase());if(a||e){if(!await checkIsOu()&&a)throw new y("An organization link cannot be deleted");if(e)throw new y("An organization path cannot be deleted")}}if(i.replace&&(i.replace[this.linkAttr]&&(s={...i.replace}),i.replace[this.pathAttr]&&(r={...i.replace})),i.add&&(i.add[this.linkAttr]&&(s={...s,...i.add}),i.add[this.pathAttr]&&(r={...r,...i.add})),Object.keys(s).length>0){await checkIsOu()||await this.checkDeptLink(s)}if(Object.keys(r).length>0){await checkIsOu()&&await this.checkDeptPath(r,t)}return[t,i,a,e]},ldapdeleterequest:async([t,i])=>{const a=Array.isArray(t)?t:[t];for(const t of a)/^\s*ou\s*=/i.test(t)&&await this.isEmptyOrganization(t);return[t,i]},ldaprenamerequest:([t,i,a])=>[t,i,a]},this.sizeLimitWarned=new Set,!this.config.ldap_top_organization)throw new Error("Missing --ldap-top-organization");if(this.pathAttr=this.config.ldap_organization_path_attribute,this.linkAttr=this.config.ldap_organization_link_attribute,t.ldap.declareObjectClasses(this.config.ldap_top_organization,this.config.ldap_organization_class||[],!0),this.config.organization_schema){const t=this.config.organization_schema;O(t,{config:this.config}).then(t=>{this.schema=t,this.server.ldap.knowAttributeNames(Object.keys(t.attributes)),this.logger.debug("Organization schema loaded")}).catch(i=>this.logger.error(`Failed to load organization schema from ${t}: ${i}`))}}api(t){t.get(`${this.config.api_prefix}/v1/ldap/organizations/top`,async(t,i)=>{await a(i,async()=>this.hideNeverReturn(await this.getOrganisationTop(t)))}),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn`,async(t,i)=>{const e=decodeURIComponent(t.params.dn);await a(i,async()=>this.hideNeverReturn(await this.getOrganisationByDn(e,t)))}),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn/subnodes`,async(t,i)=>{const e=decodeURIComponent(t.params.dn);await a(i,async()=>this.hideNeverReturn(await this.getOrganisationSubnodes(e,t)))}),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn/subnodes/search`,r(async(t,i)=>{const e=decodeURIComponent(t.params.dn),n=t.query.q;if(!n)throw new y('query parameter "q" is required');await a(i,async()=>this.hideNeverReturn(await this.searchOrganisationSubnodes(e,n,t)))})),t.get(`${this.config.api_prefix}/v1/ldap/organizations/:dn/search`,r(async(t,i)=>{const e=decodeURIComponent(t.params.dn),n=t.query.q;if(!n)throw new y('query parameter "q" is required');await a(i,async()=>this.hideNeverReturn(await this.searchOrganisationTree(e,n,t)))})),t.post(`${this.config.api_prefix}/v1/ldap/organizations`,r(async(t,i)=>this.apiAdd(t,i))),t.put(`${this.config.api_prefix}/v1/ldap/organizations/:dn`,r(async(t,i)=>this.apiModify(t,i))),t.delete(`${this.config.api_prefix}/v1/ldap/organizations/:dn`,r(async(t,i)=>this.apiDelete(t,i))),t.post(`${this.config.api_prefix}/v1/ldap/organizations/:dn/move`,r(async(t,i)=>this.apiMove(t,i)))}async apiAdd(t,i){const a=e(t,i,"ou");if(!a)return;A(this.schema,Object.keys(a),"ou"),o(a.ou,"ou");const s=a.parentDn||this.config.ldap_top_organization,r=`ou=${h(a.ou)},${s}`,c={ou:a.ou,...Object.fromEntries(Object.entries(a).filter(([t])=>"ou"!==t&&"parentDn"!==t)),objectClass:this.config.ldap_organization_class};await n(i,this.addOrganization.bind(this),r,c,t)}async apiModify(t,a){const s=e(t,a);if(!s)return;i(s);const r=decodeURIComponent(t.params.dn);if(!r)throw new y("dn is required");A(this.schema,C(s)),await n(a,this.modifyOrganization.bind(this),r,s,t)}async apiDelete(t,i){if(!s(t,i))return;const a=decodeURIComponent(t.params.dn);if(!a)throw new y("dn is required");await n(i,this.deleteOrganization.bind(this),a,t)}async apiMove(t,i){if(!s(t,i))return;const n=e(t,i,"targetOrgDn");if(!n)return;const r=decodeURIComponent(t.params.dn);if(!r)throw new y("dn is required");const{targetOrgDn:o}=n;if(!o||"string"!=typeof o)throw new y("Missing or invalid targetOrgDn in request body");await a(i,this.moveOrganization.bind(this),r,o,t)}async checkDeptLink(t){if(t[this.linkAttr]){const i=t[this.linkAttr],a=Array.isArray(i)?i[0]:i,e=await this.server.ldap.system.search({paged:!1,scope:"base"},a);if(0===e.searchEntries.length)throw new b(`Organization ${a} does not exist`);if(!new RegExp(`(.*,)?${this.config.ldap_top_organization}`).test(e.searchEntries[0].dn))throw new y(`Entry ${a} isn't in top organization branch`)}}async checkDeptPath(t,i){if(t[this.pathAttr]){const a=t[this.pathAttr],e=Array.isArray(a)?a[0]:a,n=this.config.ldap_organization_path_separator||" / ",s=this.config.ldap_top_organization||"",r=i&&s&&/^ou=/i.test(c(i))&&d(i,s)?l(i):void 0,o=t.ou,h=(Array.isArray(o)?o[0]:o)||r;let f=e;if((this.isOu(t)||void 0!==r)&&h){const t=s?l(s):"";if(t&&e.startsWith(h+n)&&e.endsWith(n+t))return;if(e===h){const t=s?g(s):"";if(!i||!t||!d(i,s)||g(i)===t||g(p(i))===t)return;throw new y(`Organization path "${e}" names no parent, but ${i} is not directly under ${s}`)}if(!e.endsWith(n+h))throw new y(`Organization path must end with its own name, preceded by separator "${n}"`);f=e.slice(0,e.length-n.length-h.length)}const w=await this.server.ldap.system.search({paged:!1,scope:"sub",filter:`(${this.pathAttr}=${u(f)})`,attributes:["dn"]},this.config.ldap_top_organization);if(!w.searchEntries||0===w.searchEntries.length)throw new y(`Invalid organization path ${e}: no organization holds "${f}"`)}}async isEmptyOrganization(t){if((await this.server.ldap.system.search({paged:!1,filter:`(${this.config.ldap_organization_link_attribute}=${u(t)})`})).searchEntries.length>0)throw new $(`Organization ${t} is not empty`)}isOu(t){if(!t.objectClass)return!1;const i=[].concat(t.objectClass).map(t=>String(t).toLowerCase());return this.config.ldap_organization_class.filter(t=>"top"!==t.toLowerCase()).some(t=>i.includes(t.toLowerCase()))}async getOrganisationTop(t){if(!this.config.ldap_top_organization)throw new y("No top organization configured");const i=await this.server.ldap.search({paged:!1,scope:"base"},this.config.ldap_top_organization,t);if(1!==i.searchEntries.length)throw new b("Top organization not found");const[,a]=await f(this.registeredHooks.getOrganisationTop,[t,i.searchEntries[0]]);return a}async getOrganisationByDn(t,i){let a;try{a=await this.server.ldap.search({paged:!1,scope:"base",filter:"(objectClass=organizationalUnit)"},t,i)}catch(i){const a=v(i);if(32===a)throw new b(`Organization ${t} not found`);if(34===a)throw new y(`${t} is not a valid DN`);throw i}if(1!==a.searchEntries.length)throw new b(`Organization ${t} not found`);return a.searchEntries[0]}async getOrganisationSubnodes(t,i){const a=[],e=this.config.ldap_organization_max_subnodes||50,n=i?.query?.objectClass;n&&"organizationalUnit"!==n||a.push(...await this.childOrganizations(t,"(objectClass=organizationalUnit)",e,i));const s=this.config.ldap_top_organization,r=p(s);let o=`(${this.config.ldap_organization_link_attribute}=${u(t)})`;return n&&(o=`(&${o}(objectClass=${u(n)}))`),this.server.logger.debug(`Searching for linked entities with filter: ${o} in ${r}`),a.push(...await this.linkedEntities(r,o,e,t,i)),a}warnSizeLimit(t,i){this.sizeLimitWarned.has(t)?this.server.logger.debug(i):(this.sizeLimitWarned.size<LdapOrganizations.SIZE_LIMIT_WARNED_MAX&&this.sizeLimitWarned.add(t),this.server.logger.warn(i))}static moreIndicator(t,i,a,e){return{dn:t,cn:[i],objectClass:["moreIndicator"],_isMoreIndicator:"true",...void 0===e?{}:{_totalCount:e.toString()},_displayedCount:a.toString()}}async childOrganizations(t,i,a,e){try{const a=await this.server.ldap.search({paged:!0,scope:"one",filter:i},t,e),n=[];for await(const t of a)n.push(...t.searchEntries);return this.server.logger.debug(`Found ${n.length} sub-OUs for ${t}`),n}catch(i){const a=v(i);if(32===a)return this.server.logger.debug(`No sub-OUs for ${t}: the node holds none`),[];if(34===a)throw new y(`${t} is not a valid DN`);if(4!==a)throw i}const n=(await this.server.ldap.search({paged:!1,scope:"one",filter:i,sizeLimit:a+1},t,e)).searchEntries.slice(0,a);return this.warnSizeLimit(`children:${t}`,`Organization ${t} holds more child organizations than the directory will list in one answer, so ${n.length} are returned and the rest are hidden. Raise the size limit for the account ldap-rest binds as (olcLimits, or olcSizeLimit) to list them all.`),[...n,LdapOrganizations.moreIndicator(`more-organizations-${t}`,"... more organizations than the directory will list",n.length)]}async linkedEntities(t,i,a,e,n){const s=[];let r=0;try{const e=await this.server.ldap.search({paged:!0,filter:i},t,n);for await(const t of e){r+=t.searchEntries.length;const i=a-s.length;i>0&&s.push(...t.searchEntries.slice(0,i))}}catch(s){if(t!==e&&(w(s)||403===s?.statusCode))return this.linkedEntities(e,i,a,e,n);if(4!==v(s))throw s;const r=await this.server.ldap.search({paged:!1,filter:i,sizeLimit:a+1},t,n);this.warnSizeLimit(`linked:${e}`,`More entries are attached to ${e} than the directory will list in one answer. Raise the size limit for the account ldap-rest binds as (olcLimits, or olcSizeLimit) to count them all.`);const o=r.searchEntries.slice(0,a);return[...o,LdapOrganizations.moreIndicator(`more-${e}`,"... more elements than the directory will list",o.length)]}return this.server.logger.debug(`Found ${r} linked entities for ${e}, returning ${s.length}`),r<=a?s:[...s,LdapOrganizations.moreIndicator(`more-${e}`,`... ${r-a} more ${r-a===1?"element":"elements"}`,a,r)]}async addOrganization(t,i,a){return L(this.schema,i),await this.server.ldap.authorize("ldapaddrequest",[t,i,a]),await this.validator().validateNew(i),await this.server.ldap.add(t,i,a)}async modifyOrganization(t,i,a){return await this.server.ldap.authorize("ldapmodifyrequest",[t,i,this.opNumber(),a]),await this.validator().validateChanges(i),await this.server.ldap.modify(t,i,a)}validator(){return new k(this.schema,{entryExists:t=>this.entryExists(t),loadedPlugins:this.server.loadedPlugins,singularName:"organization"})}async entryExists(t){try{return(await this.server.ldap.system.search({paged:!1,scope:"base",attributes:["dn"]},t)).searchEntries.length>0}catch{return!1}}async moveOrganization(t,i,a){const e=`${c(t)},${i}`;let n,s;await this.server.ldap.authorize("ldaprenamerequest",[t,e,a]);try{n=await this.server.ldap.system.search({paged:!1,scope:"base"},i)}catch(t){throw new b(`Target organization ${i} not found: ${t instanceof Error?t.message:String(t)}`)}if(!n.searchEntries||0===n.searchEntries.length)throw new b(`Target organization ${i} not found`);if(!this.isOu(n.searchEntries[0]))throw new y(`Target ${i} is not an organizational unit`);try{s=await this.server.ldap.system.search({paged:!1,scope:"base"},t)}catch(t){throw new b(`Source organization not found: ${t}`)}if(!s.searchEntries||0===s.searchEntries.length)throw new b(`Source organization ${t} not found`);if(e===t)throw new y("Cannot move organization to its current location");if(i.toLowerCase()===t.toLowerCase()||m(i,t))throw new y("Cannot move organization into itself or its descendant");try{await this.server.ldap.rename(t,e,a),this.logger.info(`Moved organization from ${t} to ${e}`)}catch(t){if(t instanceof _)throw t;throw new Error(`Failed to move organization: ${t}`)}return{newDn:e}}async deleteOrganization(t,i){try{return await this.server.ldap.delete(t,i)}catch(i){if(32===v(i))throw new b(`Organization ${t} not found`);throw i}}async searchOrganisationSubnodes(t,i,a){const e=[],n=this.config.ldap_organization_max_subnodes||50;e.push(...await this.childOrganizations(t,`(&(objectClass=organizationalUnit)${z(i,"ou,description")})`,n,a));const s=this.config.ldap_top_organization,r=p(s),o=u(t),h=this.config.display_name_attribute||"displayName",c=`(&(${this.config.ldap_organization_link_attribute}=${o})${z(i,`uid,cn,mail,sn,givenName,${h}`)})`;return this.server.logger.debug(`Searching for linked entities with filter: ${c} in ${r}`),e.push(...await this.linkedEntities(r,c,n,t,a)),e}async searchOrganisationTree(t,i,a){const e=this.config.ldap_organization_max_subnodes||50,n=this.pathAttr?`ou,description,${this.pathAttr}`:"ou,description",s=`(&(objectClass=organizationalUnit)${z(i,n)})`,r=[];let o=0;try{const i=await this.server.ldap.search({paged:!0,scope:"sub",filter:s},t,a);for await(const t of i){o+=t.searchEntries.length;const i=e-r.length;i>0&&r.push(...t.searchEntries.slice(0,i))}}catch(i){const n=v(i);if(32===n)return this.server.logger.debug(`No organizations under ${t}: no such node`),[];if(34===n)throw new y(`${t} is not a valid DN`);if(4!==n)throw i;const r=(await this.server.ldap.search({paged:!1,scope:"sub",filter:s,sizeLimit:e+1},t,a)).searchEntries.slice(0,e);return this.warnSizeLimit(`search:${t}`,`A search under ${t} matched more organizations than the directory will list in one answer, so ${r.length} are returned and the rest are hidden. Raise the size limit for the account ldap-rest binds as (olcLimits, or olcSizeLimit) to search them all.`),[...r,LdapOrganizations.moreIndicator(`more-organizations-${t}`,"... more organizations than the directory will list",r.length)]}if(o<=e)return r;const h=o-e;return[...r,LdapOrganizations.moreIndicator(`more-organizations-${t}`,`... ${h} more ${1===h?"organization":"organizations"}, narrow the search`,e,o)]}getConfigApiData(){const t=this.config.api_prefix||"/api",i=this.config.organization_schema?E(this.server,this.config.organization_schema):void 0;return{enabled:!0,topOrganization:this.config.ldap_top_organization||"",organizationClass:this.config.ldap_organization_class||["top","organizationalUnit"],linkAttribute:this.linkAttr||"",pathAttribute:this.pathAttr||"",pathSeparator:this.config.ldap_organization_path_separator||" / ",maxSubnodes:this.config.ldap_organization_max_subnodes||50,schema:this.schema,schemaUrl:i,endpoints:{getTop:`${t}/v1/ldap/organizations/top`,get:`${t}/v1/ldap/organizations/:dn`,getSubnodes:`${t}/v1/ldap/organizations/:dn/subnodes`,searchSubnodes:`${t}/v1/ldap/organizations/:dn/subnodes/search`,search:`${t}/v1/ldap/organizations/:dn/search`,create:`${t}/v1/ldap/organizations`,update:`${t}/v1/ldap/organizations/:dn`,move:`${t}/v1/ldap/organizations/:dn/move`,delete:`${t}/v1/ldap/organizations/:dn`}}}}LdapOrganizations.SIZE_LIMIT_WARNED_MAX=500;export{LdapOrganizations as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createServer as e}from"node:http";import{Registry as t,collectDefaultMetrics as s,Gauge as o}from"prom-client";import r from"../abstract/plugin.js";import{registry as i}from"../lib/metrics.js";class Metrics extends r{constructor(e){super(e),this.name="metrics",this.own=new t,s({register:this.own});const r=new o({name:"ldap_rest_ldap_pool_connections",help:"Pooled directory connections, by state",labelNames:["state"],registers:[this.own],collect:()=>{const e=this.server.ldap.poolStats();r.set({state:"busy"},e.busy),r.set({state:"idle"},e.idle)}}),n=new o({name:"ldap_rest_ldap_pool_waiting",help:"Operations waiting for a pooled directory connection",registers:[this.own],collect:()=>{n.set(this.server.ldap.poolStats().waiting)}}),a=new o({name:"ldap_rest_ldap_pool_max",help:"Pooled directory connections at most, --ldap-pool-size",registers:[this.own],collect:()=>{a.set(this.server.ldap.poolStats().max)}});this.exposed=t.merge([i,this.own])}async api(t){const s=e((e,t)=>{this.answer(e,t)});await new Promise((e,t)=>{s.once("error",t),s.listen(this.config.metrics_port,()=>{s.off("error",t),e()})}),this.listener=s,this.logger.notice(`Metrics served on port ${this.port()}`)}port(){const e=this.listener?.address();return e&&"object"==typeof e?e.port:void 0}async answer(e,t){if("GET"!==e.method||"/metrics"!==e.url?.split("?")[0])return t.statusCode=404,void t.end();try{const e=await this.exposed.metrics();t.setHeader("Content-Type",this.exposed.contentType),t.end(e)}catch(e){this.logger.warn(`Metrics not collected: ${e instanceof Error?e.message:String(e)}`),t.statusCode=500,t.end()}}async close(){const e=this.listener;e&&(this.listener=void 0,e.closeAllConnections(),await new Promise(t=>e.close(()=>t())))}}export{Metrics as default};
|
package/dist/plugins/rabbitmq.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"../abstract/plugin.js";import{
|
|
1
|
+
import t from"../abstract/plugin.js";import{outsideAnyRequest as i}from"../lib/requestContext.js";class RabbitMq extends t{constructor(t){super(t),this.name="rabbitmq",this.client=null,this.clientInit=null,this.closed=!1,this.rabbitmqUrl=this.config.rabbitmq_url||"",this.rabbitmqUrl||this.logger.warn(`${this.name}: rabbitmq_url is empty — AMQP publishes/subscribes will be skipped`)}isAvailable(){return this.rabbitmqUrl.length>0}health(){return this.rabbitmqUrl?this.client?.isConnected()?"ok":"degraded":"ok"}async publish(t,i,e,r){const n=await this.getClient();n&&await n.publish(t,i,e,r)}async subscribe(t,i,e,r,n){const s=await this.getClient();s&&await s.subscribe(t,i,e,r,n)}async unsubscribe(t){const i=await this.getClient();i&&await i.unsubscribe(t)}async getRawClient(){return this.getClient()}async getClient(){return this.client?this.client:!this.rabbitmqUrl||this.closed?null:(this.clientInit||(this.clientInit=(async()=>{try{const t=await i(()=>this.connect());return this.closed?(await t.close().catch(()=>{}),null):(this.client=t,this.logger.info(`${this.name}: connected to RabbitMQ at ${function(t){try{const i=new URL(t);return i.username="",i.password="",i.toString()}catch{return"amqp://[broker]"}}(this.rabbitmqUrl)}`),t)}catch(t){return this.logger.warn({plugin:this.name,event:"rabbitmq_init",message:"@linagora/rabbitmq-client unavailable or broker unreachable — AMQP disabled",error:`${t}`}),this.clientInit=null,null}})()),this.clientInit)}async connect(){const{RabbitMQClient:t}=await import("@linagora/rabbitmq-client");return this.open(t)}async open(t){const i=new t({url:this.rabbitmqUrl,logger:this.clientLogger()});return await i.init(),i}clientLogger(){const write=t=>(i,e)=>{const{error:r,...n}="object"==typeof e&&null!==e?e:{};this.logger.log(t,i,{plugin:this.name,...n,...void 0!==r&&{error:describeError(r)}})};return{debug:write("debug"),info:write("info"),warn:write("warn"),error:write("error")}}async close(){this.closed=!0;const t=this.client;this.client=null,this.clientInit=null,t&&await t.close().catch(t=>{this.logger.warn({plugin:this.name,event:"shutdown",error:`${t}`})})}}function describeError(t){if(!(t instanceof Error))return t;const{errors:i,code:e}=t;return Array.isArray(i)&&i.length?i.map(describeError).join("; "):t.message||"string"!=typeof e?String(t):`${t.name}: ${e}`}export{RabbitMq as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"fs";import{assertIdentityMode as s,identityFor as r}from"../../lib/auth/base.js";import{
|
|
1
|
+
import e from"fs";import{assertIdentityMode as s,identityFor as r}from"../../lib/auth/base.js";import{fillPattern as t,escapeDnValue as a,isChildOf as o}from"../../lib/utils.js";class BaseResolver{constructor(r){s(r,"scim base resolver"),this.config=r;const t=r.ldap_base||"";this.defaultUserBase=r.scim_user_base||t,this.defaultGroupBase=r.scim_group_base||t,this.userTemplate=r.scim_user_base_template||"",this.groupTemplate=r.scim_group_base_template||"",this.userBaseHeader=(r.scim_user_base_header||"").toLowerCase(),this.groupBaseHeader=(r.scim_group_base_header||"").toLowerCase(),this.headerRoot=r.scim_base_header_root||"";const a=r.scim_base_map||"";if(a)try{const s=e.readFileSync(a,"utf8");this.map=JSON.parse(s)}catch(e){throw new Error(`Failed to load SCIM base map from ${a}: ${e instanceof Error?e.message:String(e)}`)}}applyTemplate(e,s){return t(e,"{user}",s?a(s):"")}readHeader(e,s){if(!e||"object"!=typeof e)return;const r=e;if("function"==typeof r.get){const e=r.get(s);if("string"==typeof e&&e.length>0)return e}const t=r.headers?.[s];return"string"==typeof t&&t.length>0?t:Array.isArray(t)&&"string"==typeof t[0]&&t[0].length>0?t[0]:void 0}resolve(e,s){const t=s&&"object"==typeof s?r(s,this.config).value:void 0;if(this.map&&t&&this.map[t]){const s=this.map[t];if("user"===e&&s.userBase)return s.userBase;if("group"===e&&s.groupBase)return s.groupBase}const a="user"===e?this.userBaseHeader:this.groupBaseHeader;if(a&&this.headerRoot){const e=this.readHeader(s,a)?.trim();if(e&&!/[\u0000-\u001f\u007f]/.test(e)&&(e.toLowerCase()===this.headerRoot.toLowerCase()||o(e,this.headerRoot)))return e}if(this.map&&this.map["*"]){const s=this.map["*"];if("user"===e&&s.userBase)return this.applyTemplate(s.userBase,t);if("group"===e&&s.groupBase)return this.applyTemplate(s.groupBase,t)}const i="user"===e?this.userTemplate:this.groupTemplate;return i?this.applyTemplate(i,t):"user"===e?this.defaultUserBase:this.defaultGroupBase}userBase(e){return this.resolve("user",e)}groupBase(e){return this.resolve("group",e)}}export{BaseResolver};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{launchHooks as t}from"../../lib/utils.js";import{SCHEMA_BULK_RESPONSE as
|
|
1
|
+
import{launchHooks as t}from"../../lib/utils.js";import{SCHEMA_BULK_RESPONSE as e}from"./types.js";import{scimInvalidValue as s,kindOf as o,scimErrorFromException as r}from"./errors.js";export{writeScimErrorFromException}from"./errors.js";const i=/^bulkId:([A-Za-z0-9_-]+)$/;class ScimBulk{constructor(t){this.config=t.config,this.logger=t.logger,this.users=t.users,this.groups=t.groups,this.scimPrefix=t.scimPrefix,this.hooks=t.hooks}async execute(o,r){const i=this.config.scim_bulk_max_operations||100;if(!r.Operations||!Array.isArray(r.Operations))throw s("Missing Operations array");if(r.Operations.length>i)throw s(`Too many operations: ${r.Operations.length} (max ${i})`);const a=new Map,n=[];let c=0;const h=r.failOnErrors??0;for(const t of r.Operations){if(h>0&&c>=h)break;const e=await this.executeOne(o,t,a);n.push(e),parseInt(e.status,10)>=400&&c++}const u={schemas:[e],Operations:n};return t(this.hooks.scimbulkdone,u),u}async executeOne(t,e,a){const n=!!e&&"object"==typeof e&&!Array.isArray(e),c={method:n?e.method:void 0,bulkId:n?e.bulkId:void 0,status:"200"};try{if(!n)throw s(`Each operation must be an object, got ${o(e)}`);if("string"!=typeof e.method||"string"!=typeof e.path)throw s("method and path are required, as strings");if("DELETE"!==e.method&&(!e.data||"object"!=typeof e.data||Array.isArray(e.data)))throw s(`data must be an object, got ${o(e.data)}`);e.data&&"object"==typeof e.data&&this.resolveRefs(e.data,a);const r=e.path.replace(/^\//,"").split("/"),h=r[0],u=r[1];if("Users"!==h&&"Groups"!==h)throw s(`Unsupported bulk path '${e.path}'`);const d="Users"===h;let p=u;if(p&&i.test(p)){const t=i.exec(p),e=a.get(t[1]);if(!e)throw s(`Unknown bulkId reference '${t[1]}'`);p=e.id}switch(e.method){case"POST":{if(p)throw s("POST must not include an id");const o=d?await this.users.create(t,e.data):await this.groups.create(t,e.data);return c.status="201",c.location=this.buildLocation(h,o.id,t),c.version=o.meta?.version||void 0,e.bulkId&&a.set(e.bulkId,{id:o.id,type:d?"User":"Group"}),c}case"PUT":{if(!p)throw s("PUT requires an id");const o=d?await this.users.replace(t,p,e.data):await this.groups.replace(t,p,e.data);return c.status="200",c.location=this.buildLocation(h,o.id,t),c}case"PATCH":{if(!p)throw s("PATCH requires an id");const o=d?await this.users.patch(t,p,e.data):await this.groups.patch(t,p,e.data);return c.status="200",c.location=this.buildLocation(h,o.id,t),c}case"DELETE":if(!p)throw s("DELETE requires an id");return d?await this.users.delete(t,p):await this.groups.delete(t,p),c.status="204",c;default:throw s(`Unsupported method '${String(e.method)}'`)}}catch(t){const e=r(t);return c.status=e.status,c.response=e,c}}resolveRefs(t,e,o=0){if(o>64)throw s("Operation data nested too deeply");for(const[s,r]of Object.entries(t)){if("string"==typeof r){const o=i.exec(r);if(o){const r=e.get(o[1]);r&&(t[s]=r.id)}continue}if(Array.isArray(r)){const t=r;for(let s=0;s<t.length;s++){const r=t[s];if("string"==typeof r){const o=i.exec(r);if(o){const r=e.get(o[1]);r&&(t[s]=r.id)}}else r&&"object"==typeof r&&this.resolveRefs(r,e,o+1)}continue}r&&"object"==typeof r&&this.resolveRefs(r,e,o+1)}}buildLocation(t,e,s){const o=this.config.scim_base_url||"";return`${o?o.replace(/\/$/,""):s?.protocol&&s.get?`${s.protocol}://${String(s.get("host")||"")}`:""}${this.scimPrefix}/${t}/${encodeURIComponent(e)}`}}export{ScimBulk};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HttpError as r,AUTHZ_REFUSED as t}from"../../lib/errors.js";import{isSchemaRefusal as e,extractLdapCode as i}from"../../lib/ldapCodes.js";import{SCHEMA_ERROR as
|
|
1
|
+
import{HttpError as r,AUTHZ_REFUSED as t}from"../../lib/errors.js";import{isSchemaRefusal as e,extractLdapCode as i}from"../../lib/ldapCodes.js";import{SCHEMA_ERROR as n}from"./types.js";const o="application/scim+json";class ScimError extends r{constructor(r,t,e){super(t,r),this.name="ScimError",this.scimType=e}}const kindOf=r=>{if(null===r)return"null";if(Array.isArray(r))return"an array";const t=typeof r;return`${/^[aeiou]/.test(t)?"an":"a"} ${t}`},scimInvalidFilter=(r="Invalid filter")=>new ScimError(400,r,"invalidFilter"),scimInvalidPath=(r="Invalid path")=>new ScimError(400,r,"invalidPath"),scimInvalidValue=(r="Invalid value")=>new ScimError(400,r,"invalidValue"),scimInvalidSyntax=(r="Invalid syntax")=>new ScimError(400,r,"invalidSyntax"),scimNoTarget=(r="No target")=>new ScimError(400,r,"noTarget"),scimMutability=(r="Immutable attribute")=>new ScimError(400,r,"mutability"),scimUniqueness=(r="Uniqueness violation")=>new ScimError(409,r,"uniqueness"),scimTooMany=(r="Too many results")=>new ScimError(400,r,"tooMany"),scimNotFound=(r="Resource not found")=>new ScimError(404,r);function writeScimError(r,t,e,i){const s={schemas:[n],status:String(t),...i?{scimType:i}:{},detail:e};r.status(t).type(o).json(s)}function scimErrorFromException(o,s=500){const sanitize=r=>/\[authz-forbidden\]/.test(r)?t:r,body=(r,t,e)=>({schemas:[n],status:String(r),...e?{scimType:e}:{},detail:t});if(o instanceof ScimError)return body(o.statusCode,sanitize(o.message),o.scimType);if(o instanceof r){const r=400===o.statusCode&&e(i(o))?"invalidValue":void 0;return body(o.statusCode,sanitize(o.message),r)}const a=o instanceof Error?o.message:String(o);if(/\[authz-forbidden\]/.test(a))return body(403,t);const c=i(o);return 32===c?body(404,"Resource not found"):68===c?body(409,sanitize(a),"uniqueness"):e(c)?body(400,`The directory rejected this write against its schema: ${sanitize(a)}`,"invalidValue"):body(s,sanitize(a)||"Internal error")}function writeScimErrorFromException(r,t,e=500){const i=scimErrorFromException(t,e);r.status(Number(i.status)).type(o).json(i)}const scimAsyncHandler=r=>(t,e,i)=>{Promise.resolve().then(()=>r(t,e,i)).catch(r=>{e.headersSent?i(r):writeScimErrorFromException(e,r)})};export{o as SCIM_CONTENT_TYPE,ScimError,i as extractLdapCode,kindOf,scimAsyncHandler,scimErrorFromException,scimInvalidFilter,scimInvalidPath,scimInvalidSyntax,scimInvalidValue,scimMutability,scimNoTarget,scimNotFound,scimTooMany,scimUniqueness,writeScimError,writeScimErrorFromException};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{escapeLdapFilter as t}from"../../lib/utils.js";import{scimPathToLdapAttribute as e,DEFAULT_LOCK_ATTRIBUTE as s,DEFAULT_LOCK_VALUE as o}from"./mapping.js";import{scimInvalidFilter as n}from"./errors.js";const r=new Set(["and","or","not","pr","eq","ne","co","sw","ew","gt","ge","lt","le","true","false","null"]);const i="\0active";class Parser{constructor(t,e,s={}){this.tokens=t,this.mapping=e,this.opts=s,this.pos=0}peek(t=0){return this.tokens[this.pos+t]}consume(){return this.tokens[this.pos++]}expect(t,e){const s=this.tokens[this.pos];if(s.kind!==t||e&&s.value.toLowerCase()!==e)throw n(`Expected ${e||t} at position ${s.pos}, got '${s.value}'`);return this.pos++,s}parse(){const t=this.parseOr();if("EOF"!==this.peek().kind)throw n(`Unexpected token '${this.peek().value}' at position ${this.peek().pos}`);return t}parseOr(){const t=[this.parseAnd()];for(;"WORD"===this.peek().kind&&"or"===this.peek().value.toLowerCase();)this.consume(),t.push(this.parseAnd());return 1===t.length?t[0]:`(|${t.join("")})`}parseAnd(){const t=[this.parseNot()];for(;"WORD"===this.peek().kind&&"and"===this.peek().value.toLowerCase();)this.consume(),t.push(this.parseNot());return 1===t.length?t[0]:`(&${t.join("")})`}parseNot(){if("WORD"===this.peek().kind&&"not"===this.peek().value.toLowerCase()){this.consume();return`(!${this.parsePrimary()})`}return this.parsePrimary()}parsePrimary(){const t=this.peek();if("LPAREN"===t.kind){this.consume();const t=this.parseOr();return this.expect("RPAREN"),t}if("WORD"===t.kind){const t=this.consume().value;if("LBRACK"===this.peek().kind)throw n(`Complex multi-valued filters ('${t}[...]') are not supported; use 'and' at top level instead`);const e=this.consume();if("WORD"!==e.kind)throw n(`Expected comparison operator at position ${e.pos}`);const s=e.value.toLowerCase();if("pr"===s){const e=this.resolvePath(t);return e===i?"(objectClass=*)":`(${e}=*)`}if(!r.has(s)||["and","or","not"].includes(s))throw n(`Unknown operator '${e.value}' at position ${e.pos}`);const o=this.consume(),a=this.tokenToValue(o);return this.emitComparison(t,s,a)}throw n(`Unexpected token '${t.value}' at position ${t.pos}`)}tokenToValue(t){if("STRING"===t.kind)return t.value;if("NUMBER"===t.kind){const e=Number(t.value);if(Number.isNaN(e))throw n(`Invalid number '${t.value}' at position ${t.pos}`);return e}if("WORD"===t.kind){const e=t.value.toLowerCase();return"true"===e||"false"!==e&&("null"===e?null:t.value)}throw n(`Unexpected value token at position ${t.pos}`)}resolvePath(t){if("id"===t)throw n("filter on 'id' only supports 'eq' with a string value");if("active"===t&&this.opts.supportsActive)return i;const s=e(t,this.mapping);if(!s)throw n(`Unknown attribute path '${t}'`);return s}emitComparison(e,r,a){const
|
|
1
|
+
import{escapeLdapFilter as t}from"../../lib/utils.js";import{scimPathToLdapAttribute as e,DEFAULT_LOCK_ATTRIBUTE as s,DEFAULT_LOCK_VALUE as o}from"./mapping.js";import{scimInvalidFilter as n}from"./errors.js";const r=new Set(["and","or","not","pr","eq","ne","co","sw","ew","gt","ge","lt","le","true","false","null"]);const i="\0active";class Parser{constructor(t,e,s={}){this.tokens=t,this.mapping=e,this.opts=s,this.pos=0,this.depth=0}peek(t=0){return this.tokens[this.pos+t]}consume(){return this.tokens[this.pos++]}expect(t,e){const s=this.tokens[this.pos];if(s.kind!==t||e&&s.value.toLowerCase()!==e)throw n(`Expected ${e||t} at position ${s.pos}, got '${s.value}'`);return this.pos++,s}parse(){const t=this.parseOr();if("EOF"!==this.peek().kind)throw n(`Unexpected token '${this.peek().value}' at position ${this.peek().pos}`);return t}parseOr(){const t=[this.parseAnd()];for(;"WORD"===this.peek().kind&&"or"===this.peek().value.toLowerCase();)this.consume(),t.push(this.parseAnd());return 1===t.length?t[0]:`(|${t.join("")})`}parseAnd(){const t=[this.parseNot()];for(;"WORD"===this.peek().kind&&"and"===this.peek().value.toLowerCase();)this.consume(),t.push(this.parseNot());return 1===t.length?t[0]:`(&${t.join("")})`}parseNot(){if("WORD"===this.peek().kind&&"not"===this.peek().value.toLowerCase()){this.consume();return`(!${this.nested(()=>this.parsePrimary())})`}return this.parsePrimary()}nested(t){if(++this.depth>32)throw n("Filter nested too deeply");try{return t()}finally{this.depth--}}parsePrimary(){const t=this.peek();if("LPAREN"===t.kind){this.consume();const t=this.nested(()=>this.parseOr());return this.expect("RPAREN"),t}if("WORD"===t.kind){const t=this.consume().value;if("LBRACK"===this.peek().kind)throw n(`Complex multi-valued filters ('${t}[...]') are not supported; use 'and' at top level instead`);const e=this.consume();if("WORD"!==e.kind)throw n(`Expected comparison operator at position ${e.pos}`);const s=e.value.toLowerCase();if("pr"===s){const e=this.resolvePath(t);return e===i?"(objectClass=*)":`(${e}=*)`}if(!r.has(s)||["and","or","not"].includes(s))throw n(`Unknown operator '${e.value}' at position ${e.pos}`);const o=this.consume(),a=this.tokenToValue(o);return this.emitComparison(t,s,a)}throw n(`Unexpected token '${t.value}' at position ${t.pos}`)}tokenToValue(t){if("STRING"===t.kind)return t.value;if("NUMBER"===t.kind){const e=Number(t.value);if(Number.isNaN(e))throw n(`Invalid number '${t.value}' at position ${t.pos}`);return e}if("WORD"===t.kind){const e=t.value.toLowerCase();return"true"===e||"false"!==e&&("null"===e?null:t.value)}throw n(`Unexpected value token at position ${t.pos}`)}resolvePath(t){if("id"===t)throw n("filter on 'id' only supports 'eq' with a string value");if("active"===t&&this.opts.supportsActive)return i;const s=e(t,this.mapping);if(!s)throw n(`Unknown attribute path '${t}'`);return s}emitComparison(e,r,a){const p=this.resolvePath(e);if(p===i){const e=!0===a||"string"==typeof a&&"true"===a.toLowerCase(),i=this.opts.lockAttribute||s;if(!this.opts.lockValue&&i.toLowerCase()!==s.toLowerCase())throw new Error(`No lock value given for '${i}'`);const p=`(${i}=${t(this.opts.lockValue||o)})`,u=`(!${p})`;if("eq"===r)return e?u:p;if("ne"===r)return e?p:u;throw n(`Operator '${r}' not supported for 'active'`)}if(null===a){if("eq"===r)return`(!(${p}=*))`;if("ne"===r)return`(${p}=*)`;throw n(`Operator '${r}' not supported with null`)}const u=String(a),h=t(u);switch(r){case"eq":return`(${p}=${h})`;case"ne":return`(!(${p}=${h}))`;case"co":return`(${p}=*${h}*)`;case"sw":return`(${p}=${h}*)`;case"ew":return`(${p}=*${h})`;case"gt":return`(&(${p}>=${h})(!(${p}=${h})))`;case"ge":return`(${p}>=${h})`;case"lt":return`(&(${p}<=${h})(!(${p}=${h})))`;case"le":return`(${p}<=${h})`;default:throw n(`Unknown operator '${r}'`)}}}function scimFilterToLdap(t,e,s={}){const o=t.trim();if(!o)return{ldapFilter:"(objectClass=*)",touchesId:!1};const r=/^id\s+eq\s+"([^"\\]*(?:\\.[^"\\]*)*)"\s*$/i.exec(o);if(r)return{ldapFilter:"(objectClass=*)",touchesId:!0,idEquals:r[1].replace(/\\(.)/g,"$1")};const i=function(t){const e=[];let s=0;for(;s<t.length;){const o=t[s];if(" "!==o&&"\t"!==o&&"\n"!==o&&"\r"!==o)if("("!==o)if(")"!==o)if("["!==o){if("]"!==o){if('"'===o){const o=s;s++;let r="";for(;s<t.length&&'"'!==t[s];){if("\\"===t[s]&&s+1<t.length){const e=t[s+1];if('"'===e){r+='"',s+=2;continue}if("\\"===e){r+="\\",s+=2;continue}if("n"===e){r+="\n",s+=2;continue}if("t"===e){r+="\t",s+=2;continue}}r+=t[s],s++}if(s>=t.length)throw n(`Unterminated string literal at position ${o}`);s++,e.push({kind:"STRING",value:r,pos:o});continue}if(o>="0"&&o<="9"){const o=s;for(;s<t.length&&/[0-9.+\-eE]/.test(t[s])&&!/[\s()[\]]/.test(t[s]);)s++;e.push({kind:"NUMBER",value:t.slice(o,s),pos:o});continue}if(/[A-Za-z_$:]/.test(o)){const o=s;for(;s<t.length&&/[A-Za-z0-9_.$:]/.test(t[s]);)s++;e.push({kind:"WORD",value:t.slice(o,s),pos:o});continue}throw n(`Unexpected character '${o}' at position ${s}`)}e.push({kind:"RBRACK",value:"]",pos:s}),s++}else e.push({kind:"LBRACK",value:"[",pos:s}),s++;else e.push({kind:"RPAREN",value:")",pos:s}),s++;else e.push({kind:"LPAREN",value:"(",pos:s}),s++;else s++}return e.push({kind:"EOF",value:"",pos:t.length}),e}(o);return{ldapFilter:new Parser(i,e,s).parse(),touchesId:/\bid\b/.test(o)}}export{scimFilterToLdap};
|