Code coverage report for lib\common\util\validate.js

Statements: 75.38% (150 / 199)      Branches: 66.02% (68 / 103)      Functions: 79.55% (35 / 44)      Lines: 75.38% (150 / 199)      Ignored: none     

All files » lib/common/util/ » validate.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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498                                1 1   1 1 1 1 1 1   1   1 2514 2514           2514 19   2514     2514                   1 111   111 111 111     111 165         111 111                 1 5 1   4                 1 144 1   143 143 143 2     141 141       141 2       139                 1                                         1 71   71 69   2                   1           1   1743         1743 3       1740 16     1724                 1 1038 1038 1038 1038     1038   1038 1032 1032   6                     1 2   2 2 2     2       2       2 2                 1 512 512 512 512     512   512 508 508   4                   1 193   193 193 193     193   193 189 189   4                   1 633   633 633 633     633       633 1     632 1     631   628 628   3                       1                                                                   1 111 111 111 333 333     111     111                 1                                           1 25   25 25 25     25       25 25         1 23     1 3073     1   3280 3266           1637           1980 1977 3         10199 23         2453 2453           112                       2459 2453       120                                 1 3073 3073     1 1
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var _ = require('underscore');
var util = require('util');
 
var constants = require('./../util/constants');
var blobConstants = constants.BlobConstants;
var FileUtilities = require('./../../services/file/fileutilities');
var azureutil = require('./util');
var SR = require('./sr');
var check = require('validator');
 
exports = module.exports;
 
function initCallback(callbackParam, resultsCb) {
  var fail;
  Iif (callbackParam) {
    fail = function (err) {
      callbackParam(new Error(err));
      return false;
    };
  } else {
    fail = function (err) {
      throw new Error(err);
    };
    callbackParam = function () {};
  }
 
  resultsCb(fail, callbackParam);
}
 
/**
* Checks if the given value is a valid enumeration or not.
*
* @param {object} value     The value to validate.
* @param {object} list      The enumeration values.
* @return {boolean}
*/
exports.isValidEnumValue = function (value, list, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  Iif (!list.some(function (current) {
    return current.toLowerCase() === value.toLowerCase();
  })) {
    return fail(util.format( 'Invalid value: %s. Options are: %s.', value, list));
  }
 
  callback();
  return true;
};
 
/**
* Creates a anonymous function that check if the given uri is valid or not.
*
* @param {string} uri     The uri to validate.
* @return {boolean}
*/
exports.isValidUri = function (uri) {
  if (!check.isURL(uri)){
    throw new Error('The provided URI "' + uri + '" is invalid.');
  }
  return true;
};
 
/**
* Checks if the given host is valid or not.
*
* @param {string|object} host     The host to validate.
* @return {boolean}
*/
exports.isValidHost= function (host) {
  if (azureutil.objectIsNull(host)) {
    throw new Error(SR.STORAGE_HOST_LOCATION_REQUIRED);
  } else {
    var storageHost = {};
    storageHost.primaryHost = _.isString(host) ? host : host.primaryHost;
    if (storageHost.primaryHost && !check.isURL(storageHost.primaryHost)){
      throw new Error('The provided URI "' + storageHost.primaryHost + '" is invalid.');
    }
 
    storageHost.secondaryHost = _.isString(host) ? undefined : host.secondaryHost;
    Iif (storageHost.secondaryHost && !check.isURL(storageHost.secondaryHost)){
      throw new Error('The provided URI "' + storageHost.secondaryHost + '" is invalid.');
    }
 
    if (!storageHost.primaryHost && !storageHost.secondaryHost) {
      throw new Error(SR.STORAGE_HOST_LOCATION_REQUIRED);
    }
  } 
 
  return true;
};
 
/**
* Checks if the given value is a valid UUID or not.
*
* @param {string|object} uuid     The uuid to validate.
* @return {boolean}
*/
exports.isValidUuid = function(uuid, callback) {
  var validUuidRegex = /^[a-zA-Z0-9]{8}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{12}$/;
 
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  if (!validUuidRegex.test(uuid)) {
    return fail('The value is not a valid UUID format.');
  }
};
 
