From d60cc81ad2478ab26a11ff95acc97815827bf02f Mon Sep 17 00:00:00 2001 From: Marten de Vries Date: Sat, 19 Dec 2015 19:26:37 +0100 Subject: [PATCH] (pouchdb/express-pouchdb#232) - Add test suite & documentation --- .gitignore | 3 +- .travis.yml | 27 ++++ README.md | 126 ++++++++++++++- index.js | 13 +- package.json | 16 +- test/features.js | 394 +++++++++++++++++++++++++++++++++++++++++++++ test/http.js | 33 ++++ test/signatures.js | 9 ++ test/utils.js | 14 ++ 9 files changed, 614 insertions(+), 21 deletions(-) create mode 100644 .travis.yml create mode 100644 test/features.js create mode 100644 test/http.js create mode 100644 test/signatures.js create mode 100644 test/utils.js diff --git a/.gitignore b/.gitignore index de4d1f0..0e75fe5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ -dist node_modules +dist +coverage diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..2de911b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,27 @@ +sudo: false +language: node_js + +cache: + directories: + - node_modules + +node_js: + - "0.10" + +services: + - couchdb + +before_install: + - npm i -g npm@^2.0.0 + +before_script: + - npm prune + +script: npm run $COMMAND + +env: + matrix: + - COMMAND='helper -- lint' + - COMMAND='helper -- js-test' + - COMMAND='build' + diff --git a/README.md b/README.md index 8339738..7975338 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,126 @@ pouchdb-validation ================== -A PouchDB plug-in that allows you to re-use your CouchDB -validate_doc_update functions on the client side. A browser version is -available. +[![Build Status](https://travis-ci.org/pouchdb/pouchdb-validation.svg?branch=master)](https://travis-ci.org/pouchdb/pouchdb-validation) +[![Dependency Status](https://david-dm.org/pouchdb/pouchdb-validation.svg)](https://david-dm.org/pouchdb/pouchdb-validation) +[![devDependency Status](https://david-dm.org/pouchdb/pouchdb-validation/dev-status.svg)](https://david-dm.org/pouchdb/pouchdb-validation#info=devDependencies) -See also [pouchdb-validation's documentation](http://pythonhosted.org/Python-PouchDB/js-plugins.html#pouchdb-validation-plug-in) +> A PouchDB plug-in that allows you to re-use your CouchDB validate_doc_update functions on the client side. -[Website of this plug-in and a few others](http://python-pouchdb.marten-de-vries.nl/plugins.html) +A browser version is available. + +- [NodeJS package](https://www.npmjs.org/package/pouchdb-validation) +- Browser object name: ``window.validation`` + +First, make sure you understand how validation functions work in CouchDB. A good +start is [the CouchDB guide entry on validation functions](http://guide.couchdb.org/draft/validation.html). + +Usage +----- + +First, you need to register the plug-in with PouchDB. That can be done using the +``PouchDB.plugin()`` function. In NodeJS, you can just pass in the result of the +``require()`` function. In the browser, you pass in the browser object name +given above. + +An example (using the list plug-in): + +```javascript +//NodeJS (and Browserify) +PouchDB.plugin(require("pouchdb-validation")); + +//Browser - after the JavaScript file containing the plug-in has been +//included via a script tag (or something similar). +PouchDB.plugin(Validation); +``` + +All functions have two ways of returning the output to the user. One is +a callback parameter, which should have the signature ``(err, resp)``. +The other is the Promise all functions return. PouchDB itself uses the +same system. + +### db.validatingPut(doc[, options[, callback]]) +Exactly the same as the ``db.put`` function, but checks with all validation +functions ('validate_doc_update') in all design documents of the current +database if it is ok to save ``doc``. In short, this method acts more like its +CouchDB equivalent than the original PouchDB version does. The only thing you +get to see of it is a few extra errors, i.e. of the 'unauthorized' or the +'forbidden' type. It also has a few extra ``options`` (defaults are shown): + +- ``secObj``: e.g.: + + ```javascript + { + admins: { + names: [], + roles: [] + }, + members: { + names: [], + roles: [] + } + } + ``` + +- ``userCtx``: e.g.: + + ```javascript: + { + db: "test_db", + name: "username", + roles: [ + "_admin" + ] + } + ``` + +- ``checkHttp``: Set this to ``true`` if you want to validate HTTP database + documents offline too. Unnecessary for CouchDB, but handy for e.g. + pouchdb-express-router, which doesn't validate itself. + +### db.validatingPost(doc[, options[, callback]]) + +See the ``db.validatingPut()`` function. + +### db.validatingRemove(doc[, options[, callback]]) + +See the ``db.validatingPut()`` function. + +### db.validatingBulkDocs(bulkDocs[, options[, callback]]) + +See the ``db.validatingPut()`` function. Returns an array, like +``db.bulkDocs()``. The ``all_or_nothing`` attribute on ``bulkDocs`` is +unsupported. Also, the result array might not be in the same order as +the passed in documents. + +### db.validatingPutAttachment(docId, attachmentId, rev, attachment, type[, options[, callback]]) + +See the ``db.validatingPut()`` function. Output is the same as +``db.putAttachment()`` (except for a few extra errors being possible.) + +### db.validatingRemoveAttachment(docId, attachmentId, rev[, options[, callback]]) + +See the ``db.validatingPut()`` function. Output is the same as +``db.removeAttachment()`` (except for a few extra errors being possible.) + +### db.installValidationMethods() + +Installs the validation methods on this database. In other words, the ``db.*`` +methods are replaced by their ``db.validating*`` counterparts. This method is +always synchronous. + +**Throws**: an error if the methods are already installed. +**Returns**: nothing + +### db.uninstallValidationMethods() + +Undoes what ``db.installValidationMethods`` did. This method is always +synchronous. + +**Throws**: an error if the methods aren't currently installed. +**Returns**: nothing + +License +------- + +Apache-2.0 diff --git a/index.js b/index.js index efc8130..0a78a4c 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,5 @@ /* - Copyright 2013-2014, Marten de Vries + Copyright 2013-2015, Marten de Vries Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -60,9 +60,9 @@ function validate(validationFuncs, newDoc, oldDoc, options) { //passed all validation functions (no errors thrown) -> success } -function doValidation(db, newDoc, options, callback) { +function doValidation(db, newDoc, options) { var isHttp = ["http", "https"].indexOf(db.type()) !== -1; - if (isHttp && !(options || {}).checkHttp) { + if (isHttp && !options.checkHttp) { //CouchDB does the checking for itself. Validate succesful. return Promise.resolve(); } @@ -86,9 +86,6 @@ function doValidation(db, newDoc, options, callback) { } function completeValidationOptions(db, options) { - if (!options) { - options = {}; - } if (!options.secObj) { options.secObj = {}; } @@ -106,7 +103,7 @@ function completeValidationOptions(db, options) { }); } -function getValidationFunctions(db, callback) { +function getValidationFunctions(db) { return db.allDocs({ startkey: "_design/", endkey: "_design0", @@ -154,7 +151,7 @@ wrapperApi.bulkDocs = createBulkDocsWrapper(function (doc, args) { wrapperApi.putAttachment = function (orig, args) { return args.db.get(args.docId, {rev: args.rev, revs: true}) - .catch(function (err) { + .catch(function () { return {_id: args.docId}; }) .then(function (doc) { diff --git a/package.json b/package.json index 820fdba..813aee2 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,10 @@ "version": "1.2.1", "main": "index.js", "description": "A PouchDB plug-in that allows you to re-use your CouchDB validate_doc_update functions on the client side.", - "repository": "pouchdb/pouchdb-validation", + "repository": { + "type": "git", + "url": "https://github.com/pouchdb/pouchdb-validation.git" + }, "homepage": "http://python-pouchdb.marten-de-vries.nl/plugins.html", "keywords": [ "pouch", @@ -26,12 +29,11 @@ "pouchdb-bulkdocs-wrapper": "^1.0.0" }, "devDependencies": { - "browserify": "^4.1.8", - "uglify-js": "^2.4.13", - "es3ify": "^0.1.3" + "pouchdb-plugin-helper": "^2.0.0" }, - "scripts": { - "build-js": "mkdir -p dist && browserify index.js -g es3ify -s Validation -o dist/pouchdb-validation.js", - "build": "npm run build-js; cd dist; uglifyjs pouchdb-validation.js -mc > pouchdb-validation.min.js" + "scripts": { + "helper": "./node_modules/.bin/pouchdb-plugin-helper", + "test": "npm run helper -- test", + "build": "npm run helper -- build Validation" } } diff --git a/test/features.js b/test/features.js new file mode 100644 index 0000000..d2f1284 --- /dev/null +++ b/test/features.js @@ -0,0 +1,394 @@ +import {setup, setupWithDoc, setupWithDocAndAttachment, teardown, should, shouldThrowError, onlyTestValidationDoc} from './utils'; + +let db; + +describe('basic validation tests', () => { + beforeEach(async () => { + db = setup(); + await db.put(onlyTestValidationDoc); + }); + + afterEach(teardown); + + it('should allow put', async () => { + const doc = await db.validatingPut({_id: 'test'}); + doc.ok.should.be.ok; + }); + it('should allow post', async () => { + const doc = await db.validatingPost({_id: 'test'}); + doc.ok.should.be.ok; + }); + it('should allow remove', async() => { + const info = await db.put({_id: 'test'}); + const rmInfo = await db.validatingRemove({ + _id: 'test', + _rev: info.rev + }); + rmInfo.ok.should.be.ok; + }); + it('should allow bulkDocs', async () => { + const resp = await db.validatingBulkDocs([ + { + _id: 'test' + } + ]); + resp[0].should.be.ok; + }); + it('should allow putAttachment', (cb) => { + function getCb(resp) { + resp.toString('ascii').should.equal('Hello world!'); + cb(); + } + function putCb(err, resp) { + resp.ok.should.be.ok; + db.getAttachment('test', 'test').then(getCb) + } + const blob = new Buffer('Hello world!', 'ascii'); + db.validatingPutAttachment('test', 'test', blob, "text/plain", putCb); + }); + it('should fail', async () => { + //setup - put an attachment + const blob = new Buffer('Hello world!', 'ascii'); + const resp = await db.putAttachment('mytest', 'test', blob, 'text/plain'); + const error = await shouldThrowError(async () => { + await db.validatingRemoveAttachment('mytest', 'test', resp.rev); + }); + error.status.should.equal(403); + error.name.should.equal('forbidden'); + }); +}); + +describe('unauthorized validation tests', () => { + let rev; + beforeEach(async () => { + const data = await setupWithDoc(); + db = data.db; + rev = data.rev; + await db.put({ + _id: '_design/test', + validate_doc_update: `function (newDoc, oldDoc, userCtx, secObj) { + if (newDoc._id !== "test") { + throw({unauthorized: "only a document named 'test' is allowed."}); + } + }` + }); + }); + afterEach(teardown); + + function checkError(err) { + err.name.should.equal('unauthorized'); + err.message.should.equal("only a document named 'test' is allowed.") + } + + it('should fail an invalid put', async () => { + checkError(await shouldThrowError(async () => { + await db.validatingPut({_id: 'test_invalid'}); + })); + }); + it('should fail an invalid post', async () => { + checkError(await shouldThrowError(async () => { + await db.validatingPost({}); + })); + }); + it('should fail an invalid remove', async () => { + checkError(await shouldThrowError(async () => { + await db.validatingRemove({ + _id: 'mytest', + _rev: rev + }) + })); + }) + it('should fail an invalid bulkDocs', async () => { + // Also tests validatingBulkDocs with docs: [] property (which is + // deprecated, but still supported). + const resp = await db.validatingBulkDocs({ + docs: [ + { + _id: 'test_invalid' + } + ] + }); + checkError(resp[0]); + }); +}); + +describe('forbidden validation tests', async () => { + let rev; + beforeEach(async () => { + const data = await setupWithDoc(); + db = data.db; + rev = data.rev; + + await db.put(onlyTestValidationDoc); + }); + afterEach(teardown); + + function checkError(err) { + err.name.should.equal('forbidden'); + err.message.should.equal("only a document named 'test' is allowed."); + } + + it('should fail an invalid put', async () => { + checkError(await shouldThrowError(async () => { + await db.validatingPut({_id: 'test_invalid'}); + })); + }); + it('should fail an invalid post', async () => { + checkError(await shouldThrowError(async () => { + await db.validatingPost({}); + })); + }); + it('should fail an invalid remove', async () => { + checkError(await shouldThrowError(async () => { + await db.validatingRemove({ + _id: 'mytest', + _rev: rev + }) + })); + }); + it('should fail an invalid bulk docs', async () => { + const resp = await db.validatingBulkDocs([ + { + _id: 'test_invalid' + }, + {} + ]); + checkError(resp[0]); + checkError(resp[1]); + }); + it('should never fail a design doc', async () => { + // A design doc is always valid, so no matter the validate_doc_update + // function, the stuff below should succeed. + (await db.validatingPut({ + _id: '_design/mytest' + })).ok.should.be.ok; + }); + it('should never fail a local doc', async () => { + // A local doc is always valid, so no matter the validate_doc_update + // function, the stuff below should succeed. + await db.validatingPut({ + _id: '_local/mytest' + }); + }) +}); + +describe('compilation error validation tests', () => { + beforeEach(() => { + db = setup(); + }); + afterEach(teardown); + + function checkError(err) { + err.name.should.equal('compilation_error') + err.message.should.contain('Expression does not eval to a function.'); + } + + it('should fail syntax error', async () => { + await db.put({ + "_id": "_design/test", + "validate_doc_update": `function (newDoc, oldDoc, userCtx, secObj) { + return; + }324j3lkl;` + }); + checkError(await shouldThrowError(async () => { + await db.validatingPut({_id: 'test'}); + })); + }); + + it('should fail a non-function', async () => { + await db.put({ + _id: '_design/test', + validate_doc_update: "'a string instead of a function'" + }); + + checkError(await shouldThrowError(async () => { + await db.validatingPut({_id: 'test'}); + })); + }); +}); + +describe('exception validation tests', () => { + beforeEach(async () => { + db = setup(); + + await db.put({ + _id: '_design/test', + validate_doc_update: `function (newDoc, oldDoc, userCtx, secObj) { + //reference error + test; + }` + }) + }); + afterEach(teardown); + + it('should fail for put()', async () => { + const err = await shouldThrowError(async () => { + await db.validatingPut({_id: 'test'}); + }); + err.name.should.equal('ReferenceError'); + //'test' is the name of the missing variable. + err.message.should.contain('test') + }); +}); + +describe('attachment validation tests', async () => { + let rev; + const forbiddenDesignDoc = { + _id: '_design/test', + validate_doc_update: `function (newDoc, oldDoc, userCtx, secObj) { + throw({forbidden: JSON.stringify(newDoc)}); + }` + } + beforeEach(async () => { + const info = await setupWithDocAndAttachment(); + db = info.db; + rev = info.attRev; + }); + afterEach(teardown); + + it('should succesfully remove an attachment', async () => { + await db.validatingRemoveAttachment('attachment_test', 'text', rev); + }); + it("shouldn't remove the attachment when forbidden", async () => { + await db.put(forbiddenDesignDoc); + const err = await shouldThrowError(async () => { + await db.validatingRemoveAttachment('attachment_test', 'text', rev); + }); + err.name.should.equal('forbidden'); + // checks if the newDoc argument is filled in correctly + err.message.should.contain('"_attachments":{}'); + }); + it('should succesfully put an attachment', async () => { + await db.validatingPutAttachment('attachment_test2', 'text', new Buffer('tést', 'UTF-8'), 'text/plain'); + }); + it("shouldn't put an attachment when forbidden", async () => { + await db.put(forbiddenDesignDoc); + const err = await shouldThrowError(async () => { + await db.validatingPutAttachment('attachment_test2', 'text', new Buffer('tést', 'UTF-8'), 'text/plain'); + }); + err.name.should.equal('forbidden'); + // checks if the newDoc argument is filled in correctly + err.message.should.contain('text/plain'); + }); +}); + +describe('validation args tests', () => { + let rev; + beforeEach(async () => { + const info = await setupWithDoc(); + db = info.db; + rev = info.rev; + await db.put({ + _id: '_design/test', + validate_doc_update: `function (newDoc, oldDoc, userCtx, secObj) { + throw({forbidden: JSON.stringify({ + newDoc: newDoc, + oldDoc: oldDoc, + userCtx: userCtx, + secObj: secObj + })}); + }` + }); + }); + afterEach(teardown); + + it.skip('should have the right args with a new doc', async () => { + const doc = {_id: 'test'}; + const err = await shouldThrowError(async () => { + await db.validatingPut(doc); + }); + const i = JSON.parse(err.message); + i.newDoc.should.eql(doc); + should.not.exist(i.oldDoc); + + i.userCtx.should.eql({ + db: 'test', + name: null, + roles: ['_admin'] + }); + i.secObj.should.eql({}); + }); + it('should have the right args with an existing doc', async () => { + const doc = {_id: 'mytest', _rev: rev}; + const err = await shouldThrowError(async () => { + await db.validatingPut(doc); + }); + const i = JSON.parse(err.message); + i.oldDoc.test.should.be.ok; + i.oldDoc._revisions.should.have.property('ids'); + i.newDoc._revisions.should.have.property('ids'); + }); + it('should support changing the userCtx', async () => { + const theUserCtx = { + db: 'test', + name: 'pypouchtest', + roles: ['the_boss'] + } + + const err = await shouldThrowError(async () => { + await db.validatingPost({}, {userCtx: theUserCtx}); + }); + const i = JSON.parse(err.message); + i.userCtx.should.eql(theUserCtx); + }); + it('should support changing the security object', async () => { + const theSecObj = { + admins: { + names: ['the_boss'], + roles: [] + }, + members: { + names: [], + roles: [] + } + }; + + const err = await shouldThrowError(async () => { + await db.validatingPost({}, {secObj: theSecObj}); + }); + const i = JSON.parse(err.message); + + i.secObj.should.eql(theSecObj); + }); +}); + +describe('install validation methods tests', () => { + beforeEach(async () => { + db = setup(); + await db.put(onlyTestValidationDoc); + }); + afterEach(teardown); + + it('basics should work', async () => { + db.installValidationMethods(); + + const err = await shouldThrowError(async () => { + await db.put({_id: 'mytest'}); + }); + err.status.should.equal(403); + + db.uninstallValidationMethods(); + + const resp = await db.put({_id: 'mytest'}); + resp.ok.should.be.ok; + }); + it('should fail when installing twice', async () => { + db.installValidationMethods(); + const err = await shouldThrowError(async () => { + await db.installValidationMethods(); + }); + err.name.should.equal('already_installed'); + }); + it('should fail uninstalling when not installed', async () => { + const err = await shouldThrowError(async () => { + await db.uninstallValidationMethods(); + }); + err.name.should.equal('already_not_installed'); + }); + it('should support reinstalling methods', async () => { + for (let i = 0; i < 2; i++) { + db.installValidationMethods(); + db.uninstallValidationMethods(); + } + }); +}); diff --git a/test/http.js b/test/http.js new file mode 100644 index 0000000..eb2d275 --- /dev/null +++ b/test/http.js @@ -0,0 +1,33 @@ +import {setupHTTP, teardown, shouldThrowError, onlyTestValidationDoc} from './utils'; + +let db; +function before() { + db = setupHTTP(); +} + +describe('signature http tests', () => { + beforeEach(before); + afterEach(teardown); + it('should work with post', async () => { + // Tests one special validation case to complete JS coverage + await db.validatingPost({}); + }); +}); + +describe('http tests', () => { + beforeEach(before); + afterEach(teardown); + //FIXME: re-enable (related to bug report) + it.skip('should work', async () => { + await db.put(onlyTestValidationDoc); + const error = await shouldThrowError(async () => { + await db.validatingPost({}); + }); + error.status.should.equal(403); + error.name.should.equal('forbidden'); + error.message.should.equal("only a document named 'test' is allowed."); + + const resp = await db.validatingPut({_id: 'test'}); + resp.ok.should.be.ok; + }); +}); diff --git a/test/signatures.js b/test/signatures.js new file mode 100644 index 0000000..29c65ef --- /dev/null +++ b/test/signatures.js @@ -0,0 +1,9 @@ +import {setup, teardown} from './utils'; + +describe('callback usage', () => { + it('should allow passing in a callback', async () => { + const db = setup(); + await db.validatingPost({}, () => {}); + await teardown(); + }); +}); diff --git a/test/utils.js b/test/utils.js new file mode 100644 index 0000000..0dd67d4 --- /dev/null +++ b/test/utils.js @@ -0,0 +1,14 @@ +import Validation from '../'; +import stuff from 'pouchdb-plugin-helper/testutils'; + +stuff.PouchDB.plugin(Validation); +stuff.onlyTestValidationDoc = { + _id: '_design/test', + validate_doc_update: `function (newDoc, oldDoc, userCtx, secObj) { + if (newDoc._id !== "test") { + throw({forbidden: "only a document named 'test' is allowed."}); + } + }` +}; + +module.exports = stuff;