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
| Name | What it is |
|---|---|
add | add creates an entry from a DN and an attribute map, returning the Result (check .code). |
addEntry | addEntry inserts an entry, replacing any existing entry with the same DN. |
allOf | allOf builds a conjunction: (&(f1)(f2)...). |
anyOf | anyOf builds a disjunction: (|(f1)(f2)...). |
approx | approx builds an approximate-match (attr~=value) filter; the server treats it as equality. |
bind | bind performs a simple bind and returns the Result (check .code against ldap.SUCCESS / ldap.INVALID_CREDENT... |
bindSasl | bindSasl performs a SASL SCRAM bind (algo "sha1" -> SCRAM-SHA-1, "sha256" -> SCRAM-SHA-256), verifying the ... |
change | change builds one modify change (operation is ldap.MOD_ADD / MOD_DELETE / MOD_REPLACE). |
close | close closes the connection without sending an unbind. |
connect | connect opens an LDAP connection. |
connectWith | connectWith is connect with TLS options for LDAPS and StartTLS, the net.TLSOptions of net.connectTLS ... |
delete | delete removes an entry by DN, returning the Result. |
deleteEntry | deleteEntry removes the entry with the given DN if present. |
directory | directory builds a mutable in-memory directory the server answers for - the lightweight, ephemeral default. |
entry | entry builds a directory entry from a DN and an attribute map (name -> values). |
equals | equals builds an equality filter: (attr=value). |
escapeFilterValue | Escape a value for use inside an RFC 4515 filter string: \, *, (, ) and NUL become \5c, \2a,... |
firstValue | firstValue returns an entry's first value for an attribute, or "" if absent. |
getEntry | getEntry returns the entry with the given DN, or an empty Entry (dn == "") if absent. |
greaterOrEqual | greaterOrEqual builds an (attr>=value) filter. |
group | group builds a groupOfNames entry (objectClass + cn from the DN's RDN + member) from members. |
hasEntry | hasEntry reports whether an entry with the given DN exists. |
lessOrEqual | lessOrEqual builds an (attr<=value) filter. |
listEntries | listEntries returns a snapshot of every entry currently in the directory. |
listen | listen opens a listening socket for the server ("host:port"; port defaults to 389). |
modify | modify applies a list of changes to an entry, returning the Result. |
modifyDn | modifyDn renames or moves an entry: newRdn is the new relative DN, deleteOldRdn drops the old RDN attribute... |
modifyEntry | modifyEntry replaces the entry with the same DN (an alias for addEntry). |
negate | negate builds a negation: (!(f)). |
openDirectory | openDirectory opens a file-backed directory that persists across restarts (a kv.openFile store at path). |
parseFilter | parseFilter compiles an RFC 4515 filter string (e.g. |
password | password hashes a plaintext password into an LDAP userPassword value. |
passwordModify | passwordModify changes a password via the RFC 3062 extended operation. |
present | present builds a presence filter: (attr=*). |
search | search runs a search and returns the matching entries. |
searchPaged | searchPaged runs a search in pages of pageSize via the simple-paged-results control. |
serve | serve binds address and serves dir until the process ends (blocks). |
serveOn | serveOn serves dir on an already-open listener, one spawn per connection, until the listener is closed (whi... |
setAttribute | setAttribute creates or replaces one attribute's values on an existing entry. |
startTls | startTls upgrades a plaintext connection to TLS via the StartTLS extended operation, then hands the same ha... |
startTlsWith | startTlsWith is startTls with TLS options (caCert to trust a private CA, skipVerify to accept any cer... |
substrings | substrings builds a substring filter, e.g. |
unbind | unbind sends an unbind request and closes the connection. |
values | values returns an entry's values for an attribute (case-insensitive name), or an empty list. |
Attribute | struct: One attribute of a directory entry. |
Change | struct: One change in a modify request. |
Conn | struct: An open LDAP connection. |
Directory | struct: A mutable in-memory directory the server answers for. |
Entry | struct: A directory entry. |
LdapError | struct: A failed LDAP operation. |
Result | struct: The outcome of a bind (or any LDAPResult). |
| constants | the module's constants |
Functions
add
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
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
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
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
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
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
allowInsecureAuthis 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
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
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
ldap.close(conn as Conn)close closes the connection without sending an unbind.
conn- the connection to close
connect
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
allowInsecureAuthis set (see bind). - Throws
LdapError - on a connection or StartTLS failure
connectWith
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
search
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
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
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
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
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
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
securityis Starttls) - Throws
LdapError - if the server refuses StartTLS
startTlsWith
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
securityis Starttls) - Throws
LdapError - if the server refuses StartTLS
substrings
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
ldap.unbind(conn as Conn)unbind sends an unbind request and closes the connection.
conn- the connection to unbind and close
values
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.
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.
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.
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
startTlsupgrades 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.
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.
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.
def struct LdapError {
kind as string,
message as string,
code as int,
matchedDn as string,
diagnostic as string
};kind- always
"ldap" messageldap:and what failed, with the result code and diagnostic when the server sent themcode- 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).
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.