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

Support Skills in Azure Government #1835

Merged
merged 6 commits into from
Mar 3, 2020
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: 22 additions & 20 deletions libraries/botbuilder/src/botFrameworkAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export enum StatusCodes {
}

export class StatusCodeError extends Error {
constructor(public readonly statusCode: StatusCodes, message?: string) {
public readonly statusCode: StatusCodes;
public constructor(statusCode: StatusCodes, message?: string) {
super(message);
this.statusCode = statusCode;
}
Expand Down Expand Up @@ -94,7 +95,7 @@ const TYPE: any = os.type();
const RELEASE: any = os.release();
const NODE_VERSION: any = process.version;

// tslint:disable-next-line:no-var-requires no-require-imports
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pjson: any = require('../package.json');
export const USER_AGENT: string = `Microsoft-BotFramework/3.1 BotBuilder/${ pjson.version } ` +
`(Node.js,Version=${ NODE_VERSION }; ${ TYPE } ${ RELEASE }; ${ ARCHITECTURE })`;
Expand Down Expand Up @@ -174,7 +175,7 @@ export class BotFrameworkAdapter extends BotAdapter implements CredentialTokenPr
* The [BotFrameworkAdapterSettings](xref:botbuilder.BotFrameworkAdapterSettings) class defines
* the available adapter settings.
*/
constructor(settings?: Partial<BotFrameworkAdapterSettings>) {
public constructor(settings?: Partial<BotFrameworkAdapterSettings>) {
super();
this.settings = { appId: '', appPassword: '', ...settings };

Expand Down Expand Up @@ -214,7 +215,7 @@ export class BotFrameworkAdapter extends BotAdapter implements CredentialTokenPr
// Relocate the tenantId field used by MS Teams to a new location (from channelData to conversation)
// This will only occur on activities from teams that include tenant info in channelData but NOT in conversation,
// thus should be future friendly. However, once the the transition is complete. we can remove this.
this.use(async(context, next) => {
this.use(async (context, next): Promise<void> => {
if (context.activity.channelId === 'msteams' && context.activity && context.activity.conversation && !context.activity.conversation.tenantId && context.activity.channelData && context.activity.channelData.tenant) {
context.activity.conversation.tenantId = context.activity.channelData.tenant.id;
}
Expand Down Expand Up @@ -638,9 +639,9 @@ export class BotFrameworkAdapter extends BotAdapter implements CredentialTokenPr
*
* @returns A map of the [TokenResponse](xref:botframework-schema.TokenResponse) objects by resource URL.
*/
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[]): Promise<{[propertyName: string]: TokenResponse;}>;
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[], oAuthAppCredentials?: AppCredentials): Promise<{[propertyName: string]: TokenResponse;}>;
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[], oAuthAppCredentials?: AppCredentials): Promise<{[propertyName: string]: TokenResponse;}> {
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[]): Promise<{[propertyName: string]: TokenResponse}>;
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[], oAuthAppCredentials?: AppCredentials): Promise<{[propertyName: string]: TokenResponse}>;
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[], oAuthAppCredentials?: AppCredentials): Promise<{[propertyName: string]: TokenResponse}> {
if (!context.activity.from || !context.activity.from.id) {
throw new Error(`BotFrameworkAdapter.getAadTokens(): missing from or from.id`);
}
Expand Down Expand Up @@ -961,12 +962,6 @@ export class BotFrameworkAdapter extends BotAdapter implements CredentialTokenPr
// Since the scope is different, we will create a new instance of the AppCredentials
// so this.credentials.oAuthScope isn't overridden.
credentials = await this.buildCredentials(botAppId, scope);

if (JwtTokenValidation.isGovernment(this.settings.channelService)) {
credentials.oAuthEndpoint = GovernmentConstants.ToChannelFromBotLoginUrl;
// Not sure that this code is correct because the scope was set earlier.
credentials.oAuthScope = GovernmentConstants.ToChannelFromBotOAuthScope;
}
}
}

Expand All @@ -984,7 +979,7 @@ export class BotFrameworkAdapter extends BotAdapter implements CredentialTokenPr
// Check if we have a streaming server. Otherwise, requesting a connector client
// for a non-existent streaming connection results in an error
if (!this.streamingServer) {
throw new Error(`Cannot create streaming connector client for serviceUrl ${serviceUrl} without a streaming connection. Call 'useWebSocket' or 'useNamedPipe' to start a streaming connection.`)
throw new Error(`Cannot create streaming connector client for serviceUrl ${ serviceUrl } without a streaming connection. Call 'useWebSocket' or 'useNamedPipe' to start a streaming connection.`);
}

return new ConnectorClient(
Expand Down Expand Up @@ -1023,14 +1018,21 @@ export class BotFrameworkAdapter extends BotAdapter implements CredentialTokenPr
/**
*
* @remarks
* When building credentials for bot-to-bot communication, oAuthScope must be passed in.
* @param appId
* @param oAuthScope
*/
protected async buildCredentials(appId: string, oAuthScope?: string): Promise<AppCredentials> {
// There is no cache for AppCredentials in JS as opposed to C#.
// Instead of retrieving an AppCredentials from the Adapter instance, generate a new one
const appPassword = await this.credentialsProvider.getAppPassword(appId);
return new MicrosoftAppCredentials(appId, appPassword, undefined, oAuthScope);
const credentials = new MicrosoftAppCredentials(appId, appPassword, this.settings.channelAuthTenant, oAuthScope);
if (JwtTokenValidation.isGovernment(this.settings.channelService)) {
credentials.oAuthEndpoint = GovernmentConstants.ToChannelFromBotLoginUrl;
credentials.oAuthScope = oAuthScope || GovernmentConstants.ToChannelFromBotOAuthScope;
}

return credentials;
}

/**
Expand Down Expand Up @@ -1368,10 +1370,10 @@ function parseRequest(req: WebRequest): Promise<Activity> {
}
} else {
let requestData = '';
req.on('data', (chunk: string) => {
req.on('data', (chunk: string): void => {
requestData += chunk;
});
req.on('end', () => {
req.on('end', (): void => {
try {
req.body = JSON.parse(requestData);
returnActivity(req.body);
Expand All @@ -1384,15 +1386,15 @@ function parseRequest(req: WebRequest): Promise<Activity> {
}

function delay(timeout: number): Promise<void> {
return new Promise((resolve) => {
return new Promise((resolve): void => {
setTimeout(resolve, timeout);
});
}

function abortWebSocketUpgrade(socket: INodeSocket, code: number, message?: string) {
function abortWebSocketUpgrade(socket: INodeSocket, code: number, message?: string): void {
if (socket.writable) {
const connectionHeader = `Connection: 'close'\r\n`;
socket.write(`HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n${message}\r\n${connectionHeader}\r\n`);
socket.write(`HTTP/1.1 ${ code } ${ STATUS_CODES[code] }\r\n${ message }\r\n${ connectionHeader }\r\n`);
}

socket.destroy();
Expand Down
5 changes: 2 additions & 3 deletions libraries/botbuilder/src/botFrameworkHttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,10 @@ export class BotFrameworkHttpClient {
const appPassword = await this.credentialProvider.getAppPassword(appId);
let appCredentials;
if (JwtTokenValidation.isGovernment(this.channelService)) {
appCredentials = new MicrosoftAppCredentials(appId, appPassword, this.channelService, oAuthScope);
appCredentials = new MicrosoftAppCredentials(appId, appPassword, undefined, oAuthScope);
appCredentials.oAuthEndpoint = GovernmentConstants.ToChannelFromBotLoginUrl;
appCredentials.oAuthScope = GovernmentConstants.ToChannelFromBotOAuthScope;
} else {
appCredentials = new MicrosoftAppCredentials(appId, appPassword, this.channelService, oAuthScope);
appCredentials = new MicrosoftAppCredentials(appId, appPassword, undefined, oAuthScope);
}
return appCredentials;
}
Expand Down
39 changes: 28 additions & 11 deletions libraries/botframework-connector/src/auth/appCredentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,33 +29,50 @@ export abstract class AppCredentials implements msrest.ServiceClientCredentials

public appId: string;

public oAuthEndpoint: string;
private _oAuthEndpoint: string;
private _oAuthScope: string;
private _tenant: string;
public tokenCacheKey: string;
protected refreshingToken: Promise<adal.TokenResponse> | null = null;
protected readonly authenticationContext: adal.AuthenticationContext;
protected authenticationContext: adal.AuthenticationContext;

constructor(appId: string, channelAuthTenant?: string, oAuthScope: string = AuthenticationConstants.ToBotFromChannelTokenIssuer) {
public constructor(appId: string, channelAuthTenant?: string, oAuthScope: string = AuthenticationConstants.ToBotFromChannelTokenIssuer) {
this.appId = appId;
const tenant = channelAuthTenant && channelAuthTenant.length > 0
? channelAuthTenant
: AuthenticationConstants.DefaultChannelAuthTenant;
this.oAuthEndpoint = AuthenticationConstants.ToChannelFromBotLoginUrlPrefix + tenant;
this.tenant = channelAuthTenant;
this.oAuthEndpoint = AuthenticationConstants.ToChannelFromBotLoginUrlPrefix + this.tenant;
this.oAuthScope = oAuthScope;
// aadApiVersion is set to '1.5' to avoid the "spn:" concatenation on the audience claim
// For more info, see https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/issues/128
this.authenticationContext = new adal.AuthenticationContext(this.oAuthEndpoint, true, undefined, '1.5');
}

private get tenant(): string {
return this._tenant;
}

private set tenant(value: string) {
this._tenant = value && value.length > 0
? value
: AuthenticationConstants.DefaultChannelAuthTenant;
}

public get oAuthScope(): string {
return this._oAuthScope
return this._oAuthScope;
}

public set oAuthScope(value: string) {
this._oAuthScope = value;
this.tokenCacheKey = `${ this.appId }${ this.oAuthScope }-cache`;
}

public get oAuthEndpoint(): string {
return this._oAuthEndpoint;
}

public set oAuthEndpoint(value: string) {
// aadApiVersion is set to '1.5' to avoid the "spn:" concatenation on the audience claim
// For more info, see https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/issues/128
this._oAuthEndpoint = value;
this.authenticationContext = new adal.AuthenticationContext(value, true, undefined, '1.5');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if there would value in the future on extracting the 1.5 into a constant. Depends if it will be referenced somewhere else at some point, in that case it would be valuable

}

/**
* Adds the host of service url to trusted hosts.
* If expiration time is not provided, the expiration date will be current (utc) date + 1 day.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export namespace AuthenticationConstants {
*
* DEPRECATED: DO NOT USE
*/
export const ToChannelFromBotLoginUrl = 'https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token';
export const ToChannelFromBotLoginUrl = 'https://login.microsoftonline.com/botframework.com';

/**
* TO CHANNEL FROM BOT: Login URL prefix
Expand All @@ -31,7 +31,7 @@ export namespace AuthenticationConstants {
/**
* TO CHANNEL FROM BOT: OAuth scope to request
*/
export const ToChannelFromBotOAuthScope = 'https://api.botframework.com/.default';
export const ToChannelFromBotOAuthScope = 'https://api.botframework.com/';

/**
* TO BOT FROM CHANNEL: Token issuer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ export namespace GovernmentConstants {
/**
* TO CHANNEL FROM BOT: Login URL
*/
export const ToChannelFromBotLoginUrl = 'https://login.microsoftonline.us/cab8a31a-1906-4287-a0d8-4eef66b95f6e/oauth2/v2.0/token';
export const ToChannelFromBotLoginUrl = 'https://login.microsoftonline.us/cab8a31a-1906-4287-a0d8-4eef66b95f6e';

/**
* TO CHANNEL FROM BOT: OAuth scope to request
*/
export const ToChannelFromBotOAuthScope = 'https://api.botframework.us/.default';
export const ToChannelFromBotOAuthScope = 'https://api.botframework.us';

/**
* TO BOT FROM CHANNEL: Token issuer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Licensed under the MIT License.
*/

import * as adal from 'adal-node'
import * as adal from 'adal-node';
import { AppCredentials } from './appCredentials';

/**
Expand All @@ -15,21 +15,21 @@ import { AppCredentials } from './appCredentials';
export class MicrosoftAppCredentials extends AppCredentials {
public appPassword: string;

constructor(appId: string, appPassword: string, channelAuthTenant?: string, oAuthScope?: string) {
public constructor(appId: string, appPassword: string, channelAuthTenant?: string, oAuthScope?: string) {
super(appId, channelAuthTenant, oAuthScope);
this.appPassword = appPassword;
}

protected async refreshToken(): Promise<adal.TokenResponse> {
if (!this.refreshingToken) {
this.refreshingToken = new Promise<adal.TokenResponse>((resolve, reject) => {
this.authenticationContext.acquireTokenWithClientCredentials(this.oAuthScope, this.appId, this.appPassword, function(err, tokenResponse) {
this.refreshingToken = new Promise<adal.TokenResponse>((resolve, reject): void => {
this.authenticationContext.acquireTokenWithClientCredentials(this.oAuthScope, this.appId, this.appPassword, function(err, tokenResponse): void {
if (err) {
reject(err);
} else {
resolve(tokenResponse as adal.TokenResponse);
}
});
});

});
}
Expand Down
2 changes: 1 addition & 1 deletion libraries/testbot/bots/dialogAndWelcomeBot.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

const { CardFactory } = require('botbuilder-core');
const { CardFactory } = require('botbuilder');
const { DialogBot } = require('./dialogBot');
const WelcomeCard = require('./resources/welcomeCard.json');

Expand Down