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

Application Insights front-end telemetry #607

Merged
merged 1 commit into from
Sep 16, 2024
Merged
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
42 changes: 41 additions & 1 deletion Dfe.Academies.External.Web/Pages/Cookies.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
</table>

<h2 class="govuk-heading-m">Analytics cookies (optional)</h2>

<h3 class="govuk-heading-s">Google Analytics</h3>
<p class="govuk-body">With your permission, we use Google Analytics to collect data about how you use Apply to become an academy. This information helps us improve our service.</p>
<p class="govuk-body">Google is not allowed to share our analytics data with anyone.</p>
<p class="govuk-body">Google Analytics stores anonymised information about:</p>
Expand Down Expand Up @@ -101,6 +103,44 @@
</tbody>
</table>

<h3 class="govuk-heading-s">Azure Application Insights</h3>
<p class="govuk-body">We use Azure Application Insights software to collect information about how you use this website. We do this to help make sure the site is meeting the needs of its users and to help us make improvements.</p>
<p class="govuk-body">Azure Application Insights stores information about:</p>
<ul class="govuk-list govuk-list--bullet">
<li>the pages you visit on this website</li>
<li>how long you spend on each page</li>
<li>how you got to the site</li>
<li>what you click on while you're visiting the site</li>
</ul>
<p class="govuk-body">We don't allow Microsoft to use or share our analytics data.</p>
<p class="govuk-body">Azure Application Insights sets the following cookies:</p>
<table class="govuk-table">
<thead class="govuk-table__head">
<tr class="govuk-table__row">
<th scope="col" class="govuk-table__header">Name</th>
<th scope="col" class="govuk-table__header">Purpose</th>
<th scope="col" class="govuk-table__header">Expires</th>
</tr>
</thead>
<tbody class="govuk-table__body">
<tr class="govuk-table__row">
<td class="govuk-table__cell">ai_session</td>
<td class="govuk-table__cell">This helps us track activity happening over a single browser session</td>
<td class="govuk-table__cell">1 hour</td>
</tr>
<tr class="govuk-table__row">
<td class="govuk-table__cell">ai_user</td>
<td class="govuk-table__cell">This helps us to identify the number of distinct users accessing the site over time by tracking if you've visited before</td>
<td class="govuk-table__cell">1 year</td>
</tr>
<tr class="govuk-table__row">
<td class="govuk-table__cell">ai_authuser</td>
<td class="govuk-table__cell">This helps us to authenticated users and how they interact with the site</td>
<td class="govuk-table__cell">When you close your browser</td>
</tr>
</tbody>
</table>

<h2 class="govuk-heading-m">Cookie settings</h2>
<p class="govuk-body">You can choose which cookies you’re happy for us to use.</p>
<form method="post" name="frmCookies" novalidate="">
Expand Down Expand Up @@ -129,4 +169,4 @@
</div>
<button type="submit" class="govuk-button" data-module="govuk-button">Save changes</button>
</form>
</div>
</div>
27 changes: 27 additions & 0 deletions Dfe.Academies.External.Web/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
@using Microsoft.Extensions.Configuration
@using Microsoft.AspNetCore.Http.Features
@using System.Security.Claims;
@inject IConfiguration _configuration

@{
var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
var canTrack = consentFeature?.CanTrack ?? false;
var authenticatedUserId = User.Identity is not null && User.Identity.IsAuthenticated ? User.FindFirst(ClaimTypes.Email)?.Value ?? "Unknown" : "Anonymous";
}

<!DOCTYPE html>
Expand All @@ -25,6 +27,31 @@
})(window, document, 'script', 'dataLayer', '@_configuration["Google:TagManagerId"]');
</script>
<!-- End Google Tag Manager -->