/**
* Creates a anonymous function that check if a given key is base 64 encoded.
*
* @param {string} key The key to validate.
* @return {function}
*/
exports.isBase64Encoded = function (key) {
  var isValidBase64String = key.match(/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/);
 
  if (isValidBase64String) {
    return true;
  } else {
    throw new Error('The provided account key ' + key + ' is not a valid base64 string.');
  }
};
 
/**
* Validates a function.
*
* @param {object} function The function to validate.
* @return {function}
*/
exports.isValidFunction = function (functionObject, functionName) {
  if (!functionObject || !_.isFunction(functionObject)) {
    throw new Error(functionName + ' must be specified.');
  }
};
 
var getNameError = function(name) {
  // checks if name is null, undefined or empty
  Iif (azureutil.stringIsEmpty(name)) {
    return '%s name must be a non empty string.';
  }
 
  // check if name is between 3 and 63 characters
  if (name.length < 3 || name.length > 63) {
    return '%s name must be between 3 and 63 characters long.';
  }
 
  // check if name follows naming rules
  if (name.match(/^([a-z0-9]+(-[a-z0-9]+)*)$/) === null) {
    return '%s name format is incorrect.';
  }
 
  return null;
};
 
/**
* Validates a container name.
*
* @param {string} containerName The container name.
* @return {undefined}
*/
exports.containerNameIsValid = function (containerName, callback) {
  var fail;
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  var nameErrorString = getNameError(containerName);
 
  if (!nameErrorString || containerName.match(/^(\$root|\$logs)$/)) {
    callback();
    return true;
  } else {
    return fail(util.format(nameErrorString, 'Container'));
  }
};
 
/**
* Validates a blob name.
*
* @param {string} containerName The container name.
* @param {string} blobname      The blob name.
* @return {undefined}
*/
exports.blobNameIsValid = function (containerName, blobName, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
  
  Iif (!blobName) {
    return fail('Blob name is not specified.');
  }
  
  Iif (containerName === '$root' && blobName.indexOf('/') !== -1) {
    return fail('Blob name format is incorrect.');
  }
  
  callback();
  return true;
};
 
/**
* Validates a share name.
*
* @param {string} shareName The share name.
* @return {undefined}
*/
exports.shareNameIsValid = function (shareName, callback) {
  var fail;
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  var nameErrorString = getNameError(shareName);
 
  if (!nameErrorString) {
    callback();
    return true;
  } else {
    return fail(util.format(nameErrorString, 'Share'));
  }
};
 
/**
* Validates a queue name.
*
* @param {string} queueName The queue name.
* @return {undefined}
*/
exports.queueNameIsValid = function (queueName, callback) {
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  var nameErrorString = getNameError(queueName);
 
  if (!nameErrorString) {
    callback();
    return true;
  } else {
    return fail(util.format(nameErrorString, 'Queue'));
  }
};
 
/**
* Validates a table name.
*
* @param {string} table  The table name.
* @return {undefined}
*/
exports.tableNameIsValid = function (table, callback) {
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  Iif (azureutil.stringIsEmpty(table)) {
    return fail('Table name must be a non empty string.');
  }
 
  if (table.length < 3 || table.length > 63) {
    return fail('Table name must be between 3 and 63 characters long.');
  }
 
  if(table.toLowerCase() == 'tables') {
    return fail('Table name cannot be \'Tables\'.');
  }
 
  if (table.match(/^([A-Za-z][A-Za-z0-9]{2,62})$/) !== null || table === '$MetricsCapacityBlob' || table.match(/^(\$Metrics(HourPrimary|MinutePrimary|HourSecondary|MinuteSecondary)?(Transactions)(Blob|Queue|Table))$/) !== null) 
  {
    callback();
    return true;
  } else {
    return fail('Table name format is incorrect.');
  }
};
 
/**
* Validates page ranges.
*
* @param {int} rangeStart             The range starting position.
* @param {int} rangeEnd               The range ending position.
* @param {int} writeBlockSizeInBytes  The block size.
* @return {undefined}
*/
exports.pageRangesAreValid = function (rangeStart, rangeEnd, writeBlockSizeInBytes, callback) {
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  if (rangeStart % 512 !== 0) {
    return fail('Start byte offset must be a modulus of 512.');
  }
 
  var size = null;
  if (!azureutil.objectIsNull(rangeEnd)) {
    if ((rangeEnd + 1) % 512 !== 0) {
      return fail('End byte offset must be a modulus of 512 minus 1.');
    }
 
    size = (rangeEnd - rangeStart) + 1;
    if (size > this.writeBlockSizeInBytes) {
      return fail('Page blob size cant be larger than ' + writeBlockSizeInBytes + ' bytes.');
    }
  }
  
  callback();
  return true;
};
 
