fix: Improve sanitization on file keys

This commit is contained in:
Tom Moor
2024-08-01 20:24:46 +01:00
parent a120427943
commit 08a6376947
2 changed files with 22 additions and 0 deletions

View File

@@ -48,4 +48,12 @@ describe("#ValidateKey.sanitize", () => {
ValidateKey.sanitize(`public/${uuid1}/${uuid2}/~\.\u0000\malicious_key`)
).toEqual(`public/${uuid1}/${uuid2}/~.malicious_key`);
});
it("should remove potential path traversal", () => {
const uuid1 = uuidv4();
const uuid2 = uuidv4();
expect(
ValidateKey.sanitize(`public/${uuid1}/${uuid2}/../../malicious_key`)
).toEqual(`public/${uuid1}/${uuid2}/malicious_key`);
});
});

View File

@@ -174,6 +174,13 @@ export const assertCollectionPermission = (
};
export class ValidateKey {
/**
* Checks if key is valid. A valid key is of the form
* <bucket>/<uuid>/<uuid>/<name>
*
* @param key
* @returns true if key is valid, false otherwise
*/
public static isValid = (key: string) => {
let parts = key.split("/");
const bucket = parts[0];
@@ -189,11 +196,18 @@ export class ValidateKey {
);
};
/**
* Sanitizes a key by removing any invalid characters
*
* @param key
* @returns sanitized key
*/
public static sanitize = (key: string) => {
const [filename] = key.split("/").slice(-1);
return key
.split("/")
.slice(0, -1)
.filter((part) => part !== "" && part !== ".." && part !== ".")
.join("/")
.concat(`/${sanitize(filename)}`);
};