<!-- Application insights -->
<script type="text/javascript" integrity="sha384-g/ZkzetdQypWdY0NBZT5r2L3BR9/hURD8OBcd1rEaBpgX6QC7EaTL+o+mzWrBcXW" crossorigin="anonymous" src="https://js.monitor.azure.com/scripts/b/ext/ai.clck.2.8.18.min.js"></script>
<script type="text/javascript" asp-add-nonce>
// Load the Click analytics plugin
var clickPluginInstance = new Microsoft.ApplicationInsights.ClickAnalyticsPlugin();

// Application Insights JavaScript (Web) SDK Loader Script code
!(function (cfg){function e(){cfg.onInit&&cfg.onInit(i)}var S,u,D,t,n,i,C=window,x=document,w=C.location,I="script",b="ingestionendpoint",E="disableExceptionTracking",A="ai.device.";"instrumentationKey"[S="toLowerCase"](),u="crossOrigin",D="POST",t="appInsightsSDK",n=cfg.name||"appInsights",(cfg.name||C[t])&&(C[t]=n),i=C[n]||function(l){var d=!1,g=!1,f={initialize:!0,queue:[],sv:"7",version:2,config:l};function m(e,t){var n={},i="Browser";function a(e){e=""+e;return 1===e.length?"0"+e:e}return n[A+"id"]=i[S](),n[A+"type"]=i,n["ai.operation.name"]=w&&w.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(f.sv||f.version),{time:(i=new Date).getUTCFullYear()+"-"+a(1+i.getUTCMonth())+"-"+a(i.getUTCDate())+"T"+a(i.getUTCHours())+":"+a(i.getUTCMinutes())+":"+a(i.getUTCSeconds())+"."+(i.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z",iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}},ver:4,seq:"1",aiDataContract:undefined}}var h=-1,v=0,y=["js.monitor.azure.com","js.cdn.applicationinsights.io","js.cdn.monitor.azure.com","js0.cdn.applicationinsights.io","js0.cdn.monitor.azure.com","js2.cdn.applicationinsights.io","js2.cdn.monitor.azure.com","az416426.vo.msecnd.net"],k=l.url||cfg.src;if(k){if((n=navigator)&&(~(n=(n.userAgent||"").toLowerCase()).indexOf("msie")||~n.indexOf("trident/"))&&~k.indexOf("ai.3")&&(k=k.replace(/(\/)(ai\.3\.)([^\d]*)$/,function(e,t,n){return t+"ai.2"+n})),!1!==cfg.cr)for(var e=0;e<y.length;e++)if(0<k.indexOf(y[e])){h=e;break}var i=function(e){var a,t,n,i,o,r,s,c,p,u;f.queue=[],g||(0<=h&&v+1<y.length?(a=(h+v+1)%y.length,T(k.replace(/^(.*\/\/)([\w\.]*)(\/.*)$/,function(e,t,n,i){return t+y[a]+i})),v+=1):(d=g=!0,o=k,c=(p=function(){var e,t={},n=l.connectionString;if(n)for(var i=n.split(";"),a=0;a<i.length;a++){var o=i[a].split("=");2===o.length&&(t[o[0][S]()]=o[1])}return t[b]||(e=(n=t.endpointsuffix)?t.location:null,t[b]="https://"+(e?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||l.instrumentationKey||"",p=(p=p[b])?p+"/v2/track":l.endpointUrl,(u=[]).push((t="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",n=o,r=p,(s=(i=m(c,"Exception")).data).baseType="ExceptionData",s.baseData.exceptions=[{typeName:"SDKLoadFailed",message:t.replace(/\./g,"-"),hasFullStack:!1,stack:t+"\nSnippet failed to load ["+n+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(w&&w.pathname||"_unknown_")+"\nEndpoint: "+r,parsedStack:[]}],i)),u.push((s=o,t=p,(r=(n=m(c,"Message")).data).baseType="MessageData",(i=r.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+s+")").replace(/\"/g,"")+'"',i.properties={endpoint:t},n)),o=u,c=p,JSON&&((r=C.fetch)&&!cfg.useXhr?r(c,{method:D,body:JSON.stringify(o),mode:"cors"}):XMLHttpRequest&&((s=new XMLHttpRequest).open(D,c),s.setRequestHeader("Content-type","application/json"),s.send(JSON.stringify(o))))))},a=function(e,t){g||setTimeout(function(){!t&&f.core||i()},500),d=!1},T=function(e){var n=x.createElement(I),e=(n.src=e,cfg[u]);return!e&&""!==e||"undefined"==n[u]||(n[u]=e),n.onload=a,n.onerror=i,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||a(0,t)},cfg.ld&&cfg.ld<0?x.getElementsByTagName("head")[0].appendChild(n):setTimeout(function(){x.getElementsByTagName(I)[0].parentNode.appendChild(n)},cfg.ld||0),n};T(k)}try{f.cookie=x.cookie}catch(p){}function t(e){for(;e.length;)!function(t){f[t]=function(){var e=arguments;d||f.queue.push(function(){f[t].apply(f,e)})}}(e.pop())}var r,s,n="track",o="TrackPage",c="TrackEvent",n=(t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+o,"stop"+o,"start"+c,"stop"+c,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),f.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},(l.extensionConfig||{}).ApplicationInsightsAnalytics||{});return!0!==l[E]&&!0!==n[E]&&(t(["_"+(r="onerror")]),s=C[r],C[r]=function(e,t,n,i,a){var o=s&&s(e,t,n,i,a);return!0!==o&&f["_"+r]({message:e,url:t,lineNumber:n,columnNumber:i,error:a,evt:C.event}),o},l.autoExceptionInstrumented=!0),f}(cfg.cfg),(C[n]=i).queue&&0===i.queue.length?(i.queue.push(e),i.trackPageView({})):e();})({
src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js",
crossOrigin: "anonymous",
cfg: {
connectionString: '@_configuration["ApplicationInsights:ConnectionString"]',
extensions: [ clickPluginInstance ],
extensionConfig: { [clickPluginInstance.identifier] : {
autoCapture : true,
dataTags: { useDefaultContentNameOrId: true }
} },
}
});

// Set Authenticated User Context
window.appInsights.setAuthenticatedUserContext("@authenticatedUserId", null, true);
</script>
<!-- End Application insights -->
}

<meta charset="utf-8">
Expand Down
26 changes: 16 additions & 10 deletions Dfe.Academies.External.Web/Security/SecureHeadersDefinitions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,26 @@

public static class SecureHeadersDefinitions
{
private static readonly string[] DefaultSrcExclusions =
{
"wss://localhost:*/Dfe.Academies.External.Web/", "https://*.googletagmanager.com",
"https://*.google-analytics.com"
};
private static readonly string[] DefaultSrcExclusions = ["wss://localhost:*/Dfe.Academies.External.Web/"];

private static readonly string[] ScriptSrcExclusions =
{
"https://*.googletagmanager.com", "https://*.google-analytics.com"
};
[
"https://*.googletagmanager.com", "https://*.google-analytics.com",
"https://js.monitor.azure.com/scripts/b/ext/ai.clck.2.8.18.min.js",
"https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js"
];

private static readonly string[] ImageSrcExclusions =
{
[
"https://www.googletagmanager.com", "https://*.google-analytics.com"
};
];

private static readonly string[] ConnectSrcExclusions =
[
"https://js.monitor.azure.com/scripts/b/ai.config.1.cfg.json",
"https://*.in.applicationinsights.azure.com/v2/track", "https://*.googletagmanager.com",
"https://*.google-analytics.com"
];

public static HeaderPolicyCollection GetHeaderPolicyCollection()
{
Expand Down Expand Up @@ -46,6 +51,7 @@ public static HeaderPolicyCollection GetHeaderPolicyCollection()
builder.AddFontSrc().Self();
builder.AddImgSrc().Self().From(ImageSrcExclusions);
builder.AddFrameSrc().Self();
builder.AddConnectSrc().Self().From(ConnectSrcExclusions);
})
.AddPermissionsPolicy(builder =>
{
Expand Down
Loading