# The identity model

> How the directory is built, users, groups and agents as types linked to each other, and the one API that reads and writes them all.

Everything in the directory is an object of a **type**. Users, groups and agents are the three types every realm
starts with; a type of your own, such as a cost center or a department, works exactly the same way. Learn the pattern
once and you can read and write anything the realm keeps.

Humans and agents live in the same directory, side by side. A user can own an agent, an agent can act for a user,
and both are found, linked and audited through the same calls. See [Agents in the directory](../../agents/).

## Before you begin

- **Privilege:** `RealmViewer` to read; `RealmOwner`, or a privilege of your own, to write. The table in
  [Who may do what](#who-may-do-what) has the detail.
- **Where:** the API, with your session in `$CVYUH_SESSION` (see [Call the API](../../../develop/api/)).

## How it works

### A type is a schema

Each type is a JSON Schema (draft 2020-12) that lists its attributes, the kind of value each one takes, and its
**links**, the attributes that point at objects of another type. It also carries **policies**, the rules every write
must pass, such as "`uid` is required and unique".

Besides its profile and groups, a user carries what other products keep about them: the entitlements they hold,
their second factors, their session limits, their vault and their devices. See
[Add and change users](../../users/add-and-change-users/).

Each realm has its own copy of these types, made when the realm was created. You can add to your realm's copy, as
long as you keep every shipped attribute on it. See [Attributes and validation](../attributes-and-validation/) and
[Custom types](../custom-types/).

### An object is an id, a revision and attributes

Every object answers in the same shape:

```json
{
  "id": "<internal id>",
  "objectId": "maya",
  "typeName": "user",
  "rev": 4,
  "attributes": { "uid": "maya", "email": "maya@example.com", "status": "active" },
  "createTime": "<RFC 3339 time>",
  "updateTime": "<RFC 3339 time>"
}
```

`objectId` is the id you name the object by in every address. `rev` goes up with every change; the realm also sends
it as the `ETag` header, and you send it back in `If-Match` so that a write made over someone else's change is
refused (`412`) rather than lost.

### A link is stored once and read from both ends

A link joins two objects and is stored once. A group's `member` and a user's `memberOf` are the two ends of the same
links; an agent's `businessOwner` and a user's `ownedAgents` are another pair. Add a link from either end and both
change, in one step. A link can carry properties of its own, such as the window on an entitlement grant.

Reads leave links out unless you ask for them with `expand`: `?expand=memberOf` for the links themselves,
`?expand=memberOf/*` for the objects they point at. Each expanded link carries the far object's `objectId`, its
`type` and its attributes in `object`.

### Every change is recorded

Each object keeps its own history: `/objects/v1/{type}/{id}/history` lists every change to it, newest first, 50 to a
page unless you set `pageSize` (at most 500). The entries come from the realm's audit trail
(see [Change history](../../../audit-reports/audit-trail/change-history/)), and leave out every value no read would
show, such as a password. One entry, for Maya's phone number changed:

```json
{
  "id": "<record id>",
  "eventType": "PATCHED",
  "eventTime": "<RFC 3339 time>",
  "objectId": "<internal id>",
  "changedBy": "<administrator's id>",
  "subjectRev": 5,
  "changedFields": ["telephoneNumber"],
  "before": { "uid": "maya", "telephoneNumber": "+44 20 7946 0000" },
  "after":  { "uid": "maya", "telephoneNumber": "+44 20 7946 0999" },
  "edgeChanges": null
}
```

`eventType` is `CREATED`, `PATCHED`, `UPDATED` (a `PUT`, or a link added or removed, listed in `edgeChanges`) or
`DELETED`. Entries also carry the request's trace identifiers. The history is kept for the life of the realm, like
the rest of the audit trail, with nothing to set: see [Retention and clean-up](../../../platform/data/retention/). A deleted
object's history can't be read at its address any more, but its records stay on the trail.

### Who may do what

Every call here is checked against what the caller may administer in the realm, from the privileges their groups hold
(see [Delegated administration](../../../platform/realms/delegated-administration/)). Reads (`GET`, `QUERY`) need
`READ`; every other call needs `MODIFY`.

| To | Privilege that's enough |
|---|---|
| Read and search users, groups, agents and types, and read history | `RealmViewer` |
| Create, change, link and delete objects; change types and the identity binding | `RealmOwner` |
| A narrower role, such as "may change users and nothing else" | A privilege of your own, with a template such as `*REALM/identitySource/user/*` and `MODIFY` |

The shipped `user` and `group` are administered as `identitySource` (`*REALM/identitySource/user/*`,
`*REALM/identitySource/group/*`); every other type, `agent` and your own included, as `entity`
(`*REALM/entity/agent/*`), and type definitions as `*REALM/entity/type/*`. A call outside the caller's privileges is
refused `403`. Every page in this docset names the privilege it needs under **Before you begin**.

## Set it up

There's nothing to turn on. Every type is reached at the same addresses, as a realm administrator with your session
in `$CVYUH_SESSION` (see [Call the API](../../../develop/api/)). On
`https://foobar.cvyuh.com/api/v0/am`:

| To | Call |
|---|---|
| List the realm's types | `GET /types/v1` |
| Read one type | `GET /types/v1/{type}` |
| Create | `POST /objects/v1/{type}?id={id}`, or `PUT /objects/v1/{type}/{id}` with `If-None-Match: *` |
| List and search | `GET /objects/v1/{type}`. See [Search and paging](../../users/search/) |
| Read | `GET /objects/v1/{type}/{id}` |
| Change some attributes | `PATCH /objects/v1/{type}/{id}`: an object is a merge patch, a list a JSON Patch |
| Replace all of them | `PUT /objects/v1/{type}/{id}` with `If-Match` |
| Delete | `DELETE /objects/v1/{type}/{id}` with `If-Match` |
| Link | `POST /objects/v1/{type}/{id}/relationships/{link}` with `{ "targetId": "{id}" }` |
| List links | `GET /objects/v1/{type}/{id}/relationships/{link}` |
| Unlink | `DELETE /objects/v1/{type}/{id}/relationships/{link}/{target id}` |
| Read the history | `GET /objects/v1/{type}/{id}/history` |

For example, Maya's history:

```sh
curl https://foobar.cvyuh.com/api/v0/am/objects/v1/user/maya/history \
  -H "Cookie: x-cvyuh-token=$CVYUH_SESSION"
```

## Limits and defaults

| What | Default or limit |
|---|---|
| A list's page | 20 objects unless you set `pageSize`, at most 100; a larger `pageSize` is cut to 100 |
| A history page | 50 entries unless you set `pageSize`, at most 500 |
| Links returned by `expand` | At most 10,000 per link attribute; past that the read is refused `413`, and you page the links instead |
| Depth of nested expansion | 4 levels |
| A request body | About 2 MB; a larger one is refused `400` |
| Attributes per type, value size | No fixed cap; give an attribute `max-length` to bound it |
| Rate of calls | No rate limit today; see [Bring users in](../../lifecycle/bring-users-in/#limits-and-defaults) for pacing a load |

## When a call fails

Every refusal answers a JSON body `{ "code", "message", "detail" }`:

| Answer | Code | What it means |
|---|---|---|
| `400` | `POLICY_VIOLATION`, `SCHEMA_VALIDATION_FAILED` | A rule of the type, or its schema, refused the write; `detail` names each failure |
| `400` | `INVALID_REQUEST` | The request itself is malformed: bad JSON, an unknown filter field, a malformed `If-Match` |
| `403` | `FORBIDDEN` | The caller's privileges don't cover the call |
| `404` | `NOT_FOUND` | No such object or type |
| `405` | `METHOD_NOT_ALLOWED` | A type was patched or deleted |
| `409` | `ALREADY_EXISTS` | The id is taken |
| `412` | `REVISION_CONFLICT` | `If-Match` named a revision that's no longer current, or `If-Match: *` an object that isn't there |
| `413` | `PAYLOAD_TOO_LARGE` | An `expand` would return more than 10,000 links |
| `428` | `PRECONDITION_REQUIRED` | A type was saved without `If-Match` |

## Audit record

Every write to an object is on the audit trail and in its history: `CREATED`, `PATCHED`, `UPDATED` (a `PUT`, or a link
made or removed) and `DELETED`. A type's definition being created or saved is recorded as `CREATED` or `UPDATED`, with
the definition before and after. See
[What is recorded](../../../audit-reports/audit-trail/what-is-recorded/).

## Good to know

- **`If-Match: *` asks only that the object exists.** It writes whatever the revision is now, and answers `412` if
  the object isn't there. A malformed `If-Match` is refused `400`.
- **Creating with an id that's taken is refused.** Leave out `?id=` and the realm makes an id for you.
- **What you can see is what you may read.** Every call is checked against what the caller may administer in the
  realm; see [Who may do what](#who-may-do-what).
- **Your realm's types are its own copies.** Its `user`, `group` and `agent` were made from the shipped definitions
  when the realm was created, so an improvement to the shipped types doesn't reach a realm that already exists. See
  [What's next for attributes](../whats-next/).
- **An attribute the type doesn't define is stored as sent,** unchecked and not searchable. Define what you write.
- **Every body is JSON,** sent as `Content-Type: application/json`.

## Related

- [Add and change users](../../users/add-and-change-users/) and
  [Add groups and members](../../groups/add-groups-and-members/): the two types you'll use most.
- [Attributes and validation](../attributes-and-validation/): add to a shipped type.
- [Custom types](../custom-types/): define types of your own.