/**
* Validates a blob type.
*
* @param {string} type  The type name.
* @return {undefined}
*/
exports.blobTypeIsValid = function (type, callback) {
  var getEnumValues = function (obj) {
    var values = [];
    for (var prop in obj) {
      Eif (obj.hasOwnProperty(prop)) {
        values.push(obj[prop]);
      }
    }
    return values;
  };
  
  return this.isValidEnumValue(type, getEnumValues(blobConstants.BlobTypes), callback);
};
 
/**
* Validates share ACL type.
*
* @param {string} type  The type name.
* @return {undefined}
*/
exports.shareACLIsValid = function (type, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
  
  if (type != FileUtilities.SharePublicAccessType.OFF) {
    fail('The access type is not supported.');
  }
 
  callback();
  return true;
};
 
/**
* Validates share quota value.
*
* @param {int} type  The quota value.
* @return {undefined}
*/
exports.shareQuotaIsValid = function (quota, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
  
  Iif (quota && quota <= 0) {
    fail('The share quota value, in GB, must be greater than 0.');
  }
  
  callback();
  return true;
};
 
// common functions for validating arguments
 
function throwMissingArgument(name, func) {
  throw new Error('Required argument ' + name + ' for function ' + func + ' is not defined');
}
 
function ArgumentValidator(functionName) {
  this.func = functionName;
}
 
_.extend(ArgumentValidator.prototype, {
  string: function (val, name) {
    this.exists(val, name);
    Iif (typeof val !== 'string') {
      throw new Error('Parameter ' + name + ' for function ' + this.func + ' should be a non-empty string');
    }
  },
 
  stringAllowEmpty: function (val, name) {
    Iif (typeof val !== 'string') {
      throw new Error('Parameter ' + name + ' for function ' + this.func + ' should be a string');
    }
  },
 
  object: function (val, name) {
    this.exists(val, name);
    if (typeof val !== 'object') {
      throw new Error('Parameter ' + name + ' for function ' + this.func + ' should be an object');
    }
  },
 
  exists: function (val, name) {
    if (!val) {
      throwMissingArgument(name, this.func);
    }
  },
 
  function: function (val, name) {
    this.exists(val, name);
    Iif (typeof val !== 'function') {
      throw new Error('Parameter ' + name + ' for function ' + this.func + ' should be a function');
    }
  },
 
  value: function (val, name) {
    Iif (!val && val !== 0) {
      throwMissingArgument(name, this.func);
    }
  },
 
  nonEmptyArray: function (val, name) {
    if (!val || val.length === 0) {
      throw new Error('Required array argument ' + name + ' for function ' + this.func + ' is either not defined or empty');
    }
  },
 
  callback: function (val) {
    this.exists(val, 'callback');
    this.function(val, 'callback');
  },
 
  test: function (predicate, message) {
    Iif (!predicate()) {
      throw new Error(message + ' in function ' + this.func);
    }
  },
 
  tableNameIsValid: exports.tableNameIsValid,
  containerNameIsValid: exports.containerNameIsValid,
  shareNameIsValid: exports.shareNameIsValid,
  blobNameIsValid: exports.blobNameIsValid,
  pageRangesAreValid: exports.pageRangesAreValid,
  queueNameIsValid: exports.queueNameIsValid,
  blobTypeIsValid: exports.blobTypeIsValid,
  shareACLIsValid: exports.shareACLIsValid,
  shareQuotaIsValid: exports.shareQuotaIsValid,
  isValidEnumValue: exports.isValidEnumValue
});
 
function validateArgs(functionName, validationRules) {
  var validator = new ArgumentValidator(functionName);
  validationRules(validator);
}
 
exports.ArgumentValidator = ArgumentValidator;
exports.validateArgs = validateArgs;