fix(security): close cross-event thumbnail leak, bulk-op ownership bypass, + hardening

Auth/access-control audit fixes (all pre-existing on main; none are
regressions). Verified end-to-end where noted.

HIGH
- Thumbnail enumeration: photoAuth granted any gallery token access to any
  flat /thumbnails/thumb_* file, so a visitor to one gallery could
  enumerate another (password-protected) gallery's entire thumbnail set.
  Scope thumbnail access to the token's event via photos.thumbnail_path.
  Live-verified: cross-event fetch now 404s, own-event still 200s.
- Bulk ownership bypass: bulk-archive/bulk-delete acted on body-supplied
  event ids with no owner filter (single-event routes enforce
  requireEventOwnership), letting admin/editor archive or cascade-delete
  any event. Add filterOwnedEventIds; also guard rename + import-external;
  tighten photo-retry to scope admin (not just editor). Fix misleading
  bulk-delete comment.

MED
- verifyGalleryAccess never checked decoded.type — assert 'gallery'
  instead of relying on other token types incidentally lacking eventId.
- secure-images generate-token/secure-download missing denySlideshowToken
  (#646 bypass): a leaked slideshow token could download originals.
- Frontend: AuthenticatedImage + api.ts attached the gallery bearer token
  to absolute/external URLs — only attach to relative same-app paths.

LOW hardening
- Pin algorithms:['HS256'] on all auth-boundary jwt.verify calls.
- crypto.timingSafeEqual for share-token + HMAC compares (utils/timingSafe).
- Remove dead photoAuth import in galleryFeedback.

Tests: new regression suites for thumbnail scoping + filterOwnedEventIds;
fixed verifyGalleryAccess.customerRevoke fixture (real customer tokens
carry type:'gallery'). Full backend suite at the pre-existing baseline
(5 suites/27 tests fail on main too), zero new failures.
This commit is contained in:
Paul Nothaft
2026-07-03 10:27:28 +02:00
parent e513e8345b
commit 081f3edcdf
22 changed files with 372 additions and 60 deletions
+3 -1
View File
@@ -18,6 +18,7 @@ async function adminAuth(req, res, next) {
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'picpeak-auth',
complete: true
});
@@ -140,6 +141,7 @@ async function galleryAuth(req, res, next) {
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'picpeak-auth',
complete: true
});
@@ -209,7 +211,7 @@ async function photoAuth(req, res, next) {
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET);
decoded = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
} catch (err) {
return res.status(401).json({ error: 'Invalid token' });
}
+1
View File
@@ -34,6 +34,7 @@ async function customerAuth(req, res, next) {
let decoded;
try {
const verified = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'picpeak-auth',
complete: true,
});
+13 -2
View File
@@ -66,18 +66,29 @@ async function verifyGalleryAccess(req, res, next) {
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'picpeak-auth'
});
} catch (error) {
// If verification fails with issuer, try without issuer (backward compatibility)
if (error.name === 'JsonWebTokenError' && error.message.includes('jwt issuer invalid')) {
decoded = jwt.verify(token, process.env.JWT_SECRET);
decoded = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
} else {
throw error;
}
}
logger.debug('[verifyGalleryAccess] Token decoded successfully', { eventId: decoded.eventId, slug: requestedSlug });
// Only gallery-scoped tokens grant gallery access. Every legitimate
// path (password login, share link, client access, customer-minted,
// slideshow) mints type:'gallery'. Reject anything else — e.g. a guest
// identity token (type:'guest', for feedback attribution) that carries a
// matching eventId — instead of relying on other token types incidentally
// lacking an eventId to fail the id match below.
if (decoded.type !== 'gallery') {
return res.status(403).json({ error: 'Invalid token type for gallery access' });
}
// If we have a slug in the URL params or from pre-middleware, verify it matches
if (requestedSlug) {
// Verify by slug and ensure it matches the token's event
+1
View File
@@ -23,6 +23,7 @@ async function resolveGuest(req, res, next) {
let decoded;
try {
const verified = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'picpeak-auth',
complete: true,
});
+33 -1
View File
@@ -32,4 +32,36 @@ function requireEventOwnership(req, res, next) {
});
}
module.exports = { requireEventOwnership };
/**
* Return the subset of `eventIds` the admin may act on, mirroring
* requireEventOwnership for bulk routes that can't use it (they take an
* array in the body, not an :id param). super_admin gets everything;
* other roles get events they created plus ownerless legacy/system
* events (created_by IS NULL). Ids that are foreign OR non-existent both
* land in `denied` — deliberately indistinguishable, so bulk routes
* don't become an ownership/existence oracle.
*
* @returns {Promise<{allowed: Array, denied: Array}>}
*/
async function filterOwnedEventIds(admin, eventIds) {
if (admin.roleName === 'super_admin') {
return { allowed: [...eventIds], denied: [] };
}
const rows = await db('events')
.whereIn('id', eventIds)
.andWhere((q) => q.whereNull('created_by').orWhere('created_by', admin.id))
.select('id');
const allowedSet = new Set(rows.map((r) => r.id));
const allowed = [];
const denied = [];
for (const id of eventIds) {
if (allowedSet.has(id) || allowedSet.has(Number(id))) {
allowed.push(id);
} else {
denied.push(id);
}
}
return { allowed, denied };
}
module.exports = { requireEventOwnership, filterOwnedEventIds };
+25 -12
View File
@@ -28,12 +28,13 @@ async function photoAuth(req, res, next) {
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'picpeak-auth'
});
} catch (issuerError) {
// If verification fails with issuer, try without issuer (backward compatibility)
if (issuerError.name === 'JsonWebTokenError' && issuerError.message.includes('jwt issuer invalid')) {
decoded = jwt.verify(token, process.env.JWT_SECRET);
decoded = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
} else {
throw issuerError;
}
@@ -43,24 +44,36 @@ async function photoAuth(req, res, next) {
if (decoded.type === 'gallery') {
// For thumbnails, we need to verify the token is for a valid event
if (!eventSlug) {
// Extract event ID from the decoded token
// Resolve the token's event (by id, or legacy slug fallback)...
let event = null;
if (decoded.eventId) {
const event = await db('events')
event = await db('events')
.where({ id: decoded.eventId, is_active: formatBoolean(true) })
.first();
if (event) {
}
if (!event && decoded.eventSlug) {
event = await db('events')
.where({ slug: decoded.eventSlug, is_active: formatBoolean(true) })
.first();
}
// ...then confirm the REQUESTED thumbnail actually belongs to
// that event. Thumbnails are stored flat (thumbnails/thumb_<name>)
// with deterministic, enumerable filenames derived from the
// public event name + a sequential counter. Without this
// ownership check any holder of a gallery token for any event
// could enumerate and fetch another (password-protected) event's
// entire thumbnail set, defeating the gallery password. A
// traversal or foreign filename simply fails to match → denied.
if (event) {
const requestedKey = `thumbnails${req.path}`;
const ownsThumbnail = await db('photos')
.where({ event_id: event.id, thumbnail_path: requestedKey })
.first();
if (ownsThumbnail) {
req.event = event;
return next();
}
}
// Fallback to slug
const event = await db('events')
.where({ slug: decoded.eventSlug, is_active: formatBoolean(true) })
.first();
if (event) {
req.event = event;
return next();
}
}
// For regular photos, check if token matches the event
else if (decoded.eventSlug === eventSlug) {
+2 -2
View File
@@ -86,7 +86,7 @@ async function sessionTimeoutMiddleware(req, res, next) {
try {
// Verify token is valid
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const decoded = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
// Check if this is an admin token
if (!decoded.id) {
@@ -127,7 +127,7 @@ async function sessionTimeoutMiddleware(req, res, next) {
for (const [oldToken, _] of sessions.entries()) {
if (oldToken !== token) {
try {
const oldDecoded = jwt.verify(oldToken, process.env.JWT_SECRET);
const oldDecoded = jwt.verify(oldToken, process.env.JWT_SECRET, { algorithms: ['HS256'] });
if (oldDecoded.id === userId) {
sessions.delete(oldToken);
}