All files datona-vault.js

95.73% Statements 157/164
97.8% Branches 89/91
85.11% Functions 40/47
94.81% Lines 128/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 499 500 501 502 503 504 505                                                  1x 1x 1x 1x 1x                                               176x 176x 134x 134x 134x   42x 42x 42x 42x                                       87x 87x 77x   13x   74x                 5x         5x 5x   5x 5x 4x                 15x 15x 13x 12x             12x 12x   12x 12x 8x                 18x 18x 16x 15x             15x 15x   15x 15x 12x                 30x 30x 28x           28x 28x   28x 28x 18x                 5x         5x 5x   5x 5x 4x                                 12x 10x 8x 8x                   94x 92x 92x 92x 90x   88x 7x 19x 22x 31x 7x   2x   86x   86x     6x 6x 6x                         7x       5x     15x                     20x 19x   11x           9x     30x                   33x 33x     23x 22x     22x 8x 7x     14x 12x       22x               15x 5x     10x       33x                         31x 20x         19x 19x 3x     16x       41x                     7x       4x     15x                                                                                                                                     49x 49x 49x                 66x                 1x                         134x 124x 109x   109x 104x 94x 94x 94x 94x 88x 52x       23x 23x              
"use strict";
 
/*
 * Datona Vault Library
 *
 * datona-lib vault features.
 *
 * Copyright (C) 2020 Datona Labs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */
 
const errors = require('./errors');
const assert = require('./assertions');
const crypto = require('./datona-crypto');
const comms = require('./datona-comms');
const blockchain = require('./datona-blockchain');
 
/*
 * Classes
 */
 
/*
 * Form for the name of a file within a vault.  File naming convention is as follows:
 *
 *     [directory/]<file>
 *
 * If the directory part is present it must be a single blockchain address and the file part can be any POSIX file name except . and ..
 * If not present then the file part must be a single blockchain address.
 * Nested directories are not permitted.
 *
 * E.g.:
 *    - Valid File:    0x0000000000000000000000000000000000000001
 *    - Valid File:    0x0000000000000000000000000000000000000002/my_file.txt
 *    - Invalid File:  my_file.txt
 *    - Invalid File;  0x0000000000000000000000000000000000000002/0x0000000000000000000000000000000000000001/my_file.txt
 */
class VaultFilename {
 
  constructor(filenameStr) {
    this.fullFilename = filenameStr;
    if (filenameStr.length <= 42) {
      this.isValid = assert.isAddress(filenameStr);
      this.file = filenameStr;
      this.hasDirectory = false;
    } else {
      this.directory = filenameStr.substring(0, 42);
      this.file = filenameStr.substring(43);
      this.hasDirectory = true;
      this.isValid =
        assert.isAddress(this.directory) &&
        filenameStr[42] === '/' &&                       // valid separator
        /^[^\0\/]*$/.test(this.file) &&                  // POSIX files can be any string but must not contain null or '/'
        this.file.length > 0 &&
        this.file !== "." &&                             // must not be a special file
        this.file !== "..";
    }
  };
 
}
 
 
/*
 * An instance of this class represents a single vault within a vault server
 * controlled by a single S-DAC.
 */
class RemoteVault extends comms.DatonaConnector {
 
