signer.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Copyright 2012 Joyent, Inc. All rights reserved.
  2. var assert = require('assert-plus');
  3. var crypto = require('crypto');
  4. var http = require('http');
  5. var sprintf = require('util').format;
  6. ///--- Globals
  7. var Algorithms = {
  8. 'rsa-sha1': true,
  9. 'rsa-sha256': true,
  10. 'rsa-sha512': true,
  11. 'dsa-sha1': true,
  12. 'hmac-sha1': true,
  13. 'hmac-sha256': true,
  14. 'hmac-sha512': true
  15. };
  16. var Authorization =
  17. 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
  18. ///--- Specific Errors
  19. function MissingHeaderError(message) {
  20. this.name = 'MissingHeaderError';
  21. this.message = message;
  22. this.stack = (new Error()).stack;
  23. }
  24. MissingHeaderError.prototype = new Error();
  25. function InvalidAlgorithmError(message) {
  26. this.name = 'InvalidAlgorithmError';
  27. this.message = message;
  28. this.stack = (new Error()).stack;
  29. }
  30. InvalidAlgorithmError.prototype = new Error();
  31. ///--- Internal Functions
  32. function _pad(val) {
  33. if (parseInt(val, 10) < 10) {
  34. val = '0' + val;
  35. }
  36. return val;
  37. }
  38. function _rfc1123() {
  39. var date = new Date();
  40. var months = ['Jan',
  41. 'Feb',
  42. 'Mar',
  43. 'Apr',
  44. 'May',
  45. 'Jun',
  46. 'Jul',
  47. 'Aug',
  48. 'Sep',
  49. 'Oct',
  50. 'Nov',
  51. 'Dec'];
  52. var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  53. return days[date.getUTCDay()] + ', ' +
  54. _pad(date.getUTCDate()) + ' ' +
  55. months[date.getUTCMonth()] + ' ' +
  56. date.getUTCFullYear() + ' ' +
  57. _pad(date.getUTCHours()) + ':' +
  58. _pad(date.getUTCMinutes()) + ':' +
  59. _pad(date.getUTCSeconds()) +
  60. ' GMT';
  61. }
  62. ///--- Exported API
  63. module.exports = {
  64. /**
  65. * Adds an 'Authorization' header to an http.ClientRequest object.
  66. *
  67. * Note that this API will add a Date header if it's not already set. Any
  68. * other headers in the options.headers array MUST be present, or this
  69. * will throw.
  70. *
  71. * You shouldn't need to check the return type; it's just there if you want
  72. * to be pedantic.
  73. *
  74. * @param {Object} request an instance of http.ClientRequest.
  75. * @param {Object} options signing parameters object:
  76. * - {String} keyId required.
  77. * - {String} key required (either a PEM or HMAC key).
  78. * - {Array} headers optional; defaults to ['date'].
  79. * - {String} algorithm optional; defaults to 'rsa-sha256'.
  80. * - {String} httpVersion optional; defaults to '1.1'.
  81. * @return {Boolean} true if Authorization (and optionally Date) were added.
  82. * @throws {TypeError} on bad parameter types (input).
  83. * @throws {InvalidAlgorithmError} if algorithm was bad.
  84. * @throws {MissingHeaderError} if a header to be signed was specified but
  85. * was not present.
  86. */
  87. signRequest: function signRequest(request, options) {
  88. assert.object(request, 'request');
  89. assert.object(options, 'options');
  90. assert.optionalString(options.algorithm, 'options.algorithm');
  91. assert.string(options.keyId, 'options.keyId');
  92. assert.optionalArrayOfString(options.headers, 'options.headers');
  93. assert.optionalString(options.httpVersion, 'options.httpVersion');
  94. if (!request.getHeader('Date'))
  95. request.setHeader('Date', _rfc1123());
  96. if (!options.headers)
  97. options.headers = ['date'];
  98. if (!options.algorithm)
  99. options.algorithm = 'rsa-sha256';
  100. if (!options.httpVersion)
  101. options.httpVersion = '1.1';
  102. options.algorithm = options.algorithm.toLowerCase();
  103. if (!Algorithms[options.algorithm])
  104. throw new InvalidAlgorithmError(options.algorithm + ' is not supported');
  105. var i;
  106. var stringToSign = '';
  107. for (i = 0; i < options.headers.length; i++) {
  108. if (typeof (options.headers[i]) !== 'string')
  109. throw new TypeError('options.headers must be an array of Strings');
  110. var h = options.headers[i].toLowerCase();
  111. if (h !== 'request-line') {
  112. var value = request.getHeader(h);
  113. if (!value) {
  114. throw new MissingHeaderError(h + ' was not in the request');
  115. }
  116. stringToSign += h + ': ' + value;
  117. } else {
  118. stringToSign +=
  119. request.method + ' ' + request.path + ' HTTP/' + options.httpVersion;
  120. }
  121. if ((i + 1) < options.headers.length)
  122. stringToSign += '\n';
  123. }
  124. var alg = options.algorithm.match(/(hmac|rsa)-(\w+)/);
  125. var signature;
  126. if (alg[1] === 'hmac') {
  127. var hmac = crypto.createHmac(alg[2].toUpperCase(), options.key);
  128. hmac.update(stringToSign);
  129. signature = hmac.digest('base64');
  130. } else {
  131. var signer = crypto.createSign(options.algorithm.toUpperCase());
  132. signer.update(stringToSign);
  133. signature = signer.sign(options.key, 'base64');
  134. }
  135. request.setHeader('Authorization', sprintf(Authorization,
  136. options.keyId,
  137. options.algorithm,
  138. options.headers.join(' '),
  139. signature));
  140. return true;
  141. }
  142. };