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

# Authentication Methods

> The vsql::preview::auth capability lets an extension provide a server authentication method: declare it, implement the handler, stage active roles, and auto-create accounts.

The capabilities on this page are in preview: their APIs are not stable, and an extension that declares one requires `vsql_allow_preview_extensions = ON` to install. See [Preview Capabilities](https://villagesql.com/docs/en/extensions/build/preview-capabilities) for how to enable the preview tier and register a capability.

The auth capability (`vsql::preview::auth`) lets an extension provide a server
authentication method. An account opts in with `CREATE USER ... IDENTIFIED WITH <method-name>`; at connection time, when that name is not a loaded MySQL auth
plugin, the server consults the VEF auth registry and invokes the extension's
handler over the handshake. Use it to authenticate accounts against a credential
source the server does not know about — a bearer token, an external identity
provider, or a custom challenge — without writing a MySQL authentication plugin.

The capability name `VEF_PREVIEW_AUTH_NAME` is `"vsql::preview::auth"`.

The handler is a typed function that receives an `AuthContext`: it talks to the
client by reading and writing handshake packets through that server-owned
context, and it never sees MySQL's internal auth structures.

> [!WARNING]
>
> The auth result is fail-closed. The server treats anything other than
> `AuthResult::kOk` as a denied connection — there is deliberately no "maybe" or
> fail-open result. A handler that returns `AuthResult::kReject`, returns
> `AuthResult::kError`, or never sets the effective account denies the login.

## Declaring the Capability

Include the header, write a typed handler, build a descriptor with the fluent
`make_auth<>` builder, and hand the descriptor to an `AuthCapability` token that
you pass to `.with()`. Preview capability headers are not part of the
`<villagesql/vsql.h>` umbrella, so include `<villagesql/preview/auth.h>`
explicitly:

```cpp theme={null}
#include <villagesql/preview/auth.h>
#include <villagesql/vsql.h>

using namespace vsql;
using vsql::preview_auth::AuthContext;
using vsql::preview_auth::AuthResult;

AuthResult authenticate(AuthContext &c) {
  // ... validate the client and set the effective account ...
  return AuthResult::kOk;
}

constexpr auto MY_AUTH =
    vsql::preview_auth::make_auth<&authenticate>("my_auth")
        .client_plugin("mysql_clear_password")
        .build();

static vsql::preview_auth::AuthCapability g_auth{MY_AUTH};

VEF_GENERATE_ENTRY_POINTS(
    make_extension()
        .with(g_auth))
```

The builder has six pieces:

| Element | Meaning |
| - | - |
| `make_auth<&handler>("name")` | Starts the builder. The handler is a compile-time template argument, so a null or wrong-signature handler is a compile error rather than a runtime failure. `"name"` is the auth-method name accounts bind to (`IDENTIFIED WITH <name>`) and must be at most `VEF_AUTH_MAX_NAME_LEN` (64) bytes. |
| `.client_plugin(name)` | Optional. Overrides the client-side auth plugin the server advertises during the handshake. |
| `.accepts_client_plugin(callback)` | Optional. Takes `bool (*)(const char *offered)`. Returning `true` keeps the plugin the client offered; returning `false` switches the client to `.client_plugin()`. |
| `.auto_create(callback)` | Optional. Opts the method in to logins for accounts that do not exist (see [Auto-Creating Accounts](#auto-creating-accounts)). |
| `.roles_mode(callback)` | Optional. Chooses how the server reconciles the roles the handler stages with the account's granted roles — activate-only, also grant, or fully sync (see [Auto-Granting Roles](#auto-granting-roles)). |
| `.build()` | Yields the descriptor you hand to `AuthCapability`. |

`AuthCapability g_auth{descriptor}` is the self-registering token consumed by
`.with()`. Declare it `static` so it outlives registration.

`client_plugin` is optional. `make_auth` defaults the advertised plugin to
`"mysql_clear_password"` — the lowest common denominator every MySQL client
ships — so a method that never calls `.client_plugin()` still installs and a
naive client still connects. Call `.client_plugin(name)` to request a different
plugin; `mysql_clear_password` receives a bearer token verbatim in the password
slot.

A client that offers a plugin other than the one the method requests is switched
to the requested plugin and resends its credential verbatim, which costs a round
trip and needs a client willing to make that switch.
`.accepts_client_plugin(&callback)` lets the method keep the offered plugin
instead: the server passes each offered name to the callback, including the
requested plugin, which is accepted whatever the callback returns. A method that
sets no callback accepts no other offer, so every other offer switches to the
requested plugin. Accepting is final — the server does not switch back to the
requested plugin afterwards — so accept only a plugin whose framing the handler
really parses. The server queries the callback during handshake negotiation,
before the handler's first read, so it must be a pure predicate: no packet I/O,
no blocking, no side effects.

## The Handler Contract

The handler matches the `AuthHandler` type — it takes an `AuthContext &` and
returns an `AuthResult`:

```cpp theme={null}
AuthResult authenticate(AuthContext &c);
```

It is invoked synchronously on the connecting thread during the handshake. The
`AuthContext` wraps the server-owned per-attempt context; hold it only for the
duration of the call and do not retain it. Call its methods instead of threading
a context pointer through a function table. The methods a token-based handler
uses:

| Method | Purpose |
| - | - |
| `c.read_packet()` | Read the next packet the client sent. Returns the bytes as a `Span<const unsigned char>` valid until the next read (empty on a protocol or connection error). Paired with `mysql_clear_password`, one read yields the bearer token. |
| `c.write_packet(data)` | Send a packet to the client (e.g. a challenge). Takes a `Span<const unsigned char>` and returns `true` on failure. |
| `c.user_name()` | The account name the client connected as. |
| `c.auth_string()` | The `AS '...'` clause from `IDENTIFIED WITH <m> AS '...'`, or empty. |
| `c.host_or_ip()` | The client host or IP. |
| `c.client_auth_plugin()` | The client-side auth plugin the client advertised in its handshake reply (for example `"mysql_clear_password"`). When the method accepted that offer, it is also the plugin that framed the credential the handler reads, so the handler can parse by name instead of sniffing bytes. A forced switch to `.client_plugin()` does not update it, so on that path it still reports what the client first offered. Empty if unknown. |
| `c.authenticate_as(account)` | Set the effective account the session runs as (shown by `CURRENT_USER()`). Required before returning `AuthResult::kOk`. |
| `c.set_external_user(identity)` | Set the original external identity for the audit trail (`@@external_user`). |
| `c.set_active_roles(roles, n_roles)` | Stage the session's active roles (see [Staging Active Roles](#staging-active-roles)). |
| `c.account_unknown()` | `true` when the account being authenticated does not exist and this login was routed to the method by its `.auto_create()` opt-in. `false` for a login against an existing account. |
| `c.request_provision(account, roles, n_roles)` | Ask the server to create `account` and grant it `roles` (see [Auto-Creating Accounts](#auto-creating-accounts)). |

The handler returns one of three results:

| Result | Meaning |
| - | - |
| `AuthResult::kOk` | Authentication succeeded. The handler must have called `authenticate_as()`; the session runs as that account. |
| `AuthResult::kReject` | Authentication failed — bad credential or policy rejection. |
| `AuthResult::kError` | An internal error prevented a decision (for example, a key source was unavailable). Treated identically to a rejection by the server. |

Both `AuthResult::kReject` and `AuthResult::kError` deny the connection. Only
`AuthResult::kOk` succeeds.

When the handler maps the connecting account to a different effective account —
as the example below maps the connecting account to `vsql_auth_test_user` — that
is proxying, and it requires a `GRANT PROXY`, exactly as on the MySQL plugin auth
path.

## Staging Active Roles

`c.set_active_roles(roles, n_roles)` stages the roles that should be active on
the session, replacing the account's default-role activation for this login.
`roles` is an array of `n_roles` NUL-terminated names; the strings are copied,
so the caller need not keep them. The server applies them *after* account
resolution, using the same grant-checked activation as `SET ROLE`: only roles
actually granted to the authenticated account activate, and names that are not
granted are silently skipped — so, unless the method sets `.roles_mode()`, a token
cannot grant or escalate privileges beyond what the DBA provisioned. Passing `n_roles == 0` activates no roles
(equivalent to `SET ROLE NONE`).

## Complete Example

A minimal authenticator, condensed from the `vsql_auth_test` extension in the
server source tree at `villagesql/test-extensions/vsql-auth-test/`, which no
release includes. It accepts one fixed token, maps the connection to
`vsql_auth_test_user`, and requests `mysql_clear_password` so the token arrives
verbatim in the password slot. (The in-tree extension adds extra token paths, an
`.accepts_client_plugin()` callback, and both opt-ins described below to drive
its test suite.)

```cpp theme={null}
#include <cstring>

#include <villagesql/preview/auth.h>
#include <villagesql/vsql.h>

using namespace vsql;
using vsql::preview_auth::AuthContext;
using vsql::preview_auth::AuthResult;

namespace {

constexpr char kToken[] = "vsql-auth-test-token";
constexpr char kMappedAccount[] = "vsql_auth_test_user";

AuthResult authenticate(AuthContext &c) {
  auto pkt = c.read_packet();
  if (pkt.empty()) return AuthResult::kError;

  // mysql_clear_password sends a NUL-terminated string; drop the trailing NUL.
  size_t len = pkt.size();
  if (len && pkt[len - 1] == '\0') --len;

  if (len != std::strlen(kToken) ||
      std::memcmp(pkt.data(), kToken, len) != 0) {
    return AuthResult::kReject;
  }

  c.authenticate_as(kMappedAccount);
  // @@external_user records the connecting identity, not the mapped account.
  c.set_external_user(c.user_name());
  return AuthResult::kOk;
}

constexpr auto AUTH_METHOD =
    vsql::preview_auth::make_auth<&authenticate>("vsql_auth_test")
        .client_plugin("mysql_clear_password")
        .build();
vsql::preview_auth::AuthCapability g_auth{AUTH_METHOD};

}  // namespace

VEF_GENERATE_ENTRY_POINTS(make_extension().with(g_auth))
```

## Binding an Account and Connecting

With the preview tier enabled (see
[Enabling the Preview Tier](https://villagesql.com/docs/en/extensions/build/preview-capabilities#enabling-the-preview-tier)), build the extension,
copy its `.veb` file into `veb_dir`, install it, and bind an
account to the method. Because the handler maps to a second account,
create that account too and grant it the `PROXY` privilege that lets the
connecting account assume its identity:

```sql theme={null}
INSTALL EXTENSION vsql_auth_test;
CREATE USER auth_user IDENTIFIED WITH vsql_auth_test;
CREATE USER vsql_auth_test_user;
GRANT SELECT ON *.* TO vsql_auth_test_user;
GRANT PROXY ON vsql_auth_test_user TO auth_user;
```

`CREATE USER ... IDENTIFIED WITH vsql_auth_test` is accepted because
`vsql_auth_test` is a registered VEF auth method — the same way an installed
plugin name is accepted.

Only the `IDENTIFIED WITH <method>` form is accepted, optionally with
`AS '...'`. Adding `BY '...'` asks the method to turn a password into a stored
credential — the job a MySQL plugin does through
`generate_authentication_string()` — and no VEF auth method declares that hook
today, so the server rejects it:

```sql theme={null}
CREATE USER auth_user IDENTIFIED WITH vsql_auth_test BY 'secret';
```

```text theme={null}
ERROR 1827 (HY000): The password hash doesn't have the expected format.
```

The bound method name is written to the account's `plugin` column rather than
the table default, which is what the account's next login reads:

```sql theme={null}
SELECT plugin FROM mysql.user WHERE user = 'auth_user';
```

```text theme={null}
+----------------+
| plugin         |
+----------------+
| vsql_auth_test |
+----------------+
```

The method requests `mysql_clear_password`, so the client must pass
`--enable-cleartext-plugin` to send the token in cleartext. On a correct token,
the session runs as the mapped account and exposes the connecting account
through `@@external_user`:

```bash theme={null}
mysql --enable-cleartext-plugin --user=auth_user \
      --password=vsql-auth-test-token \
      -e "SELECT CURRENT_USER(), @@external_user"
```

```text theme={null}
+-----------------------+-----------------+
| CURRENT_USER()        | @@external_user |
+-----------------------+-----------------+
| vsql_auth_test_user@% | auth_user       |
+-----------------------+-----------------+
```

Uninstalling the extension removes the method; accounts bound to it can no
longer authenticate:

```sql theme={null}
UNINSTALL EXTENSION vsql_auth_test;
```

## Auto-Creating Accounts

A method can also handle logins for accounts that do not exist yet, and have the
server create the account as part of the successful login. Without this, an
unknown account is rejected before any method runs.

Opt in with `.auto_create(&callback)`. The callback takes no arguments and
returns `bool`; the server calls it on each unknown-account login rather than
reading it once at registration, so the method can follow a runtime setting of
its own instead of freezing the choice when the extension loads:

```cpp theme={null}
bool auto_create_enabled() { return true; }

constexpr auto AUTH_METHOD =
    vsql::preview_auth::make_auth<&authenticate>("vsql_auth_test")
        .client_plugin("mysql_clear_password")
        .auto_create(&auto_create_enabled)
        .build();
```

Leaving `.auto_create()` off, or returning `false` from the callback, keeps the
standard behavior: an unknown account is denied. Only one installed method may
opt in at a time — if two return `true`, the server declines to guess, logs a
warning to the error log, and rejects unknown accounts as if none had opted in.

In the handler, `c.account_unknown()` distinguishes the two cases. Validate the
credential first, then describe what to create and authenticate as it:

```cpp theme={null}
if (c.account_unknown()) {
  const char *roles[] = {"vsql_role_granted"};
  c.request_provision(c.user_name(), roles, 1);
  c.authenticate_as(c.user_name());
  c.set_external_user(c.user_name());
  return AuthResult::kOk;
}
```

`request_provision(account, roles, n_roles)` records intent and returns nothing.
The server runs the DDL itself, after the handler returns `AuthResult::kOk`, and
only for a login that was routed in as an unknown account — so a login the
handler goes on to deny creates nothing, and when a request names an account that
already exists, the account keeps its binding and still receives the named roles. What the server runs is
`CREATE USER IF NOT EXISTS <account>@'%' IDENTIFIED WITH <method>`, followed by
one `GRANT` per named role: the account is always created for host `%` and bound
to the method that authenticated it, and `account` need not be the connecting
user name. If the creation cannot be done — on a `super_read_only` server, for
example — the login fails rather than proceeding without an account.

The server does not write the automatic `CREATE USER`, its `GRANT`s, or the role reconciliation `GRANT`s and `REVOKE`s to the binary log. Each server in a replication topology creates and reconciles the account for itself.

Roles behave as they do for [Staging Active Roles](#staging-active-roles): the
DBA owns them. Each name must already exist as a grantable role, and one that
cannot be granted is logged and skipped rather than failing the login, so a
token can name a role but never create or escalate one. The account name comes
from the client, so the server quotes it as an identifier — a crafted name
becomes one oddly-named account, never a second statement.

The `vsql_auth_test` extension provisions the connecting user with the role
`vsql_role_granted`, and gates the opt-in behind `vsql_auth_test.auto_create`,
which starts `OFF`. Turn it on and create the role first, then connect as an
account that does not exist:

```sql theme={null}
INSTALL EXTENSION vsql_auth_test;
SET GLOBAL vsql_auth_test.auto_create = ON;
CREATE ROLE vsql_role_granted;
GRANT SELECT ON *.* TO vsql_role_granted;
```

```bash theme={null}
mysql --enable-cleartext-plugin --user=auto_created_user \
      --password=vsql-auth-test-token \
      -e "SELECT CURRENT_USER() AS who, @@external_user AS ext"
```

```text theme={null}
+---------------------+-------------------+
| who                 | ext               |
+---------------------+-------------------+
| auto_created_user@% | auto_created_user |
+---------------------+-------------------+
```

The account now exists, bound to the method, holding the granted role:

```sql theme={null}
SELECT user, host, plugin FROM mysql.user WHERE user = 'auto_created_user';
```

```text theme={null}
+-------------------+------+----------------+
| user              | host | plugin         |
+-------------------+------+----------------+
| auto_created_user | %    | vsql_auth_test |
+-------------------+------+----------------+
```

```sql theme={null}
SHOW GRANTS FOR 'auto_created_user'@'%';
```

```text theme={null}
+----------------------------------------------------------+
| Grants for auto_created_user@%                           |
+----------------------------------------------------------+
| GRANT USAGE ON *.* TO `auto_created_user`@`%`            |
| GRANT `vsql_role_granted`@`%` TO `auto_created_user`@`%` |
+----------------------------------------------------------+
```

A wrong token still fails closed, and provisions nothing:

```bash theme={null}
mysql --enable-cleartext-plugin --user=never_created --password=wrong-token \
      -e "SELECT 1"
```

```text theme={null}
ERROR 1045 (28000): Access denied for user 'never_created'@'localhost' (using password: NO)
```

> [!WARNING]
>
> Opting in makes the difference between an unknown and an existing account
> observable, which the standard unknown-account rejection deliberately hides: a
> rejected login for an unknown account reports `(using password: NO)`, where a
> rejected login for an account with an ordinary password reports `(using password: YES)`,
> and a valid credential creates the account. That is the trade this feature
> makes; weigh it before enabling the opt-in on a method whose credentials are widely held.

## Auto-Granting Roles

By default a role a token names takes effect only if the account already holds
it; one it does not hold is skipped, and the server logs why (`VEF auth: role
'<role>'@'<host>' requested for account '<user>'@'<host>' is not granted;
skipping`). `.roles_mode(&callback)` changes that: the callback returns a
`vef_auth_roles_mode_t` — `VEF_AUTH_ROLES_ACTIVATE` (the default),
`VEF_AUTH_ROLES_GRANT`, or `VEF_AUTH_ROLES_SYNC` — and the server reconciles
the staged roles with the account's granted roles accordingly on each login.

The callback matches `.auto_create()` in shape — no arguments — but returns the
mode enum instead of a `bool`, and the server calls it on each login, reading
whatever backs it live:

```cpp theme={null}
unsigned long g_auto_grant = 0;  // 0=ACTIVATE, 1=GRANT, 2=SYNC
vef_auth_roles_mode_t roles_mode_cb() {
  return static_cast<vef_auth_roles_mode_t>(g_auto_grant);
}

constexpr auto AUTH_METHOD =
    vsql::preview_auth::make_auth<&authenticate>("vsql_auth_test")
        .client_plugin("mysql_clear_password")
        .roles_mode(&roles_mode_cb)
        .build();
```

The two opt-ins run at different points in a login. `.auto_create()` decides
whether a login for an account that does not yet exist is allowed to provision
one; `.roles_mode()` runs afterward, against whatever account the login
resolved to — the one just provisioned or one that already existed — so the
same reconciliation applies either way. `VEF_AUTH_ROLES_ACTIVATE`, or no
callback at all, keeps the activate-only default.

`VEF_AUTH_ROLES_GRANT` is additive: it grants a staged role the account lacks,
and never runs the revoke step at all. `VEF_AUTH_ROLES_SYNC` runs that step:
it revokes every granted role the token did not claim, so a role dropped from
the token is dropped from the account too on the next login — except a role
set as the account's `DEFAULT ROLE` by an operator's `ALTER USER`, which SYNC
never revokes. Under either mode, a staged role that does not exist as a DB
role fails its `GRANT` and is logged and skipped rather than failing the
login.

`vsql_auth_test` exposes this as `vsql_auth_test.auto_grant`, an `OFF`/`ON`/`SYNC`
enum (also `OFF` to start) whose index order matches the mode order above. Its
`-token-roles` token stages `vsql_role_granted` and `vsql_role_denied`, and the
account below holds neither. With the setting off, the login leaves the
account's roles alone:

```sql theme={null}
CREATE USER IF NOT EXISTS auth_user IDENTIFIED WITH vsql_auth_test;
CREATE USER IF NOT EXISTS vsql_auth_test_user;
GRANT SELECT ON *.* TO vsql_auth_test_user;
GRANT PROXY ON vsql_auth_test_user TO auth_user;
CREATE ROLE IF NOT EXISTS vsql_role_granted, vsql_role_denied;
```

Connect as `auth_user` with the password `vsql-auth-test-token-roles`, in the same way as above, and
ask what is active with `SELECT CURRENT_ROLE()`:

```text theme={null}
+----------------+
| CURRENT_ROLE() |
+----------------+
| NONE           |
+----------------+
```

Turn the setting on and repeat the same login:

```sql theme={null}
SET GLOBAL vsql_auth_test.auto_grant = ON;
```

```text theme={null}
+------------------------------------------------+
| CURRENT_ROLE()                                 |
+------------------------------------------------+
| `vsql_role_denied`@`%`,`vsql_role_granted`@`%` |
+------------------------------------------------+
```

Both roles are now active, and `SHOW GRANTS` shows the grant the server added:

```sql theme={null}
SHOW GRANTS FOR vsql_auth_test_user;
```

```text theme={null}
+-----------------------------------------------------------------------------------+
| Grants for vsql_auth_test_user@%                                                  |
+-----------------------------------------------------------------------------------+
| GRANT SELECT ON *.* TO `vsql_auth_test_user`@`%`                                  |
| GRANT `vsql_role_denied`@`%`,`vsql_role_granted`@`%` TO `vsql_auth_test_user`@`%` |
+-----------------------------------------------------------------------------------+
```

> [!WARNING]
>
> With `vsql_auth_test.auto_grant` set to `ON` or `SYNC`, a valid token is enough
> to gain any role it names. A role that does not already exist as a DB role
> fails its `GRANT` and is skipped, so a token still cannot invent a role that
> was never created, but the DBA no longer decides which of the roles that do
> exist an account may reach — the auth method does. `SYNC` goes further: it
> also revokes a role a DBA granted out of band but the token never claims, when
> the account next logs in — an operator can still pin one role past that by
> setting it as the account's `DEFAULT ROLE`, which SYNC leaves alone. A role
> revoked from `vsql_auth_test_user` does not disappear from a session that
> already activated it: querying `CURRENT_ROLE()` again in that same session,
> after the revoke, still lists the role.


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