Skip to content

Commit 8173f7c

Browse files
authored
Fix Crashing with Old Node.JS Versions When Manually Instrumenting (#1362)
* Fix node 14 support by conditionally loading core-auth. * Add README note. * Remove unneeded core-auth check from the agent code. * Update package-lock.json * Update README.md * Update README.md * Update package-lock.json
1 parent 2b68662 commit 8173f7c

File tree

5 files changed

+30
-22
lines changed

5 files changed

+30
-22
lines changed

Bootstrap/Default.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import * as azureCoreAuth from "@azure/core-auth";
2-
1+
import type { TokenCredential } from "@azure/core-auth";
32
import * as types from "../applicationinsights";
43
import * as Helpers from "./Helpers";
54
import Constants = require("../Declarations/Constants");
@@ -40,7 +39,7 @@ export function setStatusLogger(statusLogger: StatusLogger) {
4039
* Try to setup and start this app insights instance if attach is enabled.
4140
* @param aadTokenCredential Optional AAD credential
4241
*/
43-
export function setupAndStart(aadTokenCredential?: azureCoreAuth.TokenCredential, isAzureFunction?: boolean): typeof types | null {
42+
export function setupAndStart(aadTokenCredential?: TokenCredential, isAzureFunction?: boolean): typeof types | null {
4443
// If app already contains SDK, skip agent attach
4544
if (!forceStart && Helpers.sdkAlreadyExists(_logger)) {
4645
_statusLogger.logStatus({

Declarations/Interfaces.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import http = require("http");
22
import https = require("https");
3-
import * as azureCoreAuth from "@azure/core-auth";
3+
import type { TokenCredential } from "@azure/core-auth";
44
import { DistributedTracingModes } from "../applicationinsights";
55
import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance";
66

@@ -224,5 +224,5 @@ export interface IConfig extends IBaseConfig {
224224
/** An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined) */
225225
httpsAgent: https.Agent;
226226
/** AAD TokenCredential to use to authenticate the app */
227-
aadTokenCredential?: azureCoreAuth.TokenCredential;
227+
aadTokenCredential?: TokenCredential;
228228
}

Library/AuthorizationHandler.ts

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,42 @@
11
import http = require("http");
22
import https = require("https");
3-
import azureCoreAuth = require("@azure/core-auth");
4-
import azureCore = require("@azure/core-rest-pipeline");
3+
import { TokenCredential } from "@azure/core-auth";
4+
import { PipelineRequest, PipelineResponse, PipelinePolicy } from "@azure/core-rest-pipeline";
5+
import Logging = require("./Logging");
56

67
const applicationInsightsResource = "https://monitor.azure.com//.default";
78

9+
let azureCore: any;
10+
try {
11+
azureCore = require("@azure/core-rest-pipeline");
12+
} catch (e) {
13+
Logging.warn("Cannot load @azure/core-auth package. This package is required for AAD token authentication. It's likely that your node.js version is not supported by the JS Azure SDK.");
14+
}
815

9-
function emptySendRequest(_request: azureCore.PipelineRequest): Promise<azureCore.PipelineResponse> {
16+
function emptySendRequest(_request: PipelineRequest): Promise<PipelineResponse> {
1017
return null;
1118
}
12-
1319
class AuthorizationHandler {
1420

15-
private _azureTokenPolicy: azureCore.PipelinePolicy;
21+
private _azureTokenPolicy: PipelinePolicy;
1622

17-
constructor(credential: azureCoreAuth.TokenCredential, aadAudience?: string) {
18-
let scopes: string[] = aadAudience ? [aadAudience] : [applicationInsightsResource];
19-
this._azureTokenPolicy = azureCore.bearerTokenAuthenticationPolicy({ credential, scopes });
23+
constructor(credential: TokenCredential, aadAudience?: string) {
24+
if (azureCore) {
25+
let scopes: string[] = aadAudience ? [aadAudience] : [applicationInsightsResource];
26+
this._azureTokenPolicy = azureCore.bearerTokenAuthenticationPolicy({ credential, scopes });
27+
}
2028
}
2129

2230
/**
2331
* Applies the Bearer token to the request through the Authorization header.
2432
*/
2533
public async addAuthorizationHeader(requestOptions: http.RequestOptions | https.RequestOptions): Promise<void> {
26-
let authHeaderName = "authorization";
27-
let webResource = azureCore.createPipelineRequest({ url: "https://" });
28-
await this._azureTokenPolicy.sendRequest(webResource, emptySendRequest);
29-
requestOptions.headers[authHeaderName] = webResource.headers.get(authHeaderName);
34+
if (azureCore) {
35+
let authHeaderName = "authorization";
36+
let webResource = azureCore.createPipelineRequest({ url: "https://" });
37+
await this._azureTokenPolicy.sendRequest(webResource, emptySendRequest);
38+
requestOptions.headers[authHeaderName] = webResource.headers.get(authHeaderName);
39+
}
3040
}
3141
}
3242

Library/Config.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import azureCoreAuth = require("@azure/core-auth");
2-
31
import CorrelationIdManager = require("./CorrelationIdManager");
42
import ConnectionStringParser = require("./ConnectionStringParser");
53
import Logging = require("./Logging");
@@ -11,6 +9,7 @@ import { JsonConfig } from "./JsonConfig";
119
import { IConfig, IWebInstrumentationConfig } from "../Declarations/Interfaces";
1210
import { DistributedTracingModes } from "../applicationinsights";
1311
import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance";
12+
import type { TokenCredential } from "@azure/core-auth";
1413

1514
class Config implements IConfig {
1615

@@ -33,7 +32,7 @@ class Config implements IConfig {
3332
public httpAgent: http.Agent;
3433
public httpsAgent: https.Agent;
3534
public ignoreLegacyHeaders: boolean;
36-
public aadTokenCredential?: azureCoreAuth.TokenCredential;
35+
public aadTokenCredential?: TokenCredential;
3736
public aadAudience?: string;
3837
public enableAutoCollectConsole: boolean;
3938
public enableLoggerErrorToTrace: boolean;

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ You can manually track more aspects of your app and system using the API describ
3232

3333

3434

35-
## Supported Node.JS versions
35+
## Supported Node.JS versions
3636

3737
| Platform Version | Supported |
3838
|------------------|-------------------------------------------------|
@@ -225,7 +225,7 @@ separately from clients created with `new appInsights.TelemetryClient()`.
225225
| noHttpAgentKeepAlive | HTTPS without a passed in agent |
226226
| httpAgent | An http.Agent to use for SDK HTTP traffic (Optional, Default undefined) |
227227
| httpsAgent | An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined)
228-
| aadTokenCredential| Azure Credential instance to be used to authenticate the App. [AAD Identity Credential Classes](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/identity/identity#credential-classes)
228+
| aadTokenCredential| Azure Credential instance to be used to authenticate the App. [AAD Identity Credential Classes](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/identity/identity#credential-classes). Only versions of Node.JS supported by the [JS Azure SDK](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) support AAD authentication.
229229
| enableWebInstrumentation | Sets the state of automatic web Instrumentation (Optional, disabled by default). If true, web instrumentation will be enabled on valid node server http response with the connection string used for SDK initialization
230230
| webInstrumentationConnectionString | Sets connection string used for web Instrumentation (Optional, Default undefined)|
231231
| webInstrumentationSrc | Sets web Instrumentation CDN url (Optional). see more details at [ApplicationInsights JavaScript SDK](https://github.com/microsoft/ApplicationInsights-JS)|

0 commit comments

Comments
 (0)