payload
Version:
Node, React, Headless CMS and Application Framework built on Next.js
109 lines (108 loc) • 3.78 kB
JavaScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../auth/executeAccess.js', ()=>({
executeAccess: vi.fn()
}));
import { executeAccess } from '../auth/executeAccess.js';
import { checkFileAccess } from './checkFileAccess.js';
const makeFindOne = (result = {
id: '1',
filename: 'logo.png'
})=>vi.fn().mockResolvedValue(result);
const makeCollection = ()=>({
config: {
slug: 'test-media',
access: {
read: vi.fn()
},
upload: {}
}
});
const makeReq = (findOne)=>({
t: vi.fn(),
payload: {
db: {
findOne
}
}
});
describe('checkFileAccess', ()=>{
beforeEach(()=>{
vi.mocked(executeAccess).mockResolvedValue({});
});
describe('prefix filtering', ()=>{
it('should add prefix clause to where query when prefix is provided', async ()=>{
const findOne = makeFindOne();
const req = makeReq(findOne);
const collection = makeCollection();
await checkFileAccess({
collection,
filename: 'logo.png',
prefix: 'abc123',
req
});
const whereArg = findOne.mock.calls[0]?.[0]?.where;
expect(whereArg?.and).toEqual(expect.arrayContaining([
{
prefix: {
equals: 'abc123'
}
}
]));
});
it('should not add prefix clause to where query when prefix is omitted', async ()=>{
const findOne = makeFindOne();
const req = makeReq(findOne);
const collection = makeCollection();
await checkFileAccess({
collection,
filename: 'logo.png',
req
});
const whereArg = findOne.mock.calls[0]?.[0]?.where;
const hasPrefixCondition = whereArg?.and?.some((clause)=>'prefix' in clause);
expect(hasPrefixCondition).toBeFalsy();
});
it('should still include filename in where query when prefix is provided', async ()=>{
const findOne = makeFindOne();
const req = makeReq(findOne);
const collection = makeCollection();
await checkFileAccess({
collection,
filename: 'logo.png',
prefix: 'abc123',
req
});
const whereArg = findOne.mock.calls[0]?.[0]?.where;
const filenameCondition = whereArg?.and?.[0];
expect(filenameCondition?.or).toEqual(expect.arrayContaining([
{
filename: {
equals: 'logo.png'
}
}
]));
});
it('should throw when no doc matches the given prefix', async ()=>{
const findOne = makeFindOne(null);
const req = makeReq(findOne);
const collection = makeCollection();
await expect(checkFileAccess({
collection,
filename: 'logo.png',
prefix: 'nonexistent',
req
})).rejects.toThrow();
});
it('should throw when filename contains path traversal sequence', async ()=>{
const findOne = makeFindOne();
const req = makeReq(findOne);
const collection = makeCollection();
await expect(checkFileAccess({
collection,
filename: '../etc/passwd',
req
})).rejects.toThrow();
});
});
});
//# sourceMappingURL=checkFileAccess.spec.js.map