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

port: [#4432] Expired JWT token exception not being handled (#6572) #4436

Merged
merged 3 commits into from
May 5, 2023
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
1 change: 1 addition & 0 deletions libraries/botbuilder/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"botbuilder-core": "4.1.6",
"botbuilder-stdlib": "4.1.6",
"botframework-connector": "4.1.6",
"botframework-schema": "4.1.6",
"botframework-streaming": "4.1.6",
"dayjs": "^1.10.3",
"filenamify": "^4.1.0",
Expand Down
67 changes: 64 additions & 3 deletions libraries/botbuilder/tests/cloudAdapter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,20 @@ const assert = require('assert');
const httpMocks = require('node-mocks-http');
const net = require('net');
const sinon = require('sinon');
const { BotFrameworkAuthenticationFactory } = require('botframework-connector');
const { CloudAdapter, ActivityTypes, INVOKE_RESPONSE_KEY } = require('..');
const {
AuthenticationConfiguration,
BotFrameworkAuthenticationFactory,
allowedCallersClaimsValidator,
} = require('botframework-connector');
const {
CloudAdapter,
ConfigurationServiceClientCredentialFactory,
ActivityTypes,
createBotFrameworkAuthenticationFromConfiguration,
INVOKE_RESPONSE_KEY,
} = require('..');
const { NamedPipeServer } = require('botframework-streaming');
const { StatusCodes } = require('botframework-schema');

const FakeBuffer = () => Buffer.from([]);
const FakeNodeSocket = () => new net.Socket();
Expand All @@ -16,7 +27,7 @@ const noop = () => null;
describe('CloudAdapter', function () {
let sandbox;
beforeEach(function () {
sandbox = sinon.createSandbox({ useFakeTimers: true });
sandbox = sinon.createSandbox({ useFakeTimers: false });
});

afterEach(function () {
Expand Down Expand Up @@ -87,6 +98,56 @@ describe('CloudAdapter', function () {

mock.verify();
});

it('throws exception on expired token', async function () {
// Expired token with removed AppID
const authorization =
'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGxWMFRPSSIsImtpZCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGxWMFRPSSJ9.eyJhdWQiOiJodHRwczovL2FwaS5ib3RmcmFtZXdvcmsuY29tIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvZDZkNDk0MjAtZjM5Yi00ZGY3LWExZGMtZDU5YTkzNTg3MWRiLyIsImlhdCI6MTY3MDM1MDQxNSwibmJmIjoxNjcwMzUwNDE1LCJleHAiOjE2NzA0MzcxMTUsImFpbyI6IkUyWmdZTkJONEpWZmxlOTJUc2wxYjhtOHBjOWpBQT09IiwiYXBwaWQiOiI5ZGRmM2QwZS02ZDRlLTQ2MWEtYjM4Yi0zMTYzZWQ3Yjg1NmIiLCJhcHBpZGFjciI6IjEiLCJpZHAiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9kNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIvIiwicmgiOiIwLkFXNEFJSlRVMXB2ejkwMmgzTldhazFoeDIwSXpMWTBwejFsSmxYY09EcS05RnJ4dUFBQS4iLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJIWDlncld2bU1rMlhESTRkS3BHSEFBIiwidmVyIjoiMS4wIn0.PBLuja5sCcDfFjweoy-VucvbfHEyEcs1GyqXjekzBqgvK-mSc1UrEfqr5834qY6dLNsXVIMJzMFuH6WyPbnAfIfRcabdiVSOAl8N8e9Tex6vHfPi4h4P2F96VkXU80EtZX4QMjsJMDJ5eXbJlIDEAxXoJbAdHqgy-lHcVBx8XK7toJ_W7vSsFhis3C4CPCHI1cf1WuHVwfFXBiNwsOzj9cnRUKpea6UELV89q4C0L6aeSNdWYXehZmgq-wlo2wIaGgQ7rOXx4MlIrc83LBzMMc6TWvBJecK6O8pJWLe6BTwOltBI8Tmo2hWnY1OnsbOhbSSlfwLaZqKI7QpA50_2GQ';

const activity = { type: ActivityTypes.Invoke, value: 'invoke' };

const req = httpMocks.createRequest({
method: 'POST',
headers: { authorization },
body: activity,
});

const res = httpMocks.createResponse();

const logic = async (context) => {
context.turnState.set(INVOKE_RESPONSE_KEY, {
type: ActivityTypes.InvokeResponse,
value: {
status: 200,
body: 'invokeResponse',
},
});
};

const validTokenIssuers = [];
const claimsValidators = allowedCallersClaimsValidator(['*']);
const authConfig = new AuthenticationConfiguration([], claimsValidators, validTokenIssuers);
const credentialsFactory = new ConfigurationServiceClientCredentialFactory({
MicrosoftAppId: '',
MicrosoftAppPassword: '',
MicrosoftAppType: '',
MicrosoftAppTenantId: '',
});

const botFrameworkAuthentication = createBotFrameworkAuthenticationFromConfiguration(
null,
credentialsFactory,
authConfig,
undefined,
undefined
);

const adapter = new CloudAdapter(botFrameworkAuthentication);

await adapter.process(req, res, logic);

assert.equal(StatusCodes.UNAUTHORIZED, res.statusCode);
});
});

describe('connectNamedPipe', function () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ export class JwtTokenExtractor {
// from a validated JWT (see `verify` above), so no harm in doing so.
return new ClaimsIdentity(claims, true);
} catch (err) {
if (err.name === 'TokenExpiredError') {
console.error(err);
throw new AuthenticationError('The token has expired', StatusCodes.UNAUTHORIZED);
}
console.error(`Error finding key for token. Available keys: ${metadata.key}`);
throw err;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
const assert = require('assert');
const { jwt } = require('botbuilder-test-utils');
const { JwtTokenExtractor } = require('../../lib/auth/jwtTokenExtractor');
const { StatusCodes } = require('../../../botframework-schema');

describe('JwtTokenExtractor', function () {
jwt.mocha();
Expand Down Expand Up @@ -37,4 +38,27 @@ describe('JwtTokenExtractor', function () {
verify();
});
});

describe('validateToken', function () {
it('throws with expired token', async function () {
const { algorithm, issuer, metadata, sign } = jwt.stub();
const key = 'value';
const token = sign({ key });

const client = new JwtTokenExtractor(
{
issuer,
clockTimestamp: Date.now(),
clockTolerance: -10,
},
metadata,
[algorithm]
);

await assert.rejects(client.getIdentityFromAuthHeader(`Bearer ${token}`), {
message: 'The token has expired',
statusCode: StatusCodes.UNAUTHORIZED,
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const {
} = require('../..');

describe('JwtTokenValidation', function () {
afterEach(function () {
beforeEach(function () {
JwtTokenExtractor.openIdMetadataCache.clear();
});

Expand Down