> ## 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.

# Integrating a product with Latchkey

> Annotate a product's protos, register its kinds, install the Connect interceptor and turn enforcement on.

A product integrates by annotating its protos and installing one Connect
interceptor. The annotations are the single source for both what the product
registers and what each RPC requires, so the two cannot drift. Products
describe their domain and never evaluate policy.

The build compiles the annotations into the product binary. When the product
starts, the SDK reads them back out and registers the product's domain
and its kinds. On
each request, the interceptor reads the same descriptors to decide which
check to run.

## Depend on the options

Add the Latchkey module to the product's `buf.yaml` and commit `buf.lock`.

```yaml theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
# buf.yaml
version: v2
modules:
  - path: protos
deps:
  - buf.build/galaxy-io/latchkey   # latchkey/v1/options.proto
```

> [!NOTE]
>
> Each release publishes the module to the Buf Schema Registry, starting
> with the first one after Latchkey's repository is public. Until then,
> vendor `protos/latchkey/v1` or point buf at a local checkout.

Products do not generate Go code for the Latchkey protos. They import the
Latchkey Go module for the extension descriptors `latchkeyv1.E_Domain`,
`latchkeyv1.E_Kind`, `latchkeyv1.E_Requires`, `latchkeyv1.E_Public` and
`latchkeyv1.E_Authenticated`, so every product uses the same generated types.
Go needs no new generator, because `protoc-gen-go` already embeds the full
descriptors in the generated files, custom options included.

## Name the domain

The domain is the prefix of every kind name. The file that holds your
services can say how people see it. The admin UI shows the display name and
logo wherever it shows your kinds, and each kind's own display name beside
the logo.

```proto theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
option (latchkey.v1.domain) = {
  name: "filament"
  display_name: "Filament"
  logo_url: "https://cdn.example.com/filament/logo.svg"
};
```

`name` is the domain your product passes to `NewRegistration`, which
refuses any other. The rest is optional, and Latchkey invents nothing for
what you leave out. A push that leaves a field out keeps the stored one. If
several of your files set the option, they must all say the same thing.

| Unset | The UI shows |
| - | - |
| A domain's `display_name` | The domain as it is, such as `acme` |
| A domain's `logo_url`, or a logo that fails to load | No logo |
| A kind's `display_name` | The kind's name as it is, such as `acme.invoice_batch` |

A logo is an escaped https URL of at most 2048 bytes. A display name is at
most 64 characters with no leading or trailing spaces and no invisible
characters, such as a zero width space. `NewRegistration` refuses anything
else, so the product does not start with a push the server would refuse.

## Annotate services and RPCs

Every service declares its kinds. Every RPC carries one of three annotations.
`requires` names the checks it needs. `public: true` means no caller is
needed, as for sign-in. `authenticated: true` admits any authenticated caller
of the tenant with no permission, as for GetSession.

```proto theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
service IngestionService {
  option (latchkey.v1.kind) = {
    name: "filament.pipeline"
    display_name: "Pipeline"
    resource_scoped: true
    actions: [ACTION_READ, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE, ACTION_INVOKE]
  };
  option (latchkey.v1.kind) = {
    name: "filament.run"
    parent_kind: "filament.pipeline"
    actions: [ACTION_READ]
  };

  rpc GetPipeline(GetPipelineRequest) returns (GetPipelineResponse) {
    option (latchkey.v1.requires) = {action: ACTION_READ};
  }

  rpc CreatePipelineVersion(CreatePipelineVersionRequest) returns (CreatePipelineVersionResponse) {
    option (latchkey.v1.requires) = {
      action: ACTION_UPDATE
      id_field: "pipeline_id"
    };
    option (latchkey.v1.requires) = {
      kind: "filament.connection"
      action: ACTION_USE
      id_field: "graph.nodes[].connection_id"
    };
  }

  rpc SignalRun(SignalRunRequest) returns (SignalRunResponse) {
    option (latchkey.v1.requires) = {
      kind: "filament.pipeline"
      action: ACTION_INVOKE
      id_field: "run_id"
      resolve_parent: "filament.run"
    };
  }
}
```

