All files / src/application/baby ensure-baby-access.ts

100% Statements 7/7
100% Branches 4/4
100% Functions 1/1
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31                                272x   272x 6x     266x   266x 41x     225x    
import { Baby } from '../../domain/baby/baby';
import { BabyRepository } from './baby-repository';
import { BabyGuardianRepository } from './baby-guardian-repository';
import { BabyNotFoundError } from './errors/baby-not-found.error';
 
// Single source of truth for "can this user touch this baby's data" — replaces the old
// `baby.userId !== requestingUserId` check now that more than one guardian can manage a baby.
// Deliberately throws the same `BabyNotFoundError` (404) whether the baby doesn't exist or the
// requester just isn't one of its guardians, so intruders can't distinguish the two cases
// (OWASP BOLA mitigation, same behavior the single-owner check had before).
export async function ensureBabyAccess(
  babyRepository: BabyRepository,
  babyGuardianRepository: BabyGuardianRepository,
  babyId: string,
  requestingUserId: string,
): Promise<Baby> {
  const baby = await babyRepository.findById(babyId);
 
  if (!baby) {
    throw new BabyNotFoundError();
  }
 
  const guardian = await babyGuardianRepository.findByBabyAndUser(babyId, requestingUserId);
 
  if (!guardian) {
    throw new BabyNotFoundError();
  }
 
  return baby;
}