feat(auth): groundwork for signing in with Google (#340)
Nothing a customer can see. The schema change and the configuration land on their own so the widest-reaching edit in the project can be reviewed for what it is rather than buried inside a feature. The password hash becomes nullable. That is one line and it is not the work; the work is that every read of the column is now a question rather than a fact. Three places compared against it with bcrypt, and all three now ask first through one shared function. That function exists because the alternative is worse than a wrong answer. bcrypt.compare throws on a null hash rather than returning false, so any call site that forgot the check would answer a sign-in attempt with a 500 instead of a refusal. On the login route that is also an oracle, because it would happen for exactly the accounts that have no password. One function rather than a null check repeated three times means the question is asked identically everywhere and a fourth site cannot forget to ask it. Nothing writes a null yet. The first accounts without a password arrive with the sign-up path, which is why this is landed ahead of them. The identities table is a table rather than columns on customers, because one customer may eventually hold more than one. Columns would make a second provider a migration and a third an embarrassment. Its important column is the provider subject, and the comment on it is the whole security posture of the feature in one place: never the email. An email is a display value its owner can change and a provider may reassign; a subject is opaque and stable for the life of the account. Matching on the email would strand a customer who changed theirs and, far worse, hand their account to whoever inherited the old address. Unique across the provider and subject together, not the subject alone. The down migration drops the table and deliberately does not restore the NOT NULL. Re-adding it fails outright once a passwordless customer exists, and a down migration that destroys accounts to satisfy a constraint is far worse than a column that is merely more permissive than it needs to be. The redirect URI is derived from PUBLIC_URL, the same single source the WebAuthn Relying Party ID uses and for the same reason: Google compares it as an exact string and answers a mismatch with a message that says nothing about which half is wrong. Deriving it means the value is correct by construction anywhere the email links already are. The tests are mostly about what must not end up in it, since a trailing slash on PUBLIC_URL is an easy way to produce a URI that is one character from the registered one. The config also reports whether it is enabled at all, so a developer without credentials gets a storefront that works and simply does not offer the button, rather than one that offers it and fails. Absent rather than disabled, the same choice made for a browser without WebAuthn. Environment validation refuses to boot on one credential without the other, matching how the SMTP pair is handled. Half-configured is the case worth catching because the failure otherwise arrives at the moment a customer presses the button. The QA compose file sets both to empty, and the comment there says why at length rather than leaving it to look like an oversight. Google refuses a redirect URI whose host is not under a domain whose ownership has been proved by DNS, and nobody can prove ownership of anything under bermudalamb.synology.me because Synology owns the registrable domain above it. That is the same wall #285 hit with Cloudflare. So QA cannot run this at all until #313 moves it to a subdomain of the real domain, at which point it is two stack variables and one console entry, with no code change either way. Also corrects the record in #332, which lists account deletion as confirming with a password. It does not; the route takes none and the confirmation is a modal in the account page. Deletion needed no change here. Verified: backend tsc clean for src and tests, 550 unit tests pass including new coverage of the config derivation, the null-hash comparison and the environment rules; lint clean apart from warnings that predate this branch. The integration suite needs a database this machine has no Docker for. Closes #340 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
d69091d5ad
commit
9cc82002b8
@@ -42,7 +42,7 @@ describe('when the database loses its schema', () => {
|
||||
|
||||
// The count and a few names, not the whole list: the point is that a reader
|
||||
// can tell at a glance this is a missing schema rather than a logic bug.
|
||||
await expect(assertSchemaPresent('in a test')).rejects.toThrow(/Missing 21 of 21 tables/);
|
||||
await expect(assertSchemaPresent('in a test')).rejects.toThrow(/Missing 22 of 22 tables/);
|
||||
await expect(assertSchemaPresent('in a test')).rejects.toThrow(/items/);
|
||||
|
||||
await migrate();
|
||||
|
||||
@@ -39,6 +39,7 @@ const REQUIRED_TABLES = [
|
||||
'checkouts',
|
||||
'customer_credentials',
|
||||
'customer_email_changes',
|
||||
'customer_identities',
|
||||
'customer_sessions',
|
||||
'customer_tokens',
|
||||
'customers',
|
||||
@@ -154,7 +155,7 @@ export async function resetDb(): Promise<void> {
|
||||
await testPool.query(`
|
||||
TRUNCATE TABLE item_drafts, upload_links, orders, checkout_items, checkouts,
|
||||
shipping_addresses, cart_items, carts, customer_tokens, customer_sessions, favorites,
|
||||
webauthn_challenges, customer_credentials, customer_email_changes,
|
||||
webauthn_challenges, customer_credentials, customer_email_changes, customer_identities,
|
||||
customers, item_tags, item_images, items, tags, categories
|
||||
RESTART IDENTITY CASCADE
|
||||
`);
|
||||
|
||||
@@ -251,4 +251,44 @@ describe('UPLOADS_BASE_URL', () => {
|
||||
expect(warnings.join(' ')).not.toMatch(/INTAKE_ACTION_SECRET/);
|
||||
});
|
||||
});
|
||||
|
||||
// #340. All or nothing, and half-configured is the case worth catching: the
|
||||
// failure would otherwise arrive when a customer presses the button.
|
||||
describe('Google sign-in credentials', () => {
|
||||
const BOTH = { GOOGLE_CLIENT_ID: 'id', GOOGLE_CLIENT_SECRET: 'shh', PUBLIC_URL: 'https://x.test' };
|
||||
|
||||
it('are not required', () => {
|
||||
expect(validateEnv(MINIMAL).errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('warn when absent, so a missing button has a stated reason', () => {
|
||||
expect(validateEnv(MINIMAL).warnings.join(' ')).toMatch(/Google sign-in is not configured/);
|
||||
});
|
||||
|
||||
it('refuse to start with only the client id', () => {
|
||||
const { errors } = validateEnv(withEnv({ GOOGLE_CLIENT_ID: 'id' }));
|
||||
expect(errors.join(' ')).toMatch(/GOOGLE_CLIENT_SECRET is required/);
|
||||
});
|
||||
|
||||
it('refuse to start with only the client secret', () => {
|
||||
const { errors } = validateEnv(withEnv({ GOOGLE_CLIENT_SECRET: 'shh' }));
|
||||
expect(errors.join(' ')).toMatch(/GOOGLE_CLIENT_ID is required/);
|
||||
});
|
||||
|
||||
it('are accepted when both are set alongside PUBLIC_URL', () => {
|
||||
const { errors, warnings } = validateEnv(withEnv(BOTH));
|
||||
expect(errors).toEqual([]);
|
||||
expect(warnings.join(' ')).not.toMatch(/Google sign-in/);
|
||||
});
|
||||
|
||||
it('warn when configured without PUBLIC_URL, because the callback falls back to localhost', () => {
|
||||
// Correct locally and wrong everywhere else, which is precisely the shape
|
||||
// that needs saying out loud rather than failing at Google later.
|
||||
const { errors, warnings } = validateEnv(
|
||||
withEnv({ GOOGLE_CLIENT_ID: 'id', GOOGLE_CLIENT_SECRET: 'shh' })
|
||||
);
|
||||
expect(errors).toEqual([]);
|
||||
expect(warnings.join(' ')).toMatch(/redirect URI falls back to localhost/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { googleConfig, GOOGLE_CALLBACK_PATH } from '../../src/google/config';
|
||||
|
||||
const CREDENTIALS = { GOOGLE_CLIENT_ID: 'id.apps.googleusercontent.com', GOOGLE_CLIENT_SECRET: 'shh' };
|
||||
|
||||
/**
|
||||
* The redirect URI is compared by Google as an exact string, and a mismatch
|
||||
* answers `redirect_uri_mismatch` — accurate, and silent about which half is
|
||||
* wrong. So these assert the derivation itself rather than that the function
|
||||
* returns something, and most of them are about what must *not* end up in it.
|
||||
*/
|
||||
describe('googleConfig', () => {
|
||||
it('builds the redirect URI from PUBLIC_URL', () => {
|
||||
const config = googleConfig({ ...CREDENTIALS, PUBLIC_URL: 'https://redefined-designs.com' });
|
||||
|
||||
expect(config.redirectUri).toBe(`https://redefined-designs.com${GOOGLE_CALLBACK_PATH}`);
|
||||
});
|
||||
|
||||
it('normalises a trailing slash away, rather than producing a double slash', () => {
|
||||
// The failure this prevents is worth naming: "https://x.com//api/..." is a
|
||||
// different string from the one registered in the console, and it is an
|
||||
// easy way to write PUBLIC_URL.
|
||||
const config = googleConfig({ ...CREDENTIALS, PUBLIC_URL: 'https://redefined-designs.com/' });
|
||||
|
||||
expect(config.redirectUri).toBe(`https://redefined-designs.com${GOOGLE_CALLBACK_PATH}`);
|
||||
expect(config.redirectUri).not.toContain('//api');
|
||||
});
|
||||
|
||||
it('discards a path on PUBLIC_URL', () => {
|
||||
const config = googleConfig({ ...CREDENTIALS, PUBLIC_URL: 'https://redefined-designs.com/shop' });
|
||||
|
||||
expect(config.redirectUri).toBe(`https://redefined-designs.com${GOOGLE_CALLBACK_PATH}`);
|
||||
});
|
||||
|
||||
it('keeps a non-default port, because the console entry carries one too', () => {
|
||||
const config = googleConfig({ ...CREDENTIALS, PUBLIC_URL: 'http://localhost:5173' });
|
||||
|
||||
expect(config.redirectUri).toBe(`http://localhost:5173${GOOGLE_CALLBACK_PATH}`);
|
||||
});
|
||||
|
||||
it('falls back to localhost when PUBLIC_URL is unset', () => {
|
||||
// Local development legitimately has no PUBLIC_URL: envValidation only
|
||||
// demands it alongside SMTP. localhost is also the one host Google accepts
|
||||
// without an authorized domain, so the fallback is the only value that
|
||||
// could work here anyway.
|
||||
const config = googleConfig({ ...CREDENTIALS });
|
||||
|
||||
expect(config.redirectUri).toBe(`http://localhost:3000${GOOGLE_CALLBACK_PATH}`);
|
||||
});
|
||||
|
||||
it('refuses a PUBLIC_URL that is not a URL', () => {
|
||||
expect(() => googleConfig({ ...CREDENTIALS, PUBLIC_URL: 'redefined-designs.com' })).toThrow(
|
||||
/not a URL/
|
||||
);
|
||||
});
|
||||
|
||||
describe('enabled', () => {
|
||||
it('is true only when both credentials are present', () => {
|
||||
expect(googleConfig(CREDENTIALS).enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('is false when neither is set, which is a legitimate environment', () => {
|
||||
// A developer without credentials gets a storefront that works and does
|
||||
// not offer the button, rather than one that offers it and fails.
|
||||
expect(googleConfig({}).enabled).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['only the id', { GOOGLE_CLIENT_ID: 'id' }],
|
||||
['only the secret', { GOOGLE_CLIENT_SECRET: 'shh' }]
|
||||
])('is false with %s', (_label, env) => {
|
||||
expect(googleConfig(env).enabled).toBe(false);
|
||||
});
|
||||
|
||||
it('treats whitespace as absent', () => {
|
||||
// A stack variable set to an empty string is the same as one never set,
|
||||
// and it is the shape a copied-and-blanked entry takes.
|
||||
expect(googleConfig({ GOOGLE_CLIENT_ID: ' ', GOOGLE_CLIENT_SECRET: 'shh' }).enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { passwordMatches, TEST_ROUNDS } from '../../src/passwordHashing';
|
||||
|
||||
/**
|
||||
* `customers.password_hash` became nullable in #340, and a null one is not an
|
||||
* edge case to tidy away — it is a customer who signed up through Google and
|
||||
* has never set a password.
|
||||
*
|
||||
* The reason this is a function rather than a null check at each call site is
|
||||
* what the second test asserts: `bcrypt.compare` throws on a null hash instead
|
||||
* of returning false, so a forgotten check answers a sign-in attempt with a 500.
|
||||
* On the login route that is also an oracle, because it happens for exactly the
|
||||
* accounts that have no password.
|
||||
*/
|
||||
describe('passwordMatches', () => {
|
||||
it('matches a correct password against a real hash', async () => {
|
||||
const hash = await bcrypt.hash('supersecret123', TEST_ROUNDS);
|
||||
|
||||
await expect(passwordMatches('supersecret123', hash)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a wrong password against a real hash', async () => {
|
||||
const hash = await bcrypt.hash('supersecret123', TEST_ROUNDS);
|
||||
|
||||
await expect(passwordMatches('nope', hash)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['null', null],
|
||||
['undefined', undefined],
|
||||
['an empty string', '']
|
||||
])('answers false rather than throwing when the stored hash is %s', async (_label, stored) => {
|
||||
// The whole point. bcrypt.compare throws "Illegal arguments" here.
|
||||
await expect(passwordMatches('anything', stored)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('answers false for a missing password rather than throwing', async () => {
|
||||
const hash = await bcrypt.hash('supersecret123', TEST_ROUNDS);
|
||||
|
||||
await expect(passwordMatches(undefined, hash)).resolves.toBe(false);
|
||||
await expect(passwordMatches(null, hash)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('does not treat an empty password as matching an absent hash', async () => {
|
||||
// Both sides missing is the combination that would be most tempting to call
|
||||
// a match, and it would let anyone sign in as any social-only customer by
|
||||
// submitting a blank password.
|
||||
await expect(passwordMatches('', null)).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user