Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 2 additions & 41 deletions server/kf/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,13 @@ docker service logs auth_auth --tail 50 2>&1 | grep -i "error\|invalid\|authoriz

import { timingSafeEqual } from 'crypto';
import { Router } from 'express';
import { Op } from 'sequelize';
import { promisify } from 'util';

import { Collection, Community, Member, Pub, PubAttribution, Release, User } from 'server/models';
import { sequelize } from 'server/sequelize';
import { getHashedUserId } from 'utils/caching/getHashedUserId';
import { ensureUserIsCommunityAdmin } from 'utils/ensureUserIsCommunityAdmin';
import { isDevelopment, isDuqDuq, isProd } from 'utils/environment';
import { slugifyString } from 'utils/strings';

import {
buildAuthorizeUrl,
Expand All @@ -40,6 +38,7 @@ import {
generateCodeVerifier,
OIDC_ISSUER_URL,
} from './auth';
import { provisionLocalUser } from './provisionLocalUser';

// ── Helpers ──────────────────────────────────────────────────────────

Expand Down Expand Up @@ -150,45 +149,7 @@ router.get('/auth/callback', async (req: any, res: any) => {
const userInfo = await fetchUserInfo(tokens.access_token);
const kfUserId = userInfo.sub;

// Look up PubPub user by ID, or auto-create on first login
let user = await User.findOne({ where: { id: kfUserId } });

if (!user) {
const firstName = (userInfo.given_name || userInfo.name || 'New').trim();
const lastName = (userInfo.family_name || 'User').trim();
const fullName = `${firstName} ${lastName}`;
const initials = `${firstName[0] || '?'}${lastName[0] || '?'}`;
const baseSlug = slugifyString(fullName) || 'user';
const existingSlugCount = await User.count({
where: { slug: { [Op.like]: `${baseSlug}%` } },
});
const slug = existingSlugCount ? `${baseSlug}-${existingSlugCount + 1}` : baseSlug;

// Use KF Auth email if available and not already taken
let email = `${kfUserId}@placeholder.invalid`;
if (userInfo.email) {
const emailTaken = await User.findOne({
where: { email: userInfo.email.toLowerCase() },
});
if (!emailTaken) {
email = userInfo.email.toLowerCase();
}
}

user = await User.create({
id: kfUserId,
slug,
firstName,
lastName,
fullName,
initials,
email,
avatar: userInfo.picture || null,
hash: '',
salt: '',
} as any);
console.log(`Auto-created PubPub user ${user.id} (${user.slug}) from KF Auth`);
}
const user = await provisionLocalUser(kfUserId, userInfo);

const protocol = isDevelopment() ? 'http' : 'https';

Expand Down
65 changes: 65 additions & 0 deletions server/kf/provisionLocalUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { OIDCUserInfo } from './oidc.server';

import { Op } from 'sequelize';

import { User } from 'server/models';
import { slugifyString } from 'utils/strings';

/**
* Look up the local PubPub `User` row that corresponds to a kf-auth subject,
* auto-creating it from kf-auth userinfo on first contact.
*
* Both the OIDC `/auth/callback` flow and the legacy `/api/login` SDK bridge
* funnel users through here so the side effects (slug allocation, placeholder
* email handling, console logging) stay identical.
*
* `kfUserId` must equal the `sub` claim from kf-auth's userinfo / JWT — PubPub
* stores it verbatim as `User.id` since the migration kept UUIDs aligned.
*/
export async function provisionLocalUser(
kfUserId: string,
userInfo: Partial<
Pick<OIDCUserInfo, 'name' | 'email' | 'picture' | 'given_name' | 'family_name'>
>,
): Promise<InstanceType<typeof User>> {
const existing = await User.findOne({ where: { id: kfUserId } });
if (existing) return existing;

const firstName = (userInfo.given_name || userInfo.name || 'New').trim();
const lastName = (userInfo.family_name || 'User').trim();
const fullName = `${firstName} ${lastName}`;
const initials = `${firstName[0] || '?'}${lastName[0] || '?'}`;
const baseSlug = slugifyString(fullName) || 'user';
const existingSlugCount = await User.count({
where: { slug: { [Op.like]: `${baseSlug}%` } },
});
const slug = existingSlugCount ? `${baseSlug}-${existingSlugCount + 1}` : baseSlug;

// Prefer the kf-auth email if it's unique on PubPub; otherwise stash a
// placeholder so the row still satisfies the not-null constraint and the
// user can update it later.
let email = `${kfUserId}@placeholder.invalid`;
if (userInfo.email) {
const emailTaken = await User.findOne({
where: { email: userInfo.email.toLowerCase() },
});
if (!emailTaken) {
email = userInfo.email.toLowerCase();
}
}

const created = await User.create({
id: kfUserId,
slug,
firstName,
lastName,
fullName,
initials,
email,
avatar: userInfo.picture || null,
hash: '',
salt: '',
} as any);
console.log(`Auto-created PubPub user ${created.id} (${created.slug}) from KF Auth`);
return created;
}
178 changes: 178 additions & 0 deletions server/login/__tests__/api.kf-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import supertest from 'supertest';
import { vi } from 'vitest';

import { SpamTag, User } from 'server/models';
import { modelize, setup, teardown } from 'stubstub';

import { __appImmutableListenOnly } from '../../server';

const normalEmail = `${crypto.randomUUID()}@email.com`;
const restrictedEmail = `${crypto.randomUUID()}@email.com`;

const models = modelize`
Community community {
Member {
permissions: "admin"
User legacyUser {
email: ${normalEmail}
}
}
Member {
permissions: "admin"
User restrictedUser {
email: ${restrictedEmail}
}
}
}
`;

setup(beforeAll, async () => {
await models.resolve();
});

teardown(afterAll);

const AUTH_URL = 'http://kf-auth.test';
const AUTH_KEY = 'test-internal-key';
const ENDPOINT = '/api/internal/legacy-pubpub-login';

function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}

beforeEach(() => {
vi.stubEnv('AUTH_INTERNAL_API_URL', AUTH_URL);
vi.stubEnv('AUTH_INTERNAL_API_KEY', AUTH_KEY);
});

afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});