* A requirement's `kind` defaults to the service's first declared kind.
* A method may carry several `requires`. All must pass, and they are
  evaluated in one `CheckBatch` against one snapshot.
* `id_field` is a field path. A repeated path such as `graph.nodes[]` expands
  to one requirement per element.
* `resolve_parent` names a child kind whose id is in `id_field`. The
  requirement's kind is the top of that child's parent chain, the kind that
  holds resource bindings, however deep the child sits. For
  `flow > job > step` a step or job id is checked on `flow`, never on `job`.
  The product's parent resolver for the child kind maps its id to the flow.

`if_set` and `unless_set` cover requests that take either an existing
resource or raw input. Filament's DiscoverResources needs `use` on a
connection when the caller names one, and `create` on connections when the
caller sends raw config instead.

```proto theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
rpc DiscoverResources(DiscoverResourcesRequest) returns (DiscoverResourcesResponse) {
  option (latchkey.v1.requires) = {
    kind: "filament.connection"
    action: ACTION_USE
    id_field: "connection_id"
    if_set: "connection_id"
  };
  option (latchkey.v1.requires) = {
    kind: "filament.connection"
    action: ACTION_CREATE
    unless_set: "connection_id"
  };
}
```

## Check in CI

`latchkey.NewRegistration` refuses annotations it cannot enforce, such as an
RPC with none of `requires`, `public` or `authenticated`, a field path the
request does not have, a requirement that names an undeclared kind, or a kind
that does not start with the domain name. A test that builds the product's
Registration, as [Register at startup](#register-at-startup) does, fails CI
on any of them without a server.

To check a build against a running Latchkey, write its push to a file and
dry run it as the domain's owner.

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
manifest, err := reg.Manifest() // the push as protobuf JSON, the same bytes for the same push
if err != nil { log.Fatal(err) }
err = os.WriteFile("latchkey.manifest.json", manifest, 0o644)
```

`latchkey register -f latchkey.manifest.json --dry-run` then lists what the
push would add, change and retire, and fails if the server would refuse it.
See [the CLI](https://latchkey.getgalaxy.io/pages/guides/usage/cli.md#registering-kinds).

## Register at startup

The SDK is the module's root package, `latchkey`.

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import "github.com/galaxy-io/latchkey"
```

The product passes its service list explicitly, so the SDK never scans protos
pulled in from dependencies. Each product registers one domain, such as
`filament`, with the semver of its build, and pushes its kinds under it when
it starts. Latchkey never pulls.

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
reg, err := latchkey.NewRegistration("filament", version, []protoreflect.ServiceDescriptor{
    ingestionv1.File_ingestion_v1_service_proto.Services().ByName("IngestionService"),
    metricsv1.File_metrics_v1_metrics_proto.Services().ByName("MetricsService"),
    authv1.File_auth_v1_service_proto.Services().ByName("AuthService"),
})
if err != nil { log.Fatal(err) } // the annotations are wrong, so refuse to start
go reg.PushUntilDone(ctx, domains) // a DomainServiceClient, retried until it succeeds
```

`NewRegistration` checks every annotation once and refuses to start the
product when any is wrong. The error lists every problem, not only the first.
Annotations are judged against the domain, so with an empty or invalid domain
it checks no service or retirement, and reports those problems once the domain
is fixed.

* A method has none of `requires`, `public: true` and `authenticated: true`,
  or more than one.
* A kind is not `<domain>.<type>`, has no actions, names an action outside
  the vocabulary, sets `retired`, or is declared twice with different
  attributes. Declaring the same kind identically in two services is fine.
* A child kind is resource scoped, is its own parent, names a parent no
  service declares, or sits in a parent loop.
* A requirement has no kind and its service declares none to default to.
* A requirement names a kind no service declares, or an action its kind does
  not support.
* `update`, `delete`, `invoke` or `use` has no `id_field`, or `read` or
  `create` has one. Those two are checked on the tenant.
* `update`, `delete`, `invoke` or `use` names a child kind directly. Check the
  top of its parent chain with `resolve_parent` naming the child instead.
* A field path names a missing field, enters a map, uses `[]` on a field that
  is not a list, or crosses a repeated field without `[]`. An `id_field` ends
  in a string. `if_set` and `unless_set` take no `[]`, and a requirement sets
  at most one of them.
* Every requirement of a method has `if_set` or `unless_set`, unless an
  `if_set` and an `unless_set` name the same field. Otherwise a request could
  meet no requirement at all.
* A client or bidirectional stream has an `id_field`, `if_set` or
  `unless_set`. The stream is checked on its first message, so only tenant
  checks fit it.
* `resolve_parent` names a kind no service declares or a kind that does not
  descend from the requirement's kind, or sits on `read` or `create`.
* An annotation carries fields the SDK does not know, or a file, service or
  method carries a Latchkey option it does not know (field numbers 50001 to
  50099\), because the product's protos were built against a newer
  `options.proto`. Upgrade the SDK.
* A retired kind or action is still declared or belongs to another domain,
  `WithRetiredActions` names no actions, or a kind is given to both
  `WithRetiredKinds` and `WithRetiredActions`.
* The domain, version or service list is empty, a service is nil, the
  domain is not a lowercase name or is `latchkey`, or the version is not
  semver (`1.4.2` or `v1.4.2`).
* Two different descriptors of one service are passed, as when an older
  vendored copy of a proto is loaded next to the current one. The same
  descriptor passed twice is fine.

`PushUntilDone` calls `RegisterDomain` and retries every failure, waiting 1
second and then twice as long each time, up to 30 seconds. It returns once a
push succeeds or its context ends, and makes no call once the context has
ended. Each attempt gets 10 seconds, so a server that takes the call and never
answers costs one attempt. A registrar of your own must return once its
context ends, or `PushUntilDone`, and a shutdown waiting for it, cannot
return. A failed push never crashes the product, even one whose registrar
panics. A failure that needs a fix, such as a domain with no owner, an invalid
push or a panicking registrar, is logged as an error, and other failures as
warnings. `reg.Ready()` reports whether a push has succeeded, so the product's
readiness probe waits for it. `reg.Push` pushes once, for a product that
handles retries itself.

`RegisterDomain` accepts a push only when the caller owns the domain, every
kind is `<domain>.<type>`, every action is in the shared vocabulary
and every parent kind exists. Pushes only add, and they are ordered by
version.

* Each push carries the product's `version`. Latchkey keeps the newest
  version it has seen, and a push from an older version changes nothing, so
  old pods restarting during a rollout cannot flip a kind back.
* A push from the newest version can add kinds and actions and change a
  kind's attributes. Actions are removed only through
  `latchkey.WithRetiredActions`, and never while a custom role names them.
  Kinds are retired with `latchkey.WithRetiredKinds`, and never while a
  role or binding names them. Until those are removed in the admin UI or CLI,
  the push fails with `FAILED_PRECONDITION`, `PushUntilDone` keeps retrying
  and the product stays unready. A binding left granting nothing denies.
* Retiring a kind Latchkey has never stored changes nothing, so a product
  that once retired a kind still registers on a fresh install.
* An unchanged push writes nothing, so the push on every boot is free.
* A push that leaves a display name or logo empty keeps the stored one.
  Changing one is audited like any other change to a domain.

## Install the interceptor

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
cfg, err := latchkey.ConfigFromEnv(os.Getenv, authConfigured)
if err != nil { log.Fatal(err) } // see Turning it on
remote := latchkey.NewRemote(serviceHTTPClient, cfg.Addr) // authenticates as the product's service
ic, err := reg.Interceptor(cfg.Mode, remote, callerFromContext, // CallerFunc, tenant and subject
    latchkey.WithParentResolver("filament.run", runs.PipelineIDForRun),
    latchkey.WithPurger(remote),
)
if err != nil { log.Fatal(err) } // a resolve_parent with no resolver fails here, at startup
go ic.Run(ctx) // purges deleted resources in the background
err = latchkey.Handle(mux, ic, ingestionv1connect.NewIngestionServiceHandler, svc,
    connect.WithInterceptors(authInterceptor)) // the product's own options run first
if err != nil { log.Fatal(err) } // a service missing from the registration is refused
```

This wiring is for `shadow` and `remote`. A product that also runs embedded
picks its Authorizer and Purger by `cfg.Mode`, passing the
`embedded.Latchkey` for `ModeEmbedded` as [Embed Latchkey](#embed-latchkey)
shows. A remote client in embedded mode has no address, so every check
denies.

`reg.Interceptor` enforces the annotations `NewRegistration` compiled, so a
method it knows nothing about is denied. `latchkey.Handle` builds a service's
handler with the interceptor and mounts it in one call, so every handler
mounted through it is checked. It adds the interceptor after the product's own
options, so the product's authentication runs first and the caller function
finds the caller, and it refuses a service that was not registered. A
product that must build handlers itself passes `ic.HandlerOption()` last. A
handler mounted without it is not checked at all. `latchkeytest.AssertMuxCovered`
fails a test when a mounted Connect path belongs to a service that was not
registered. `NewRemote` calls Latchkey with the HTTP client it is given,
which must authenticate as the product's service, since only a domain owner
may check other subjects or purge.

**1. Each request**

The SDK looks the method up by procedure. `public` passes with no
caller. `authenticated` needs a caller. `requires` needs a caller, reads
ids by field path, resolves parents and asks Latchkey for every check in
one `CheckBatch`. An unknown method is denied, so anything the startup
check missed fails closed. An empty id, or a request that needs more
than 1,000 checks, is rejected with `INVALID_ARGUMENT`. Repeated ids are
counted once. A request that yields no checks at all, such as one whose
only requirement expands an empty list, is denied with
`PERMISSION_DENIED`, as is any deny. No caller, or a subject with no
type, is `UNAUTHENTICATED`.

`if_set` and `unless_set` follow protobuf presence. A field with explicit
presence, such as a singular message field, an `optional` field or a
`oneof` member, is set when present, even at its zero value, so a `oneof` member
set to `""` counts as set. Any other field is set when it is not empty, so
an empty string, zero, false and an empty list or map count as unset.

**2. Parent resolver**

For a `resolve_parent` requirement the SDK calls the product's resolver
for the child kind, `func(ctx, tenant, childID) (parentID, error)`, and
checks the id it returns. The resolver returns the id of the kind the
requirement checks, the top of the chain for a grandchild.
Any error or empty result denies. The resolver describes the domain and
never evaluates policy. Callers cannot lie about a child's parent,
because the product looks it up within the tenant.

**3. Streaming**

A stream is checked before the handler sees its first message. A client
or bidirectional stream checks the tenant only, before the handler
starts. A server stream may read ids from its request. In `remote` mode,
every open stream with `requires` is checked again every 60 seconds,
configurable up to 5 minutes with `WithRecheckInterval`, and closed with
`PERMISSION_DENIED` on a definite deny. A recheck that cannot reach
Latchkey is retried at the next interval, and the stream is closed with
`UNAVAILABLE` if that fails too. Once closed, the handler's context ends
and its sends fail, even in a handler that ignores its context.

**4. Deletes**

After a unary handler succeeds on a `delete` requirement of a
resource-scoped kind, the SDK queues `PurgeResource` for that kind and id,
and `ic.Run` sends it, retrying with backoff from 1 to 30 seconds, up to
10 attempts. A purge that fails every attempt is logged and dropped, as
is one Latchkey refuses for good, such as one the caller may not make. A
failed purge never fails the user's request. The queue holds 1,000 purges
and drops new ones when full. A leftover binding grants nothing, because
resource ids are never reused. Without `WithPurger` nothing is purged.

**5. Caching**

A request that needs one check is cached by tenant, subject, kind, action
and resource id for the time to live, 2 seconds by default and at most
30, set with `WithDecisionCacheTTL`. Zero turns the cache off. The SDK
tracks the newest revision it has seen per tenant, and the newest
instance revision, and never serves a decision made at an older one. A
request that needs several checks skips the cache, so all of them come
from one snapshot. The cache holds 10,000 decisions.

**6. Failure**

Errors, timeouts and an unreachable service all deny with `UNAVAILABLE`.
A check times out after 500 milliseconds by default, set with
`WithCheckTimeout`.

## Embed Latchkey

In embedded mode the product runs Latchkey itself, from the `embedded`
package, so there is no service to call.

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
store, err := sqlite.Open(filepath.Join(dataDir, "latchkey.db")) // or postgres.Open as latchkey_app
if err != nil { log.Fatal(err) }
lk, err := embedded.New(ctx, store, reg.Domain(), authenticator)
if err != nil { log.Fatal(err) } // a schema behind this build refuses here
go lk.Run(ctx) // keeps the snapshot current and saves new users
go reg.PushUntilDone(ctx, lk)
lk.Mount(mux) // the management API, for the admin UI and CLI
ic, err := reg.Interceptor(latchkey.ModeEmbedded, lk, callerFromContext,
    latchkey.WithParentResolver("filament.run", runs.PipelineIDForRun),
    latchkey.WithPurger(lk),
)
if err != nil { log.Fatal(err) }
go ic.Run(ctx) // purges deleted resources in the background
```

* The product opens the store, migrates it in its own migration step and
  closes it after `Run` returns.
* A check is a function call answered from the product's snapshot, so the
  interceptor keeps no decision cache.
* The product calls as `service:<domain>`, which owns its domain and nothing
  else. It may push its kinds, provision tenants with their first Admin,
  check and purge, and nothing more in a tenant. It only calls in process,
  so `Mount` refuses a caller authenticated as it.
* `Mount` serves Latchkey's API behind the product's authenticator, the same
  API the service serves. `lk.As(caller)` makes the calls `latchkeytest` and
  seeding need in process as another caller, under the same rules.

### On Postgres

On Postgres, Latchkey's tables live in its own `latchkey` schema in the
product's database, and the product purges a deleted resource's bindings in
the same transaction as the delete, so the two commit or roll back together.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
GRANT latchkey_purger TO filament_app; -- once, by whoever runs install.sql
```

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
store, err := postgres.Open(ctx, latchkeyAppDSN) // connects as latchkey_app
lk, err := embedded.New(ctx, store, reg.Domain(), authenticator,
    embedded.WithDBRole("filament_app")) // the product's own login role

// In the product's delete, on its own connection.
tx, err := pool.Begin(ctx)
if err != nil { return err }
defer tx.Rollback(context.WithoutCancel(ctx)) // releases the connection on every return, a no-op after Commit
// ... delete the pipeline ...
if _, err := postgres.PurgeResource(ctx, tx, tenant, "filament.pipeline", id); err != nil { return err }
return tx.Commit(ctx)
```

* Only the role `WithDBRole` names may purge, and only its own domain's
  kinds. Any other role is refused. Starting without `WithDBRole` clears
  the role, and a role purges for one domain only. Every replica of the
  product passes the same `WithDBRole`, since each one writes it when it
  starts.
* A refused purge fails the delete, which fails closed. A missing grant or a
  misspelled role name shows up as every delete failing.
* Purge last in the transaction. It locks the tenant's revision until the
  commit, which holds back management writes to that tenant.
* The interceptor still purges after the handler succeeds, and finds nothing
  left.
* The product's migration step calls `postgres.Migrate(ctx, ownerDB)` as
  `latchkey_owner`, never the product at boot.
* A purge reaches the snapshot by its next poll, which runs every 5 seconds.

On SQLite the purge cannot share the delete's transaction, so the
interceptor's purge after the delete is the only one.

## Test the integration

`latchkeytest.NewEngine(t, reg)` is real Latchkey, embedded over an
in-memory database, so a product's tests and production evaluate the same
code. It registers the product's kinds, and `Grant` and `Revoke` change
what it allows. A tenant exists once something is granted in it, with
Everyone bound to Viewer as in any new tenant. A grant Latchkey would refuse
fails the test.

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
engine := latchkeytest.NewEngine(t, reg)
engine.Grant(t, "acme", "user:alice", "filament.pipeline", latchkeyv1.Action_ACTION_UPDATE, "p1")
ic, err := reg.Interceptor(latchkey.ModeEmbedded, engine, caller,
    latchkey.WithParentResolver("filament.run", runs.PipelineIDForRun),
    latchkey.WithPurger(engine),
)
if err != nil { t.Fatal(err) }
go ic.Run(t.Context()) // purges arrive in engine.Purged() shortly after a delete
```

`latchkeytest.AssertMuxCovered(t, mux, reg)` probes every service linked
into the test binary and fails when the mux serves one that is not
registered. Connect refuses the probe's content type with 415 before any
interceptor or handler runs, so no handler runs, and a catch-all such as an
SPA at `/` does not count. It checks registration, not that every handler
has the interceptor. Mount through `latchkey.Handle` for that. Services mounted on purpose without
Latchkey, such as health checks, are passed to it to ignore.

## Tenant and subject

* **Tenant per request.** The caller function returns each request's tenant
  with its subject, so one product process can serve many tenants. The tenant must be
  the platform or IdP tenant id that provisioning uses. Filament passes
  `caller.TenantExternalID`, not its own tenant UUID.
* **Reuse the product's identity.** A product that already authenticates its
  callers maps that caller to a Latchkey subject instead of adding a second
  authenticator. Filament's `identity.Authenticator` already yields a
  provider user id or service name and a tenant, from Zitadel, Keycloak or
  the trusted `X-Forwarded-User`, `X-Forwarded-Tenant` and
  `X-Forwarded-Service` headers.
* **Machine users.** The caller function returns a `service:` subject for
  machine users. Filament's Zitadel and Keycloak service accounts arrive as
  user ids, so its caller function checks the provider's machine-user marker
  first. Otherwise they would land in Everyone.
* **Routes outside Connect.** Annotations cover Connect handlers only. Wrap a
  plain HTTP route, such as Alchemy's `POST /functions/<id>/invoke`, with
  `ic.HTTP(requirement, idFrom, handler)`. The requirement names its kind and
  action, and `idFrom` reads the resource id from the request, or is nil for
  `read` and `create`. It answers 401, 403, 400 or 503.

## Turning it on

Every product reads one explicit mode, `LATCHKEY_MODE`, with
`latchkey.ConfigFromEnv`, which also reads `LATCHKEY_ADDR`.

| Value | Behavior |
| - | - |
| `off` | The interceptor passes everything, and the product behaves as it does today. The default only when no identity provider is configured. |
| `shadow` | Evaluates every request against the service at `LATCHKEY_ADDR`, logs each decision, and allows everything. Used to measure a rollout before enforcing it. Each request still waits for its check, up to the check timeout. Purges still run. |
| `remote` | Calls the service at `LATCHKEY_ADDR` and enforces its decisions. |
| `embedded` | Evaluates in process against Latchkey embedded in the product, and enforces its decisions. See [Embed Latchkey](#embed-latchkey). `LATCHKEY_ADDR` is ignored. |

The product refuses to start on an unknown value, on `remote` or `shadow`
with no `LATCHKEY_ADDR`, on any mode but `off` with no identity provider,
and on an unset value while an identity provider is configured. A typo or a
missing variable can never silently turn enforcement off.

With no identity provider, as for Filament with `AUTH_PROVIDER` unset, every
request uses a default tenant with no caller. There is nothing to authorize,
so the mode is `off` and the SDK passes every request through, exactly as
today.

## Adoption checklist

* [ ] Every service declares its kinds, and every RPC has `requires`, `public` or `authenticated`.
* [ ] A parent resolver for every child kind used with `resolve_parent`.
* [ ] The caller function maps machine users to `service:` subjects and returns the platform or IdP tenant id.
* [ ] Every service is mounted with `latchkey.Handle`, and `go ic.Run(ctx)` runs.
* [ ] Every route outside Connect is wrapped with `ic.HTTP`.
* [ ] `latchkeytest.AssertMuxCovered` runs in the server's tests.
* [ ] The rollout ran in `shadow` and the decision log was reviewed before `remote`.


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