  constructor(url, contractAddress, localPrivateKey, remoteAddress) {
    try {
      super(url, localPrivateKey, remoteAddress);
      assert.isAddress(contractAddress, "contractAddress");
    } catch (error) {
      throw new errors.VaultError("Failed to construct vault: " + error.message, error.details);
    }
    this.contract = contractAddress;
  }
 
 
  /*
   * Promises to create the vault on the remote server.  This method creates the
   * data request, signs it, initiates the request and validates the response.
   */
  create(options) {
    const request = {
      txnType: "VaultRequest",
      requestType: "create",
      contract: this.contract,
    };
    if (options !== undefined) request.options = options;
    return this.send(request)
      .then( function(response){
        comms.validateResponse(response.txn, "VaultResponse");
        if (response.txn.responseType === "error") throw errors.fromObject(response.txn.error);
        return response;
      });
  }
 
 
  /*
   * Promises to write or rewrite the given file of this vault.
   */
  write(data, file = blockchain.ZERO_ADDRESS, options) {
    const vaultFile = new VaultFilename(file);
    if (!vaultFile.isValid) throw new errors.TypeError("file: invalid filename");
    assert.isPresent(data, "data");
    const request = {
      txnType: "VaultRequest",
      requestType: "write",
      contract: this.contract,
      file: file,
      data: data
    };
    if (options !== undefined) request.options = options;
    return this.send(request)
      .then( function(response){
        comms.validateResponse(response.txn, "VaultResponse");
        if (response.txn.responseType === "error") throw errors.fromObject(response.txn.error);
        return response;
      });
  }
 
 
  /*
   * Promises to append to the given file of this vault.
   */
  append(data, file = blockchain.ZERO_ADDRESS, options) {
    const vaultFile = new VaultFilename(file);
    if (!vaultFile.isValid) throw new errors.TypeError("file: invalid filename");
    assert.isPresent(data, "data");
    const request = {
      txnType: "VaultRequest",
      requestType: "append",
      contract: this.contract,
      file: file,
      data: data
    };
    if (options !== undefined) request.options = options;
    return this.send(request)
        .then( function(response){
          comms.validateResponse(response.txn, "VaultResponse");
          if (response.txn.responseType === "error") throw errors.fromObject(response.txn.error);
          return response;
        });
  }
 
 
  /*
   * Promises to retrieve the data held in this vault, if permitted by the contract.
   */
  read(file = blockchain.ZERO_ADDRESS, options) {
    const vaultFile = new VaultFilename(file);
    if (!vaultFile.isValid) throw new errors.TypeError("file: invalid filename");
    const request = {
      txnType: "VaultRequest",
      requestType: "read",
      contract: this.contract,
      file: file
    };
    if (options !== undefined) request.options = options;
    return this.send(request)
      .then( function(response){
        comms.validateResponse(response.txn, "VaultResponse");
        if (response.txn.responseType === "error") throw errors.fromObject(response.txn.error);
        return response.txn.data;
      });
  }
 
 
  /*
   * Promises to delete the vault and its data, if permitted by the contract.
   */
  delete(options) {
    const request = {
      txnType: "VaultRequest",
      requestType: "delete",
      contract: this.contract
    };
    if (options !== undefined) request.options = options;
    return this.send(request)
      .then( function(response){
        comms.validateResponse(response.txn, "VaultResponse");
        if (response.txn.responseType === "error") throw errors.fromObject(response.txn.error);
        return response;
      });
  }
 
}
 
 
/*
 * Guardian of a Vault Data Server.  All create, update, access and delete requests
 * go through the Vault Keeper, where they are approved or rejected against the
 * Datona Smart Data Access Protocol.  If approved and permission granted by
 * the vault's Smart Data Access Contract, the raw request is passed to the
 * given VaultDataServer object.
 */
class VaultKeeper {
 