describe('/api/login (kf-auth handshake)', () => {
it('verifies via the internal endpoint and establishes a PubPub session', async () => {
const { legacyUser } = models;
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {
if (String(url).endsWith(ENDPOINT)) {
return jsonResponse({ verified: true, userId: legacyUser.id });
}
throw new Error(`Unexpected fetch: ${url}`);
});

const server = __appImmutableListenOnly.listen();
try {
const res = await supertest(server)
.post('/api/login')
.send({ email: legacyUser.email, password: 'sha3-hex-payload' })
.expect(201);

expect(res.headers.deprecation).toBe('true');
expect(res.headers.sunset).toBeTruthy();
const cookies = (res.headers['set-cookie'] as unknown as string[]) ?? [];
expect(cookies.some((c) => c.startsWith('connect.sid='))).toBe(true);
expect(cookies.some((c) => c.startsWith('pp-lic='))).toBe(true);

const call = fetchSpy.mock.calls.find(([u]) => String(u).endsWith(ENDPOINT));
expect(call).toBeDefined();
const init = call![1] as RequestInit;
expect((init.headers as Record<string, string>).Authorization).toBe(
`Bearer ${AUTH_KEY}`,
);
const body = JSON.parse(String(init.body));
expect(body).toEqual({
email: legacyUser.email,
prehashedPassword: 'sha3-hex-payload',
});
} finally {
server.close();
}
});

it('returns 401 when kf-auth reports verified:false (wrong password or unknown user)', async () => {
const { legacyUser } = models;
vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ verified: false }));

const server = __appImmutableListenOnly.listen();
try {
const res = await supertest(server)
.post('/api/login')
.send({ email: legacyUser.email, password: 'sha3-wrong' })
.expect(401);
expect(res.body).toBe('Login attempt failed');
} finally {
server.close();
}
});

it('returns 410 when kf-auth reports the hash has been migrated past pubpub-format', async () => {
const { legacyUser } = models;
vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ migrated: true }, 410));

const server = __appImmutableListenOnly.listen();
try {
const res = await supertest(server)
.post('/api/login')
.send({ email: legacyUser.email, password: 'sha3-hex' })
.expect(410);
expect(res.text).toMatch(/API token/i);
} finally {
server.close();
}
});

it('returns 403 when the local PubPub account is flagged as confirmed spam', async () => {
const { restrictedUser } = models;
const tag = await SpamTag.create({
userId: restrictedUser.id,
status: 'confirmed-spam',
spamScore: 100,
spamScoreComputedAt: new Date(),
fields: { manuallyMarkedBy: [] },
} as any);
await User.update({ spamTagId: tag.id }, { where: { id: restrictedUser.id } });

vi.spyOn(globalThis, 'fetch').mockResolvedValue(
jsonResponse({ verified: true, userId: restrictedUser.id }),
);

const server = __appImmutableListenOnly.listen();
try {
const res = await supertest(server)
.post('/api/login')
.send({ email: restrictedUser.email, password: 'sha3-hex' })
.expect(403);
expect(res.text).toMatch(/restricted/i);
} finally {
server.close();
}
});

it('auto-creates the local PubPub user when kf-auth returns an unknown id', async () => {
const newId = crypto.randomUUID();
const newEmail = `${crypto.randomUUID()}@auto.created`;
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
jsonResponse({ verified: true, userId: newId }),
);

const before = await User.findOne({ where: { id: newId } });
expect(before).toBeNull();

const server = __appImmutableListenOnly.listen();
try {
await supertest(server)
.post('/api/login')
.send({ email: newEmail, password: 'sha3-hex' })
.expect(201);
} finally {
server.close();
}

const after = await User.findOne({ where: { id: newId } });
expect(after).not.toBeNull();
expect(after!.email).toBe(newEmail);
});
});
Loading
Loading