Fix share URL permissions. (#1745)

* Fix share URL permissions.

* Add sql param logic.

* Add permissions to edit website.

* Update permissions.

* Move parameters to param injection.

* Sanitize eventdata.

* Remove caret.

* Fix avg.
This commit is contained in:
Brian Cao 2023-01-18 15:09:49 -08:00 committed by GitHub
parent 558ce268a0
commit 922c3acab3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 139 additions and 79 deletions

View File

@ -29,21 +29,24 @@ export default function Header() {
<Icon icon={<Logo />} size="large" className={styles.logo} /> <Icon icon={<Logo />} size="large" className={styles.logo} />
<Link href={isSharePage ? HOMEPAGE_URL : '/'}>umami</Link> <Link href={isSharePage ? HOMEPAGE_URL : '/'}>umami</Link>
</div> </div>
<HamburgerButton />
{user && ( {user && (
<div className={styles.links}> <>
<Link href="/dashboard"> <HamburgerButton />
<FormattedMessage id="label.dashboard" defaultMessage="Dashboard" /> <div className={styles.links}>
</Link> <Link href="/dashboard">
<Link href="/realtime"> <FormattedMessage id="label.dashboard" defaultMessage="Dashboard" />
<FormattedMessage id="label.realtime" defaultMessage="Realtime" />
</Link>
{!process.env.isCloudMode && (
<Link href="/settings">
<FormattedMessage id="label.settings" defaultMessage="Settings" />
</Link> </Link>
)} <Link href="/realtime">
</div> <FormattedMessage id="label.realtime" defaultMessage="Realtime" />
</Link>
{!process.env.isCloudMode && (
<Link href="/settings">
<FormattedMessage id="label.settings" defaultMessage="Settings" />
</Link>
)}
</div>
</>
)} )}
<div className={styles.buttons}> <div className={styles.buttons}>
<ThemeButton /> <ThemeButton />

View File

@ -35,7 +35,7 @@ export function isValidToken(token, validation) {
return false; return false;
} }
export async function allowQuery(req, type) { export async function allowQuery(req, type, allowShareToken = true) {
const { id } = req.query; const { id } = req.query;
const { userId, isAdmin, shareToken } = req.auth ?? {}; const { userId, isAdmin, shareToken } = req.auth ?? {};
@ -44,7 +44,7 @@ export async function allowQuery(req, type) {
return true; return true;
} }
if (shareToken) { if (allowShareToken && shareToken) {
return isValidToken(shareToken, { id }); return isValidToken(shareToken, { id });
} }

View File

@ -36,6 +36,18 @@ function logQuery(e) {
log(chalk.yellow(e.params), '->', e.query, chalk.greenBright(`${e.duration}ms`)); log(chalk.yellow(e.params), '->', e.query, chalk.greenBright(`${e.duration}ms`));
} }
function toUuid() {
const db = getDatabaseType(process.env.DATABASE_URL);
if (db === POSTGRESQL) {
return '::uuid';
}
if (db === MYSQL) {
return '';
}
}
function getClient(options) { function getClient(options) {
const prisma = new PrismaClient(options); const prisma = new PrismaClient(options);
@ -85,11 +97,23 @@ function getTimestampInterval(field) {
} }
} }
function getJsonField(column, property, isNumber) { function getSanitizedColumns(columns) {
return Object.keys(columns).reduce((acc, keyName) => {
const sanitizedProperty = keyName.replace(/[\w\s_]/g, '');
acc[sanitizedProperty] = columns[keyName];
return acc;
}, {});
}
function getJsonField(column, property, isNumber, params) {
const db = getDatabaseType(process.env.DATABASE_URL); const db = getDatabaseType(process.env.DATABASE_URL);
if (db === POSTGRESQL) { if (db === POSTGRESQL) {
let accessor = `${column} ->> '${property}'`; params.push(property);
let accessor = `${column} ->> $${params.length}`;
if (isNumber) { if (isNumber) {
accessor = `CAST(${accessor} AS DECIMAL)`; accessor = `CAST(${accessor} AS DECIMAL)`;
@ -99,21 +123,29 @@ function getJsonField(column, property, isNumber) {
} }
if (db === MYSQL) { if (db === MYSQL) {
return `${column} ->> "$.${property}"`; return `${column} ->> '$.${property}'`;
} }
} }
function getEventDataColumnsQuery(column, columns) { function getEventDataColumnsQuery(column, columns, params) {
const query = Object.keys(columns).reduce((arr, key) => { const query = Object.keys(columns).reduce((arr, key, i) => {
const filter = columns[key]; const filter = columns[key];
if (filter === undefined) { if (filter === undefined) {
return arr; return arr;
} }
const isNumber = ['sum', 'avg', 'min', 'max'].some(a => a === filter); switch (filter) {
case 'sum':
arr.push(`${filter}(${getJsonField(column, key, isNumber)}) as "${filter}(${key})"`); case 'avg':
case 'min':
case 'max':
arr.push(`${filter}(${getJsonField(column, key, true, params)}) as "${i}"`);
break;
case 'count':
arr.push(`${filter}(${getJsonField(column, key, false, params)}) as "${i}"`);
break;
}
return arr; return arr;
}, []); }, []);
@ -121,7 +153,7 @@ function getEventDataColumnsQuery(column, columns) {
return query.join(',\n'); return query.join(',\n');
} }
function getEventDataFilterQuery(column, filters) { function getEventDataFilterQuery(column, filters, params) {
const query = Object.keys(filters).reduce((arr, key) => { const query = Object.keys(filters).reduce((arr, key) => {
const filter = filters[key]; const filter = filters[key];
@ -131,11 +163,9 @@ function getEventDataFilterQuery(column, filters) {
const isNumber = filter && typeof filter === 'number'; const isNumber = filter && typeof filter === 'number';
arr.push( arr.push(`${getJsonField(column, key, isNumber, params)} = $${params.length + 1}`);
`${getJsonField(column, key, isNumber)} = ${
typeof filter === 'string' ? `'${filter}'` : filter params.push(filter);
}`,
);
return arr; return arr;
}, []); }, []);
@ -248,11 +278,13 @@ const prisma = global[PRISMA] || getClient(PRISMA_OPTIONS);
export default { export default {
client: prisma, client: prisma,
log, log,
toUuid,
getDateQuery, getDateQuery,
getTimestampInterval, getTimestampInterval,
getFilterQuery, getFilterQuery,
getEventDataColumnsQuery, getEventDataColumnsQuery,
getEventDataFilterQuery, getEventDataFilterQuery,
getSanitizedColumns,
parseFilters, parseFilters,
rawQuery, rawQuery,
transaction, transaction,

View File

@ -17,7 +17,7 @@ export default async (req, res) => {
const { current_password, new_password } = req.body; const { current_password, new_password } = req.body;
const { id: accountUuid } = req.query; const { id: accountUuid } = req.query;
if (!(await allowQuery(req, TYPE_ACCOUNT))) { if (!(await allowQuery(req, TYPE_ACCOUNT, false))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -1,5 +1,5 @@
import { subMinutes } from 'date-fns'; import { subMinutes } from 'date-fns';
import { ok, methodNotAllowed, createToken } from 'next-basics'; import { ok, unauthorized, methodNotAllowed, createToken } from 'next-basics';
import { useAuth } from 'lib/middleware'; import { useAuth } from 'lib/middleware';
import { getUserWebsites, getRealtimeData } from 'queries'; import { getUserWebsites, getRealtimeData } from 'queries';
import { secret } from 'lib/crypto'; import { secret } from 'lib/crypto';
@ -10,6 +10,10 @@ export default async (req, res) => {
if (req.method === 'GET') { if (req.method === 'GET') {
const { userId } = req.auth; const { userId } = req.auth;
if (!userId) {
return unauthorized(res);
}
const websites = await getUserWebsites({ userId }); const websites = await getUserWebsites({ userId });
const ids = websites.map(({ websiteUuid }) => websiteUuid); const ids = websites.map(({ websiteUuid }) => websiteUuid);
const token = createToken({ websites: ids }, secret()); const token = createToken({ websites: ids }, secret());

View File

@ -10,17 +10,21 @@ export default async (req, res) => {
const { id: websiteUuid } = req.query; const { id: websiteUuid } = req.query;
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
if (req.method === 'GET') { if (req.method === 'GET') {
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
const website = await getWebsite({ websiteUuid }); const website = await getWebsite({ websiteUuid });
return ok(res, website); return ok(res, website);
} }
if (req.method === 'POST') { if (req.method === 'POST') {
if (!(await allowQuery(req, TYPE_WEBSITE, false))) {
return unauthorized(res);
}
const { name, domain, owner, enableShareUrl, shareId } = req.body; const { name, domain, owner, enableShareUrl, shareId } = req.body;
const { accountUuid } = req.auth; const { accountUuid } = req.auth;
@ -58,7 +62,7 @@ export default async (req, res) => {
} }
if (req.method === 'DELETE') { if (req.method === 'DELETE') {
if (!(await allowQuery(req, TYPE_WEBSITE))) { if (!(await allowQuery(req, TYPE_WEBSITE, false))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -11,7 +11,7 @@ export default async (req, res) => {
const { id: websiteId } = req.query; const { id: websiteId } = req.query;
if (req.method === 'POST') { if (req.method === 'POST') {
if (!(await allowQuery(req, TYPE_WEBSITE))) { if (!(await allowQuery(req, TYPE_WEBSITE, false))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -7,6 +7,7 @@ export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
const { user_id, include_all } = req.query; const { user_id, include_all } = req.query;
const { userId: currentUserId, isAdmin } = req.auth; const { userId: currentUserId, isAdmin } = req.auth;
const accountUuid = user_id || req.auth.accountUuid; const accountUuid = user_id || req.auth.accountUuid;
let account; let account;
@ -18,7 +19,7 @@ export default async (req, res) => {
const userId = account ? account.id : user_id; const userId = account ? account.id : user_id;
if (req.method === 'GET') { if (req.method === 'GET') {
if (userId && userId !== currentUserId && !isAdmin) { if (!userId || (userId !== currentUserId && !isAdmin)) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -10,29 +10,44 @@ export async function getEventData(...args) {
} }
async function relationalQuery(websiteId, { startDate, endDate, event_name, columns, filters }) { async function relationalQuery(websiteId, { startDate, endDate, event_name, columns, filters }) {
const { rawQuery, getEventDataColumnsQuery, getEventDataFilterQuery } = prisma; const {
const params = [startDate, endDate]; rawQuery,
getEventDataColumnsQuery,
getEventDataFilterQuery,
toUuid,
getSanitizedColumns,
} = prisma;
const sanitizedColumns = getSanitizedColumns(columns);
const params = [websiteId, startDate, endDate];
if (event_name) {
params.push(event_name);
}
const columnQuery = getEventDataColumnsQuery('event_data.event_data', sanitizedColumns, params);
const filterQuery =
Object.keys(filters).length > 0
? `and ${getEventDataFilterQuery('event_data.event_data', filters, params)}`
: '';
return rawQuery( return rawQuery(
`select `select
${getEventDataColumnsQuery('event_data.event_data', columns)} ${columnQuery}
from event from event
join website join website
on event.website_id = website.website_id on event.website_id = website.website_id
join event_data join event_data
on event.event_id = event_data.event_id on event.event_id = event_data.event_id
where website_uuid='${websiteId}' where website_uuid = $1${toUuid()}
and event.created_at between $1 and $2 and event.created_at between $2 and $3
${event_name ? `and event_name = ${event_name}` : ''} ${event_name ? `and event_name = $4` : ''}
${ ${filterQuery}`,
Object.keys(filters).length > 0
? `and ${getEventDataFilterQuery('event_data.event_data', filters)}`
: ''
}`,
params, params,
).then(results => { ).then(results => {
return Object.keys(results[0]).map(a => { const fields = Object.keys(sanitizedColumns);
return { x: a, y: results[0][`${a}`] };
return Object.keys(results[0]).map((a, i) => {
return { x: `${sanitizedColumns[fields[i]]}(${fields[i]})`, y: results[0][i] };
}); });
}); });
} }

View File

@ -17,8 +17,8 @@ async function relationalQuery(
unit = 'day', unit = 'day',
filters = {}, filters = {},
) { ) {
const { rawQuery, getDateQuery, getFilterQuery } = prisma; const { rawQuery, getDateQuery, getFilterQuery, toUuid } = prisma;
const params = [start_at, end_at]; const params = [websiteId, start_at, end_at];
return rawQuery( return rawQuery(
`select `select
@ -28,8 +28,8 @@ async function relationalQuery(
from event from event
join website join website
on event.website_id = website.website_id on event.website_id = website.website_id
where website_uuid='${websiteId}' where website_uuid = $1${toUuid()}
and event.created_at between $1 and $2 and event.created_at between $2 and $3
${getFilterQuery('event', filters, params)} ${getFilterQuery('event', filters, params)}
group by 1, 2 group by 1, 2
order by 2`, order by 2`,

View File

@ -10,8 +10,8 @@ export async function getPageviewMetrics(...args) {
} }
async function relationalQuery(websiteId, { startDate, endDate, column, table, filters = {} }) { async function relationalQuery(websiteId, { startDate, endDate, column, table, filters = {} }) {
const { rawQuery, parseFilters } = prisma; const { rawQuery, parseFilters, toUuid } = prisma;
const params = [startDate, endDate]; const params = [websiteId, startDate, endDate];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table, table,
column, column,
@ -24,8 +24,8 @@ async function relationalQuery(websiteId, { startDate, endDate, column, table, f
from ${table} from ${table}
${` join website on ${table}.website_id = website.website_id`} ${` join website on ${table}.website_id = website.website_id`}
${joinSession} ${joinSession}
where website.website_uuid='${websiteId}' where website.website_uuid = $1${toUuid()}
and ${table}.created_at between $1 and $2 and ${table}.created_at between $2 and $3
${pageviewQuery} ${pageviewQuery}
${joinSession && sessionQuery} ${joinSession && sessionQuery}
${eventQuery} ${eventQuery}

View File

@ -9,8 +9,8 @@ export async function getPageviewParams(...args) {
} }
async function relationalQuery(websiteId, start_at, end_at, column, table, filters = {}) { async function relationalQuery(websiteId, start_at, end_at, column, table, filters = {}) {
const { parseFilters, rawQuery } = prisma; const { parseFilters, rawQuery, toUuid } = prisma;
const params = [start_at, end_at]; const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table, table,
column, column,
@ -24,8 +24,8 @@ async function relationalQuery(websiteId, start_at, end_at, column, table, filte
from ${table} from ${table}
${` join website on ${table}.website_id = website.website_id`} ${` join website on ${table}.website_id = website.website_id`}
${joinSession} ${joinSession}
where website.website_uuid='${websiteId}' where website.website_uuid = $1${toUuid()}
and ${table}.created_at between $1 and $2 and ${table}.created_at between $2 and $3
and ${table}.url like '%?%' and ${table}.url like '%?%'
${pageviewQuery} ${pageviewQuery}
${joinSession && sessionQuery} ${joinSession && sessionQuery}

View File

@ -21,8 +21,8 @@ async function relationalQuery(
sessionKey = 'session_id', sessionKey = 'session_id',
}, },
) { ) {
const { getDateQuery, parseFilters, rawQuery } = prisma; const { getDateQuery, parseFilters, rawQuery, toUuid } = prisma;
const params = [start_at, end_at]; const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, joinSession } = parseFilters(
'pageview', 'pageview',
null, null,
@ -37,8 +37,8 @@ async function relationalQuery(
join website join website
on pageview.website_id = website.website_id on pageview.website_id = website.website_id
${joinSession} ${joinSession}
where website.website_uuid='${websiteId}' where website.website_uuid = $1${toUuid()}
and pageview.created_at between $1 and $2 and pageview.created_at between $2 and $3
${pageviewQuery} ${pageviewQuery}
${sessionQuery} ${sessionQuery}
group by 1`, group by 1`,

View File

@ -10,8 +10,8 @@ export async function getSessionMetrics(...args) {
} }
async function relationalQuery(websiteId, { startDate, endDate, field, filters = {} }) { async function relationalQuery(websiteId, { startDate, endDate, field, filters = {} }) {
const { parseFilters, rawQuery } = prisma; const { parseFilters, rawQuery, toUuid } = prisma;
const params = [startDate, endDate]; const params = [websiteId, startDate, endDate];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters(null, filters, params); const { pageviewQuery, sessionQuery, joinSession } = parseFilters(null, filters, params);
return rawQuery( return rawQuery(
@ -23,8 +23,8 @@ async function relationalQuery(websiteId, { startDate, endDate, field, filters =
join website join website
on pageview.website_id = website.website_id on pageview.website_id = website.website_id
${joinSession} ${joinSession}
where website.website_uuid='${websiteId}' where website.website_uuid = $1${toUuid()}
and pageview.created_at between $1 and $2 and pageview.created_at between $2 and $3
${pageviewQuery} ${pageviewQuery}
${sessionQuery} ${sessionQuery}
) )

View File

@ -11,16 +11,17 @@ export async function getActiveVisitors(...args) {
} }
async function relationalQuery(websiteId) { async function relationalQuery(websiteId) {
const { rawQuery, toUuid } = prisma;
const date = subMinutes(new Date(), 5); const date = subMinutes(new Date(), 5);
const params = [date]; const params = [websiteId, date];
return prisma.rawQuery( return rawQuery(
`select count(distinct session_id) x `select count(distinct session_id) x
from pageview from pageview
join website join website
on pageview.website_id = website.website_id on pageview.website_id = website.website_id
where website.website_uuid = '${websiteId}' where website.website_uuid = $1${toUuid()}
and pageview.created_at >= $1`, and pageview.created_at >= $2`,
params, params,
); );
} }

View File

@ -10,8 +10,8 @@ export async function getWebsiteStats(...args) {
} }
async function relationalQuery(websiteId, { start_at, end_at, filters = {} }) { async function relationalQuery(websiteId, { start_at, end_at, filters = {} }) {
const { getDateQuery, getTimestampInterval, parseFilters, rawQuery } = prisma; const { getDateQuery, getTimestampInterval, parseFilters, rawQuery, toUuid } = prisma;
const params = [start_at, end_at]; const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, joinSession } = parseFilters(
'pageview', 'pageview',
null, null,
@ -33,8 +33,8 @@ async function relationalQuery(websiteId, { start_at, end_at, filters = {} }) {
join website join website
on pageview.website_id = website.website_id on pageview.website_id = website.website_id
${joinSession} ${joinSession}
where website.website_uuid='${websiteId}' where website.website_uuid = $1${toUuid()}
and pageview.created_at between $1 and $2 and pageview.created_at between $2 and $3
${pageviewQuery} ${pageviewQuery}
${sessionQuery} ${sessionQuery}
group by 1, 2 group by 1, 2