Skip to content

Commit

Permalink
PI-1514 Enable Sentry in the browser (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcus-bcl committed Sep 29, 2023
1 parent 9530c40 commit e1e16b0
Show file tree
Hide file tree
Showing 13 changed files with 48 additions and 7 deletions.
2 changes: 1 addition & 1 deletion assets/scss/local.scss
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
min-height: 600px;
}

.examples-list li {
.examples-list > li {
margin-top: govuk-spacing(8);

code {
Expand Down
2 changes: 2 additions & 0 deletions helm_deploy/probation-search-ui/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ generic-service:
TOKEN_VERIFICATION_ENABLED: "true"
APPLICATIONINSIGHTS_CONNECTION_STRING: "InstrumentationKey=$(APPINSIGHTS_INSTRUMENTATIONKEY);IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/;LiveEndpoint=https://northeurope.livediagnostics.monitor.azure.com/"
SENTRY_TRACES_SAMPLE_RATE: "0.05"
SENTRY_REPLAY_SAMPLE_RATE: "0.05"

# Pre-existing kubernetes secrets to load as environment variables in the deployment.
# namespace_secrets:
Expand All @@ -54,6 +55,7 @@ generic-service:
SYSTEM_CLIENT_SECRET: "SYSTEM_CLIENT_SECRET"
SESSION_SECRET: "SESSION_SECRET"
SENTRY_DSN: "SENTRY_DSN"
SENTRY_LOADER_SCRIPT_ID: "SENTRY_LOADER_SCRIPT_ID"
elasticache-redis:
REDIS_HOST: "primary_endpoint_address"
REDIS_AUTH_TOKEN: "auth_token"
Expand Down
1 change: 1 addition & 0 deletions helm_deploy/values-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ generic-service:
PRISON_API_URL: "https://prison-api-dev.prison.service.justice.gov.uk"
DELIUS_URL: "https://ndelius.test.probation.service.justice.gov.uk"
SENTRY_TRACES_SAMPLE_RATE: "1.0"
SENTRY_REPLAY_SAMPLE_RATE: "1.0"

generic-prometheus-alerts:
businessHoursOnly: true
3 changes: 2 additions & 1 deletion packages/probation-search-frontend/routes/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,11 @@ function defaultResultFormatter(
})
}

function securityParams(res: Response): { csrfToken: string; cspNonce: string } {
function securityParams(res: Response): { csrfToken: string; cspNonce: string; user: { username: string } } {
return {
csrfToken: res.locals.csrfToken,
cspNonce: res.locals.cspNonce,
user: res.locals.user,
}
}

Expand Down
5 changes: 4 additions & 1 deletion server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export default {
},
sentry: {
dsn: process.env.SENTRY_DSN,
tracesSampleRate: process.env.SENTRY_TRACES_SAMPLE_RATE,
loaderScriptId: process.env.SENTRY_LOADER_SCRIPT_ID,
environment: get('ENVIRONMENT', 'local', requiredInProduction),
tracesSampleRate: Number(get('SENTRY_TRACES_SAMPLE_RATE', 1.0)),
replaySampleRate: Number(get('SENTRY_REPLAY_SAMPLE_RATE', 1.0)),
},
delius: {
url: get('DELIUS_URL', '*', requiredInProduction),
Expand Down
1 change: 1 addition & 0 deletions server/data/hmppsAuthClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function getSystemClientTokenFromHmppsAuth(username?: string): Promise<superagen

export interface User {
name: string
username: string
activeCaseLoadId: string
}

Expand Down
2 changes: 2 additions & 0 deletions server/middleware/populateCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { RequestHandler } from 'express'
import * as Sentry from '@sentry/node'
import logger from '../../logger'
import UserService from '../services/userService'

Expand All @@ -9,6 +10,7 @@ export default function populateCurrentUser(userService: UserService): RequestHa
const user = res.locals.user && (await userService.getUser(res.locals.user.token))
if (user) {
res.locals.user = { ...user, ...res.locals.user }
Sentry.setUser({ username: res.locals.user.username })
} else {
logger.info('No user available')
}
Expand Down
7 changes: 6 additions & 1 deletion server/middleware/setUpWebSecurity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ export default function setUpWebSecurity(): Router {
// <link href="http://example.com/" rel="stylesheet" nonce="{{ cspNonce }}">
// This ensures only scripts we trust are loaded, and not anything injected into the
// page by an attacker.
scriptSrc: ["'self'", (_req: Request, res: Response) => `'nonce-${res.locals.cspNonce}'`],
scriptSrc: [
"'self' https://*.sentry-cdn.com",
(_req: Request, res: Response) => `'nonce-${res.locals.cspNonce}'`,
],
connectSrc: ["'self' https://*.sentry.io"],
workerSrc: ["'self' blob:"],
styleSrc: ["'self'", (_req: Request, res: Response) => `'nonce-${res.locals.cspNonce}'`],
fontSrc: ["'self'"],
formAction: [`'self' ${config.apis.hmppsAuth.externalUrl}`],
Expand Down
3 changes: 2 additions & 1 deletion server/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default function routes(service: Services): Router {
router,
path: '/',
template: 'pages/index',
templateFields: () => ({ sentry: config.sentry }),
environment: config.environment,
oauthClient: service.hmppsAuthClient,
})
Expand All @@ -47,7 +48,7 @@ export default function routes(service: Services): Router {
router,
path: '/delius/nationalSearch',
template: 'pages/deliusSearch/index',
templateFields: () => ({ deliusUrl: config.delius.url }),
templateFields: () => ({ deliusUrl: config.delius.url, sentry: config.sentry }),
resultsFormatter: async (res, req) =>
nunjucks.render('pages/deliusSearch/results.njk', await mapResults(res, req, service.hmppsAuthClient)),
allowEmptyQuery: true,
Expand Down
8 changes: 6 additions & 2 deletions server/utils/sentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ export default function initSentry(app: Express): void {
if (config.sentry.dsn) {
Sentry.init({
dsn: config.sentry.dsn,
environment: config.environment,
environment: config.sentry.environment,
integrations: [new Sentry.Integrations.Http({ tracing: true }), new Sentry.Integrations.Express({ app })],
tracesSampleRate: config.sentry.tracesSampleRate ? +config.sentry.tracesSampleRate : 1.0,
tracesSampleRate: config.sentry.tracesSampleRate,
})
app.use(Sentry.Handlers.requestHandler())
app.use(Sentry.Handlers.tracingHandler())
app.use((req, res, next) => {
res.locals.sentry = config.sentry
return next()
})
}
}
1 change: 1 addition & 0 deletions server/views/pages/deliusSearch/index.njk
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
<script src="/assets/govuk/all.js"></script>
<script src="/assets/govukFrontendInit.js"></script>
<script src="/assets/moj/all.js"></script>
{% include "../../partials/sentry.njk" %}
<script nonce="{{ cspNonce }}">
function debounce(func, wait) {
let timeoutId;
Expand Down
1 change: 1 addition & 0 deletions server/views/partials/layout.njk
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@
<script src="/assets/govuk/all.js"></script>
<script src="/assets/govukFrontendInit.js"></script>
<script src="/assets/moj/all.js"></script>
{% include "./sentry.njk" %}
{% endblock %}
19 changes: 19 additions & 0 deletions server/views/partials/sentry.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{% if sentry and sentry.loaderScriptId %}
<script src="https://js.sentry-cdn.com/{{ sentry.loaderScriptId }}.min.js" nonce="{{ cspNonce }}" crossorigin="anonymous"></script>
<script nonce="{{ cspNonce }}">
Sentry.onLoad(function() {
Sentry.init({
dsn: "{{ sentry.dsn }}",
release: "probation-search-ui@{{ version }}",
environment: "{{ sentry.environment }}",
integrations: [new Sentry.BrowserTracing(), new Sentry.Replay()],
tracesSampleRate: {{ sentry.tracesSampleRate }},
replaysSessionSampleRate: {{ sentry.replaySampleRate }},
replaysOnErrorSampleRate: 1.0, // Capture replays for any sessions with an error
initialScope: {
user: { username: "{{ user.username }}" },
},
});
});
</script>
{% endif %}

0 comments on commit e1e16b0

Please sign in to comment.