Skip to content

Commit

Permalink
refactor: call transformError when error is thrown outside of actions
Browse files Browse the repository at this point in the history
- Previously transformError was not called when an error occured in kernel.authenticate() for instance
- Enable better sanitization of errors
  • Loading branch information
lionelhorn committed Sep 9, 2024
1 parent be915e8 commit 17f309e
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
4 changes: 4 additions & 0 deletions packages/rpc/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -737,5 +737,9 @@ export function rpcDecodeError(error: EncodedError): Error {
const e = new Error(error.message);
e.stack = error.stack + '\nat ___SERVER___';

if(error.stack === "") {
e.stack = ""
}

return e;
}
2 changes: 1 addition & 1 deletion packages/rpc/src/server/kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ export class RpcKernelConnection extends RpcKernelBaseConnection {
return await this.actionHandler.handle(message, response);
}
} catch (error: any) {
response.error(error);
response.error(this.security.transformError(error));
}
}

Expand Down
30 changes: 30 additions & 0 deletions packages/rpc/tests/security.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,36 @@ test('authentication errors', async () => {
expect(memoryLogger.messages.length).toBe(1);
});

test('authentication errors and calls transformError', async () => {
let transformedError: Error | null = null;

class MyKernelSecurity extends RpcKernelSecurity {
async authenticate(token: any): Promise<Session> {
throw new Error('Malformed token');
}

override transformError(err: Error) {
transformedError = new Error("Transformed");
transformedError.stack = "";
return transformedError;
}
}

const kernel = new RpcKernel([{ provide: RpcKernelSecurity, useClass: MyKernelSecurity, scope: 'rpc' }]);
const client = new DirectClient(kernel);

client.token.set('generic');

try {
await client.connect()
} catch(e: any) {
expect(e.stack).toBe('');
}

expect(transformedError).toBeInstanceOf(Error);
expect(transformedError!.message).toBe('Transformed');
});


test('onAuthenticate controllers', async () => {
class AuthenticatedSession extends Session {
Expand Down

0 comments on commit 17f309e

Please sign in to comment.