# Code coverage report for lib/git/hooks/webhook.js

## Statements: 100% (82 / 82) Branches: 100% (50 / 50) Functions: 100% (15 / 15) Lines: 100% (81 / 81) Ignored: 2 statements, 3 branches

All files » lib/git/hooks/ » webhook.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    2231

    1
    1

    1

    1

    1

    15
    1

    15
    1

    14
    1

    13
    13
    4

    4
    4

    4
    4
    9
    3

    9

    4

    4

    4

    4
    4

    9
    1

    12

    12

    1
    15

    12
    48
    9

    9

    8

    8
    8
    2
    2

    6
    8
    8
    8

    8
    8
    4

    4

    4

    7

    12

    1

    3

    3
    2

    1

    1

    3

    3
    3
    5

    5
    4

    3

    1

    3
    2
    2
    2

    1

    2
    2
    2

    2
    2

    2

    1
    3
    15

     var util = require('util');

    var express = require('express');
    var bodyParser = require('body-parser');

    var logger = require('../../logging.js');

    // Create an object to map from host port to app.  Multiple hosts can be configured to listen
    // on the same port.
    var server_apps = {};

    /**
     * Create a listener for calls from the Webhook, whether stash or github.
     */
    function init_express(config) {

      // Validate config.  Fail if the provided config matches an existing host / port combination.
      /* istanbul ignore next */
      Iif (!config) {
        throw 'Invalid config provided to webhook';
      }
      if (!config.port || isNaN(config.port)) {
        throw 'Invalid webhook port ' + config.port;
      }
      if (!config.url) {
        throw 'No config url provided';
      }

      // Each webhook port maps to a server_app object, a container we create to store both the express
      // app and the set of routes registered in that app.  We use the latter data to make sure more than
      // one webhook does not try to register the same route on the same port.
      var server_app = server_apps[config.port];
      if (!server_app) {
        server_app = {};

        var app = express();
        server_app.app = app;

        // Stash's webhook sends a totally bogus content-encoding.  Smack it before the body parser runs.
        app.use(function() {
          return function(req, res, next) {
            if (req.headers['content-encoding'] == 'UTF-8') {
              delete req.headers['content-encoding'];
            }
            next();
          }
        }());

        // Parse application/json
        app.use(bodyParser.json());

        // Parse form data (for bitbucket)
        app.use(bodyParser.urlencoded({extended:true}));

        app.listen(config.port);

        server_app.urls = {};
        server_apps[config.port] = server_app;
      } else {
        // Two webhooks can't have the same url and port, so fail if this is the case.
        if (server_app.urls[config.url]) {
          throw "A webhook is already listening on " + config.port + ", " + config.url;
        }
      }

      // In all cases where we made it here, we want to track the config.url to make sure that no duplicate
      // webhook routes can be created.
      server_app.urls[config.url] = true;

      return server_app.app;
    }

    // Create a webhook function for all common operations.  It will use the provided config to initialize
    // an express app (if one has not been initialized yet), and it will call into the enclosed implementation
    // object to perform Git or Stash-specific functions.
    function create_webhook(config, repo, implementation) {
      var app = init_express(config);

      // We don't care what method is used, so use them all.
      ['get','post','put','delete'].forEach(function(verb) {
        app[verb](config.url, function(req, res){
          logger.debug('Got pinged by %s hook, checking request', implementation.type);

          /* istanbul ignore else */
          if (implementation.isValid(req)) {

            logger.trace(util.inspect(req.body, {depth: 10}));

            // Only pull changed branches
            var changes = implementation.getHeadChanges(req);
            if (changes.length === 0) {
              logger.trace('No changes in a relevant branch.');
              return res.send('ok');
            }

            for (var i=0; i<changes.length; ++i) {
              var change = changes[i];
              var to_hash = change.to_hash;
              logger.info('Webhook noted change to branch %s with commit id %s', change.branch, change.to_hash);

              // Update consul git branch
              var branch = repo.branches[change.branch];
              if (branch) {
                branch.handleRefChange(change.to_hash, function(err) {
                  /* istanbul ignore next */
                  Iif (err) logger.error(err);

                  logger.debug('Updates in branch %s complete', change.branch);
                });
              }
            }
          }

          res.send('ok');
        });
      });

      logger.info('%s listener initialized at http://localhost:%s%s', implementation.type, config.port, config.url);
    };

    /**
     * This object defines the properties unique to a github webhook.
     */
    exports.github = {

      type: 'github',

      isValid: function(req) {
        return req && req.body && req.body.ref && req.body.head_commit && req.body.head_commit.id;
      },

      getHeadChanges: function(req) {
        // Return a change to head, if any.
        if (req.body.ref.indexOf('refs/heads/') === 0) {
          return [{
            'to_hash': req.body.head_commit.id,
            'branch': req.body.ref.substring(11)
          }];
        }

        // Otherwise, return an empty array.
        return [];
      }
    };

    /**
     * This object defines the properties unique to a stash webhook.
     */
    exports.stash = {

      type: 'stash',

      isValid: function(req) {
        return req && req.body && req.body.refChanges;
      },

      getHeadChanges: function(req) {
        var changes = [];
        for (var i=0; i<req.body.refChanges.length; ++i) {
          var refChange = req.body.refChanges[i];

          // Only update if the head of a branch changed
          /* istanbul ignore else */
          if (refChange.refId && (refChange.refId.indexOf('refs/heads/') === 0) && refChange.toHash) {
            changes.push({
              'to_hash': refChange.toHash,
              'branch': refChange.refId.substring(11)
            });
          }
        }
        return changes;
      }
    };

    /**
     * This object defines the properties unique to a bitbucket webhook.
     */
    exports.bitbucket = {

      type: 'bitbucket',

      isValid: function(req) {

        if (req && req.body && req.body.payload) {
          try {
            req.body = JSON.parse(req.body.payload);
            return req.body && req.body.commits && req.body.commits.length;
          /* istanbul ignore next */
          } catch(e) {
            // We don't care about a busted message.
          }
        }

        return false;
      },

      getHeadChanges: function(req) {
        var changes = [];
        for (var i=0; i<req.body.commits.length; ++i) {
          var commit = req.body.commits[i];

          // Only update if the head of a branch changed
          /* istanbul ignore else */
          Eif (commit.branch && (commit.parents.length !== 0) && commit.node) {
            changes.push({
              'to_hash': commit.node,
              'branch': commit.branch
            });
          }
        }
        return changes;
      }
    };

    /**
     * Register an init method for each support webhook implementation.
     */
    [exports.bitbucket, exports.github, exports.stash].forEach(function(hook_impl) {
      hook_impl.init = function(repo, config) {
        create_webhook(repo, config, hook_impl);
      };
    });