diff --git a/.changeset/managed-email-password-held-off.md b/.changeset/managed-email-password-held-off.md new file mode 100644 index 00000000000..83eb1157e50 --- /dev/null +++ b/.changeset/managed-email-password-held-off.md @@ -0,0 +1,22 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: a cloud-managed runtime keeps email and password sign-in off when its deployment declares it off + +Clause-②: yes (narrowing) — narrowed: on a cloud-managed runtime (`OS_CLOUD_MANAGED=1`) whose deployment declares `emailAndPassword.enabled: false`, an auth settings save (`PUT /api/settings/auth`, `SettingsService.setMany('auth', …)`) that changes `email_password_enabled` to a value that reads on answers `400 SETTINGS_VALIDATION` (`invalid_value` at the key) and saves nothing in the batch, where it saved; a stored `email_password_enabled` that reads on is no longer applied there, so `GET /api/v1/auth/config` keeps answering `emailPassword.enabled: false`; and there a Google change no longer counts email and password as a way in, whatever the same save sets it to. Widened: on that runtime, a save that turns `email_password_enabled` off or clears it answers `200` and saves, where the sign-in method floor refused it `400 SETTINGS_VALIDATION`, because the host holds email and password off either way; the field error at that key can carry `constraint: { cloudManaged: true, declaredEmailPassword: false }`; a `managedEmailPassword` key on the sign-in floor copy, in all 11 locales; a module export (not on the package entry) `emailPasswordHeldOffByHost`. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the auth settings save or the email and password switch; `content/docs/deployment/self-hosting.mdx` and `content/docs/permissions/sso.mdx` gain the cloud-managed case in this change. + + + +**BREAKING** for a cloud-managed runtime whose deployment declares email and password off: saving the auth settings with `email_password_enabled` changed to on is refused `400 SETTINGS_VALIDATION` and nothing in that save is written, and a value stored on earlier no longer turns email and password sign-in on. Self-hosted deployments, and cloud-managed ones whose deployment declares email and password on, are unchanged. + +On a cloud-managed runtime (`OS_CLOUD_MANAGED=1`) the host refuses every password door. When such a runtime's deployment declared `emailAndPassword.enabled: false`, a stored `auth.email_password_enabled` that read on still overrode the declaration: `GET /api/v1/auth/config` answered `emailPassword.enabled: true`, and the sign-in page drew an email and password form whose every submit was refused. + +- **The settings pass.** On such a runtime a stored `auth.email_password_enabled` that reads on is not applied, and the server says so once at `error`, with the remedy: clear the setting (or set it off) in the settings console. An `OS_AUTH_EMAIL_PASSWORD_ENABLED` value is the deployment's own declaration and still applies. +- **The save door.** A save that turns `auth.email_password_enabled` on there is refused with `400 SETTINGS_VALIDATION` and an `invalid_value` field error at the key, in the caller's language. Turning it off or clearing it is accepted there: the host holds it off either way, so the sign-in method floor no longer refuses that save. + +Self-hosted deployments, and cloud-managed ones whose deployment declares email and password on, keep the toggle exactly as before. + +What to do: nothing to migrate. On such a runtime, clear `auth.email_password_enabled` (or set it off) in the settings console if the server reports it stored on and not applied. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 61e7dc720a9..adb1a3189b0 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -813,6 +813,17 @@ wins over a stored `auth.email_password_enabled = false` and over the stack config, and email and password sign-in comes back. Or restore the sign-in method the configuration no longer declares. +A cloud-managed runtime (`OS_CLOUD_MANAGED=1`) whose deployment declares email +and password off is the exception. The host refuses every password sign-in +there, so the settings never turn it back on: a save of +`auth.email_password_enabled` that reads on is refused +`400 SETTINGS_VALIDATION` at the field, a value stored on earlier is not +applied (the server says so once at **error**), and `GET /api/v1/auth/config` +keeps answering `emailPassword.enabled: false`. Turning the switch off or +clearing it is accepted there without the checks above, because it removes no +way in. `OS_AUTH_EMAIL_PASSWORD_ENABLED` is the deployment's own declaration +and still applies. + ## Who may sign up — and what each posture tells a stranger `auth.audience.posture` is the one declaration answering who may become a user diff --git a/content/docs/permissions/sso.mdx b/content/docs/permissions/sso.mdx index 47d07d2df22..89352bd4b9b 100644 --- a/content/docs/permissions/sso.mdx +++ b/content/docs/permissions/sso.mdx @@ -843,6 +843,13 @@ Recover by setting `OS_AUTH_DIRECT_SIGN_IN_LOCAL_PATH=hidden`, and `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` too when email and password sign-in is off, then restarting. +On a cloud-managed runtime whose deployment declares email and password off, +the email and password switch is judged before these checks, under `off` or +not: a save that turns it on is refused `400 SETTINGS_VALIDATION`, a value +stored on earlier is not applied, and email and password does not count as a +way in for a Google change in the same save +([Self-hosting](/docs/deployment/self-hosting)). + **What a visit does.** The Console sign-in page reads `features.directSignIn` from `GET /api/v1/auth/config`. That is `true` only while a provider can be started, and only when this server mounted the door: a setting turned on diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index cd9bb3b4ec5..37cb30ada34 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -151,6 +151,7 @@ import { type SignInPathConfigView, } from './boot-sign-in-reachability.js'; import { + emailPasswordHeldOffByHost, providerCredentialIndex, providerCredentialsFrom, registerSignInMethodFloor, @@ -704,6 +705,8 @@ export class AuthPlugin implements Plugin { private allowListUndeterminedWarned = false; /** Set once the settings pass has said that `auth.mfa_required` reads a toggle spelling. */ private legacyMfaRequiredNoted = false; + /** Whether the not-applied stored `email_password_enabled` was said (see `bindAuthSettings`). */ + private heldOffEmailPasswordNoted = false; private allowListUntrustedHeaderWarned = false; /** The applied allow-list value whose unreadable value or entries were last reported, so one is reported once. */ private allowListUnreadableReportedFor: string | undefined; @@ -2430,6 +2433,7 @@ export class AuthPlugin implements Plugin { env: () => ((globalThis as any)?.process?.env ?? {}) as Record, // [#30312] A cleared toggle returns to the declaration: judge it there. declaredEmailPasswordEnabled: () => this.declaredAuthOptions.emailAndPassword?.enabled !== false, + cloudManaged: () => isCloudManaged(), }; } @@ -2582,10 +2586,33 @@ export class AuthPlugin implements Plugin { options, }); }; + // A cloud-managed runtime whose deployment declared email and password + // off keeps it off: the host refuses every password door there, so a + // stored value that reads on would only advertise a form that signs + // nobody in. The save door refuses turning it on (sign-in-method-floor.ts); + // a row stored before that check, or a re-save of the manifest default + // the save door is never asked about, is not applied. An + // `OS_AUTH_EMAIL_PASSWORD_ENABLED` value is the deployment's own + // declaration and still applies. + let emailPasswordHeldOff = false; if (isExplicit('email_password_enabled')) { - emailAndPasswordField('email_password_enabled', { - enabled: asBoolean(values.email_password_enabled, true), - }); + const enabled = asBoolean(values.email_password_enabled, true); + emailPasswordHeldOff = enabled && sources.email_password_enabled !== 'env' + && emailPasswordHeldOffByHost(this.signInMethodFloorDeps(ctx, authManager)); + if (!emailPasswordHeldOff) emailAndPasswordField('email_password_enabled', { enabled }); + } + if (emailPasswordHeldOff && !this.heldOffEmailPasswordNoted) { + this.heldOffEmailPasswordNoted = true; + // `error`, as for the audience settings below: the console shows the + // stored value as saved while the runtime does not apply it. + ctx.logger.error( + '[auth] auth.email_password_enabled is stored on, and NOT APPLIED: this environment is cloud-managed and its ' + + 'deployment turns email and password sign-in off, so people sign in through the hosting organisation\'s ' + + 'identity provider and the sign-in page offers no email and password form. Clear ' + + 'auth.email_password_enabled (or set it off) in the settings console so the page matches what runs.', + ); + } else if (!emailPasswordHeldOff) { + this.heldOffEmailPasswordNoted = false; } if (isExplicit('signup_enabled')) { emailAndPasswordField('signup_enabled', { diff --git a/packages/plugins/plugin-auth/src/cloud-managed.test.ts b/packages/plugins/plugin-auth/src/cloud-managed.test.ts index f41e1c9cf4f..64d0c7e2476 100644 --- a/packages/plugins/plugin-auth/src/cloud-managed.test.ts +++ b/packages/plugins/plugin-auth/src/cloud-managed.test.ts @@ -549,6 +549,26 @@ describe('[#25083] the password doors on a cloud-managed environment', () => { expect(s.credentialOf(s.ids.member)?.password).not.toBe(before); }, 120_000); + it('admin update-user takes no password: data.password is refused and no credential is written or moved', async () => { + // better-auth's own admin route refuses the key on every deployment + // (`PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER`); pinned here so a vendor + // upgrade that starts accepting it cannot open a password door on a + // managed runtime unnoticed. + const s = await stage(); + setManaged(true); + const before = s.credentialOf(s.ids.member)?.password; + expect(before).toBeDefined(); + for (const userId of [s.ids.member, s.ids.idp]) { + const v = await verdict( + await s.fire('/admin/update-user', { userId, data: { password: NEW_PASSWORD } }, s.bearers.admin), + ); + expect(v.status, v.text).toBe(400); + expect(v.code, v.text).toBe('PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER'); + } + expect(s.credentialOf(s.ids.member)?.password).toBe(before); + expect(s.credentialOf(s.ids.idp)).toBeUndefined(); + }, 120_000); + it('set-initial-password refuses a caller without platform-admin standing with 409 and writes no credential', async () => { const s = await stage(); setManaged(true); diff --git a/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts b/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts index 0b0932c9b6b..4ffd9df485e 100644 --- a/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts +++ b/packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts @@ -57,10 +57,24 @@ * 12. the exits still count under `'off'`, on the save, the delete and the * boot report: another provider row, a social or OIDC provider with * credentials, a host handoff. + * + * On a cloud-managed runtime (`OS_CLOUD_MANAGED=1`) whose deployment declared + * email and password off, the host refuses every password door, so: + * 13. a stored `email_password_enabled` that reads on is not applied, and + * `getPublicConfig()` keeps answering `emailPassword.enabled: false` + * (measured before the fix: `true`), said once at `error`; a save that + * turns it on is refused at the save door (400 `SETTINGS_VALIDATION`, in + * the caller's language), and turning it off or clearing it passes; + * the `OS_AUTH_EMAIL_PASSWORD_ENABLED` declaration still applies; a + * Google change does not count email and password as a way in there; + * CONTROLS: self-hosted with the same declaration, and managed with + * email and password declared on, keep the toggle as before. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +// Paid during collection, not inside a clocked case: the auth manager loads it lazily. +import '@objectstack/core/egress'; +import { ObjectKernel, resetCloudManagedForTesting, type Plugin, type PluginContext } from '@objectstack/core'; import type { IHttpRequest, IHttpResponse, IHttpServer, RouteHandler } from '@objectstack/spec/contracts'; import { ObjectQLPlugin, @@ -1002,3 +1016,219 @@ describe('the floor judges a provider delete and a boot by what it can read (#30 await expect(reportIfNoSignInMethodAtBoot(deps(), throwing as any)).resolves.toContain(NO_SIGN_IN_METHOD_AT_BOOT); }); }); + +describe('a cloud-managed runtime keeps email and password off when its deployment declares it off', () => { + const MANAGED_ENV_KEYS = ['OS_CLOUD_MANAGED', 'OS_AUTH_EMAIL_PASSWORD_ENABLED', 'OS_AUTH_SSO_ONLY'] as const; + const savedEnv: Partial> = {}; + const ADMIN = { enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }; + + /** The managed switch as the cloud's containers set it; off = unset, as on a self-hosted image. */ + const setManaged = (on: boolean) => { + if (on) process.env.OS_CLOUD_MANAGED = '1'; + else delete process.env.OS_CLOUD_MANAGED; + // `isCloudManaged()` memoizes its first read. + resetCloudManagedForTesting(); + }; + + beforeEach(() => { + for (const key of MANAGED_ENV_KEYS) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } + setManaged(true); + }); + + afterEach(() => { + for (const key of MANAGED_ENV_KEYS) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } + resetCloudManagedForTesting(); + vi.restoreAllMocks(); + }); + + const makeSettings = (env: Record = {}) => { + const settings = new SettingsService({ env, crypto: new ConfidentialTestAdapter() }); + settings.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); + return settings; + }; + + /** Boot as a host does (init → start → kernel:ready), with email and password declared as given. */ + const boot = async (opts: { settings?: SettingsService; emailPassword?: boolean } = {}) => { + const settings = opts.settings ?? makeSettings(); + const hooks = new Map Promise>>(); + const logger = { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }; + const ctx = { + registerService: vi.fn(), + getService: vi.fn((name: string) => { + if (name === 'manifest') return { register: vi.fn() }; + if (name === 'settings') return settings; + return undefined; + }), + getServices: vi.fn(() => new Map()), + hook: vi.fn((name: string, handler: () => Promise) => { + hooks.set(name, [...(hooks.get(name) ?? []), handler]); + }), + trigger: vi.fn(), + logger, + getKernel: vi.fn(), + } as unknown as PluginContext; + const plugin = new AuthPlugin({ + secret: SECRET, + baseUrl: 'http://localhost:3000', + emailAndPassword: { enabled: opts.emailPassword ?? false }, + }); + await plugin.init(ctx); + const manager = (ctx.registerService as any).mock.calls.find(([name]: [string]) => name === 'auth')?.[1] as AuthManager; + await plugin.start(ctx); + for (const handler of hooks.get('kernel:ready') ?? []) await handler(); + const heldOffSaid = () => + logger.error.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('auth.email_password_enabled is stored on')); + return { settings, manager, heldOffSaid }; + }; + + const passwordOn = (manager: AuthManager) => manager.getPublicConfig().emailPassword.enabled; + /** Let the settings pass a write's change event started run to its end. */ + const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); + + /** `PUT /api/settings/auth` through the real settings route. */ + const put = async (settings: SettingsService, body: Record, headers: Record = {}) => { + const routes = new Map(); + const add = (method: string) => (path: string, handler: RouteHandler) => { + routes.set(`${method} ${path}`, handler); + return http; + }; + const http = { + get: add('GET'), post: add('POST'), put: add('PUT'), delete: add('DELETE'), patch: add('PATCH'), + use: () => http, listen: async () => {}, close: async () => {}, getInstance: () => null, + } as unknown as IHttpServer; + registerSettingsRoutes(http, settings, { contextFromRequest: () => ({ ...ADMIN }) }); + const state: { status: number; body?: any } = { status: 200 }; + const res = { + json: vi.fn((data: unknown) => { state.body = data; }), + send: vi.fn(), + status: vi.fn((code: number) => { state.status = code; return res; }), + header: vi.fn(() => res), + } as unknown as IHttpResponse; + const req = { + params: { namespace: 'auth' }, query: {}, body, headers, method: 'PUT', path: '/api/settings/auth', + } as unknown as IHttpRequest; + await routes.get('PUT /api/settings/:namespace')!(req, res); + return state; + }; + + it('a stored value that reads on is not applied: the public config keeps answering off, said once', async () => { + const { settings, manager, heldOffSaid } = await boot(); + expect(passwordOn(manager)).toBe(false); + + // With nothing stored the value resolves to the manifest default (on), so + // this save is no change to the settings service, reaches no predicate, + // and is stored. Measured before the fix: the public config answered true. + await settings.setMany('auth', { email_password_enabled: true }); + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: true, source: 'global' }); + await settle(); + expect(passwordOn(manager)).toBe(false); + expect(heldOffSaid()).toHaveLength(1); + + // Another pass (any auth save re-runs it) keeps it off and says nothing again. + await settings.setMany('auth', { password_min_length: 12 }); + await vi.waitFor(() => expect((manager as any).config.emailAndPassword?.minPasswordLength).toBe(12)); + expect(passwordOn(manager)).toBe(false); + expect(heldOffSaid()).toHaveLength(1); + }); + + it('a row stored on before this check, read at boot, is not applied either', async () => { + const settings = makeSettings(); + await settings.set('auth', 'email_password_enabled', true, {}); + const { manager, heldOffSaid } = await boot({ settings }); + await settle(); + expect(passwordOn(manager)).toBe(false); + expect(heldOffSaid()).toHaveLength(1); + }); + + it('turning it on is refused at the save door, at the key, in the caller language; nothing is written', async () => { + const { settings, manager } = await boot(); + // Off (or a clear) is never refused here: the host holds it off either way. + await settings.setMany('auth', { email_password_enabled: false }); + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: false, source: 'global' }); + + const refusal = await refusalOf(settings.setMany('auth', { email_password_enabled: true, password_min_length: 12 })); + expect(refusal.code).toBe('SETTINGS_VALIDATION'); + expect(refusal.fields).toEqual([ + expect.objectContaining({ + field: 'email_password_enabled', + code: 'invalid_value', + constraint: { cloudManaged: true, declaredEmailPassword: false }, + }), + ]); + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: false }); + expect(await settings.get('auth', 'password_min_length')).toMatchObject({ source: 'default' }); + + const http = await put(settings, { email_password_enabled: 'true' }, { 'accept-language': 'zh-CN,zh;q=0.9' }); + expect(http.status).toBe(400); + expect(http.body.error.code).toBe('SETTINGS_VALIDATION'); + const [field] = http.body.error.details.fields; + expect(field).toMatchObject({ field: 'email_password_enabled', code: 'invalid_value' }); + expect(field.message).toBe(SIGN_IN_FLOOR_COPY['zh-CN'].managedEmailPassword); + await settle(); + expect(passwordOn(manager)).toBe(false); + }); + + it('a row stored on is put right by clearing it, which the sign-in floor does not refuse', async () => { + const { settings, manager, heldOffSaid } = await boot(); + await settings.setMany('auth', { email_password_enabled: true }); + await settle(); + expect(heldOffSaid()).toHaveLength(1); + + await settings.setMany('auth', { email_password_enabled: null }); + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ source: 'default' }); + await settle(); + expect(passwordOn(manager)).toBe(false); + }); + + it('email and password counts as no way in for a Google change in the same save', async () => { + const { settings, manager } = await boot(); + await settings.setMany('auth', GOOGLE); + await vi.waitFor(() => expect( + manager.getPublicConfig().socialProviders.some((p: { id: string }) => p.id === 'google'), + ).toBe(true)); + // `true` is the resolved default here, so no predicate is asked at that key; + // the Google key must not read it as a way in the runtime will offer. + const refusal = await refusalOf(settings.setMany('auth', { email_password_enabled: true, google_enabled: false })); + expect(refusal.code).toBe('SETTINGS_VALIDATION'); + expect(refusal.fields).toEqual([ + expect.objectContaining({ field: 'google_enabled', code: 'invalid_value', constraint: { lastSignInMethod: 'google' } }), + ]); + expect(await settings.get('auth', 'google_enabled')).toMatchObject({ value: true }); + expect(passwordOn(manager)).toBe(false); + }); + + it('the OS_AUTH_EMAIL_PASSWORD_ENABLED declaration still applies', async () => { + const { manager } = await boot({ settings: makeSettings({ OS_AUTH_EMAIL_PASSWORD_ENABLED: 'true' }) }); + await vi.waitFor(() => expect(passwordOn(manager)).toBe(true)); + }); + + it('CONTROL: self-hosted, the same declaration takes the stored toggle as before', async () => { + setManaged(false); + const { settings, manager, heldOffSaid } = await boot(); + expect(passwordOn(manager)).toBe(false); + await settings.setMany('auth', { email_password_enabled: true }); + await vi.waitFor(() => expect(passwordOn(manager)).toBe(true)); + // The sign-in floor still judges turning it off there (nothing else signs anyone in). + await refusalOf(settings.setMany('auth', { email_password_enabled: false })); + expect(heldOffSaid()).toHaveLength(0); + }); + + it('CONTROL: managed with email and password declared on, the floor judges the toggle as before', async () => { + const { settings, manager, heldOffSaid } = await boot({ emailPassword: true }); + expect(passwordOn(manager)).toBe(true); + const refusal = await refusalOf(settings.setMany('auth', { email_password_enabled: false })); + expect(refusal.fields).toEqual([ + expect.objectContaining({ field: 'email_password_enabled', constraint: { lastSignInMethod: 'email_password' } }), + ]); + await expect(settings.setMany('auth', { email_password_enabled: true })).resolves.toBeDefined(); + await settle(); + expect(passwordOn(manager)).toBe(true); + expect(heldOffSaid()).toHaveLength(0); + }); +}); diff --git a/packages/plugins/plugin-auth/src/sign-in-method-floor.ts b/packages/plugins/plugin-auth/src/sign-in-method-floor.ts index de318e83dfb..6e215db8591 100644 --- a/packages/plugins/plugin-auth/src/sign-in-method-floor.ts +++ b/packages/plugins/plugin-auth/src/sign-in-method-floor.ts @@ -54,7 +54,14 @@ * config backs. Under `'off'` the refusal says so (`googleLocalOff`): the * email-off copy's remedy, keep email and password on, does nothing there. * - * Under `'off'` the `email_password_enabled` key itself is never refused: + * - on a cloud-managed runtime whose deployment declared email and password + * off, `email_password_enabled` turned on ({@link emailPasswordHeldOffByHost}): + * the host refuses every password door there, so the toggle would only + * advertise a form that signs nobody in. Judged before the rest, and under + * `'off'` too; there any other save of the key passes, since the host holds + * it off whatever is stored. + * + * Apart from that last case, under `'off'` the `email_password_enabled` key itself is never refused: * the page draws email and password neither way, so the save removes no way * in the page offers. * @@ -168,6 +175,11 @@ export interface SignInMethodFloorDeps { * `email_password_enabled` hands the running value back to. Absent ⇒ on. */ declaredEmailPasswordEnabled?(): boolean; + /** + * Whether this process is a cloud-managed environment (`isCloudManaged()` + * from `@objectstack/core`), read per call. Absent ⇒ not managed. + */ + cloudManaged?(): boolean; } const hasCredentialPair = (entry: unknown): boolean => { @@ -268,6 +280,11 @@ interface SignInFloorCopy { enterpriseSsoLocalOff: string; /** The provider list could not be read to judge that delete. */ enterpriseSsoUnverified: string; + /** + * Turning email and password on, on a cloud-managed runtime whose deployment + * declared it off ({@link signInMethodFloorPredicate}). + */ + managedEmailPassword: string; } /** @@ -303,6 +320,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'The identity provider was not deleted: the list of identity providers could not be read to confirm that ' + 'another way to sign in remains, and the sign-in page offers no email and password sign-in, so this one may be ' + 'the last. Try again once the database is reachable.', + managedEmailPassword: + 'This environment is cloud-managed, and its deployment turns email and password sign-in off: people sign in ' + + 'through the identity provider of the organisation that hosts it, and every password sign-in is refused ' + + 'there. So email and password sign-in cannot be turned on here. Nothing was saved.', }, 'zh-CN': { emailPassword: @@ -324,6 +345,8 @@ export const SIGN_IN_FLOOR_COPY: Record = { '然后再删除它。', enterpriseSsoUnverified: '身份提供方未删除:无法读取身份提供方列表来确认仍有其他登录方式,而登录页不提供邮箱/密码登录,它可能是最后一种。请在数据库可以访问时重试。', + managedEmailPassword: + '本环境由云端托管,其部署已关闭邮箱/密码登录:用户通过托管本环境的组织的身份提供方登录,所有密码登录在此都会被拒绝。因此无法在这里开启邮箱/密码登录。本次保存未生效。', }, 'ja-JP': { emailPassword: @@ -353,6 +376,9 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'ID プロバイダーは削除されませんでした。ID ' + 'プロバイダーの一覧を読み取れず、他のログイン方法が残ることを確認できませんでした。ログインページはメール/パスワードログ' + 'インを表示しないため、これが最後のログイン方法かもしれません。データベースに接続できるようになってから再試行してください。', + managedEmailPassword: + 'この環境はクラウドで管理されており、デプロイでメールアドレスとパスワードによるサインインがオフになっています。利用者はこの環境をホストする組織の ID ' + + 'プロバイダーでサインインし、パスワードによるサインインはすべて拒否されます。そのため、ここでメールアドレスとパスワードによるサインインをオンにすることはできません。何も保存されていません。', }, 'es-ES': { emailPassword: @@ -387,6 +413,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'confirmar que queda otra forma de iniciar sesión y, como la página de inicio de sesión no ofrece el inicio de ' + 'sesión con correo y contraseña, este podría ser el último. Vuelva a intentarlo cuando la base de datos esté ' + 'disponible.', + managedEmailPassword: + 'Este entorno está gestionado en la nube y su implementación desactiva el inicio de sesión con correo y ' + + 'contraseña: las personas inician sesión con el proveedor de identidad de la organización que lo aloja, y ' + + 'allí se rechaza todo inicio de sesión con contraseña. Por eso no se puede activar aquí el inicio de sesión ' + + 'con correo y contraseña. No se guardó nada.', }, 'zh-Hant': { emailPassword: @@ -408,6 +439,8 @@ export const SIGN_IN_FLOOR_COPY: Record = { '然後再刪除它。', enterpriseSsoUnverified: '身分提供者未刪除:無法讀取身分提供者清單來確認仍有其他登入方式,而登入頁不提供電子郵件/密碼登入,它可能是最後一種。請在資料庫可以存取時重試。', + managedEmailPassword: + '本環境由雲端託管,其部署已關閉電子郵件/密碼登入:使用者透過託管本環境之組織的身分提供者登入,所有密碼登入在此都會被拒絕。因此無法在這裡開啟電子郵件/密碼登入。本次儲存未生效。', }, ar: { emailPassword: @@ -436,6 +469,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'لم يُحذف موفّر الهوية: تعذّرت قراءة قائمة موفّري الهوية للتأكد من بقاء طريقة أخرى لتسجيل الدخول، ولأن صفحة ' + 'تسجيل الدخول لا تعرض تسجيل الدخول بالبريد الإلكتروني وكلمة المرور قد يكون هذا آخرها. أعد المحاولة عندما تصبح ' + 'قاعدة البيانات متاحة.', + managedEmailPassword: + 'هذه البيئة مُدارة سحابيًا، ونشرها يوقف تسجيل الدخول بالبريد الإلكتروني وكلمة المرور: يسجّل المستخدمون ' + + 'الدخول عبر موفّر الهوية الخاص بالمؤسسة التي تستضيفها، وكل تسجيل دخول بكلمة مرور مرفوض فيها. لذلك لا يمكن ' + + 'تفعيل تسجيل الدخول بالبريد الإلكتروني وكلمة المرور هنا. لم يُحفظ أي شيء.', }, fr: { emailPassword: @@ -469,6 +506,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'pour vérifier qu’un autre moyen de connexion subsiste et, comme la page de connexion n’offre pas la connexion ' + 'par e-mail et mot de passe, celui-ci est peut-être le dernier. Réessayez quand la base de données sera ' + 'accessible.', + managedEmailPassword: + 'Cet environnement est géré dans le cloud et son déploiement désactive la connexion par e-mail et mot de ' + + 'passe : les utilisateurs se connectent via le fournisseur d’identité de l’organisation qui l’héberge, et ' + + 'toute connexion par mot de passe y est refusée. La connexion par e-mail et mot de passe ne peut donc pas ' + + 'être activée ici. Rien n’a été enregistré.', }, 'pt-BR': { emailPassword: @@ -500,6 +542,10 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'O provedor de identidade não foi excluído: não foi possível ler a lista de provedores de identidade para ' + 'confirmar que resta outra forma de entrar e, como a página de login não oferece login com e-mail e senha, ' + 'este pode ser o último. Tente novamente quando o banco de dados estiver acessível.', + managedEmailPassword: + 'Este ambiente é gerenciado na nuvem e sua implantação desativa o login com e-mail e senha: as pessoas ' + + 'entram pelo provedor de identidade da organização que o hospeda, e todo login com senha é recusado ali. Por ' + + 'isso, o login com e-mail e senha não pode ser ativado aqui. Nada foi salvo.', }, ru: { emailPassword: @@ -531,6 +577,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'Поставщик удостоверений не удалён: не удалось прочитать список поставщиков удостоверений, чтобы убедиться, ' + 'что останется другой способ входа, а страница входа не предлагает вход по электронной почте и паролю, поэтому ' + 'этот может быть последним. Повторите попытку, когда база данных станет доступна.', + managedEmailPassword: + 'Эта среда управляется облаком, и её развёртывание отключает вход по электронной почте и паролю: ' + + 'пользователи входят через поставщика удостоверений организации, которая её размещает, а любой вход по ' + + 'паролю там отклоняется. Поэтому включить здесь вход по электронной почте и паролю нельзя. Ничего не ' + + 'сохранено.', }, de: { emailPassword: @@ -564,6 +615,11 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'zu bestätigen, dass eine andere Anmeldemöglichkeit bleibt, und da die Anmeldeseite keine Anmeldung mit E-Mail ' + 'und Passwort anbietet, ist dieser vielleicht der letzte. Versuchen Sie es erneut, sobald die Datenbank ' + 'erreichbar ist.', + managedEmailPassword: + 'Diese Umgebung wird in der Cloud verwaltet, und ihre Bereitstellung schaltet die Anmeldung mit E-Mail und ' + + 'Passwort aus: Benutzer melden sich über den Identitätsanbieter der Organisation an, die sie hostet, und ' + + 'jede Anmeldung mit Passwort wird dort abgelehnt. Die Anmeldung mit E-Mail und Passwort kann hier daher ' + + 'nicht eingeschaltet werden. Es wurde nichts gespeichert.', }, ko: { emailPassword: @@ -593,6 +649,9 @@ export const SIGN_IN_FLOOR_COPY: Record = { 'ID 공급자를 삭제하지 않았습니다. 다른 로그인 방법이 남아 있는지 확인하기 위해 ID 공급자 목록을 읽을 ' + '수 없었고, 로그인 페이지가 이메일/비밀번호 로그인을 제공하지 않으므로 이것이 마지막 방법일 수 있습니다. ' + '데이터베이스에 연결할 수 있게 되면 다시 시도하세요.', + managedEmailPassword: + '이 환경은 클라우드에서 관리되며, 배포에서 이메일/비밀번호 로그인이 꺼져 있습니다. 사용자는 이 환경을 호스팅하는 조직의 ID 공급자를 통해 로그인하며, 비밀번호 로그인은 모두 거부됩니다. ' + + '따라서 여기서 이메일/비밀번호 로그인을 켤 수 없습니다. 아무것도 저장되지 않았습니다.', }, }; @@ -620,7 +679,25 @@ export interface SignInFloorWriteInput { /** A refusal, in the settings service's `SettingsWriteRefusal` shape. */ export interface SignInFloorRefusal { message: string; - constraint: { lastSignInMethod: 'email_password' | 'google' }; + constraint: + | { lastSignInMethod: 'email_password' | 'google' } + | { cloudManaged: true; declaredEmailPassword: false }; +} + +/** + * Whether email and password stays off whatever is stored: a cloud-managed + * runtime ({@link SignInMethodFloorDeps.cloudManaged}) whose deployment + * declared it off ({@link SignInMethodFloorDeps.declaredEmailPasswordEnabled}). + * The host refuses every password door there (its relay answers each with a + * conflict), so a stored or saved `email_password_enabled` that reads on would + * only make `/auth/config` advertise a form that signs nobody in. The save + * door refuses turning it on ({@link signInMethodFloorPredicate}), and the + * settings pass does not apply a stored value that reads on (`bindAuthSettings`). + * Self-hosted deployments, and a managed one that declared it on, keep the + * toggle as before. + */ +export function emailPasswordHeldOffByHost(deps: Pick): boolean { + return deps.cloudManaged?.() === true && deps.declaredEmailPasswordEnabled?.() === false; } /** Reads one resolved `auth` setting as it stands (`SettingsService.get`). */ @@ -699,17 +776,39 @@ async function googleAfter( * turns it off (never under `'off'`, where that key changes nothing the page * draws), and at a `google_*` key when the save removes a Google provider that * was in force. + * + * Ahead of that, at `email_password_enabled` on a runtime where the host holds + * email and password off ({@link emailPasswordHeldOffByHost}): a save of a value + * that reads on. The settings service asks a predicate only about a change from + * the value it resolves, and with nothing stored that is the manifest default + * (on), so re-saving that default reaches no predicate; the settings pass is + * what keeps such a row from taking effect. */ export function signInMethodFloorPredicate(deps: SignInMethodFloorDeps, read: AuthSettingReader) { return async (input: SignInFloorWriteInput): Promise => { const { key, next, locale } = input; const batch = input.batch ?? { [key]: next }; + // A cloud-managed runtime whose deployment declared email and password + // off: a save of a value that reads on is refused, whatever else is in + // force. Any other save of the key (off, or a clear, which hands the value + // back to the declaration) passes: the host holds it off either way, so it + // removes no way in, and it is how a row stored on is put right. + if (key === 'email_password_enabled' && emailPasswordHeldOffByHost(deps)) { + if (!readToggle(next, false)) return undefined; + return { + message: signInFloorCopy(locale).managedEmailPassword, + constraint: { cloudManaged: true, declaredEmailPassword: false }, + }; + } const config = deps.publicConfig(); // The page draws no local way in under the local sign-in path `'off'`, so // email and password counts for nothing there, whatever this save sets it to. const localOffered = pageOffersLocalSignIn(config); if (!localOffered && key === 'email_password_enabled') return undefined; - const emailPasswordAfter = localOffered && (Object.prototype.hasOwnProperty.call(batch, 'email_password_enabled') + // Held off by the host, email and password stays off whatever the batch + // says (the settings pass does not apply it), so it is no way in after it. + const emailPasswordAfter = localOffered && !emailPasswordHeldOffByHost(deps) + && (Object.prototype.hasOwnProperty.call(batch, 'email_password_enabled') ? readToggle( await valueAfter(read, input, batch, 'email_password_enabled'), deps.declaredEmailPasswordEnabled?.() ?? true,