From 2fcb16cb33c549572052fc39ae755d5b06c66ed7 Mon Sep 17 00:00:00 2001 From: DebaucheryLibrarian Date: Sun, 29 Nov 2026 06:17:04 +0100 Subject: [PATCH] Improved API access setup, only requires e-mail verification, integrated with bans, added admin panel. --- components/admin/admin.vue | 11 + components/admin/api-ban.vue | 267 +++++++++++++++++++ config/default.cjs | 7 + pages/admin/+Page.vue | 11 + pages/admin/keys/+Page.vue | 312 +++++++++++++++++++++++ pages/admin/keys/+onBeforeRender.js | 27 ++ pages/users/@username/+Page.vue | 22 +- pages/users/@username/+onBeforeRender.js | 11 +- src/auth.js | 156 ++++++++++-- src/key-rates.js | 122 +++++++++ src/users.js | 123 ++++++++- src/web/auth.js | 12 +- 12 files changed, 1051 insertions(+), 30 deletions(-) create mode 100644 components/admin/api-ban.vue create mode 100644 pages/admin/keys/+Page.vue create mode 100644 pages/admin/keys/+onBeforeRender.js create mode 100644 src/key-rates.js diff --git a/components/admin/admin.vue b/components/admin/admin.vue index 618d29c..6fdaa71 100644 --- a/components/admin/admin.vue +++ b/components/admin/admin.vue @@ -60,6 +60,17 @@ :class="{ active: pageContext.urlPathname.startsWith('/admin/emails') }" >E-mails + + + + + + + + + + diff --git a/config/default.cjs b/config/default.cjs index c5575b7..855b155 100755 --- a/config/default.cjs +++ b/config/default.cjs @@ -165,12 +165,19 @@ module.exports = { }, bans: { defaultExpiry: 60 * 24 * 3, // in minutes, 3 days + ipv6Prefix: 64, // ban IPv6 addresses by network, ISPs commonly randomize the rest + cacheExpiry: 60, // seconds an IP's ban verdict is cached for checks on every request, flushed when a ban is created }, apiAccess: { graphqlEnabled: true, keySize: 24, // bytes keyLimit: 5, // max keys per user keyCooldown: 1, // minutes between key generation + rateLimit: 120, // requests per key per minute + rateExemptRoles: ['admin'], // users with the sync ability are exempt too + rateRetention: 7, // days of hourly request counts kept for the admin panel + failLimit: 20, // invalid credentials per IP before it's blocked + failWindow: 15, // minutes }, revisions: { unapprovedLimit: 3, diff --git a/pages/admin/+Page.vue b/pages/admin/+Page.vue index cdfa149..de79b81 100644 --- a/pages/admin/+Page.vue +++ b/pages/admin/+Page.vue @@ -37,12 +37,23 @@ class="link" >Reports + +
  • + API Keys +
  • diff --git a/pages/admin/keys/+onBeforeRender.js b/pages/admin/keys/+onBeforeRender.js new file mode 100644 index 0000000..1d3d4d1 --- /dev/null +++ b/pages/admin/keys/+onBeforeRender.js @@ -0,0 +1,27 @@ +import config from 'config'; +import { render } from 'vike/abort'; + +import { fetchAllKeys } from '#/src/auth.js'; + +export async function onBeforeRender(pageContext) { + if (pageContext.user?.role !== 'admin') { + throw render(404); + } + + const keys = await fetchAllKeys(pageContext.user); + + return { + pageContext: { + title: 'API keys', + pageProps: { + keys, + rateLimit: config.apiAccess.rateLimit, + retention: config.apiAccess.rateRetention, + ipv6Prefix: config.bans.ipv6Prefix, + }, + routeParams: { + section: 'keys', + }, + }, + }; +} diff --git a/pages/users/@username/+Page.vue b/pages/users/@username/+Page.vue index 8126254..717c322 100644 --- a/pages/users/@username/+Page.vue +++ b/pages/users/@username/+Page.vue @@ -85,12 +85,18 @@ >Filters API Keys + API Keys + curateKey(key)); } +// admin overview of every user's keys +export async function fetchAllKeys(reqUser) { + if (reqUser?.role !== 'admin') { + throw new HttpError('You are not permitted to view API keys.', 403); + } + + const keys = await knex('users_keys') + .select( + 'users_keys.*', + 'users.username', + 'users.email_verified', + 'users.last_ip', + getBanRange('users.last_ip').wrap('(', ') as login_range'), + getBanRange('users_keys.last_used_ip').wrap('(', ') as key_range'), + knex.raw(`exists ( + select 1 from bans + where bans.user_id = users.id + and (bans.scope = 'api' or bans.scope is null) + and bans.expires_at > now() + ) as is_banned`), + ) + .leftJoin('users', 'users.id', 'users_keys.user_id') + .orderByRaw('users_keys.last_used_at desc nulls last, users_keys.created_at desc'); + + const rates = await fetchKeyRates(keys.map((key) => key.id)); + + return keys.map((key) => ({ + ...curateKey(key), + rates: rates[key.id], + user: { + id: key.user_id, + username: key.username, + isEmailVerified: key.email_verified, + lastIp: key.last_ip?.replace(/\/\d+$/, '') || null, + loginRange: key.login_range, + isBanned: key.is_banned, + }, + lastUsedRange: key.key_range, + })); +} + +// keys are 24 random bytes, a fast hash is as safe as a slow one and doesn't make every request expensive +function hashKey(key) { + return crypto.createHash('sha256').update(key).digest('hex'); +} + +// keys created before SHA-256 hashes are 128-character scrypt hashes, re-hashed on their first use +// remove this once no 128-character keys remain in users_keys +async function migrateLegacyKey(userId, key, hashedKey) { + const legacyKeys = await knex('users_keys') + .where('user_id', userId) + .whereRaw('length(key) = 128'); + + if (legacyKeys.length === 0) { + return null; // only users that still hold legacy keys pay for scrypt + } + + const legacyHash = (await scrypt(key, '', 64)).toString('hex'); + const legacyKey = legacyKeys.find((storedKey) => storedKey.key === legacyHash); + + if (!legacyKey) { + return null; + } + + await knex('users_keys') + .where('id', legacyKey.id) + .update('key', hashedKey); + + logger.info(`Migrated API key '${legacyKey.identifier}' of user ${userId} to SHA-256`); + + return { + ...legacyKey, + key: hashedKey, + }; +} + export async function verifyKey(userId, key, req) { if (!key || !userId) { throw new HttpError('The API credentials are not provided.', 401); @@ -641,17 +721,32 @@ export async function verifyKey(userId, key, req) { throw new HttpError('Key is not a string', 400); } - const hashedKey = (await scrypt(key, '', 64)).toString('hex'); // salt redundant for randomly generated key + // before anything else, a banned IP can't use any key, even one created elsewhere + await verifyIpNotBanned(req.userIp, 'api', 'You are not allowed to use the API'); + await checkFailedAttempts(req); + + const hashedKey = hashKey(key); const storedKey = await knex('users_keys') .where('user_id', userId) .where('key', hashedKey) - .first(); + .first() || await migrateLegacyKey(userId, key, hashedKey); if (!storedKey) { + await registerFailedAttempt(req); + throw new HttpError('The API credentials are invalid.', 401); } + const user = await fetchUser(storedKey.user_id); + + // checked on every request, so revoking a user's verification also suspends their existing keys + if (!user.isEmailVerified) { + throw new HttpError('API access requires a verified e-mail address.', 403); + } + + const minuteCount = await countKeyRequest(storedKey.id, user, req); + accessLogger.access({ userId, identifier: storedKey.identifier, @@ -660,18 +755,30 @@ export async function verifyKey(userId, key, req) { userAgent: req.headers['user-agent'], }); - knex('users_keys') - .where('id', storedKey.id) - .update('last_used_at', knex.raw('now()')) - .update('last_used_ip', req.userIp) - .then(() => { - // no need to wait for this - }); + // once a minute is precise enough for the overview, the request counts live in Redis + if (minuteCount === 1) { + knex('users_keys') + .where('id', storedKey.id) + .update('last_used_at', knex.raw('now()')) + .update('last_used_ip', req.userIp) + .then(() => { + // no need to wait for this + }); + } - return fetchUser(storedKey.user_id); + return { + ...user, + ip: req.userIp, // like session users, so other ban checks apply to API requests too + }; } export async function createKey(reqUser) { + if (!reqUser.isEmailVerified) { + throw new HttpError('Please verify your e-mail address to create API keys.', 403); + } + + await verifyNotBanned(reqUser, 'api', 'You are not allowed to create API keys'); + const cooldownKey = `traxxx:key_create_cooldown:${reqUser.id}`; if (reqUser.role !== 'admin' && await redis.exists(cooldownKey)) { @@ -685,9 +792,9 @@ export async function createKey(reqUser) { } const key = crypto.randomBytes(config.apiAccess.keySize).toString('base64url'); - const hashedKey = (await scrypt(key, '', 64)).toString('hex'); // salt redundant for randomly generated key + const hashedKey = hashKey(key); - const identifier = slugify([faker.word.adjective(), faker.animal[faker.animal.type()]()]); + const identifier = slugify([faker.word.adjective(), faker.animal[faker.helpers.arrayElement(keyAnimals)]()]); const [newKey] = await knex('users_keys') .insert({ @@ -706,11 +813,28 @@ export async function createKey(reqUser) { }; } -export async function removeUserKey(reqUser, identifier) { - await knex('users_keys') - .where('user_id', reqUser.id) +// users can remove their own keys, admins can revoke anyone's +export async function removeKey(userId, identifier, reqUser) { + if (!reqUser || (reqUser.id !== userId && reqUser.role !== 'admin')) { + throw new HttpError('You are not permitted to remove this API key.', 403); + } + + const removed = await knex('users_keys') + .where('user_id', userId) .where('identifier', identifier) .delete(); + + if (removed === 0) { + throw new HttpError(`API key '${identifier}' not found`, 404); + } + + if (reqUser.id !== userId) { + logger.info(`API key '${identifier}' of user ${userId} revoked by ${reqUser.username} (${reqUser.id})`); + } +} + +export async function removeUserKey(reqUser, identifier) { + return removeKey(reqUser.id, identifier, reqUser); } export async function flushUserKeys(reqUser) { diff --git a/src/key-rates.js b/src/key-rates.js new file mode 100644 index 0000000..0bb427b --- /dev/null +++ b/src/key-rates.js @@ -0,0 +1,122 @@ +import config from 'config'; + +import verifyAbility from '../utils/verify-ability.js'; +import { HttpError } from './errors.js'; +import redis from './redis.js'; + +// per-minute buckets enforce the limit and cover the last hour, per-hour buckets are kept longer for review +const minuteBuckets = 60; + +function getMinute(time = Date.now()) { + return Math.floor(time / 60_000); +} + +function getMinuteKey(keyId, minute) { + return `traxxx:api_rate:${keyId}:m:${minute}`; +} + +function getHourKey(keyId, hour) { + return `traxxx:api_rate:${keyId}:h:${hour}`; +} + +function getFailKey(ip) { + return `traxxx:api_fails:${ip}`; +} + +function setRetryAfter(req, seconds) { + req?.res?.set('Retry-After', String(Math.max(1, Math.ceil(seconds)))); +} + +// checked before a key is hashed or looked up, so guessing keys costs the guesser more than us +export async function checkFailedAttempts(req) { + if (!req?.userIp) { + return; + } + + const failKey = getFailKey(req.userIp); + const fails = Number(await redis.get(failKey)); + + if (fails >= config.apiAccess.failLimit) { + setRetryAfter(req, await redis.ttl(failKey)); + + throw new HttpError('Too many invalid API credentials, please try again later.', 429); + } +} + +export async function registerFailedAttempt(req) { + if (!req?.userIp) { + return; + } + + const failKey = getFailKey(req.userIp); + const fails = await redis.incr(failKey); + + if (fails === 1) { // the window starts at the first failure + await redis.expire(failKey, config.apiAccess.failWindow * 60); + } +} + +export function isRateExempt(user) { + return config.apiAccess.rateExemptRoles.includes(user.role) || verifyAbility(user, 'sync'); +} + +// counts the request even when it's over the limit, so abuse stays visible in the admin panel +// returns the count for the current minute +export async function countKeyRequest(keyId, user, req) { + const minute = getMinute(); + const hour = Math.floor(minute / 60); + + const [minuteCount] = await redis.multi() + .incr(getMinuteKey(keyId, minute)) + .expire(getMinuteKey(keyId, minute), (minuteBuckets + 5) * 60) + .incr(getHourKey(keyId, hour)) + .expire(getHourKey(keyId, hour), config.apiAccess.rateRetention * 24 * 60 * 60) + .exec(); + + if (minuteCount > config.apiAccess.rateLimit && !isRateExempt(user)) { + setRetryAfter(req, 60 - ((Date.now() / 1000) % 60)); + + throw new HttpError(`API rate limit exceeded, keys are limited to ${config.apiAccess.rateLimit} requests per minute.`, 429); + } + + return Number(minuteCount); +} + +function sum(values) { + return values.reduce((acc, value) => acc + value, 0); +} + +export async function fetchKeyRates(keyIds) { + if (keyIds.length === 0) { + return {}; + } + + const minute = getMinute(); + const hour = Math.floor(minute / 60); + const hourBuckets = config.apiAccess.rateRetention * 24; + + const minuteOffsets = Array.from({ length: minuteBuckets }, (_value, index) => index); + const hourOffsets = Array.from({ length: hourBuckets }, (_value, index) => index); + + const values = await redis.mGet(keyIds.flatMap((keyId) => [ + ...minuteOffsets.map((offset) => getMinuteKey(keyId, minute - offset)), + ...hourOffsets.map((offset) => getHourKey(keyId, hour - offset)), + ])); + + const counts = values.map((value) => Number(value) || 0); + const stride = minuteBuckets + hourBuckets; + + return Object.fromEntries(keyIds.map((keyId, keyIndex) => { + const minutes = counts.slice(keyIndex * stride, keyIndex * stride + minuteBuckets); // newest first + const hours = counts.slice(keyIndex * stride + minuteBuckets, (keyIndex + 1) * stride); + + return [keyId, { + lastMinute: minutes[0], + lastHour: sum(minutes), + peakMinute: Math.max(...minutes), + lastDay: sum(hours.slice(0, 24)), + total: sum(hours), // over the retention period + hours: hours.slice(0, 24).reverse(), // oldest first, for charting + }]; + })); +} diff --git a/src/users.js b/src/users.js index ee5a0b1..6d69c37 100755 --- a/src/users.js +++ b/src/users.js @@ -1,9 +1,11 @@ +import { isIP } from 'node:net'; import config from 'config'; import { parse } from 'yaml'; // import { curateStash } from './stashes.js'; import { HttpError } from './errors.js'; import { knexOwner as knex } from './knex.js'; +import redis from './redis.js'; function curateTemplate(template) { return { @@ -127,8 +129,43 @@ export async function removeTemplate(templateId, reqUser) { } // a ban without a scope applies to everything that checks for bans -export const banScopes = ['revisions', 'reports']; +// 'api' blocks creating API keys by user or IP, and using any key from the IP +export const banScopes = ['revisions', 'reports', 'api']; +// ISPs commonly randomize the second half of an IPv6 address, so ban the subscriber's network instead +// takes a column name, or '?' with the IP as binding +export function getBanRange(ipExpression, bindings = []) { + return knex.raw(`case when family(${ipExpression}::inet) = 6 then set_masklen(${ipExpression}::inet::cidr, ?) else ${ipExpression}::inet::cidr end`, [ + ...bindings, + ...bindings, + config.bans.ipv6Prefix, + ...bindings, + ]); +} + +function curateBanIp(ip) { + const address = String(ip).replace(/\/\d+$/, ''); // inet and cidr columns may include a prefix length + + if (!isIP(address)) { + throw new HttpError(`Invalid IP address '${ip}'`, 400); + } + + return address; +} + +const ipBanCachePrefix = 'traxxx:ip_ban:'; + +async function flushIpBanCache() { + for await (const keys of redis.scanIterator({ MATCH: `${ipBanCachePrefix}*`, COUNT: 1000 })) { + const batch = [].concat(keys); // batches in node-redis 5+, single keys before + + if (batch.length > 0) { + await redis.del(batch); + } + } +} + +// one ban row per IP, each with the user if given, matches the user OR any of the IPs export async function createBan(ban, reqUser) { if (reqUser?.role !== 'admin') { throw new HttpError('You do not have sufficient privileges to set a ban', 403); @@ -138,21 +175,89 @@ export async function createBan(ban, reqUser) { throw new HttpError(`Invalid ban scope '${ban.scope}', must be one of: ${banScopes.join(', ')}`, 400); } + const expiry = ban.expiry ?? config.bans.defaultExpiry; // in minutes + + if (!Number.isInteger(expiry) || expiry <= 0) { + throw new HttpError('Ban expiry must be a positive number of minutes', 400); + } + const targetUser = ban.userId && await knex('users').where('id', ban.userId).first(); - const curatedBan = { - user_id: ban.userId, - username: ban.username, - ip: ban.banIp && targetUser?.last_ip, + if (ban.userId && !targetUser) { + throw new HttpError(`User ${ban.userId} not found`, 404); + } + + const ips = [ + ...(ban.ips || []), + ban.banIp && targetUser?.last_ip, // the user's last login IP + ].filter(Boolean).map((ip) => curateBanIp(ip)); + + if (!ban.userId && !ban.username && ips.length === 0) { + throw new HttpError('A ban needs a user, username or IP', 400); + } + + const ranges = await Promise.all(ips.map(async (ip) => { + const { rows: [{ range }] } = await knex.raw('select ? as range', [getBanRange('?', [ip])]); + + return range; + })); + + const curatedBans = Array.from(new Set(ranges.length > 0 ? ranges : [null]), (range) => ({ + user_id: ban.userId || null, + username: ban.username || targetUser?.username || null, + ip: range, scope: ban.scope || null, banned_by: reqUser.id, - expires_at: knex.raw('now() + make_interval(mins => :minutes)', { minutes: config.bans.defaultExpiry }), - }; + expires_at: knex.raw('now() + make_interval(mins => ?)', [expiry]), + })); - await knex('bans').insert(curatedBan); + const newBans = await knex('bans') + .insert(curatedBans) + .returning(['id', 'ip', 'expires_at']); + + if (ranges.length > 0) { + await flushIpBanCache(); // cached verdicts are per IP, so any of them may now be wrong + } + + return newBans; +} + +async function isIpBanned(ip, scope) { + const ban = await knex('bans') + .where('expires_at', '>', knex.fn.now()) + .where((builder) => { + builder + .whereNull('scope') + .orWhere('scope', scope); + }) + .whereRaw('ip >>= ?::inet', [ip]) + .first(); + + return !!ban; +} + +// for checks on every request, verdicts are cached briefly and flushed when a ban is created +export async function verifyIpNotBanned(ip, scope, message = 'You are not allowed to do this') { + if (!ip) { + return; + } + + const cacheKey = `${ipBanCachePrefix}${scope}:${ip}`; + const cached = await redis.get(cacheKey); + + const isBanned = cached === null + ? await isIpBanned(ip, scope) + : cached === '1'; + + if (cached === null) { + await redis.set(cacheKey, isBanned ? '1' : '0', { EX: config.bans.cacheExpiry }); + } + + if (isBanned) { + throw new HttpError(message, 403); + } } -// throws if an active ban for this scope (or an unscoped ban) matches the user's ID, username or IP export async function verifyNotBanned(reqUser, scope, message = 'You are not allowed to do this') { const ban = await knex('bans') .where('expires_at', '>', knex.fn.now()) diff --git a/src/web/auth.js b/src/web/auth.js index 3513fbe..a7b2bde 100755 --- a/src/web/auth.js +++ b/src/web/auth.js @@ -9,6 +9,7 @@ import { fetchUserKeys, flushUserKeys, login, + removeKey, removeUserKey, resetPassword, sendEmailVerification, @@ -76,8 +77,8 @@ function getIp(req) { // ensure IP is in expanded notation for consistency and matching const expandedIp = unmappedIp.includes(':') - ? new IPCIDR(`${ip}/128`) // IPv6 - : new IPCIDR(`${ip}/32`); // IPv4 + ? new IPCIDR(`${unmappedIp}/128`) // IPv6 + : new IPCIDR(`${unmappedIp}/32`); // IPv4, including IPv4-mapped IPv6 like ::ffff:1.2.3.4 if (!expandedIp.addressStart?.addressMinusSuffix) { throw new Error(`Could not determine user IP from ${ip}`); @@ -238,6 +239,12 @@ export async function removeUserKeyApi(req, res) { res.status(204).send(); } +export async function removeKeyApi(req, res) { + await removeKey(Number(req.params.userId), req.params.keyIdentifier, req.user); + + res.status(204).send(); +} + export async function flushUserKeysApi(req, res) { await flushUserKeys(req.user); @@ -271,3 +278,4 @@ authRouter.get('/api/me/keys', fetchUserKeysApi); authRouter.post('/api/me/keys', createKeyApi); authRouter.delete('/api/me/keys/:keyIdentifier', removeUserKeyApi); authRouter.delete('/api/me/keys', flushUserKeysApi); +authRouter.delete('/api/users/:userId/keys/:keyIdentifier', removeKeyApi); // admin revocation, /api/me/keys is the owner's alias