Skip to content
Open
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
95 changes: 94 additions & 1 deletion spec/CloudCodeLogger.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ describe('Cloud Code Logger', () => {
const infoMessage = spy.calls.all()[0];
expect(cloudFunctionMessage.args[0]).toBe('info');
expect(cloudFunctionMessage.args[1][1].params).toEqual({});
expect(cloudFunctionMessage.args[1][0]).toMatch(
// The message is passed as a function, so it is only built if the level is enabled
expect(cloudFunctionMessage.args[1][0]).toEqual(jasmine.any(Function));
expect(cloudFunctionMessage.args[1][0]()).toMatch(
/Ran cloud function loggerTest for user [^ ]* with:\n {2}Input: {}\n {2}Result: {}/
);
expect(cloudFunctionMessage.args[1][1].functionName).toEqual('loggerTest');
Expand Down Expand Up @@ -401,4 +403,95 @@ describe('Cloud Code Logger', () => {
// Not "beforeSave failed for TestClassError for user ..."
expect(spy).toHaveBeenCalledTimes(1);
});

describe('log message building', () => {
const Utils = require('../lib/Utils');
// The server installs a new logger on each reconfiguration, so get the current one
const currentLogger = () => require('../lib/logger').getLogger();

const setUp = async logLevel => {
Parse.Cloud._removeAllHooks();
await reconfigureServer({
silent: true,
logLevel,
logLevels: {
cloudFunctionSuccess: 'info',
triggerAfter: 'info',
triggerBeforeSuccess: 'info',
},
});
Parse.Cloud.define('largeResult', () => ({ items: new Array(100).fill('x') }));
Parse.Cloud.beforeSave('TestClass', () => {});
Parse.Cloud.afterSave('TestClass', () => {});
Parse.Cloud.afterFind('TestClass', req => req.objects);
};

it('does not build the Cloud Function success message when its level is disabled', async () => {
await setUp('error');
const truncateSpy = spyOn(currentLogger(), 'truncateLogMessage').and.callThrough();
await Parse.Cloud.run('largeResult', { foo: 'bar' });
expect(truncateSpy).not.toHaveBeenCalled();
});

it('does not build trigger success messages when their level is disabled', async () => {
await setUp('error');
const truncateSpy = spyOn(currentLogger(), 'truncateLogMessage').and.callThrough();
const safeToJSONSpy = spyOn(Utils, 'safeToJSON').and.callThrough();
const obj = new Parse.Object('TestClass');
await obj.save({ foo: 'bar' });
await new Parse.Query('TestClass').find();
expect(safeToJSONSpy).not.toHaveBeenCalled();
expect(truncateSpy).not.toHaveBeenCalled();
});

it('builds the messages when their level is enabled', async () => {
await setUp('info');
const adapterSpy = spyOn(Config.get('test').loggerController.adapter, 'log').and.callThrough();
await Parse.Cloud.run('largeResult', { foo: 'bar' });
const obj = new Parse.Object('TestClass');
await obj.save({ foo: 'bar' });
await new Parse.Query('TestClass').find();
const messages = adapterSpy.calls.all().map(call => call.args[1]);
expect(messages).toContain(
jasmine.stringMatching(
/^Ran cloud function largeResult for user [^ ]* with:\n {2}Input: {"foo":"bar"}\n {2}Result: {"items":\["x"/
)
);
expect(messages).toContain(
jasmine.stringMatching(/^beforeSave triggered for TestClass for user [^ ]*:\n {2}Input: {"foo":"bar"/)
);
expect(messages).toContain(
jasmine.stringMatching(/^afterSave triggered for TestClass for user [^ ]*:\n {2}Input: {"foo":"bar"/)
);
expect(messages).toContain(
jasmine.stringMatching(/^afterFind triggered for TestClass for user [^ ]*:\n {2}Input: /)
);
// The pre-transform message logs the found objects as its result
const preTransform = messages.find(
m => typeof m === 'string' && m.includes('AfterFind Input (Pre-Transform)')
);
expect(preTransform).toBeDefined();
expect(preTransform).toContain(obj.id);
expect(preTransform).not.toContain('Result: undefined');
});

it('still masks a password in messages that are built when logged', async () => {
await setUp('info');
const adapterSpy = spyOn(Config.get('test').loggerController.adapter, 'log').and.callThrough();
await Parse.Cloud.run('largeResult', { password: 'secret-value' });
// The trigger input is converted from the object, so only the message masking hides it
const obj = new Parse.Object('TestClass');
await obj.save({ password: 'secret-value' });
const messages = adapterSpy.calls
.all()
.map(call => call.args[1])
.filter(m => typeof m === 'string' && /^(Ran cloud function|beforeSave|afterSave)/.test(m));
// Cloud Function, beforeSave, and afterSave (logged when triggered and with its result)
expect(messages.length).toBe(4);
for (const message of messages) {
expect(message).not.toContain('secret-value');
expect(message).toContain('********');
}
});
});
});
27 changes: 27 additions & 0 deletions spec/LoggerController.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,31 @@ describe('LoggerController', () => {
expect(adapter.log).toHaveBeenCalled();
done();
});

it('masks the request body before building a request log message', () => {
const adapter = new WinstonLoggerAdapter();
const logger = new LoggerController(adapter, null, { verbose: true });
spyOn(adapter, 'log');
// A quote in the password ends the string pattern early, so only masking the
// body object before the message is built hides the whole value
logger.logRequest({
method: 'POST',
url: '/login',
headers: {},
body: { username: 'user', password: 'pass"word-value' },
});
const message = adapter.log.calls.mostRecent().args[1];
expect(message).toContain('REQUEST for [POST] /login');
expect(message).not.toContain('word-value');
});

it('masks a message that is passed as a function', () => {
const adapter = new WinstonLoggerAdapter();
const logger = new LoggerController(adapter, null, {});
spyOn(adapter, 'log');
logger.info(() => 'Input: {"password":"secret-value"}');
const message = adapter.log.calls.mostRecent().args[1];
expect(message).not.toContain('secret-value');
expect(message).toContain('********');
});
});
17 changes: 6 additions & 11 deletions src/Controllers/LoggerController.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,12 @@ export class LoggerController extends AdaptableController {
}

log(level, args) {
// make the passed in arguments object an array with the spread operator
args = this.maskSensitive([...args]);
args = [].concat(
level,
args.map(arg => {
if (typeof arg === 'function') {
return arg();
}
return arg;
})
);
// Mask the arguments first, so that a message passed as a function is built
// from masked objects, such as the request body of `logRequest`
const maskedArgs = this.maskSensitive([...args]);
// Then build the messages passed as a function and mask them as well
const builtArgs = maskedArgs.map(arg => (typeof arg === 'function' ? arg() : arg));
args = [].concat(level, this.maskSensitive(builtArgs));
this.adapter.log.apply(this.adapter, args);
}

Expand Down
11 changes: 8 additions & 3 deletions src/Routers/FunctionsRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,15 @@ export class FunctionsRouter extends PromiseRouter {
result => {
try {
if (req.config.logLevels.cloudFunctionSuccess !== 'silent') {
const cleanInput = logger.truncateLogMessage(JSON.stringify(redactBuffers(params)));
const cleanResult = logger.truncateLogMessage(JSON.stringify(result.response.result));
// Pass the message as a function, so it is only built if the level is enabled
logger[req.config.logLevels.cloudFunctionSuccess](
`Ran cloud function ${functionName} for user ${userString} with:\n Input: ${cleanInput}\n Result: ${cleanResult}`,
() => {
const cleanInput = logger.truncateLogMessage(JSON.stringify(redactBuffers(params)));
const cleanResult = logger.truncateLogMessage(
JSON.stringify(result.response.result)
);
return `Ran cloud function ${functionName} for user ${userString} with:\n Input: ${cleanInput}\n Result: ${cleanResult}`;
},
{
functionName,
params,
Expand Down
45 changes: 29 additions & 16 deletions src/triggers.js
Original file line number Diff line number Diff line change
Expand Up @@ -430,15 +430,24 @@ function userIdForLog(auth) {
return auth && auth.user ? auth.user.id : undefined;
}

// A logged input or result can be passed as a function, so that converting it
// for the log message only happens if the message is built
function resolveLogInput(input) {
return typeof input === 'function' ? input() : input;
}

function logTriggerAfterHook(triggerType, className, input, auth, logLevel) {
if (logLevel === 'silent') {
return;
}
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
// Pass the message as a function, so it is only built if the level is enabled
logger[logLevel](
`${triggerType} triggered for ${className} for user ${userIdForLog(
auth
)}:\n Input: ${cleanInput}`,
() => {
const cleanInput = logger.truncateLogMessage(JSON.stringify(resolveLogInput(input)));
return `${triggerType} triggered for ${className} for user ${userIdForLog(
auth
)}:\n Input: ${cleanInput}`;
},
{
className,
triggerType,
Expand All @@ -451,12 +460,15 @@ function logTriggerSuccessBeforeHook(triggerType, className, input, result, auth
if (logLevel === 'silent') {
return;
}
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
const cleanResult = logger.truncateLogMessage(JSON.stringify(result));
// Pass the message as a function, so it is only built if the level is enabled
logger[logLevel](
`${triggerType} triggered for ${className} for user ${userIdForLog(
auth
)}:\n Input: ${cleanInput}\n Result: ${cleanResult}`,
() => {
const cleanInput = logger.truncateLogMessage(JSON.stringify(resolveLogInput(input)));
const cleanResult = logger.truncateLogMessage(JSON.stringify(resolveLogInput(result)));
return `${triggerType} triggered for ${className} for user ${userIdForLog(
auth
)}:\n Input: ${cleanInput}\n Result: ${cleanResult}`;
},
{
className,
triggerType,
Expand Down Expand Up @@ -530,9 +542,10 @@ export function maybeRunAfterFindTrigger(
triggerType,
classNameQuery,
'AfterFind Input (Pre-Transform)',
JSON.stringify(
objectsInput.map(o => (o instanceof Parse.Object ? o.id + ':' + o.className : o))
),
() =>
JSON.stringify(
objectsInput.map(o => (o instanceof Parse.Object ? o.id + ':' + o.className : o))
),
auth,
config.logLevels.triggerBeforeSuccess
);
Expand Down Expand Up @@ -570,7 +583,7 @@ export function maybeRunAfterFindTrigger(
logTriggerAfterHook(
triggerType,
classNameQuery,
JSON.stringify(resultsAsJSON),
() => JSON.stringify(resultsAsJSON),
auth,
config.logLevels.triggerAfter
);
Expand Down Expand Up @@ -967,7 +980,7 @@ export function maybeRunTrigger(
logTriggerSuccessBeforeHook(
triggerType,
parseObject.className,
Utils.safeToJSON(parseObject),
() => Utils.safeToJSON(parseObject),
object,
auth,
triggerType.startsWith('after')
Expand Down Expand Up @@ -1019,7 +1032,7 @@ export function maybeRunTrigger(
logTriggerAfterHook(
triggerType,
parseObject.className,
Utils.safeToJSON(parseObject),
() => Utils.safeToJSON(parseObject),
auth,
config.logLevels.triggerAfter
);
Expand Down Expand Up @@ -1113,7 +1126,7 @@ export async function maybeRunFileTrigger(triggerType, fileObject, config, auth)
logTriggerSuccessBeforeHook(
triggerType,
'Parse.File',
{ ...fileObject.file.toJSON(), fileSize: fileObject.fileSize },
() => ({ ...fileObject.file.toJSON(), fileSize: fileObject.fileSize }),
result,
auth,
config.logLevels.triggerBeforeSuccess
Expand Down