Skip to content

Add key validation for FileStore #830

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 2, 2025
Merged
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
26 changes: 26 additions & 0 deletions packages/ui-keyring/src/stores/File.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,28 @@ export class FileStore implements KeyringStore {
this.#path = path;
}

private validateKey (key: string): boolean {
// Make sure the key has a .json extension
if (!key.endsWith('.json')) {
console.error('Non-JSON file requested: ', key);

return false;
}

// Remove '.json'
const keyWithoutExtension = key.slice(0, -5);
// Only allow alphanumeric characters, hyphens, and underscores in the base filename
const safeKeyRegex = /^[a-zA-Z0-9_-]+$/;

if (!safeKeyRegex.test(keyWithoutExtension)) {
console.error('Invalid key format detected: ', key);

return false;
}

return true;
}

public all (fn: (key: string, value: KeyringJson) => void): void {
fs
.readdirSync(this.#path)
Expand Down Expand Up @@ -51,6 +73,10 @@ export class FileStore implements KeyringStore {
}

private _getPath (key: string): string {
if (!this.validateKey(key)) {
throw new Error('Invalid key format');
}

return path.join(this.#path, key);
}

Expand Down