Skip to content
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

chore: improve log verbosity #372

Merged
merged 4 commits into from
Apr 26, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions .changeset/long-trainers-pretend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'hasura-auth': patch
---

chore(logs): add masked headers and query parameters to logs
14 changes: 6 additions & 8 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import express from 'express';
import helmet from 'helmet';
import { json } from 'body-parser';
import cors from 'cors';

import router from './routes';
import express from 'express';
import helmet from 'helmet';
import { serverErrors } from './errors';
import { httpLogger, uncaughtErrorLogger } from './logger';
import { authMiddleware } from './middleware/auth';
import { addOpenApiRoute } from './openapi';
import { uncaughtErrorLogger, httpLogger } from './logger';
import router from './routes';

const app = express();

Expand All @@ -16,12 +15,11 @@ if (process.env.NODE_ENV === 'production') {
}

addOpenApiRoute(app);
app.use(httpLogger);

app.use(httpLogger);
app.use(helmet(), json(), cors());
app.use(authMiddleware);

app.use(router);

app.use(uncaughtErrorLogger, serverErrors);

export { app };
47 changes: 37 additions & 10 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import winston from 'winston';
import expressWinston, { LoggerOptions } from 'express-winston';
import { Response } from 'express';
import expressWinston, { LoggerOptions } from 'express-winston';
import winston from 'winston';
export const LOG_LEVEL = process.env.AUTH_LOG_LEVEL || 'info';

// * Create a common Winston logger that can be used in both middlewares and manually
Expand All @@ -12,13 +12,39 @@ export const logger = winston.createLogger({
// * Give more importance to Unauthorized and Forbidden status codes to give more visibility to hacking attempts
const SUSPICIOUS_REQUEST_CODES = [401, 403];

const rewriteUrl = (url: string) => {
if (LOG_LEVEL !== 'debug' && (url.includes('?') || url.includes('#'))) {
const pathname = new URL(url, 'http://noop').pathname;
const char = url.includes('?') ? '?' : '#';
return `${pathname}${char}*****`;
const maskUrl = (url: string) => {
if (LOG_LEVEL === 'debug' || (!url.includes('?') && !url.includes('#'))) {
return url;
}

const { pathname, searchParams, hash } = new URL(url, 'http://noop');
const queryParameters = Array.from(searchParams.keys());

if (queryParameters.length > 0) {
return `${pathname}?${queryParameters
.map((param) => `${param}=*****`)
.join('&')})}`;
}
return url;

if (hash) {
return `${pathname}#*****`;
}

return pathname;
};

const maskHeaders = (headers: Record<string, unknown>) => {
if (LOG_LEVEL === 'DEBUG') {
return headers;
}

return Object.keys(headers).reduce(
(returnableHeaders, key) => ({
...returnableHeaders,
[key]: '*****',
}),
{}
);
};

const loggerOptions: LoggerOptions = {
Expand All @@ -27,7 +53,7 @@ const loggerOptions: LoggerOptions = {
metaField: null,
responseField: null,
msg: (req, res) =>
`${req.method} ${rewriteUrl(req.url)} ${res.statusCode} ${
`${req.method} ${maskUrl(req.url)} ${res.statusCode} ${
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(res as any).responseTime
}ms`,
Expand All @@ -45,7 +71,8 @@ const loggerOptions: LoggerOptions = {
meta.url = url;
meta.headers = headers;
} else {
meta.url = rewriteUrl(url);
meta.url = maskUrl(url);
meta.headers = maskHeaders(headers);
}
const userId = auth?.userId;
if (userId) {
Expand Down
7 changes: 7 additions & 0 deletions src/utils/__generated__/graphql-request.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.