Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion api/server/routes/agents/__tests__/openapi.contract.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ describe('Agents OpenAPI actual HTTP contract', () => {
await mongoose.connect(mongoServer.getUri());
createModels(mongoose);
db = require('~/models');
await db.seedDefaultRoles();

user = await mongoose.models.User.create({
email: 'openapi-contract@example.test',
Expand Down Expand Up @@ -240,8 +241,9 @@ describe('Agents OpenAPI actual HTTP contract', () => {
});

const { getSkillManagementFileSaver } = require('~/server/services/Endpoints/agents/skillDeps');
const { getSkillsHandlers } = require('~/server/services/Skills/handlers');
const skillHandlers = createSkillManagementHandlers({
handlers: {},
handlers: getSkillsHandlers(),
getSkillById: db.getSkillById,
getRoleByName,
checkPermission: async () => true,
Expand All @@ -263,7 +265,9 @@ describe('Agents OpenAPI actual HTTP contract', () => {
restoreTenantContextFromReq,
fileHandlers.upload,
);
app.post('/api/agents/v1/skills', skillHandlers.create);
app.put('/api/agents/v1/skills/:id/files/*relativePath', skillHandlers.updateFile);
app.delete('/api/agents/v1/skills/:id/files/*relativePath', skillHandlers.deleteFile);
app.get('/api/agents/v1/agents/:id', (_req, _res, next) =>
next(new Error('contract fixture escaped error')),
);
Expand Down Expand Up @@ -353,6 +357,40 @@ describe('Agents OpenAPI actual HTTP contract', () => {
expect(fs.readFileSync(diskPath, 'utf8')).toBe(content);
});

it('documents and validates Skill creation and file deletion', async () => {
const created = await request(app)
.post('/api/agents/v1/skills')
.set('Authorization', `Bearer ${token}`)
.send({
name: 'managed-contract-skill',
description: 'Created through the versioned management contract.',
body: '# Managed contract Skill',
});
expect(created.status).toBe(201);
expectResponseToMatchSpec(spec, 'createSkill', created);
expect(await mongoose.models.Skill.findById(created.body.id).lean()).toMatchObject({
tenantId,
});

const file = await request(app)
.put(`/api/agents/v1/skills/${created.body.id}/files/references/delete-me.md`)
.set('Authorization', `Bearer ${token}`)
.send({ content: 'temporary' });
expect(file.status).toBe(200);

const deletedFile = await request(app)
.delete(`/api/agents/v1/skills/${created.body.id}/files/references/delete-me.md`)
.set('Authorization', `Bearer ${token}`);
expect(deletedFile.status).toBe(200);
expectResponseToMatchSpec(spec, 'deleteSkillFile', deletedFile);
expect(
await mongoose.models.SkillFile.findOne({
skillId: created.body.id,
relativePath: 'references/delete-me.md',
}).lean(),
).toBeNull();
});

it('validates parser and normalized management errors against their documented JSON forms', async () => {
const malformed = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/contract.md`)
Expand Down
2 changes: 2 additions & 0 deletions api/server/routes/agents/__tests__/skills.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ jest.mock('@librechat/api', () => ({
mockDeps = deps;
return {
list: mockList,
create: mockWrite,
get: mockList,
update: mockWrite,
listFiles: mockList,
getFile: mockList,
updateFile: mockWrite,
deleteFile: mockWrite,
};
},
mapAgentManagementError: () => ({ status: 404, body: { error: { code: 'not_found' } } }),
Expand Down
2 changes: 2 additions & 0 deletions api/server/routes/agents/skills.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ const handlers = createSkillManagementHandlers({
});
router.use(requireAgentManagementAuth, requireTermsAcceptance, checkBan, configMiddleware);
router.get('/', handlers.list);
router.post('/', handlers.create);
router.get('/:id', handlers.get);
router.patch('/:id', handlers.update);
router.get('/:id/files', handlers.listFiles);
router.get('/:id/files/*relativePath', handlers.getFile);
router.put('/:id/files/*relativePath', handlers.updateFile);
router.delete('/:id/files/*relativePath', handlers.deleteFile);
router.use((_req, res) => {
const { status, body } = mapAgentManagementError('not_found');
body.error.message = 'Skill or file not found';
Expand Down
3 changes: 2 additions & 1 deletion api/server/routes/skills.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ jest.mock('~/server/middleware/config/app', () => (req, _res, next) => {
jest.mock('~/server/services/Files/strategies', () => ({
getStrategyFunctions: jest.fn().mockReturnValue({
saveBuffer: jest.fn().mockResolvedValue('/uploads/test/file.txt'),
deleteFile: jest.fn().mockResolvedValue(undefined),
getDownloadStream: jest.fn().mockResolvedValue({
pipe: jest.fn(),
on: jest.fn(),
Expand Down Expand Up @@ -871,7 +872,7 @@ describe('Skill routes', () => {
expect((await upload('stale', initial.body.file_id)).status).toBe(409);
const stored = await SkillFile.findOne({ skillId: created.body._id });
expect(stored.file_id).toBe(replaced.body.file_id);
await request(app).delete(`${url}/references/revision.md`);
await request(app).delete(`${url}/references/revision.md`).expect(200);
expect((await upload('resurrect', replaced.body.file_id)).status).toBe(409);
expect(await SkillFile.countDocuments({ skillId: created.body._id })).toBe(0);
});
Expand Down
34 changes: 14 additions & 20 deletions api/server/services/Files/Azure/crud.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const fetch = require('node-fetch');
const { logger } = require('@librechat/data-schemas');
const {
deleteRagFile,
createOwnedBlobFileDeleter,
extractAzureBlobPath,
assertRemoteFileURL,
getSafeErrorMetadata,
getAzureContainerClient,
Expand Down Expand Up @@ -120,26 +122,18 @@ async function getAzureURL({ fileName, basePath = defaultBasePath, userId, conta
* @param {ServerRequest} params.req - The Express request object.
* @param {MongoFile} params.file - The file object.
*/
async function deleteFileFromAzure(req, file) {
await deleteRagFile({ userId: req.user.id, file });

try {
const containerClient = await getAzureContainerClient(AZURE_CONTAINER_NAME);
const blobPath = file.filepath.split(`${AZURE_CONTAINER_NAME}/`)[1];
if (!blobPath.includes(req.user.id)) {
throw new Error('User ID not found in blob path');
}
const blockBlobClient = containerClient.getBlockBlobClient(blobPath);
await blockBlobClient.delete();
logger.debug('[deleteFileFromAzure] Blob deleted successfully from Azure Blob Storage');
} catch (error) {
logger.error('[deleteFileFromAzure] Error deleting blob:', error);
if (error.statusCode === 404) {
return;
}
throw error;
}
}
const deleteFileFromAzure = (req, file) =>
createOwnedBlobFileDeleter({
extractPath: (filepath) => extractAzureBlobPath(filepath, AZURE_CONTAINER_NAME),
deleteBlob: async (blobPath) => {
const containerClient = await getAzureContainerClient(AZURE_CONTAINER_NAME);
const blockBlobClient = containerClient.getBlockBlobClient(blobPath);
await blockBlobClient.delete();
logger.debug('[deleteFileFromAzure] Blob deleted successfully from Azure Blob Storage');
},
isMissing: (error) => error?.statusCode === 404,
deleteRagFile,
})(req, file);

/**
* Streams a file from disk directly to Azure Blob Storage without loading
Expand Down
46 changes: 9 additions & 37 deletions api/server/services/Files/Firebase/crud.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const fetch = require('node-fetch');
const { logger } = require('@librechat/data-schemas');
const {
deleteRagFile,
createOwnedBlobFileDeleter,
extractFirebaseBlobPath,
getFirebaseStorage,
assertRemoteFileURL,
getSafeErrorMetadata,
Expand Down Expand Up @@ -153,26 +155,6 @@ async function saveBufferToFirebase({ userId, buffer, fileName, basePath = 'imag
* @param {string} urlString - The Firebase Storage URL.
* @returns {string} The decoded file path.
*/
function extractFirebaseFilePath(urlString) {
try {
const url = new URL(urlString);
const pathRegex = /\/o\/(.+?)(\?|$)/;
const match = url.pathname.match(pathRegex);

if (match && match[1]) {
return decodeURIComponent(match[1]);
}

return '';
} catch {
logger.debug(
'[extractFirebaseFilePath] Failed to extract Firebase file path from URL, returning empty string',
);
// If URL parsing fails, return an empty string
return '';
}
}

/**
* Deletes a file from Firebase storage. This function determines the filepath from the
* Firebase storage URL via regex for deletion. Validated by the user's ID.
Expand All @@ -185,23 +167,13 @@ function extractFirebaseFilePath(urlString) {
* A promise that resolves when the file has been successfully deleted from Firebase storage.
* Throws an error if there is an issue with deletion.
*/
const deleteFirebaseFile = async (req, file) => {
await deleteRagFile({ userId: req.user.id, file });

const fileName = extractFirebaseFilePath(file.filepath);
if (!fileName.includes(req.user.id)) {
throw new Error('Invalid file path');
}
try {
await deleteFile('', fileName);
} catch (error) {
logger.error('Error deleting file from Firebase:', error);
if (error.code === 'storage/object-not-found') {
return;
}
throw error;
}
};
const deleteFirebaseFile = (req, file) =>
createOwnedBlobFileDeleter({
extractPath: extractFirebaseBlobPath,
deleteBlob: (filepath) => deleteFile('', filepath),
isMissing: (error) => error?.code === 'storage/object-not-found',
deleteRagFile,
})(req, file);

/**
* Uploads a file to Firebase Storage.
Expand Down
70 changes: 0 additions & 70 deletions api/server/services/Files/Local/__tests__/crud-delete.spec.js

This file was deleted.

Loading
Loading