  constructor(vaultDataServer, key) {
    assert.isInstanceOf(vaultDataServer, "VaultKeeper vaultDataServer", VaultDataServer);
    assert.isInstanceOf(key, "VaultKeeper key", crypto.Key);
    this.key = key;
    this.vaultDataServer = vaultDataServer;
  }
 
 
  /*
   * Decodes and processes a signed VaultRequest, checking the validity of the
   * signature, validating the request and executing it via the
   * VaultDataServer
   */
  handleSignedRequest(signedRequestStr) {
    assert.isString(signedRequestStr, "VaultKeeper handleSignedRequest signedRequestStr");
    const key = this.key;
    try {
      const {txn, signatory} = comms.decodeTransaction(signedRequestStr);
      if (txn.txnType !== "VaultRequest") throw new errors.RequestError("Invalid transaction type ('"+txn.txnType+"')");
      var func;
      switch (txn.requestType) {
        case "create": func = this.createVault.bind(this); break;
        case "write": func = this.writeVault.bind(this); break;
        case "append": func = this.appendVault.bind(this); break;
        case "read": func = this.readVault.bind(this); break;
        case "delete": func = this.deleteVault.bind(this); break;
        default:
          throw new errors.InvalidTransactionError("Invalid request type ('" + txn.requestType + "')");
      }
      return func(txn, signatory)
        .then( function encode(response){
          return comms.encodeTransaction(response, key);
        });
    } catch (error) {
      const exception = error instanceof errors.DatonaError ? error : new errors.TransactionError("VaultKeeper handleSignedRequest: "+error.message);
      return new Promise(function(resolve, reject) {
        resolve(comms.encodeTransaction(createErrorResponse(exception), key));
      });
    }
  }
 
 
  /*
   * Handles a valid create request and promises to create a new vault via the
   * VaultDataServer.
   */
  createVault(request, signatory) {
 
    function checkPermissions(contract, signatory, file) {
      return contract.assertOwner(signatory).then(contract.assertNotExpired.bind(contract));
    }
 
    function callDataServer(contractAddress, file, data, options) { // bound to this instance
      return this.vaultDataServer.create(contractAddress, options);
    }
 
    return _handleVaultKeeperRequest("create", request, signatory, checkPermissions, callDataServer.bind(this));
  }
 
 
  /*
   * Handles a valid write request and promises to write the vault via the
   * VaultDataServer.
   */
  writeVault(request, signatory) {
 
    function checkPermissions(contract, signatory, vaultFile) {
      if (!assert.isNotNull(request.data)) throw new errors.MalformedTransactionError("Missing request data field");
      return contract.assertCanWrite(signatory, (vaultFile.hasDirectory ? vaultFile.directory : vaultFile.file))
        .then( (permissions) => {
          if (permissions.isDirectory() && !vaultFile.hasDirectory) throw new errors.PermissionError("Cannot write to a directory")
        })
        .then(contract.assertNotExpired.bind(contract));
    }
 
    function callDataServer(contractAddress, file, data, options) { // bound to this instance
      return this.vaultDataServer.write(contractAddress, file, data, options);
    }
 
    return _handleVaultKeeperRequest("write", request, signatory, checkPermissions, callDataServer.bind(this));
  }
 
 
  /*
   * Handles a valid append request and promises to append to the vault via the
   * VaultDataServer.
   */
  appendVault(request, signatory) {
 
    var directoryIsWritable = false;
    var fileWithinDirectory = false;
 
    function checkPermissions(contract, signatory, vaultFile) {
      if (!assert.isNotNull(request.data)) throw new errors.MalformedTransactionError("Missing request data field");
      fileWithinDirectory = vaultFile.hasDirectory;
 
      function checkFileOrDirectoryPermissions(permissions) {
        if (vaultFile.hasDirectory) { // file within a directory.  Permit append if directory has either append or full write permissions.
          if (permissions.canWrite() === false && permissions.canAppend() === false) throw new errors.PermissionError("permission denied");
          directoryIsWritable = permissions.canWrite();
        }
        else { // file or directory in the root
          if (permissions.isDirectory() && !vaultFile.hasDirectory) throw new errors.PermissionError("Cannot append data to a directory")
          if (permissions.canAppend() === false) throw new errors.PermissionError("permission denied");
        }
      }
 
      return contract.getPermissions(signatory, (vaultFile.hasDirectory ? vaultFile.directory : vaultFile.file))
        .then(checkFileOrDirectoryPermissions)
        .then(contract.assertNotExpired.bind(contract));
    }
 
    function callDataServer(contractAddress, file, data, options) { // bound to this instance
      // If appending to a directory that is not fully writable then this is a createFile command.
      // Otherwise it is an unconditional append which will create the file if it doesn't exist or append the data if it does.
      if (fileWithinDirectory && !directoryIsWritable) {
        return this.vaultDataServer.createFile(contractAddress, file, data, options);
      }
      else {
        return this.vaultDataServer.append(contractAddress, file, data, options);
      }
    }
 
    return _handleVaultKeeperRequest("append", request, signatory, checkPermissions, callDataServer.bind(this));
  }
 
 
  /*
   * Handles a valid read request and promises to return the data from the
   * vault via VaultDataServer.
   */
  readVault(request, signatory) {
 
    var filePermissions;
 
    function checkPermissions(contract, signatory, vaultFile) {
      return contract.assertCanRead(signatory, (vaultFile.hasDirectory ? vaultFile.directory : vaultFile.file))
        .then( function(permissions){ filePermissions = permissions; })
        .then(contract.assertNotExpired.bind(contract));
     }
 
    function callDataServer(contractAddress, file, data, options) { // bound to this instance
      const vaultFile = new VaultFilename(file);
      if (filePermissions.isDirectory() && !vaultFile.hasDirectory) {
        return this.vaultDataServer.readDir(contractAddress, file, options);
      }
      else{
        return this.vaultDataServer.read(contractAddress, file, options);
      }
    }
 
    return _handleVaultKeeperRequest("read", request, signatory, checkPermissions, callDataServer.bind(this));
  }
 
 
  /*
   * Handles a valid delete request and promises to delete the vault via the
   * VaultDataServer.
   */
  deleteVault(request, signatory) {
 
    function checkPermissions(contract, signatory, file) {
      return contract.assertOwner(signatory).then(contract.assertHasExpired.bind(contract));
    }
 
    function callDataServer(contractAddress, file, data, options) { // bound to this instance
      return this.vaultDataServer.delete(contractAddress, options);
    }
 
    return _handleVaultKeeperRequest("delete", request, signatory, checkPermissions, callDataServer.bind(this));
  }
 
}
 
 
/*
 * Interface.  A class that implements this interface must be given to the
 * VaultKeeper on construction to provide the data vault server capability.
 */
