From 9f2eeb19dd3fc65cdd65850710936f716bed243f Mon Sep 17 00:00:00 2001 From: Dario Piotrowicz Date: Thu, 23 Feb 2023 15:31:20 +0000 Subject: [PATCH] improve typing and security of getObjectBy function --- backend/src/activitypub/activities/handle.ts | 2 +- backend/src/activitypub/objects/index.ts | 29 ++++++++++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/backend/src/activitypub/activities/handle.ts b/backend/src/activitypub/activities/handle.ts index 3fa0dee..c2841fd 100644 --- a/backend/src/activitypub/activities/handle.ts +++ b/backend/src/activitypub/activities/handle.ts @@ -116,7 +116,7 @@ export async function handle( } // check current object - const object = await objects.getObjectBy(db, 'original_object_id', objectId.toString()) + const object = await objects.getObjectBy(db, objects.ObjectByKey.originalObjectId, objectId.toString()) if (object === null) { throw new Error(`object ${objectId} does not exist`) } diff --git a/backend/src/activitypub/objects/index.ts b/backend/src/activitypub/objects/index.ts index a8ac91c..9a1be6c 100644 --- a/backend/src/activitypub/objects/index.ts +++ b/backend/src/activitypub/objects/index.ts @@ -95,7 +95,7 @@ export async function cacheObject( ): Promise { const sanitizedProperties = await sanitizeObjectProperties(properties) - const cachedObject = await getObjectBy(db, 'original_object_id', originalObjectId.toString()) + const cachedObject = await getObjectBy(db, ObjectByKey.originalObjectId, originalObjectId.toString()) if (cachedObject !== null) { return { created: false, @@ -168,23 +168,34 @@ export async function updateObjectProperty(db: Database, obj: APObject, key: str } export async function getObjectById(db: Database, id: string | URL): Promise { - return getObjectBy(db, 'id', id.toString()) + return getObjectBy(db, ObjectByKey.id, id.toString()) } export async function getObjectByOriginalId(db: Database, id: string | URL): Promise { - return getObjectBy(db, 'original_object_id', id.toString()) + return getObjectBy(db, ObjectByKey.originalObjectId, id.toString()) } export async function getObjectByMastodonId(db: Database, id: UUID): Promise { - return getObjectBy(db, 'mastodon_id', id) + return getObjectBy(db, ObjectByKey.mastodonId, id) } -export async function getObjectBy(db: Database, key: string, value: string) { +export enum ObjectByKey { + id = 'id', + originalObjectId = 'original_object_id', + mastodonId = 'mastodon_id', +} + +const allowedObjectByKeysSet = new Set(Object.values(ObjectByKey)) + +export async function getObjectBy(db: Database, key: ObjectByKey, value: string) { + if (!allowedObjectByKeysSet.has(key)) { + throw new Error('getObjectBy run with invalid key: ' + key) + } const query = ` -SELECT * -FROM objects -WHERE objects.${key}=? - ` + SELECT * + FROM objects + WHERE objects.${key}=? + ` const { results, success, error } = await db.prepare(query).bind(value).all() if (!success) { throw new Error('SQL error: ' + error)