Skip to main content
NetScriptdocs Search docs ⌘K v0.0.9
Browse documentation

Directory queries

Authentication answers "who is this request" through AuthBackendPort and Principal. Live directory queries answer "what does the enterprise directory say about this user, now": look up users and groups, read a stable provider-immutable identifier, and evaluate transitive membership against a bounded set of candidate group identifiers.

alpha

Identity provider OIDC / OAuth sign-in Keycloak, Entra, Okta, WorkOS ID token: sub, plus optional directory immutableId claim authenticates only — no per-group role mappers NetScript framework Authentication (existing) @netscript/plugin-auth: sign-in & sessions Principal { subject, roles, scopes } @netscript/service authz role & scope guards (.withAuthn / .withAuthz) Live directory queries (RFC #2664) @netscript/plugin-directory multi-instance routing & bounded cache · planned DirectoryPort + conformance suite @netscript/plugin-directory-core directory-ldap ldapts · AD / Samba directory-entra Graph · planned directory-scim SCIM 2.0 · planned Enterprise directories (read-only) Active Directory / Samba LDAPS / StartTLS, strict CA Microsoft Entra ID Graph API · planned Your NetScript application Identity binding (iss, sub) -> DirectoryRef Grant evaluator which granted groups apply now? Grant store group immutableId -> role Fail-closed: disabled or expired accounts return [], and unreachable directories raise DirectoryUnavailable. Immutable keys: grants bind to (directoryInstance, immutableId) — never mutable UPNs or display names. Explicit freshness: every memberOfAny call returns evaluatedAt and consistency { source, ageMs }. subject effective roles memberOfAny NetScript seams definePlugin runtime config typed errors DB schemas telemetry Aspire wiring health & doctor
How live directory queries compose with plugin-auth and service authorization without duplicating directory state.

The port and its contract

@netscript/plugin-directory-core holds contracts, fail-closed invariants, typed errors, and the reusable conformance testing kit. It imports zero provider SDKs so Active Directory / LDAP, Microsoft Entra ID, and SCIM adapters implement one stable contract.

  • Immutable keys only. Users and groups are keyed by DirectoryRef { directoryInstance, immutableId } (objectGUID on Active Directory, objectId on Entra ID). Display names, email addresses, and user principal names are attributes, never keys.
  • Bounded queries everywhere. searchUsers and searchGroups require a positive integer limit, capped by normalizeDirectorySearchLimit, and every Page<T> reports truncated and evaluatedAt. memberOfAny evaluates only an explicit candidateGroupIds set instead of enumerating every group a user belongs to.
  • Fail-closed account state. getUser returns enabled and optional expiresAt so callers can inspect account state, while memberOfAny evaluates disabled and expired accounts to an empty membership list (isDirectoryUserActive).
  • Typed failure boundaries. Adapters raise DirectoryUnavailable, DirectoryUnauthorized, DirectoryTimeout, or DirectoryUnsupported instead of falling back silently to partial membership or empty scans.

Evaluating bounded membership

TypeScript
import {
  DirectoryUnsupported,
  type DirectoryPort,
  type DirectoryRef,
} from '@netscript/plugin-directory-core';

declare const directory: DirectoryPort;

if (!directory.capabilities.has('transitive-membership')) {
  throw new DirectoryUnsupported(
    directory.name,
    'memberOfAny',
    'Configured directory adapter does not support transitive membership.',
  );
}

const user: DirectoryRef = {
  directoryInstance: 'corp-example',
  immutableId: '20000000-0000-4000-8000-000000000001',
};

const result = await directory.memberOfAny(
  {
    user,
    candidateGroupIds: ['10000000-0000-4000-8000-000000000002'],
  },
  { timeoutMs: 2_000 },
);

console.log(result.memberOf, result.evaluatedAt, result.consistency.source);

Consistency and revocation budgets

Every memberOfAny response carries evaluatedAt (an ISO-8601 UTC timestamp) and consistency: { source: 'live' | 'cache', ageMs }. Direct adapters report { source: 'live', ageMs: 0 }. Consumers and future caching layers reason about revocation delay using DirectoryConsistencyBudget and computeRevocationBoundMs:

TypeScript
import { computeRevocationBoundMs } from '@netscript/plugin-directory-core';

const revocationBoundMs = computeRevocationBoundMs({
  replicationAllowanceMs: 30_000,
  membershipCacheTtlMs: 60_000,
  maxStalenessMs: 120_000,
});
console.log(revocationBoundMs); // 90000

Testing adapters with the conformance suite

@netscript/plugin-directory-core/testing provides an in-memory DirectoryPort, a deterministic clock (createDeterministicClock), an invented example.test conformance dataset (DIRECTORY_CONFORMANCE_DATASET), and runDirectoryConformanceSuite. Every directory adapter runs the same one-call suite to verify:

  • direct, multi-level nested, and cyclic group membership (including non-members against cycles);
  • Active Directory-style primary-group membership (direct and nested) and never-expiring accounts;
  • disabled users and clock-driven expired users failing closed on memberOfAny;
  • mandatory search limit validation, ceiling capping, exact-fit boundaries, and truncated reporting;
  • hostile payloads (LDAP, OData, SCIM, URL, CR/LF, NUL, blank) across search, getUser, and memberOfAny, plus ambiguous secondary getUser lookups failing closed;
  • unknown, duplicated, and large (>40) candidateGroupIds batches;
  • deadlines, timeouts, and caller aborts across all five methods (including health());
  • redacted health() and error outputs verified against caller-supplied sensitiveValues.
TypeScript
import {
  createDeterministicClock,
  createInMemoryDirectoryPort,
  DIRECTORY_CONFORMANCE_DATASET,
  verifyDirectoryConformance,
} from '@netscript/plugin-directory-core/testing';

const report = await verifyDirectoryConformance({
  name: 'in-memory',
  createFixture: () => {
    const clock = createDeterministicClock(DIRECTORY_CONFORMANCE_DATASET.initialTimeIso);
    const base = {
      directoryInstance: DIRECTORY_CONFORMANCE_DATASET.directoryInstance,
      clock,
      maxSearchLimit: 3,
      users: DIRECTORY_CONFORMANCE_DATASET.users,
      groups: DIRECTORY_CONFORMANCE_DATASET.groups,
    };
    return {
      clock,
      maxSearchLimit: 3,
      port: createInMemoryDirectoryPort(base),
      timeoutPort: createInMemoryDirectoryPort({ ...base, operationDelayMs: 250 }),
    };
  },
});

console.log(report.passed, report.failed);

Active Directory & Samba AD adapter (@netscript/directory-ldap)

@netscript/directory-ldap implements DirectoryPort for Active Directory and Samba AD on ldapts with strict production defaults:

  • Strict TLS by default. Uses ldaps:// or explicit StartTLS (tls: { mode: 'starttls' }) with rejectUnauthorized: true and optional custom enterprise CA bundles via tls.caFile. Plaintext ldap:// is refused unless tls.allowInsecurePlaintextDev: true is explicitly opted in.
  • *_FILE bind secrets only. Service-account bind passwords are read once at startup from bindPasswordFile; inline passwords and URL credentials are rejected, and errors/health probes never echo passwords or distinguished names.
  • Pure filter ASTs & bounded wire reads. Every query constructs ldapts filter objects (AndFilter, OrFilter, NotFilter, EqualityFilter, SubstringFilter, ExtensibleFilter) rather than concatenating LDAP filter strings, and searchUsers/searchGroups iterate searchPaginated to stop strictly at limit + 1 entries on the wire.
  • Transitive membership & AD primary group. memberOfAny evaluates LDAP_MATCHING_RULE_IN_CHAIN (1.2.840.113556.1.4.1941) strictly bounded to candidateGroupIds (recorded via 'transitive-membership' in capabilities) and resolves Active Directory primaryGroupID against group objectSid RIDs under baseDn.
  • Multi-host failover & health. Ordered urls slice timeout budgets across remaining hosts, prefer the last healthy host, fail fast on unauthorized credentials or bad base DNs, and probe both RootDSE and configured base DNs in health().
TypeScript
import { createLdapDirectoryPort } from '@netscript/directory-ldap';

const connectDirectory = () =>
  createLdapDirectoryPort({
    directoryInstance: 'corp-example',
    urls: ['ldaps://dc1.example.test:636', 'ldaps://dc2.example.test:636'],
    baseDn: 'DC=example,DC=test',
    bindDn: 'CN=svc-directory,OU=ServiceAccounts,DC=example,DC=test',
    bindPasswordFile: '/run/secrets/ldap_bind_password',
    tls: { caFile: '/etc/ssl/certs/corp-root-ca.pem' },
  });

console.log(typeof connectDirectory);

Next steps

Search all documentation

Type a term to search the documentation.