class VaultDataServer {
 
  constructor() {};
 
  /*
   * Unconditionally creates a new vault controlled by the given contract.
   */
  create(contract, options) { throw new errors.DeveloperError("Vault server's create function has not been implemented"); };
 
  /*
   * Unconditionally creates or overwrites data in a file within the vault controlled by the given contract.
   */
  write(contract, file, data, options) { throw new errors.DeveloperError("Vault server's write has not been implemented"); };
 
  /*
   * Creates a new file within the vault controlled by the given contract and writes the given data to it.
   * Must throw a VaultError if the file already exists
   */
  createFile(contract, file, data, options)  { throw new errors.DeveloperError("Vault server's createFile has not been implemented"); };
 
  /*
   * Unconditionally appends data to a file within the vault controlled by the given contract.
   */
  append(contract, file, data, options) { throw new errors.DeveloperError("Vault server's append has not been implemented"); };
 
  /*
   * Unconditionally reads the data from a file within the vault controlled by the given contract.
   */
  read(contract, file, options) { throw new errors.DeveloperError("Vault server's read function has not been implemented"); };
 
  /*
   * Unconditionally reads a list of the files from a directory within the vault controlled by the given contract.
   * Returns the list as a '\n' separated string of the form
   *    [<file1>][\n<file2>]...
   * If no files exist then the empty string is returned.
   */
  readDir(contract, dir, options) { throw new errors.DeveloperError("Vault server's readDir function has not been implemented"); };
 
  /*
   * Unconditionally deletes a file controlled by the given contract.  If the file is null then the
   * entire vault is deleted.
   */
  delete(contract, file, options) { throw new errors.DeveloperError("Vault server's delete function has not been implemented"); };
 
}
 
 
/*
 * External Functions
 */
 
 
/*
 * Constructs a success VaultResponse to return from a Vault Server in response
 * to a VaultRequest
 */
function createSuccessResponse(data) {
 var response = comms.createSuccessResponse("VaultResponse");
 response.data = data;
 return response;
}
 
 
/*
 * Constructs a failure VaultResponse to return from a Vault Server in response
 * to a VaultRequest
 */
function createErrorResponse(error) {
  return comms.createErrorResponse(error, "VaultResponse");
}
 
 
 
/*
 * Exports
 */
 
module.exports = {
  RemoteVault: RemoteVault,
  VaultKeeper: VaultKeeper,
  VaultDataServer: VaultDataServer
};
 
 
 
/*
 * Internal Functions
 */
 
function _handleVaultKeeperRequest(requestType, request, signatory, permissionFunction, dataServerFunction) {
  assert.isObject(request, "VaultKeeper "+requestType+"Vault request");
  assert.isAddress(signatory, "VaultKeeper "+requestType+"Vault signatory");
  try {
    // validate the request and obtain the contract
    if (request.requestType !== requestType) throw new errors.InvalidTransactionError("attempted to "+requestType+" a vault with an invalid request type '"+request.requestType+"'");
    if (!assert.isAddress(request.contract)) throw new errors.MalformedTransactionError("Invalid request contract field", request.contract);
    const contract = new blockchain.GenericSmartDataAccessContract(request.contract);
    const file = (request.file !== undefined) ? request.file : blockchain.ZERO_ADDRESS;
    const vaultFile = new VaultFilename(file);
    if (!vaultFile.isValid) throw new errors.MalformedTransactionError("invalid file");
    return permissionFunction(contract, signatory, vaultFile)
      .then( function(){ return dataServerFunction(request.contract, file, request.data, request.options) })
      .then(createSuccessResponse)
      .catch(createErrorResponse);
  } catch (error) {
    const exception = error instanceof errors.DatonaError ? error : new errors.TransactionError("VaultKeeper "+requestType+"Vault: "+error.message);
    return new Promise(function(resolve, reject) { resolve(createErrorResponse(exception)) });
  }
}