<commit_before>const request = require('supertest');
const express = require('express');
const should = require('should');
const serverHelper = require('../../common/server-helper');
const config = require('../../../lib/config');
const testHelper = require('../../common/routing.helper')();

const originalGatewayConfig = JSON.parse(JSON.stringify(config.gatewayConfig));
const originalSystemConfig = JSON.parse(JSON.stringify(config.systemConfig));

let callCount = 0;
let gateway;
let introspectApp;
let backend;

const gatewayConfig = (port) => ({
  http: { port: 0 },
  serviceEndpoints: {
    backend: {
      url: `http://localhost:${port}`
    }
  },
  apiEndpoints: {
    authorizedEndpoint: {
      host: '*'
    }
  },
  policies: ['oauth2-introspect', 'proxy'],
  pipelines: {
    pipeline1: {
      apiEndpoints: ['authorizedEndpoint'],
      policies: [
        {
          'oauth2-introspect': {
            action: {
              endpoint: 'http://localhost:7777/introspect',
              authorization_value: '<KEY>
            }
          }
        },
        { proxy: [{ action: { serviceEndpoint: 'backend' } }] }
      ]
    }
  }
});

describe('oAuth2 Introspection Policy', () => {
  before(() => {
    return serverHelper.findOpenPortNumbers(2)
      .then(([port, introspectPort]) => {
        config.gatewayConfig = gatewayConfig(port);
        const app = express();
        app.post('/introspect', express.urlencoded({ extended: true }), (req, res) => {
          callCount++;
          if (req.header('authorization') !== '<KEY> {
            return res.sendStatus(401);
          }

          if (req.body.token !== 'example_token_value') {
            return res.json({ active: false });
          }

          return res.json({ active: true });
        });
        return new Promise((resolve, reject) => {
          introspectApp = app.listen(7777, (err) => {
            if (err) return reject(err);
            resolve();
          });
        }).then(() => serverHelper.generateBackendServer(port));
      }).then(({ app }) => { backend = app; })
      .then(() => testHelper.setup()).then(({ app }) => { gateway = app; });
  });

  it('should return 401 when invalid authorization value is provided', () =>
    request(gateway)
      .get('/')
      .expect(401)
  );

  it('should return 401 when invalid token is provided', () =>
    request(gateway)
      .get('/')
      .set('Authorization', `<KEY>`)
      .type('form')
      .send({ token: 'invalid' })
      .expect(401)
  );

  it('should return 200 when valid token and authvalue are provided', () =>
    request(gateway)
      .get('/')
      .set('Authorization', `YX<KEY>=`)
      .type('form')
      .send({ token: 'example_token_value' })
      .expect(200)
  );

  it('should not call the introspection endpoint again because the token is valid already', () =>
    request(gateway)
      .get('/')
      .set('Authorization', `<KEY>`)
      .type('form')
      .send({ token: 'example_token_value' })
      .then(() => should(callCount).equal(3))
  );

  after('cleanup', (done) => {
    config.systemConfig = originalSystemConfig;<commit_msg>Use sinon to spy method calls<commit_after>const request = require('supertest');
const express = require('express');
const should = require('should');
const sinon = require('sinon');
const serverHelper = require('../../common/server-helper');
const config = require('../../../lib/config');
const testHelper = require('../../common/routing.helper')();

const originalGatewayConfig = JSON.parse(JSON.stringify(config.gatewayConfig));
const originalSystemConfig = JSON.parse(JSON.stringify(config.systemConfig));

let gateway;
let introspectApp;
let backend;
let introspectEndpointSpy;

const gatewayConfig = (port) => ({
  http: { port: 0 },
  serviceEndpoints: {
    backend: {
      url: `http://localhost:${port}`
    }
  },
  apiEndpoints: {
    authorizedEndpoint: {
      host: '*'
    }
  },
  policies: ['oauth2-introspect', 'proxy'],
  pipelines: {
    pipeline1: {
      apiEndpoints: ['authorizedEndpoint'],
      policies: [
        {
          'oauth2-introspect': {
            action: {
              endpoint: 'http://localhost:7777/introspect',
              authorization_value: '<KEY>
            }
          }
        },
        { proxy: [{ action: { serviceEndpoint: 'backend' } }] }
      ]
    }
  }
});

describe('oAuth2 Introspection Policy', () => {
  before(() => {
    return serverHelper.findOpenPortNumbers(2)
      .then(([port, introspectPort]) => {
        config.gatewayConfig = gatewayConfig(port);
        const app = express();
        introspectEndpointSpy = sinon.spy((req, res) => {
          if (req.header('authorization') !== '<KEY> {
            return res.sendStatus(401);
          }

          if (req.body.token !== 'example_token_<PASSWORD>') {
            return res.json({ active: false });
          }

          return res.json({ active: true });
        });
        app.post('/introspect', express.urlencoded({ extended: true }), introspectEndpointSpy);
        return new Promise((resolve, reject) => {
          introspectApp = app.listen(7777, (err) => {
            if (err) return reject(err);
            resolve();
          });
        }).then(() => serverHelper.generateBackendServer(port));
      }).then(({ app }) => { backend = app; })
      .then(() => testHelper.setup()).then(({ app }) => { gateway = app; });
  });

  it('should return 401 when invalid authorization value is provided', () =>
    request(gateway)
      .get('/')
      .expect(401)
  );

  it('should return 401 when invalid token is provided', () =>
    request(gateway)
      .get('/')
      .set('Authorization', `<KEY>`)
      .type('form')
      .send({ token: 'invalid' })
      .expect(401)
  );

  it('should return 200 when valid token and authvalue are provided', () =>
    request(gateway)
      .get('/')
      .set('Authorization', `<KEY>`)
      .type('form')
      .send({ token: '<PASSWORD>' })
      .expect(200)
  );

  it('should not call the introspection endpoint again because the token is valid already', () =>
    request(gateway)
      .get('/')
      .set('Authorization', `<KEY>`)
      .type('form')
      .send({ token: '<PASSWORD>' })
      .then(() => should(introspectEndpointSpy.callCount).equal(3))
  );

  after('cleanup', (done) => {
    config.systemConfig = originalSystemConfig;
{'fraction_non_alphanumeric': 0.17643381778402875, 'fraction_numerical': 0.011408032505078918, 'mean_word_length': 2.5437430786267994, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 50, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6644942', 'n_tokens_mistral': 1936, 'n_tokens_neox': 1885, 'n_words': 403}