Skip to content

Commit

Permalink
Merge pull request #1216 from navikt/put-utfyltsoknad-metrics
Browse files Browse the repository at this point in the history
Prom metrics express.json and verify idporten token
  • Loading branch information
akgagnat authored Jun 17, 2024
2 parents fd495a4 + b3b1abb commit d160aa4
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/fyllut-backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { checkConfigConsistency, config } from './config/config';
import { NaisCluster } from './config/nais-cluster';
import { buildDirectory } from './context.js';
import { setupDeprecatedEndpoints } from './deprecatedEndpoints.js';
import expressJsonMetricHandler from './middleware/expressJsonMetricHandler';
import globalErrorHandler from './middleware/globalErrorHandler.js';
import httpRequestLogger from './middleware/httpRequestLogger.js';
import { stripTrailingSlash } from './middleware/stripTrailingSlash';
Expand All @@ -20,7 +21,7 @@ export const createApp = (setupDev: boolean = false) => {
const app = express();
app.use(httpRequestLogger);

app.use(express.json({ limit: '50mb' }));
app.use(expressJsonMetricHandler(express.json({ limit: '50mb' })));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(correlator());
app.use(cors());
Expand Down
21 changes: 21 additions & 0 deletions packages/fyllut-backend/src/middleware/expressJsonMetricHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextFunction, Request, Response } from 'express';
import { appMetrics } from '../services';

const expressJsonMetricHandler = (fn: Function) => async (req: Request, res: Response, next: NextFunction) => {
if (req.method === 'PUT' && req.url.includes('/send-inn/utfyltsoknad')) {
const stopTimer = appMetrics.expressJsonBodyParserDuration.startTimer({ endpoint: 'put-utfyltsoknad' });
let errorOccured = false;
try {
await fn(req, res, next);
} catch (err) {
errorOccured = true;
throw err;
} finally {
stopTimer({ error: String(errorOccured) });
}
} else {
await fn(req, res, next);
}
};

export default expressJsonMetricHandler;
4 changes: 4 additions & 0 deletions packages/fyllut-backend/src/security/idportenAuthHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FlattenedJWSInput, JWSHeaderParameters, createRemoteJWKSet, jwtVerify }
import { GetKeyFunction } from 'jose/dist/types/types';
import { config } from '../config/config';
import { logger } from '../logger.js';
import { appMetrics } from '../services';
import { IdportenTokenPayload } from '../types/custom';

const { isDevelopment, mockIdportenJwt, mockIdportenPid } = config;
Expand Down Expand Up @@ -31,11 +32,14 @@ const idportenAuthHandler = async (req: Request, res: Response, next: NextFuncti

logger.debug('Verifying jwt...');
let tokenContent: IdportenTokenPayload;
const stopTimer = appMetrics.idportenVerifyTokenDuration.startTimer();
try {
tokenContent = await verifyToken(token);
} catch (err) {
logger.warn('Failed to verify jwt signature', err);
return res.sendStatus(401);
} finally {
stopTimer();
}
const currentTime = new Date().getTime() / 1000;
const expired = tokenContent.exp! - 10 < currentTime;
Expand Down
28 changes: 28 additions & 0 deletions packages/fyllut-backend/src/services/AppMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ class AppMetrics {
private readonly _exstreamPdfRequestsCounter: Counter;
private readonly _exstreamPdfFailuresCounter: Counter;
private readonly _outgoingRequestDuration: Histogram;
private readonly _expressJsonBodyParserDuration: Histogram;
private readonly _idportenVerifyTokenDuration: Histogram;

constructor() {
logger.info('Initializing metrics client');
Expand Down Expand Up @@ -36,6 +38,24 @@ class AppMetrics {
this._outgoingRequestDuration.zero({ service: 'exstream', method: 'createPdf', error: 'false' });
this._outgoingRequestDuration.zero({ service: 'exstream', method: 'createPdf', error: 'true' });

this._expressJsonBodyParserDuration = new Histogram({
name: 'fyllut_express_json_body_parser_seconds',
help: 'Express json body parser duration',
labelNames: ['endpoint', 'error'],
buckets: [0.025, 0.05, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4, 12.8],
registers: [this._register],
});
this._expressJsonBodyParserDuration.zero({ endpoint: 'put-utfyltsoknad', error: 'false' });
this._expressJsonBodyParserDuration.zero({ endpoint: 'put-utfyltsoknad', error: 'true' });

this._idportenVerifyTokenDuration = new Histogram({
name: 'fyllut_idporten_verify_token_seconds',
help: 'Idporten auth duration',
labelNames: [],
buckets: [0.025, 0.05, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4, 12.8],
registers: [this._register],
});

collectDefaultMetrics({ register: this._register });
}

Expand All @@ -54,6 +74,14 @@ class AppMetrics {
public get outgoingRequestDuration() {
return this._outgoingRequestDuration;
}

public get idportenVerifyTokenDuration() {
return this._idportenVerifyTokenDuration;
}

public get expressJsonBodyParserDuration() {
return this._expressJsonBodyParserDuration;
}
}

export default AppMetrics;

0 comments on commit d160aa4

Please sign in to comment.