agent-native icon indicating copy to clipboard operation
agent-native copied to clipboard

Email change is refused in a multi-app workspace: each app only knows its own identity column declarations, but the rekey scans the shared database

Open renansantos opened this issue 3 weeks ago • 1 comments

Environment: @agent-native/core 0.227.0 on main at c141e722ac (2026-11-11). Also reproduced on 0.223.0 in a workspace with Dispatch and one more app sharing one DATABASE_URL, which multi-app-workspace.mdx describes as the default ("share the same database"). Any platform.

What happens: in the non-Dispatch app, a user goes to Settings → Profile → Change and submits a new address. The rekey preflight refuses the change, and the server logs:

ERROR [Better Auth]: Failed to run background task: Error: dispatch_destinations.created_by looks identity-bearing but has no identity policy; declare it with registerIdentityColumns() from @agent-native/core/org. Refusing to run an incomplete identity migration.

No email is sent. The UI reports success instead of this error; that part is #9067.

Cause:

  • resolveIdentityColumns (packages/core/src/identity/rekey.ts:458) reads every table in the database from information_schema.columns. It refuses the whole rekey on the first identity-shaped column without a policy (line 498).
  • Identity policies live in process memory. Dispatch registers its own in packages/dispatch/src/server/plugins/db.ts, and that plugin only loads in the Dispatch process. The other app's process never sees those declarations, but Dispatch's tables are in the same database.
  • The preflight runs in sendChangeEmailConfirmation (packages/core/src/server/better-auth-instance.ts:2479), so no email change can start from any app other than Dispatch. By the same logic, a change started in Dispatch should hit any column the other app declares; I did not test that direction.
  • The CLI (agent-native identity rekey) accepts one --identity-declarations file, so it does not cover two apps either.

Reproduction in core: this spec passes on main from packages/core. It creates the Better Auth, organization and Dispatch tables (packages/dispatch/src/db/migrations.ts) in one PGlite database and runs the same dry run as the preflight. Without Dispatch's declarations the dry run refuses. With them, copied from the Dispatch plugin, it passes.

import { afterEach, expect, it, vi } from "vitest";

import { dispatchMigrations } from "../../../dispatch/src/db/migrations.js";
import {
  SINGLE_CONNECTION_NEON_URL,
  createSingleConnectionNeonPool,
} from "../db/test-single-connection-neon-pool.js";
import { ORG_MIGRATIONS } from "../org/migrations.js";
import { BETTER_AUTH_MIGRATIONS } from "../server/better-auth-migrations.js";

const OLD = "[email protected]";
const NEW = "[email protected]";

afterEach(async () => {
  const { closeDbExec } = await import("../db/client.js");
  await closeDbExec();
  vi.unstubAllEnvs();
  vi.resetModules();
});

function rekeyDb(pglite: any) {
  const wrap = (client: any) => ({
    async unsafe(sql: string, args: unknown[] = []) {
      const result = await client.query(sql, args);
      return Object.assign(result.rows, { count: result.affectedRows ?? 0 });
    },
  });
  return {
    ...wrap(pglite),
    transaction: (run: any) => pglite.transaction((tx: any) => run(wrap(tx))),
  } as any;
}

it("an email change from a non-Dispatch app refuses on Dispatch's tables in a shared database", async () => {
  vi.stubEnv("DATABASE_URL", SINGLE_CONNECTION_NEON_URL);
  vi.stubEnv("AWS_LAMBDA_FUNCTION_NAME", "repro");
  vi.stubEnv("DB_OP_TIMEOUT_MS", "2000");
  vi.stubEnv("BETTER_AUTH_SECRET", "s".repeat(48));
  vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "0");
  const { pool, pglite } = await createSingleConnectionNeonPool();
  for (const entry of BETTER_AUTH_MIGRATIONS) {
    const sql = typeof entry.sql === "string" ? entry.sql : entry.sql.postgres;
    if (sql) await pglite.exec(sql);
  }
  for (const entry of ORG_MIGRATIONS) await pglite.exec(entry.sql);
  for (const entry of dispatchMigrations) {
    if (typeof entry.sql === "string") await pglite.exec(entry.sql);
  }
  const { getRuntimeDatabaseUrl, sharedDbPool } =
    await import("../db/client.js");
  sharedDbPool("neon", getRuntimeDatabaseUrl("pglite:./data/pglite"), () => pool);
  const { getBetterAuth } = await import("../server/better-auth-instance.js");
  const auth = await getBetterAuth();
  await auth.api.signUpEmail({
    body: { email: OLD, password: "correct-horse-battery", name: "Alice" },
  });

  // This process is the other app: Dispatch's registerIdentityColumns() never ran.
  const { rekeyIdentity, registerIdentityColumns } = await import("./rekey.js");
  const preflight = () =>
    rekeyIdentity(rekeyDb(pglite), OLD, NEW, {
      dryRun: true,
      revokeSessions: false,
    });
  await expect(preflight()).rejects.toThrow(/has no identity policy/);

  // Same database once Dispatch's declarations are loaded.
  registerIdentityColumns([
    { table: "dispatch_identity_links", column: "owner_email", emailChange: "rekey", offboard: "delete", reason: "copy" },
    { table: "dispatch_link_tokens", column: "owner_email", emailChange: "rekey", offboard: "delete", reason: "copy" },
    { table: "identity_sso_authorization_code", column: "email", emailChange: "delete", offboard: "delete", reason: "copy" },
    { table: "identity_sso_bootstrap", column: "email", emailChange: "delete", offboard: "delete", reason: "copy" },
    ...["dispatch_destinations", "dispatch_dreams", "dispatch_link_tokens", "vault_secrets", "workspace_resources"].map(
      (table) => ({ table, column: "created_by", emailChange: "retain" as const, offboard: "retain" as const, reason: "copy" }),
    ),
  ]);
  await expect(preflight()).resolves.toBeTruthy();
});

Possible fixes:

  • Persist the declarations: each app writes its policies to a table during its migrations, and the rekey reads every app's policies from the database instead of from process memory.
  • Or scope the rekey to the tables the running app owns, and run it once per app, the way separate databases are already handled ("Run once per app").

Which direction would you prefer?

renansantos avatar Nov 11 '26 15:11 renansantos

The email-change fix needs further work before it is safe to ship: the shared-data migration and verification flow still fail the expanded regression. A maintainer needs to review the remaining safety and atomicity work.

builder-factory avatar Nov 14 '26 01:11 builder-factory