# `PgRest.Auth`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/auth.ex#L1)

Who a request runs as: RLS mode's bearer token, role allowlist and request GUCs
(`PgRest.Plug`'s `rls:` option), or, without it, the `anonymous?` predicate.

## RLS mode

`rls:` makes every request run as a database role, as PostgREST does:

    forward "/api", PgRest.Plug,
      repo: MyApp.AuthenticatorRepo,
      rls: [
        roles: ["anon", "authenticated", "service_role"],
        jwt: {PgRest.JWT.HS256, secret: {:system, "JWT_SECRET"}},
        pre_request: "public.check_request"
      ]

  1. No `Authorization: Bearer` header: the `default_role` (`"anon"`; `nil` makes the request
     a 401 `PGRST302`). A token is verified by `jwt:` (`{PgRest.JWT.HS256, secret: ...}`, or
     `:context` to take the claims a `:context_builder` verified from `context[:jwt_claims]`).
  2. The role is the claim at `role_claim` (`"role"`, or a key path such as
     `["app_metadata", "role"]`), else `default_role`. A role outside the `roles:` allowlist
     is a 401 `22023` `role "<role>" does not exist`, before any SQL runs.
  3. The request transaction's setup statement sets the role's `ALTER ROLE ... SET` settings
     (database-wide, of the roles the login is a member of, as PostgREST reads them), then
     `role`, `request.jwt.claims` (the claims with `role` inserted), `request.method`,
     `request.path`, `request.headers` (lowercase names, no `Cookie`; a repeated header keeps
     its last value where the adapter keeps duplicates, as Plug.Test and Bandit do, while
     Plug.Cowboy joins them with `", "`) and `request.cookies`; reads run in a read-only
     transaction. `pre_request: "schema.fn"` is then called in the same transaction.

A request is authenticated when its role is not `default_role` (PostgREST's
`authRole /= anonRole`): a `42501` is then a 403 instead of a 401.

`ALTER ROLE ... SET` changes need a restart or `PgRest.Catalog.forget/1` for the plug's repo.

The repo must log in as a role that is neither superuser nor `BYPASSRLS` (a `NOINHERIT`
authenticator granted the API roles): otherwise every request raises `ArgumentError`, unless
`allow_privileged_login: true`, which logs a warning once per repo instead.

## Differences from PostgREST

  * Roles are an allowlist: a token naming `none`, `postgres` or any role outside `roles:` is
    a 401 `22023`. PostgREST switches to any role the authenticator may assume
    (`role: "none"` runs as the authenticator; `role: "postgres"` is a 403 `42501`
    `permission denied to set role`).
  * `request.path` is relative to the plug's mount (`forward "/api"` sees `/rls_notes`);
    PostgREST's is the full request path.
  * `pre_request` runs after PgRest has planned the request, so an error found while planning
    (an unknown column) answers before the function's own. PostgREST calls it before the
    database sees the query: `select=nope` with a pre-request that raises gets its `P0001`.
  * A superuser or `BYPASSRLS` login raises (see above); PostgREST serves it.
  * A role's `default_transaction_isolation` setting is not applied; PostgREST opens that
    role's transactions at that isolation level. PgRest's run at the server default.

# `rls`

```elixir
@type rls() :: %{
  roles: [String.t()],
  role_claim: [String.t()],
  default_role: String.t() | nil,
  jwt: {module(), keyword()} | :context,
  pre_request: String.t() | nil,
  allow_privileged_login: boolean()
}
```

# `t`

```elixir
@type t() :: %{claims: map(), db_role: String.t() | nil, authenticated?: boolean()}
```

# `anonymous`

```elixir
@spec anonymous() :: t()
```

An anonymous resolution without RLS mode: no claims, no role.

# `check_login!`

```elixir
@spec check_login!(module(), PgRest.Catalog.Facts.t(), rls()) :: :ok
```

Raises when RLS mode's repo logs in as a superuser or `BYPASSRLS` role (from
`PgRest.Catalog.facts/1`), unless `allow_privileged_login: true`, which logs the same text as
a warning once per repo.

# `default_anonymous?`

```elixir
@spec default_anonymous?(Plug.Conn.t(), map()) :: boolean()
```

The default `anonymous?` predicate of non-RLS mode: whether `context[:role]` (the default
context reads it from `conn.assigns`) is `nil`, `:anon` or `"anon"`.

# `init`

```elixir
@spec init(keyword() | nil) :: rls() | nil
```

Validates the `rls:` plug option and fills its defaults (`role_claim: "role"`,
`default_role: "anon"`, `pre_request: nil`, `allow_privileged_login: false`). `nil` (no RLS
mode) stays `nil`. Raises `ArgumentError`.

# `resolve`

```elixir
@spec resolve(Plug.Conn.t(), rls() | nil, map(), (Plug.Conn.t(), map() -&gt; boolean())) ::
  {:ok, t()} | {:error, PgRest.Error.t()}
```

Resolves who `conn` runs as. In RLS mode (`rls` from `init/1`), from the bearer token (see the
moduledoc); otherwise `claims` are empty, `db_role` is `nil` and the request is authenticated
unless `anonymous?.(conn, context)`.

# `role`

```elixir
@spec role(map() | nil) :: :anon | :authenticated
```

The role `PgRest.Error` constructors and `PgRest.Error.Translate` take, from anything that
carries `authenticated?` (a resolution, a request, a context or an executor config).

# `transaction`

```elixir
@spec transaction(Plug.Conn.t(), t(), rls() | nil, PgRest.Catalog.Facts.t()) :: map()
```

What the request transaction needs from an RLS-mode request: the role's `ALTER ROLE` settings
(`PgRest.Catalog.Facts`, set before the role, as PostgREST does), the setup statement's GUCs
in PostgREST's order, whether a read is read-only, and the `pre_request` call. Without RLS
mode only `authenticated?` is set (for error statuses).

---

*Consult [api-reference.md](api-reference.md) for complete listing*
