> ## Documentation Index
> Fetch the complete documentation index at: https://latchkey.getgalaxy.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Directory sync

> How the directory owner pushes users, groups and memberships into Latchkey through DirectoryService.

Directory sync is how users, groups and group memberships reach Latchkey
from the system that owns them. One service, the directory owner named by
`LATCHKEY_DIRECTORY_OWNER`, calls `DirectoryService`. Nobody else can call
it, and the records it writes are read only everywhere else. In Galaxy Cloud
the directory owner is the Management Service.

> [!WARNING]
>
> Send the ids the authenticator produces for each user. If they differ, a
> deactivation lands on a row nobody signs in as, and the real user is still
> created on their first check. See
> [Security](https://latchkey.getgalaxy.io/pages/guides/concepts/security.md#caller-authentication).

## Before the first call

* Set `LATCHKEY_DIRECTORY_OWNER` to the caller's service identity, as in
  [Configuration](https://latchkey.getgalaxy.io/pages/guides/deployment/configuration.md). With it unset,
  every call is refused.
* Provision the tenant with `TenantService.EnsureTenant`. Being the directory
  owner gives no right to, so call it as an operator or a domain owner.

## Changes

`ApplyDirectoryChanges` applies 1 to 1,000 changes in order, in one
transaction. Every change lands or none does.

| Change | What it does |
| - | - |
| `upsert_subject` | Creates the user, or sets its `active`, `display_name` and `email`. An empty name or email clears the stored one. A user first seen by a check, or added by an Admin, becomes a directory user and keeps its bindings and memberships. |
| `deactivate_subject` | Sets the user inactive and makes it a directory user. Bindings and memberships stay, so a later upsert with `active` true restores its access. A user Latchkey has never seen is stored inactive, so a check cannot create it. |
| `upsert_group` | Creates the group for `external_id`, renames it, or brings back a deleted group with no members. Names are stored as sent, and a directory group may share its name with any other group. |
| `delete_group` | Deletes the group and its members. Its bindings stay and grant nothing. An unknown group is skipped. |
| `add_member` | Adds an existing user or service, active or not, to an existing group. |
| `remove_member` | Removes a subject from a group. A missing group or subject is skipped. |

Directory subjects are users, so `upsert_subject` and `deactivate_subject`
refuse a service. `upsert_subject` carries `active` as a plain bool, so a
record sent without it deactivates the user. A subject must exist before it
is added, and its `upsert_subject` may come earlier in the same call.

`ReplaceDirectoryGroupMembers` sets a group's whole membership. It lists at
most 10,000 subjects, removes every member it does not list, and writes only
the difference. A group with more members is synced with `add_member` and
`remove_member` only.

Each response returns the tenant's revision. A check that passes it as
`min_revision` sees the change on any replica.

## Versions and ordering

Every change carries a `source_version` of 1 or more. Every user and every
group stores the version of the newest change applied to it, and a group's
version covers its name, its deletion and its members. A change older than
the stored version is dropped and counted as `stale`. A change with the same
or a newer version is applied.

The caller follows five rules.

1. Read the directory from an ordered feed and send its changes in that
   order. With WorkOS, consume the Events API, not webhooks.
2. Number calls, not changes. Every change in a call carries that call's
   number, each new call takes a higher one, and a call sent again keeps its
   own.
3. Treat a group and its memberships as one object, handled by one worker at
   a time.
4. Do not send a later change for an object until the call carrying the
   earlier one has succeeded. A timeout is not success, so send the same call
   again first.
5. For a replace, take the version before reading the member list, so a
   removal that lands in between is newer than the replace.

In return, sending the same call again is always safe, and a late copy of an
older call never undoes a newer change.

A caller that numbers each change on its own stays safe, but a call sent
again then reports its earlier changes to one object as stale.

## Counts and stale

`ApplyDirectoryChanges` returns `applied`, the changes that altered
something, `skipped`, the changes that altered nothing such as a repeat, and
`stale`. The three add up to the number of changes sent.
`ReplaceDirectoryGroupMembers` returns `added`, `removed` and `stale`.

A stale change was dropped because something newer was already stored. A
late copy of a call that already landed reports its changes as stale and
loses nothing. Any other stale change was lost, so alarm on it and repair
what it touched with a new call at a new version.

| Lost change | Repair |
| - | - |
| A user | `upsert_subject` or `deactivate_subject` |
| A group's name, deletion or restore | `upsert_group` or `delete_group` |
| A group's members | `ReplaceDirectoryGroupMembers` |

## Limits

| Limit | Value |
| - | - |
| Changes per `ApplyDirectoryChanges` | 1,000 |
| Subjects per `ReplaceDirectoryGroupMembers` | 10,000 |
| Request size | 4 MiB |

Each call that changes something reloads the tenant on every replica, so
send changes in batches rather than one call per change. On Postgres a call
costs a fixed number of statements under the tenant's write lock, whatever
its size.

## Errors

Every error Latchkey returns leaves the tenant unchanged. A timeout or a
dropped connection is different, since the call may have committed before
the reply was lost, so send the same call again. An error inside a batch
names the change by position, such as `changes[12]`.

| Code | When | Retry |
| - | - | - |
| `PERMISSION_DENIED` | The caller is not the directory owner, no owner is configured, or the caller acts as someone else | No. Fix the configuration. |
| `INVALID_ARGUMENT` | No changes or more than 1,000, more than 10,000 subjects, a change with nothing set, a `source_version` below 1, a subject with no id, a service in `upsert_subject` or `deactivate_subject`, or an empty `external_id` or group name | No. The same request fails again. |
| `NOT_FOUND` | The tenant is not provisioned, `add_member` or a replace names a group that does not exist or is deleted, or a subject to add does not exist | After sending what is missing, which is `EnsureTenant`, `upsert_group` or `upsert_subject` |
| `INTERNAL`, `UNAVAILABLE`, `DEADLINE_EXCEEDED` | The database or the server failed | Yes, the same call |

A malformed change is refused whatever the versions say. A stale change is
dropped before any check on stored state, so a late copy of an old call
never fails on a group deleted since.

## Keeping an Admin

The directory is not held to the last-Admin guard, so it can deactivate a
tenant's only Admin. Once groups are synced, bind Admin to a directory group.
The directory can then always name the next Admin by adding them.

A tenant left with no Admin gets one from an operator. `EnsureTenant` with
`first_admin`, or `latchkey tenants ensure <tenant> --admin <subject>`, binds
that subject as Admin when the tenant has none. The subject must be active.
See [Security](https://latchkey.getgalaxy.io/pages/guides/concepts/security.md#admin-ui).

## Audit

Directory writes are audited with the actor `directory`, whichever service
called. A replace that changes more than 1,000 members is recorded as
several `group.members` entries.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.