Skip to content
Jennifer Programming Language

ldap API reference

An LDAP v3 client and a lightweight, read-only directory server (RFC 4511), over TCP with the wire messages built and parsed as ASN.1 BER (the asn1 library) on the net transport. The client binds (simple or SASL SCRAM), searches with RFC 4515 string filters, follows paged results, and unbinds; LDAPS and StartTLS reuse net's TLS. The server answers simple bind and search for an in-memory directory you build in a few lines - enough to back any LDAP client (an authentication portal such as Authelia, or an app that authenticates its users against LDAP): it validates userPassword on bind and evaluates search filters against the entries so a client can find users and read their groups.

The server is read-only over the LDAP protocol (it answers bind and search and answers add / modify / delete with unwillingToPerform), yet the in-memory directory is fully mutable from your own code: after building it you can addEntry / modifyEntry / deleteEntry / setAttribute at runtime, so a web interface or a database sync can update the directory a running server is serving. The Directory is shared mutable state (a kv-backed store shared across the serve loop's connection tasks), so a change is visible to the live server immediately. No schema enforcement, no ACLs.

Client failures throw an ldap.LdapError (kind "ldap"); one the server answered with an LDAPResult (a refused StartTLS, a failed SASL bind or search) carries its result code, matchedDn and diagnostic message. bind does not throw on bad credentials: it returns the Result.

Import with import "ldap.j" as ldap;. See the ldap guide for prose and examples.

Contents

NameWhat it is
addadd creates an entry from a DN and an attribute map, returning the Result (check .code).
addEntryaddEntry inserts an entry, replacing any existing entry with the same DN.
allOfallOf builds a conjunction: (&(f1)(f2)...).
anyOfanyOf builds a disjunction: (|(f1)(f2)...).
approxapprox builds an approximate-match (attr~=value) filter; the server treats it as equality.
bindbind performs a simple bind and returns the Result (check .code against ldap.SUCCESS / ldap.INVALID_CREDENT...
bindSaslbindSasl performs a SASL SCRAM bind (algo "sha1" -> SCRAM-SHA-1, "sha256" -> SCRAM-SHA-256), verifying the ...
changechange builds one modify change (operation is ldap.MOD_ADD / MOD_DELETE / MOD_REPLACE).
closeclose closes the connection without sending an unbind.
connectconnect opens an LDAP connection.
connectWithconnectWith is connect with TLS options for LDAPS and StartTLS, the net.TLSOptions of net.connectTLS ...
deletedelete removes an entry by DN, returning the Result.
deleteEntrydeleteEntry removes the entry with the given DN if present.
directorydirectory builds a mutable in-memory directory the server answers for - the lightweight, ephemeral default.
entryentry builds a directory entry from a DN and an attribute map (name -> values).
equalsequals builds an equality filter: (attr=value).
escapeFilterValueEscape a value for use inside an RFC 4515 filter string: \, *, (, ) and NUL become \5c, \2a,...
firstValuefirstValue returns an entry's first value for an attribute, or "" if absent.
getEntrygetEntry returns the entry with the given DN, or an empty Entry (dn == "") if absent.
greaterOrEqualgreaterOrEqual builds an (attr>=value) filter.
groupgroup builds a groupOfNames entry (objectClass + cn from the DN's RDN + member) from members.
hasEntryhasEntry reports whether an entry with the given DN exists.
lessOrEquallessOrEqual builds an (attr<=value) filter.
listEntrieslistEntries returns a snapshot of every entry currently in the directory.
listenlisten opens a listening socket for the server ("host:port"; port defaults to 389).
modifymodify applies a list of changes to an entry, returning the Result.
modifyDnmodifyDn renames or moves an entry: newRdn is the new relative DN, deleteOldRdn drops the old RDN attribute...
modifyEntrymodifyEntry replaces the entry with the same DN (an alias for addEntry).
negatenegate builds a negation: (!(f)).
openDirectoryopenDirectory opens a file-backed directory that persists across restarts (a kv.openFile store at path).
parseFilterparseFilter compiles an RFC 4515 filter string (e.g.
passwordpassword hashes a plaintext password into an LDAP userPassword value.
passwordModifypasswordModify changes a password via the RFC 3062 extended operation.
presentpresent builds a presence filter: (attr=*).
searchsearch runs a search and returns the matching entries.
searchPagedsearchPaged runs a search in pages of pageSize via the simple-paged-results control.
serveserve binds address and serves dir until the process ends (blocks).
serveOnserveOn serves dir on an already-open listener, one spawn per connection, until the listener is closed (whi...
setAttributesetAttribute creates or replaces one attribute's values on an existing entry.
startTlsstartTls upgrades a plaintext connection to TLS via the StartTLS extended operation, then hands the same ha...
startTlsWithstartTlsWith is startTls with TLS options (caCert to trust a private CA, skipVerify to accept any cer...
substringssubstrings builds a substring filter, e.g.
unbindunbind sends an unbind request and closes the connection.
valuesvalues returns an entry's values for an attribute (case-insensitive name), or an empty list.
Attributestruct: One attribute of a directory entry.
Changestruct: One change in a modify request.
Connstruct: An open LDAP connection.
Directorystruct: A mutable in-memory directory the server answers for.
Entrystruct: A directory entry.
LdapErrorstruct: A failed LDAP operation.
Resultstruct: The outcome of a bind (or any LDAPResult).
constantsthe module's constants

Functions

add

jennifer
ldap.add(
    conn as Conn,
    dn as string,
    attrs as map of string to list of string)

add creates an entry from a DN and an attribute map, returning the Result (check .code).

conn
an open, bound connection
dn
the DN of the entry to create
attrs
the entry's attributes (name -> values)
Returns Result
the operation result (check .code)
Throws LdapError
on a protocol error or a malformed reply; a net error, "timeout" or "closed" as it is

addEntry

jennifer
ldap.addEntry(dir as Directory, e as Entry)

addEntry inserts an entry, replacing any existing entry with the same DN.

dir
the directory to modify
e
the entry to insert (or replace a same-DN entry with)

allOf

jennifer
ldap.allOf(filters as list of asn1.Value)

allOf builds a conjunction: (&(f1)(f2)...).

filters
the sub-filters that must all match
Returns asn1.Value
the combined filter, for search

anyOf

jennifer
ldap.anyOf(filters as list of asn1.Value)

anyOf builds a disjunction: (|(f1)(f2)...).

filters
the sub-filters, any of which may match
Returns asn1.Value
the combined filter, for search

approx

jennifer
ldap.approx(attr as string, value as string)

approx builds an approximate-match (attr~=value) filter; the server treats it as equality.

attr
the attribute name
value
the value to match approximately
Returns asn1.Value
the encoded filter, for search

bind

jennifer
ldap.bind(conn as Conn, dn as string, password as string)

bind performs a simple bind and returns the Result (check .code against ldap.SUCCESS / ldap.INVALID_CREDENTIALS). An empty dn and password is an anonymous bind. A non-empty dn with an empty password is refused before anything is sent: RFC 4513 5.1.2 makes it an unauthenticated bind, which many servers answer with SUCCESS without checking anything.

conn
an open connection
dn
the bind DN ("" for anonymous)
password
the password ("" for anonymous)
Returns Result
the bind result (check .code) A password is never sent over an unencrypted connection (security None): such a bind is refused before anything is sent unless the Conn's allowInsecureAuth is set; connect with Tls or Starttls instead.
Throws LdapError
kind "ldap" on a protocol error or a malformed reply, a non-empty dn with an empty password, or a password over an unencrypted connection (code 0); a net error, "timeout", "closed" or "limit" as it is

bindSasl

jennifer
ldap.bindSasl(
    conn as Conn,
    algo as string,
    user as string,
    password as string)

bindSasl performs a SASL SCRAM bind (algo "sha1" -> SCRAM-SHA-1, "sha256" -> SCRAM-SHA-256), verifying the server signature. Returns the Result on success or throws on a protocol / verification failure.

conn
an open connection
algo
the SCRAM hash: "sha1" or "sha256"
user
the SCRAM authentication username
password
the user's password
Returns Result
the bind result on success
Throws LdapError
on a protocol or server-signature-verification failure

change

jennifer
ldap.change(operation as int, name as string, values as list of string)

change builds one modify change (operation is ldap.MOD_ADD / MOD_DELETE / MOD_REPLACE).

operation
ldap.MOD_ADD, MOD_DELETE, or MOD_REPLACE
name
the attribute to change
values
the values for the change (empty deletes the attribute)
Returns Change
the change, for modify

close

jennifer
ldap.close(conn as Conn)

close closes the connection without sending an unbind.

conn
the connection to close

connect

jennifer
ldap.connect(address as string, security as transport.Security)

connect opens an LDAP connection. security selects the transport: transport.Security.None is plaintext (port defaults to 389), transport.Security.Tls is LDAPS / implicit TLS (port defaults to 636), and transport.Security.Starttls connects in plaintext then upgrades in-band via the StartTLS extended operation.

address
the server "host:port" (port defaults to 389, or 636 for Tls)
security
the transport: None, Tls, or Starttls
Returns Conn
the open connection A password is refused over transport.Security.None unless the returned Conn's allowInsecureAuth is set (see bind).
Throws LdapError
on a connection or StartTLS failure

connectWith

jennifer
ldap.connectWith(
    address as string,
    security as transport.Security,
    tls as net.TLSOptions)

connectWith is connect with TLS options for LDAPS and StartTLS, the net.TLSOptions of net.connectTLS / net.startTLS: set caCert to a PEM certificate to trust a private CA or a self-signed server (it is trusted in place of the system roots, and the server is still authenticated), or skipVerify to accept any certificate (insecure: no server authentication). A zero net.TLSOptions is connect: full verification against the system roots. The options are ignored for transport.Security.None.

address
the server "host:port" (port defaults to 389, or 636 for Tls)
security
the transport: None, Tls, or Starttls
tls
the TLS verification options (caCert, skipVerify)
Returns Conn
the open connection
Throws LdapError
on a refused StartTLS; a connection or TLS handshake failure (an untrusted certificate, an invalid caCert) throws net's error

delete

jennifer
ldap.delete(conn as Conn, dn as string)

delete removes an entry by DN, returning the Result.

conn
an open, bound connection
dn
the DN of the entry to remove
Returns Result
the operation result (check .code)
Throws LdapError
on a protocol error or a malformed reply; a net error, "timeout" or "closed" as it is

deleteEntry

jennifer
ldap.deleteEntry(dir as Directory, dn as string)

deleteEntry removes the entry with the given DN if present.

dir
the directory to modify
dn
the DN of the entry to remove (matched case-insensitively)

directory

jennifer
ldap.directory(entries as list of Entry)

directory builds a mutable in-memory directory the server answers for - the lightweight, ephemeral default. Use openDirectory for one that persists.

entries
the initial entries to seed the directory with
Returns Directory
the in-memory directory

entry

jennifer
ldap.entry(dn as string, attrs as map of string to list of string)

entry builds a directory entry from a DN and an attribute map (name -> values).

dn
the entry's distinguished name
attrs
the entry's attributes (name -> values)
Returns Entry
the constructed entry

equals

jennifer
ldap.equals(attr as string, value as string)

equals builds an equality filter: (attr=value).

attr
the attribute name
value
the value to match exactly
Returns asn1.Value
the encoded filter, for search

escapeFilterValue

jennifer
ldap.escapeFilterValue(value as string)

Escape a value for use inside an RFC 4515 filter string: \, *, (, ) and NUL become \5c, \2a, \28, \29, \00. Use it for any untrusted value spliced into a filter ("(uid=" + ldap.escapeFilterValue($name) + ")"), or build the filter with equals / substrings / ..., which need no escaping.

value
the raw value
Returns string
the escaped value

firstValue

jennifer
ldap.firstValue(entry as Entry, name as string)

firstValue returns an entry's first value for an attribute, or "" if absent.

entry
the entry to read
name
the attribute name, matched case-insensitively
Returns string
the first value, or "" if the attribute has none

getEntry

jennifer
ldap.getEntry(dir as Directory, dn as string)

getEntry returns the entry with the given DN, or an empty Entry (dn == "") if absent.

dir
the directory to read
dn
the DN to look up (matched case-insensitively)
Returns Entry
the matching entry, or an empty Entry (dn == "") if absent

greaterOrEqual

jennifer
ldap.greaterOrEqual(attr as string, value as string)

greaterOrEqual builds an (attr>=value) filter.

attr
the attribute name
value
the lower bound to compare against
Returns asn1.Value
the encoded filter, for search

group

jennifer
ldap.group(dn as string, members as list of string)

group builds a groupOfNames entry (objectClass + cn from the DN's RDN + member) from members.

dn
the group's distinguished name (its RDN value becomes cn)
members
the member DNs
Returns Entry
the constructed groupOfNames entry

hasEntry

jennifer
ldap.hasEntry(dir as Directory, dn as string)

hasEntry reports whether an entry with the given DN exists.

dir
the directory to read
dn
the DN to test (matched case-insensitively)
Returns bool
true if an entry with that DN exists

lessOrEqual

jennifer
ldap.lessOrEqual(attr as string, value as string)

lessOrEqual builds an (attr<=value) filter.

attr
the attribute name
value
the upper bound to compare against
Returns asn1.Value
the encoded filter, for search

listEntries

jennifer
ldap.listEntries(dir as Directory)

listEntries returns a snapshot of every entry currently in the directory.

dir
the directory to read
Returns list of Entry
a snapshot of all current entries

listen

jennifer
ldap.listen(address as string)

listen opens a listening socket for the server ("host:port"; port defaults to 389).

address
the listen address "host:port" (port defaults to 389)
Returns net.Listener
the open listener, for serveOn
Throws LdapError
if the socket cannot be opened

modify

jennifer
ldap.modify(conn as Conn, dn as string, changes as list of Change)

modify applies a list of changes to an entry, returning the Result.

conn
an open, bound connection
dn
the DN of the entry to modify
changes
the changes to apply, from change
Returns Result
the operation result (check .code)
Throws LdapError
on a protocol error or a malformed reply; a net error, "timeout" or "closed" as it is

modifyDn

jennifer
ldap.modifyDn(
    conn as Conn,
    dn as string,
    newRdn as string,
    deleteOldRdn as bool,
    newSuperior as string)

modifyDn renames or moves an entry: newRdn is the new relative DN, deleteOldRdn drops the old RDN attribute, and newSuperior ("" to keep the parent) moves the entry under a new parent DN.

conn
an open, bound connection
dn
the DN of the entry to rename or move
newRdn
the new relative DN (e.g. "cn=bob")
deleteOldRdn
whether to drop the old RDN attribute value
newSuperior
the new parent DN, or "" to keep the current parent
Returns Result
the operation result (check .code)
Throws LdapError
on a protocol error or a malformed reply; a net error, "timeout" or "closed" as it is

modifyEntry

jennifer
ldap.modifyEntry(dir as Directory, e as Entry)

modifyEntry replaces the entry with the same DN (an alias for addEntry).

dir
the directory to modify
e
the replacement entry, keyed by its DN

negate

jennifer
ldap.negate(f as asn1.Value)

negate builds a negation: (!(f)).

f
the sub-filter to invert
Returns asn1.Value
the negated filter, for search

openDirectory

jennifer
ldap.openDirectory(path as string)

openDirectory opens a file-backed directory that persists across restarts (a kv.openFile store at path). A new file starts empty; an existing one restores its entries. Seed a fresh store on first run by checking listEntries and addEntry-ing when it is empty. Edits (addEntry / modifyEntry / ...) persist. Open a path once and share the Directory: the edit lock belongs to the returned value, so two openDirectory calls on one path do not serialise each other's edits.

path
the backing file path for the kv store
Returns Directory
the file-backed directory

parseFilter

jennifer
ldap.parseFilter(s as string)

parseFilter compiles an RFC 4515 filter string (e.g. "(&(a=1)(b=2))") into a filter value. \XX hex escapes in values are decoded (\2a is a literal *, not a wildcard); groups nest at most 64 deep. The whole string must be one filter: text after it, or an unescaped ( inside a value, is an error.

s
the RFC 4515 filter text
Returns asn1.Value
the compiled filter, for search
Throws LdapError
on a malformed filter string or one nested too deep

password

jennifer
ldap.password(scheme as string, plain as string)

password hashes a plaintext password into an LDAP userPassword value. scheme is "plain", "sha", "sha256", "ssha", "ssha256" (salted variants use a random 8-byte salt), "pbkdf2" (PBKDF2-SHA256), or "pbkdf2-sha512". Store the result as an entry's userPassword.

scheme
one of plain / sha / sha256 / ssha / ssha256 / pbkdf2 / pbkdf2-sha512
plain
the plaintext password to hash
Returns string
the encoded userPassword value (with its scheme prefix)
Throws LdapError
on an unknown scheme

passwordModify

jennifer
ldap.passwordModify(
    conn as Conn,
    userDn as string,
    oldPassword as string,
    newPassword as string)

passwordModify changes a password via the RFC 3062 extended operation. Pass userDn "" for the currently-bound user, oldPassword "" to skip the old-password check (an administrative reset), and newPassword "" to have the server generate one. Returns the Result.

conn
an open, bound connection
userDn
the target user DN, or "" for the currently-bound user
oldPassword
the current password, or "" to skip the check (admin reset)
newPassword
the new password, or "" to let the server generate one
Returns Result
the operation result (check .code)
Throws LdapError
on a protocol error or a malformed reply, or a password over an unencrypted connection without allowInsecureAuth

present

jennifer
ldap.present(attr as string)

present builds a presence filter: (attr=*).

attr
the attribute that must be present
Returns asn1.Value
the encoded filter, for search
jennifer
ldap.search(
    conn as Conn,
    baseDn as string,
    scope as int,
    filter as asn1.Value,
    attributes as list of string)

search runs a search and returns the matching entries. scope is one of ldap.SCOPE_BASE / SCOPE_ONE / SCOPE_SUB; filter comes from parseFilter or the filter constructors; attributes is the list to return (empty = all user attributes).

conn
an open, bound connection
baseDn
the search base DN
scope
ldap.SCOPE_BASE, SCOPE_ONE, or SCOPE_SUB
filter
the filter, from parseFilter or a filter constructor
attributes
the attributes to return (empty = all user attributes)
Returns list of Entry
the matching entries
Throws LdapError
on a protocol error or a malformed reply; a net error, "timeout" or "closed" as it is; kind "limit" when the whole search's replies exceed transport.MAX_RECEIVED_BYTES

searchPaged

jennifer
ldap.searchPaged(
    conn as Conn,
    baseDn as string,
    scope as int,
    filter as asn1.Value,
    attributes as list of string,
    pageSize as int)

searchPaged runs a search in pages of pageSize via the simple-paged-results control.

conn
an open, bound connection
baseDn
the search base DN
scope
ldap.SCOPE_BASE, SCOPE_ONE, or SCOPE_SUB
filter
the filter, from parseFilter or a filter constructor
attributes
the attributes to return (empty = all user attributes)
pageSize
the maximum entries per page
Returns list of Entry
all matching entries across every page
Throws LdapError
on a protocol error or a malformed reply; a net error, "timeout" or "closed" as it is; kind "limit" when the whole search's replies exceed transport.MAX_RECEIVED_BYTES

serve

jennifer
ldap.serve(dir as Directory, address as string)

serve binds address and serves dir until the process ends (blocks).

dir
the directory to answer queries from
address
the listen address "host:port" (port defaults to 389)
Throws LdapError
if the socket cannot be opened

serveOn

jennifer
ldap.serveOn(dir as Directory, listener as net.Listener)

serveOn serves dir on an already-open listener, one spawn per connection, until the listener is closed (which ends the accept loop). Close the listener from another task for a graceful stop.

dir
the directory to answer queries from
listener
an open listener from listen

setAttribute

jennifer
ldap.setAttribute(
    dir as Directory,
    dn as string,
    name as string,
    vals as list of string)

setAttribute creates or replaces one attribute's values on an existing entry.

dir
the directory to modify
dn
the DN of the entry to update
name
the attribute to create or replace
vals
the new values for the attribute
Throws LdapError
if no entry with dn exists

startTls

jennifer
ldap.startTls(conn as Conn)

startTls upgrades a plaintext connection to TLS via the StartTLS extended operation, then hands the same handle back (now encrypted).

conn
an open plaintext connection from connect
Returns Conn
the same connection, now encrypted (use it: its security is Starttls)
Throws LdapError
if the server refuses StartTLS

startTlsWith

jennifer
ldap.startTlsWith(conn as Conn, tls as net.TLSOptions)

startTlsWith is startTls with TLS options (caCert to trust a private CA, skipVerify to accept any certificate); see connectWith.

conn
an open plaintext connection from connect
tls
the TLS verification options (caCert, skipVerify)
Returns Conn
the same connection, now encrypted (use it: its security is Starttls)
Throws LdapError
if the server refuses StartTLS

substrings

jennifer
ldap.substrings(
    attr as string,
    initial as string,
    anyParts as list of string,
    final as string)

substrings builds a substring filter, e.g. (cn=abc): initial "a", any ["b"], final "c". Pass "" for an absent initial or final and an empty list for no interior parts.

attr
the attribute name
initial
the required leading substring, or "" for none
anyParts
interior substrings in order, or empty for none
final
the required trailing substring, or "" for none
Returns asn1.Value
the encoded filter, for search

unbind

jennifer
ldap.unbind(conn as Conn)

unbind sends an unbind request and closes the connection.

conn
the connection to unbind and close

values

jennifer
ldap.values(entry as Entry, name as string)

values returns an entry's values for an attribute (case-insensitive name), or an empty list.

entry
the entry to read
name
the attribute name, matched case-insensitively
Returns list of string
the attribute's values, or an empty list if absent

Structs

Attribute

One attribute of a directory entry.

jennifer
def struct Attribute {
    name as string,
    values as list of string
};
name
the attribute type (e.g. "mail", "objectClass")
values
its values (LDAP attributes are multi-valued)

Change

One change in a modify request.

jennifer
def struct Change {
    operation as int,
    name as string,
    values as list of string
};
operation
ldap.MOD_ADD / MOD_DELETE / MOD_REPLACE
name
the attribute to change
values
the values (empty deletes the whole attribute for MOD_DELETE)

Conn

An open LDAP connection.

jennifer
def struct Conn {
    handle as net.Conn,
    timeoutMs as int,
    security as transport.Security,
    allowInsecureAuth as bool
};
handle
the underlying TCP (or TLS) connection
timeoutMs
the per-read timeout in ms (0 blocks with no deadline)
security
the protection: None until startTls upgrades it
allowInsecureAuth
send a password over security None anyway (default false)

Directory

A mutable in-memory directory the server answers for. It is backed by a shared kv store, so edits made with addEntry / modifyEntry / deleteEntry / setAttribute are visible to a running server across its connection tasks. Edits are serialised by a lock every copy of the Directory shares, so concurrent tasks do not lose each other's writes.

jennifer
def struct Directory {
    store as kv.Store,
    lock as channel of bool
};
store
the shared backing store holding every entry
lock
the edit lock (holds one token while free)

Entry

A directory entry.

jennifer
def struct Entry {
    dn as string,
    attributes as list of ldap.Attribute
};
dn
the distinguished name
attributes
the entry's attributes

LdapError

A failed LDAP operation. Every error of kind "ldap" is one, so its fields are safe to read once the kind matches.

jennifer
def struct LdapError {
    kind as string,
    message as string,
    code as int,
    matchedDn as string,
    diagnostic as string
};
kind
always "ldap"
message
ldap: and what failed, with the result code and diagnostic when the server sent them
code
the server's LDAP result code (such as 32, noSuchObject, or 50, insufficientAccessRights); 0 when the failure is not a server result
matchedDn
the matched DN of the server's result, "" when none
diagnostic
the server's diagnostic message, "" when none

Result

The outcome of a bind (or any LDAPResult).

jennifer
def struct Result {
    code as int,
    matchedDn as string,
    message as string
};
code
the result code (ldap.SUCCESS, or ldap.INVALID_CREDENTIALS on a bad bind)
matchedDn
the matched DN the server reports, if any
message
the server's diagnostic message

Constants

ldap.INVALID_CREDENTIALS as int
LDAP result code: invalid credentials (a failed bind).
ldap.MOD_ADD as int
modify() change type: add the given values to the attribute.
ldap.MOD_DELETE as int
modify() change type: delete the given values (or the whole attribute if none).
ldap.MOD_REPLACE as int
modify() change type: replace the attribute with the given values.
ldap.SCOPE_BASE as int
Search scope: the base entry only.
ldap.SCOPE_ONE as int
Search scope: the base's immediate children.
ldap.SCOPE_SUB as int
Search scope: the base and its whole subtree.
ldap.SUCCESS as int
LDAP result code: success.