Improved API access setup, only requires e-mail verification, integrated with bans, added admin panel.

This commit is contained in:
2026-11-29 06:17:04 +01:00
parent d497c1fabf
commit 2fcb16cb33
12 changed files with 1051 additions and 30 deletions
+11
View File
@@ -60,6 +60,17 @@
:class="{ active: pageContext.urlPathname.startsWith('/admin/emails') }"
>E-mails</a>
</li>
<li
v-if="pageContext.user.role === 'admin'"
class="nav-item"
>
<a
href="/admin/keys"
class="nav-link nolink"
:class="{ active: pageContext.routeParams.section === 'keys' }"
>API Keys</a>
</li>
</ul>
<button
+267
View File
@@ -0,0 +1,267 @@
<template>
<Dialog
title="API ban"
@close="emit('close')"
>
<form
class="dialog-body"
@submit.prevent="ban"
>
<div class="dialog-section">
<p class="dialog-description">A banned user can't create new API keys, and no key can be used from a banned IP. IPv6 addresses are banned by their /{{ ipv6Prefix }} network.</p>
<ul class="targets nolist">
<li class="target">
<Checkbox
:checked="banUser"
@change="(checked) => banUser = checked"
/>
<span class="target-label">User</span>
<a
:href="`/user/${apiKey.user.username}`"
target="_blank"
class="target-value link"
>{{ apiKey.user.username }}</a>
</li>
<li
class="target"
:class="{ unavailable: !apiKey.user.lastIp }"
>
<Checkbox
:checked="banLoginIp"
:disabled="!apiKey.user.lastIp"
@change="(checked) => banLoginIp = checked"
/>
<span class="target-label">Last login IP</span>
<span
v-if="apiKey.user.lastIp"
:title="apiKey.user.lastIp"
class="target-value"
>{{ apiKey.user.loginRange }}</span>
<span
v-else
class="target-value"
>unknown</span>
</li>
<li
class="target"
:class="{ unavailable: !apiKey.lastUsedIp || isSameRange }"
>
<Checkbox
:checked="banKeyIp"
:disabled="!apiKey.lastUsedIp || isSameRange"
@change="(checked) => banKeyIp = checked"
/>
<span class="target-label">Last used by {{ apiKey.identifier }}</span>
<span
v-if="isSameRange"
class="target-value"
>same as login</span>
<span
v-else-if="apiKey.lastUsedIp"
:title="apiKey.lastUsedIp"
class="target-value"
>{{ apiKey.lastUsedRange }}</span>
<span
v-else
class="target-value"
>never used</span>
</li>
</ul>
<div class="expiry">
<label
for="ban-expiry"
class="target-label"
>Expires after</label>
<input
id="ban-expiry"
v-model.number="expiryAmount"
type="number"
min="1"
step="1"
required
class="input expiry-amount"
>
<select
v-model="expiryUnit"
class="input"
>
<option
v-for="(unit, key) in expiryUnits"
:key="`expiry-${key}`"
:value="key"
>{{ expiryAmount === 1 ? unit.label : `${unit.label}s` }}</option>
</select>
</div>
<p class="dialog-note">Existing keys keep working from other IPs, revoke them to stop them entirely.</p>
</div>
<div class="dialog-actions">
<button
:disabled="!hasTargets || !expiry || !done"
class="button button-primary"
>Ban</button>
</div>
</form>
</Dialog>
</template>
<script setup>
import { computed, ref } from 'vue';
import Dialog from '#/components/dialog/dialog.vue';
import Checkbox from '#/components/form/checkbox.vue';
import { post } from '#/src/api.js';
const props = defineProps({
apiKey: {
type: Object,
required: true,
},
ipv6Prefix: {
type: Number,
default: 64,
},
});
const emit = defineEmits(['close', 'banned']);
// the back-end takes minutes, months and years are approximate
const expiryUnits = {
hour: { label: 'hour', minutes: 60 },
day: { label: 'day', minutes: 60 * 24 },
week: { label: 'week', minutes: 60 * 24 * 7 },
month: { label: 'month', minutes: 60 * 24 * 30 },
year: { label: 'year', minutes: 60 * 24 * 365 },
};
// both IPs are often in the same network, one ban covers it
const isSameRange = computed(() => !!props.apiKey.lastUsedRange && props.apiKey.lastUsedRange === props.apiKey.user.loginRange);
const banUser = ref(true);
const banLoginIp = ref(!!props.apiKey.user.lastIp);
const banKeyIp = ref(!!props.apiKey.lastUsedIp && !isSameRange.value);
const expiryAmount = ref(1);
const expiryUnit = ref('year');
const expiry = computed(() => (Number.isInteger(expiryAmount.value) && expiryAmount.value > 0
? expiryAmount.value * expiryUnits[expiryUnit.value].minutes
: null));
const done = ref(true);
const hasTargets = computed(() => banUser.value || banLoginIp.value || banKeyIp.value);
async function ban() {
const { user } = props.apiKey;
done.value = false;
try {
await post('/bans', {
userId: banUser.value ? user.id : undefined,
ips: [
banLoginIp.value && user.lastIp,
banKeyIp.value && props.apiKey.lastUsedIp,
].filter(Boolean),
scope: 'api',
expiry: expiry.value,
}, {
successFeedback: banUser.value ? `Banned ${user.username} from the API` : 'Banned IPs from the API',
errorFeedback: 'Failed to set API ban',
appendErrorMessage: true,
});
emit('banned', { userId: banUser.value ? user.id : null });
emit('close');
}
catch {
// feedback is shown by the api module
}
finally {
done.value = true;
}
}
</script>
<style scoped>
.dialog-body {
width: 30rem;
max-width: 100%;
}
.dialog-section {
padding: 1rem 1rem 0 1rem;
}
.dialog-description {
margin: 0 0 1rem 0;
}
.targets {
display: flex;
flex-direction: column;
gap: .5rem;
}
.target,
.expiry {
display: flex;
align-items: center;
gap: .75rem;
}
.target.unavailable {
color: var(--glass);
}
.target-label {
flex-grow: 1;
}
.target-value {
font-family: monospace;
font-size: .9rem;
overflow-wrap: anywhere;
text-align: right;
}
.link {
color: var(--primary);
}
.expiry {
margin-top: 1rem;
}
.expiry-amount {
width: 4rem;
}
.dialog-note {
margin: 1rem 0 0 0;
color: var(--glass);
font-size: .9rem;
}
.dialog-actions {
display: flex;
justify-content: center;
padding: 1rem;
}
</style>
+7
View File
@@ -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,
+11
View File
@@ -37,12 +37,23 @@
class="link"
>Reports</a>
</li>
<li v-if="user.role === 'admin'">
<a
href="/admin/keys"
class="link"
>API Keys</a>
</li>
</ul>
</Admin>
</template>
<script setup>
import { inject } from 'vue';
import Admin from '#/components/admin/admin.vue';
const { user } = inject('pageContext');
</script>
<style scoped>
+312
View File
@@ -0,0 +1,312 @@
<template>
<Admin class="page">
<div class="header">
<h2 class="heading">API keys</h2>
<span class="summary">{{ keys.length }} {{ keys.length === 1 ? 'key' : 'keys' }} held by {{ userCount }} {{ userCount === 1 ? 'user' : 'users' }}, {{ activeCount }} used in the last 24 hours</span>
</div>
<p
v-if="keys.length === 0"
class="empty"
>No API keys.</p>
<table
v-else
class="table"
>
<thead class="table-header">
<tr>
<th class="table-heading">Key</th>
<th class="table-heading">User</th>
<th class="table-heading">Last used</th>
<th class="table-heading table-number">Last hour</th>
<th class="table-heading table-number">24 hours</th>
<th class="table-heading">Hourly</th>
<th class="table-heading table-number">{{ retention }} days</th>
<th class="table-heading">Last IP</th>
<th class="table-heading">Created</th>
<th class="table-heading">Actions</th>
</tr>
</thead>
<tbody>
<tr
v-for="key in keys"
:key="`key-${key.id}`"
class="key"
:class="{ unused: !key.lastUsedAt }"
>
<td class="table-cell table-identifier">{{ key.identifier }}</td>
<td class="table-cell table-username ellipsis">
<a
v-if="key.user.username"
:href="`/user/${key.user.username}`"
target="_blank"
class="link"
>{{ key.user.username }}</a>
<span
v-else
class="deleted"
>deleted user</span>
<Icon
v-if="key.user.username && !key.user.isEmailVerified"
v-tooltip="'E-mail address unverified, key is suspended'"
icon="warning2"
class="unverified"
/>
</td>
<td
:title="key.lastUsedAt && format(key.lastUsedAt, 'yyyy-MM-dd HH:mm:ss')"
class="table-cell table-date"
>{{ key.lastUsedAt ? `${formatDistanceStrict(key.lastUsedAt, now)} ago` : 'never' }}</td>
<td
v-tooltip="`${key.rates.lastMinute} in the last minute, peak ${key.rates.peakMinute} per minute`"
class="table-cell table-number"
:class="{ limited: key.rates.peakMinute > rateLimit }"
>{{ key.rates.lastHour }}</td>
<td class="table-cell table-number">{{ key.rates.lastDay }}</td>
<td class="table-cell table-chart">
<svg
v-if="key.rates.lastDay > 0"
:viewBox="`0 0 ${key.rates.hours.length * 3} 20`"
preserveAspectRatio="none"
class="sparkline"
>
<rect
v-for="(count, index) in key.rates.hours"
:key="`key-${key.id}-hour-${index}`"
:x="index * 3"
:y="20 - getBarHeight(key, count)"
width="2"
:height="getBarHeight(key, count)"
><title>{{ count }} requests, {{ key.rates.hours.length - index - 1 }} hours ago</title></rect>
</svg>
</td>
<td class="table-cell table-number">{{ key.rates.total }}</td>
<td class="table-cell table-ip">{{ key.lastUsedIp }}</td>
<td class="table-cell table-date">{{ format(key.createdAt, 'yyyy-MM-dd HH:mm') }}</td>
<td class="table-cell table-actions">
<Icon
v-if="key.user.username"
v-tooltip="key.user.isBanned ? `${key.user.username} is banned from creating keys` : `Ban ${key.user.username} from the API`"
icon="blocked"
class="ban"
:class="{ banned: key.user.isBanned }"
@click="banKey = key"
/>
<Icon
v-tooltip="`Revoke ${key.identifier}`"
icon="bin"
class="revoke"
@click="revokeKey(key)"
/>
</td>
</tr>
</tbody>
</table>
<ApiBan
v-if="banKey"
:api-key="banKey"
:ipv6-prefix="ipv6Prefix"
@banned="markBanned"
@close="banKey = null"
/>
</Admin>
</template>
<script setup>
import { format, formatDistanceStrict, subDays } from 'date-fns';
import { computed, inject, ref } from 'vue';
import Admin from '#/components/admin/admin.vue';
import ApiBan from '#/components/admin/api-ban.vue';
import { del } from '#/src/api.js';
const { pageProps } = inject('pageContext');
const { rateLimit, retention, ipv6Prefix } = pageProps;
const keys = ref(pageProps.keys);
const banKey = ref(null);
const now = new Date();
const userCount = computed(() => new Set(keys.value.map((key) => key.user.id)).size);
const activeCount = computed(() => keys.value.filter((key) => key.lastUsedAt && new Date(key.lastUsedAt) > subDays(now, 1)).length);
function getBarHeight(key, count) {
const peak = Math.max(...key.rates.hours);
return count > 0 ? Math.max(1, (count / peak) * 20) : 0;
}
function markBanned({ userId }) {
if (userId) {
keys.value = keys.value.map((listedKey) => (listedKey.user.id === userId
? { ...listedKey, user: { ...listedKey.user, isBanned: true } }
: listedKey));
}
}
async function revokeKey(key) {
const owner = key.user.username || 'deleted user';
if (!confirm(`Revoke API key '${key.identifier}' of ${owner}? Anything using it will stop working.`)) { // eslint-disable-line no-alert
return;
}
const revoked = await del(`/users/${key.user.id}/keys/${key.identifier}`, {
successFeedback: `Revoked ${key.identifier} of ${owner}`,
errorFeedback: `Failed to revoke ${key.identifier}`,
appendErrorMessage: true,
}).then(() => true).catch(() => false); // feedback is shown by the api module
if (revoked) {
keys.value = keys.value.filter((listedKey) => listedKey.id !== key.id);
}
}
</script>
<style scoped>
.page {
flex-grow: 1;
}
.header {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 1rem;
margin-bottom: 1rem;
}
.heading {
margin: 0;
}
.summary,
.empty {
color: var(--glass);
}
.empty {
font-style: italic;
}
.table {
border-collapse: collapse;
border: 0;
}
.table-heading {
text-align: left;
padding: 0 .5rem .25rem .5rem;
}
.table-cell {
padding: .25rem .5rem .25rem .5rem;
border-collapse: collapse;
border: 0;
}
.table-identifier {
font-family: monospace;
font-size: .9rem;
}
.table-username {
max-width: 12rem;
}
.table-number {
text-align: right;
font-variant-numeric: tabular-nums;
}
.limited {
color: var(--warn);
font-weight: bold;
}
.table-chart {
vertical-align: middle;
}
.sparkline {
display: block;
width: 6rem;
height: 1.25rem;
fill: var(--primary);
}
.table-date,
.table-ip {
white-space: nowrap;
}
.key {
&:nth-child(2n) {
background: var(--glass-weak-50);
}
&.unused .table-identifier {
color: var(--glass);
}
}
.link {
color: var(--text);
}
.deleted {
color: var(--glass);
font-style: italic;
}
.table-actions {
display: flex;
justify-content: center;
gap: .5rem;
}
.ban {
fill: var(--glass);
&:hover {
fill: var(--warn);
cursor: pointer;
}
&.banned {
fill: var(--warn);
}
}
.revoke {
fill: var(--glass);
&:hover {
fill: var(--warn);
cursor: pointer;
}
}
.unverified {
margin-left: .25rem;
fill: var(--warn);
transform: translateY(1px);
}
</style>
+27
View File
@@ -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',
},
},
};
}
+21 -1
View File
@@ -85,12 +85,18 @@
><Icon icon="filter" />Filters</span>
<a
v-if="profile.isIdentityVerified"
v-if="user.isEmailVerified"
:href="`/user/${profile.username}/api`"
class="domain nolink"
:class="{ active: section === 'api' }"
><Icon icon="key" />API Keys</a>
<span
v-else
v-tooltip="'Verify your e-mail address under Account to use API keys'"
class="domain disabled"
><Icon icon="key" />API Keys</span>
<a
:href="`/user/${profile.username}/preferences`"
class="domain nolink"
@@ -301,6 +307,20 @@ function scrollHorizontal(event) {
fill: var(--text-light);
}
}
&.disabled {
opacity: .5;
&:hover {
background: var(--background-dark-20);
color: var(--glass-strong-20);
cursor: default;
.icon {
fill: var(--glass-strong-20);
}
}
}
}
.revisions {
+9 -2
View File
@@ -1,4 +1,4 @@
import { render } from 'vike/abort';
import { redirect, render } from 'vike/abort';
import { fetchActorRevisions } from '#/src/actors.js';
import { fetchAlerts } from '#/src/alerts.js';
@@ -32,13 +32,20 @@ async function fetchRevisions(pageContext) {
}
export async function onBeforeRender(pageContext) {
const isApiSection = pageContext.routeParams.section === 'api';
// API keys require a verified e-mail address, the profile page explains why the button is disabled
if (isApiSection && (pageContext.routeParams.username !== pageContext.user?.username || !pageContext.user.isEmailVerified)) {
throw redirect(`/user/${pageContext.routeParams.username}`);
}
const [profile, alerts, userRevisions, keys] = await Promise.all([
fetchUser(pageContext.routeParams.username, { throwError: false }, pageContext.user),
pageContext.routeParams.section === 'alerts' && pageContext.routeParams.username === pageContext.user?.username
? fetchAlerts(pageContext.user)
: [],
fetchRevisions(pageContext),
pageContext.routeParams.section === 'api'
isApiSection
? fetchUserKeys(pageContext.user)
: [],
]);
+140 -16
View File
@@ -11,15 +11,19 @@ import { verify as verifyCaptcha } from 'hcaptcha';
import slugify from '../utils/slugify.js';
import { sendEmails } from './email.js';
import { HttpError } from './errors.js';
import { checkFailedAttempts, countKeyRequest, fetchKeyRates, registerFailedAttempt } from './key-rates.js';
import { knexOwner as knex } from './knex.js';
import initLogger, { initAccessLogger } from './logger.js';
import redis from './redis.js';
import { curateUser, fetchUser } from './users.js';
import { curateUser, fetchUser, getBanRange, verifyIpNotBanned, verifyNotBanned } from './users.js';
const logger = initLogger();
const accessLogger = initAccessLogger();
const scrypt = util.promisify(crypto.scrypt);
// faker.animal.type() returns names like 'polar bear' that don't all have a faker.animal method, use the methods directly
const keyAnimals = ['bear', 'bird', 'cat', 'cetacean', 'cow', 'crocodilia', 'dog', 'fish', 'horse', 'insect', 'lion', 'rabbit', 'rodent', 'snake'];
async function verifyPassword(password, storedPassword) {
const [salt, hash] = storedPassword.split('/');
const hashedPassword = (await scrypt(password, salt, 64)).toString('hex');
@@ -628,6 +632,82 @@ export async function fetchUserKeys(reqUser) {
return keys.map((key) => 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) {
+122
View File
@@ -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
}];
}));
}
+114 -9
View File
@@ -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())
+10 -2
View File
@@ -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