diff --git a/.travis.yml b/.travis.yml index ae0d2ba..3d33488 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,6 +17,7 @@ notifications: skip_join: false before_install: + - npm install -g npm@2 - npm config set spin false before_script: diff --git a/bin/db_patcher.js b/bin/db_patcher.js old mode 100644 new mode 100755 diff --git a/bin/mem.js b/bin/mem.js new file mode 100644 index 0000000..3a6049b --- /dev/null +++ b/bin/mem.js @@ -0,0 +1,43 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var config = require('../config') +var dbServer = require('fxa-auth-db-server') +var error = dbServer.errors +var logger = require('../lib/logging')('bin.server') +var DB = require('../lib/db/mem')(logger, error) + +function shutdown() { + process.nextTick(process.exit) +} + +// defer to allow ass code coverage results to complete processing +if (process.env.ASS_CODE_COVERAGE) { + process.on('SIGINT', shutdown) +} + +DB.connect(config) + .done(function (db) { + var server = dbServer.createServer(db) + server.listen(config.port, config.hostname, function() { + logger.info('start', { port : config.port }) + }) + server.on('error', function (err) { + logger.error('start', { message: err.message }) + }) + server.on('success', function (d) { + logger.info('summary', d) + }) + server.on('failure', function (err) { + if (err.statusCode >= 500) { + logger.error('summary', err) + } + else { + logger.warn('summary', err) + } + }) + server.on('mem', function (stats) { + logger.info('mem', stats) + }) + }) diff --git a/fxa-auth-db-server/.eslintrc b/fxa-auth-db-server/.eslintrc new file mode 100644 index 0000000..27705a7 --- /dev/null +++ b/fxa-auth-db-server/.eslintrc @@ -0,0 +1,5 @@ +extends: fxa/server + +rules: + handle-callback-err: 0 + semi: [2, "never"] diff --git a/fxa-auth-db-server/.gitignore b/fxa-auth-db-server/.gitignore new file mode 100644 index 0000000..654e80a --- /dev/null +++ b/fxa-auth-db-server/.gitignore @@ -0,0 +1,6 @@ +node_modules +coverage.html +sandbox +*.log +*.swp +*~ diff --git a/fxa-auth-db-server/.travis.yml b/fxa-auth-db-server/.travis.yml new file mode 100644 index 0000000..d2e4a85 --- /dev/null +++ b/fxa-auth-db-server/.travis.yml @@ -0,0 +1,39 @@ +language: node_js + +node_js: + - "0.10" + - "0.12" + - "iojs-v1" + - "iojs-v2" + +notifications: + email: + - dcoates@mozilla.com + - achilton@mozilla.com + - jrgm@mozilla.com + - rfkelly@mozilla.com + irc: + channels: + - "irc.mozilla.org#fxa" + use_notice: false + skip_join: false + +before_install: + - npm config set spin false + +before_script: + - npm i grunt-cli -g + - npm run outdated + +install: + - npm install + +script: + - npm test + +matrix: + allow_failures: + - node_js: "0.12" + - node_js: "iojs-v1" + - node_js: "iojs-v2" + fast_finish: true diff --git a/fxa-auth-db-server/AUTHORS b/fxa-auth-db-server/AUTHORS new file mode 100644 index 0000000..49b3f71 --- /dev/null +++ b/fxa-auth-db-server/AUTHORS @@ -0,0 +1,5 @@ +Andrew Chilton +Danny Coates +John Morrison +Peter deHaan +Ryan Kelly diff --git a/fxa-auth-db-server/CHANGELOG b/fxa-auth-db-server/CHANGELOG new file mode 100644 index 0000000..a0a6bdc --- /dev/null +++ b/fxa-auth-db-server/CHANGELOG @@ -0,0 +1,93 @@ +train-39 + * add check password api - #141 + * docs(api): Server_API.md docs - #145 + * chore(license): Update license to be SPDX compliant - #142 + * refactor(lib): Move source files into lib/ to tidy up - #140 + * build(travis): Test on both io.js v1 and v2 - #139 + +train-36 + * chore(test): Test on node.js v0.10, v0.12 and the latest io.js - #138 + * chore(copyright): Update to grunt-copyright v0.2.0 - #137 + * refactor(tests): Generate test UIDs a different way (from crypto.randomBytes) - #136 + * docs(db): Add docs to help with developing the db repos - #126 + +train-35 + * fix(shrinkwrap): as discussed, only "top-level" repos get shrunkwrapped + * docs(changelog): belatedly add changelog note for train-34 + +train-34 + * fix(db): set createdAt, verifierSetAt and normalizedEmail in the tests - #130 + * fix(release): add tasks "grunt version" and "grunt version:patch" to create release tags - #132 + * docs(readme): better readme for help implementing a storage backend - #129 + +train-33 + * Tweak logging for compatibility with mozlog - #127 + * Emit memory stats for operational logging - #128 + +train-32 + * Add ability to mark an account as "locked" for security reasons - #123, #124 + +train-31 + * Implemented the reverse backend, so now storage repos load the server + +train-29 + * Add a CONTRIBUTING.md and an AUTHORS file - #104, #117 + * Remove references to the old .fxa_dbrc config file - #107, #113 + * Failed stored procedures return errors correctly - #95, #94 + * Add a unique index to passwordChangeTokens(uid) - #100 + * fix(build): Adding --force flag onto grunt validate-shrinkwrap task - #98 + * Update convict to newer version - #96 + * NOTE: This train will require the addition of stored procedures and a new + index on passwordChangeTokens to the stage and production databases + +train-24 + * Use the DB stored procedures, instead of raw SQL - #84 + * NOTE: This train will require the addition of stored procedures to the stage and production databases + +train-23 + * no-op. Rebuild to use nodejs 0.10.32 + +train-22 + * licence, jshint miscellany + +train-21 + * remove patchLevel from config, now in code - #69, #70 + * update node-ass version - #75 + * Use named mysql error constants rather than raw magic numbers - #74 + * show prune messages at loglevel info - #73 + +train-20 + * add code to remove stale tokens from + fxa.{accountReset,passwordForgot,passwordChange}Tokens tables - issue #2 + - adds PROCEDURE `prune` to fxa database + - controlled by options `pruneEvery' and `enablePruning' + * pass err.stack so bunyan actually prints more than "uncaughtException" - #68 + * updates to use `mysql-patcher' modules in place of db_patcher script - #71, #72 + +train-19 + * Switch to convict for config + * update ass version + * update restify and request for new qs module + +train-18 + * use a version of ass that does not pull in gh-badges at all: #58 + * email argument is already a buffer: #56, #57 + * add shrinkwrap; npm shrinkwrap --dev: #54 + * fixed log object not having 'stat' in tests + +train-17 + * added locale to accounts #53 + +train-16 + * NSTR + +train-15 + * code cleanup and test addition + +train-14 + * fix #33 - retryable is matching errno on the wrong object in some cases + * more tests + * fix coverage stats + +train-13 + * initial version diff --git a/fxa-auth-db-server/CONTRIBUTING.md b/fxa-auth-db-server/CONTRIBUTING.md new file mode 100644 index 0000000..eea2849 --- /dev/null +++ b/fxa-auth-db-server/CONTRIBUTING.md @@ -0,0 +1,83 @@ +# Contributing + +Anyone is welcome to help with Firefox Accounts. Feel free to get in touch with other community members on IRC, the +mailing list or through issues here on GitHub. + +- IRC: `#fxa` on `irc.mozilla.org` +- Mailing list: +- and of course, [the issues list](https://github.com/mozilla/fxa-auth-db-server/issues) + +## Bug Reports ## + +You can file issues here on GitHub. Please try to include as much information as you can and under what conditions +you saw the issue. + +## Sending Pull Requests ## + +Patches should be submitted as pull requests (PR). + +Before submitting a PR: +- Your code must run and pass all the automated tests before you submit your PR for review. "Work in progress" pull requests are allowed to be submitted, but should be clearly labeled as such and should not be merged until all tests pass and the code has been reviewed. + - Run `grunt jshint` to make sure your code passes linting. + - Run `npm test` to make sure all tests still pass. +- Your patch should include new tests that cover your changes. It is your and your reviewer's responsibility to ensure your patch includes adequate tests. + +When submitting a PR: +- You agree to license your code under the project's open source license ([MPL 2.0](/LICENSE)). +- Base your branch off the current `master` (see below for an example workflow). +- Add both your code and new tests if relevant. +- Run `grunt jshint` and `npm test` to make sure your code passes linting and tests. +- Please do not include merge commits in pull requests; include only commits with the new relevant code. + +After your PR is merged: +- Add yourself to the [AUTHORS](/AUTHORS) file so we can publicly recognize your contribution. + +See the main [README.md](/README.md) for information on prerequisites, installing, running and testing. + +## Code Review ## + +This project is production Mozilla code and subject to our [engineering practices and quality standards](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Committing_Rules_and_Responsibilities). Every patch must be peer reviewed. This project is part of the [Firefox Accounts module](https://wiki.mozilla.org/Modules/Other#Firefox_Accounts), and your patch must be reviewed by one of the listed module owners or peers. + +## Example Workflow ## + +This is an example workflow to make it easier to submit Pull Requests. Imagine your username is `user1`: + +1. Fork this repository via the GitHub interface + +2. The clone the upstream (as origin) and add your own repo as a remote: + + ```sh + $ git clone https://github.com/mozilla/fxa-auth-db-server.git + $ cd fxa-auth-db-server + $ git remote add user1 git@github.com:user1/fxa-auth-db-server.git +``` + +3. Create a branch for your fix/feature and make sure it's your currently checked-out branch: + + ```sh + $ git checkout -b add-new-feature +``` + +4. Add/fix code, add tests then commit and push this branch to your repo: + + ```sh + $ git add + $ git commit + $ git push user1 add-new-feature +``` + +5. From the GitHub interface for your repo, click the `Review Changes and Pull Request` which appears next to your new branch. + +6. Click `Send pull request`. + +### Keeping up to Date ### + +The main reason for creating a new branch for each feature or fix is so that you can track master correctly. If you need +to fetch the latest code for a new fix, try the following: + +```sh +$ git checkout master +$ git pull +``` + +Now you're ready to branch again for your new feature (from step 3 above). diff --git a/fxa-auth-db-server/Gruntfile.js b/fxa-auth-db-server/Gruntfile.js new file mode 100644 index 0000000..d32d3a0 --- /dev/null +++ b/fxa-auth-db-server/Gruntfile.js @@ -0,0 +1,12 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +module.exports = function (grunt) { + + require('load-grunt-tasks')(grunt) + + grunt.loadTasks('grunttasks') + + grunt.registerTask('default', ['eslint', 'copyright']) +} diff --git a/fxa-auth-db-server/LICENSE b/fxa-auth-db-server/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/fxa-auth-db-server/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/fxa-auth-db-server/README.md b/fxa-auth-db-server/README.md new file mode 100644 index 0000000..13c534a --- /dev/null +++ b/fxa-auth-db-server/README.md @@ -0,0 +1,71 @@ +Firefox Accounts DB Server +========================== + +[![Build Status](https://travis-ci.org/mozilla/fxa-auth-db-server.svg?branch=master)](https://travis-ci.org/mozilla/fxa-auth-db-server) + +## Usage + +If you would like to run an FxA Auth DB Server, then you probably want to look at the +[FxA Auth DB MySql](http://github.com/mozilla/fxa-auth-db-mysql/) repo (for production usage) or the +[FxA Auth DB Mem](http://github.com/mozilla/fxa-auth-db-mem/) repo (for testing purposes). Each of these repos +implement a storage backend and will install this repo when you run `npm install` since they each import the server +from here. + +## Usage + +```js +// Require the dbServer. This includes dbServer.createServer() and the dbServer.errors object. +var dbServer = require('fxa-auth-db-server') + +// require the database engine +var Store = require('./db.js') + +// create a DB instance and pass a logger and the dbServer.errors object +var db = new Store(console, dbServer.errors) + +// create the server and pass it the storage instance +var server = dbServer.createServer(db) + +server.listen(8080, 'localhost', function() { + console.log('Server is listening') +}) + +// this will be called at the end of each failed request +server.on('error', function (err) { + console.error('Error when starting the server:', err) +}) + +// this will be called at the end of each successful request +server.on( + 'success', + function (data) { + console.log('+ %s %s took %dms', data.method, data.url, data.t) + } +) + +// this will be called at the end of each failed request +server.on( + 'failure', + function (data) { + console.warn('- %s %s failed with %d', data.method, data.url, data.err.code) + } +) + +// this will be called every 15s +server.on( + 'mem', + function (stats) { + console.log('Memory stats:', stats) + } +) +``` + +## DB API + +If you would like to implement a +[database/storage API](https://github.com/mozilla/fxa-auth-db-server/blob/master/docs/DB_API.md), this document will be +useful. + +## License + +MPL 2.0 diff --git a/fxa-auth-db-server/docs/DB_API.md b/fxa-auth-db-server/docs/DB_API.md new file mode 100644 index 0000000..a8cfa86 --- /dev/null +++ b/fxa-auth-db-server/docs/DB_API.md @@ -0,0 +1,339 @@ +# DB API # + +There are a number of methods that a DB storage backend should implement: + +* Accounts (using `uid`) + * .createAccount(uid, data) + * .account(uid) + * .checkPassword(uid, hash) + * .verifyEmail(uid) + * .accountDevices(uid) + * .resetAccount(uid, data) + * .deleteAccount(uid) +* Accounts (using `email`) + * .emailRecord(emailBuffer) + * .accountExists(emailBuffer) +* Session Tokens + * .createSessionToken(tokenId, sessionToken) + * .sessionToken(id) + * .deleteSessionToken(tokenId) +* Key Fetch Tokens + * .createKeyFetchToken(tokenId, keyFetchToken) + * .keyFetchToken(id) + * .deleteKeyFetchToken(tokenId) +* Password Forgot Tokens + * .createPasswordForgotToken(tokenId, passwordForgotToken) + * .deletePasswordForgotToken(tokenId) + * .passwordForgotToken(id) + * .updatePasswordForgotToken(tokenId, token) + * .forgotPasswordVerified(tokenId, accountResetToken) +* Password Change Tokens + * .createPasswordChangeToken(tokenId, passwordChangeToken) + * .passwordChangeToken(id) + * .deletePasswordChangeToken(tokenId) +* Account Reset Tokens + * .createAccountResetToken(tokenId, accountResetToken) + * .accountResetToken(id) + * .deleteAccountResetToken(tokenId) +* General + * .ping() + * .close() + +## Types ## + +# Parameters # + +The types of each parameter is shown in brackets below. In some cases an extra clarification +is shown afterwards. + +* number - a number (integer only) +* string - a string of undetermined length +* Buffer - a Buffer of undetermined length +* Buffer16 - a Buffer of length 16 bytes +* Buffer32 - a Buffer of length 32 bytes +* Buffer64 - a Buffer of length 64 bytes + +The storage backends are not meant to be clever. They never infer anything and they shouldn't +default anything. The `fxa-auth-server` defaults everything it needs to. Backends shouldn't +default anything in code or in the datastore (either by default values or triggers). + +Please note that when a parameter type is specified as `Buffer` you can choose whether to store as a binary type or as +a hex encoded string. This decision will depend on what your storage backend can do or if it is faster with one or the +other. e.g. the `mysql` backend stores these fields as `binary(??)`. The test `memory` backend stores these as +hex encoded strings. + +# Promises # + +All functions return a promise. Even if we are just returning a value it is wrapped +in a promise so that you can chain calls if you need to. + +## .createAccount(uid, data) ## + +Parameters: + +* uid - (Buffer16) the uid of the account to be created - unique +* data: + * email - (string) + * normalizedEmail - (string) the same as above but `.toLowerCase()` + * emailCode - (Buffer16) + * emailVerified - (number) 0|1, to show whether an account has been verified + * createdAt - (number) an epoch, such as that created with `Date.now()` + * verifyHash - (Buffer32) + * authSalt - (Buffer32) + * wrapWrapKb - (Buffer32) + * verifierSetAt - (number) an epoch, such as that created with `Date.now()` + * verifierVersion - (number) currently always set to 1, may be 2 or more in the future + +Returns: + +* success - always returns an empty object when successful +* error (can be either): + * a `error.duplicate()` if this uid already exists + * an error from the underlying storage system + +## .account(uid) ## + +Parameters: + +* uid - (Buffer16) the uid of the account to be created - unique + +Returns: + +* success - returns the account object above +* error (can be either): + * a `error.notFound()` if this account does not exist + * an error from the underlying storage system + +## .checkPassword(uid, hash) ## + +Parameters: + +* uid - (Buffer16) the uid of the account to be queried +* hash: + * verifyHash - (Buffer32) + +Returns: + +* resolves with: + * an empty object `{}` +* rejects: with one of: + * `error.notFound()` if the credentials are invalid + * any error from the underlying storage engine + +## .verifyEmail(uid) ## + +Parameters: + +* uid - (Buffer16) the uid of the account to be queried + +Returns: + +* success - returns an empty object +* error: + * an error from the underlying storage engine + +We do not separate the fact that the account uid may not exist and always +resolve to an empty object. + +## .accountDevices(uid) ## + +Parameters: + +* uid - (Buffer16) the uid of the account to be queried + +Returns: + +* success - an array of account devices (aka Session Tokens) +* error: + * an error from the underlying storage engine (wrapped in error.wrap()) + +## .resetAccount(uid, data) ## + +Resets the account specified by `uid` using the fields provided in `data`. Deletes all tokens +related to this account. + +Parameters: + +* `uid` - (Buffer16) the uid of the account to be reset +* `data`: + * verifyHash - (Buffer32) + * authSalt - (Buffer32) + * wrapWrapKb - (Buffer32) + * verifierVersion - (number) + +Returns: + +* resolves with: + * an empty object `{}` +* rejects with: + * any errors from the underlying storage engine + +EXCEPTION TO NOTES: currently the backend sets `verifierSetAt` to be `Date.now()`. This should be moved to the +`fxa-auth-server`. + +## .deleteAccount(uid) ## + +Deletes the account specified by `uid` and deletes all tokens related to this account. + +Parameters: + +* `uid` - (Buffer16) the uid of the account to be reset + +Returns: + +* resolves with: + * an empty object `{}` +* rejects with: + * any errors from the underlying storage engine + +## .emailRecord(emailBuffer) ## + +Gets the account record related to this (normalized) email address. The email is provided in a Buffer. + +Parameters: + +* emailBuffer: the email address will be a hex encoded string, which is converted back to a string, then + `.toLowerCase()`. In the MySql backend we use `LOWER(?)` which uses the current locale for case-folding. + +Returns: + +* resolves with: + * `account` - consisting of: + * uid - (Buffer16) + * email - (string) + * normalizedEmail - (string) + * emailVerified - 0|1 + * emailCode - (Buffer16) + * kA - (Buffer32) + * wrapWrapKb - (Buffer32) + * verifierVersion - (number) + * verifyHash - (Buffer32) + * authSalt - (Buffer32) + * verifierSetAt - (number) an epoch +* rejects: with one of: + * `error.notFound()` if no account exists for this email address + * any error from the underlying storage engine + +## .accountExists(email) ## + +Checks if an account exists for this (normalized) email address. + +Parameters: + +* email: the email address will be a hex encoded string, which is converted back to a string, then `.toLowerCase()`. In + the MySql backend we use `LOWER(?)` which uses the current locale for case-folding. + +Returns: + +* resolves with: + * an empty object `{}` +* rejects: with one of: + * `error.notFound()` if no account exists for this email address + * any error from the underlying storage engine + +## Tokens ## + +All tokens (sessionTokens, keyFetchTokens, passwordForgotTokens, passwordChangeTokens, accountResetTokens) have three +functions which all work similarly. For example, the `sessionTokens` have: + +### .createSessionToken(tokenId, token) ### +### .createKeyFetchToken(tokenId, token) ### +### .createPasswordChangeToken(tokenId, token) ### +### .createPasswordForgotToken(tokenId, token) ### +### .createAccountResetToken(tokenId, token) ### + +Parameters. + +* tokenId : (Buffer32) the unique id for this token +* token : (Object) the fields to be stored in the token (see below for each token type) + +Each token takes the following fields for it's create method respectively: + +* sessionToken : data, uid, createdAt +* keyFetchToken : authKey, uid, keyBundle, createdAt +* passwordChangeToken : data, uid, createdAt +* passwordForgotToken : data, uid, passCode, createdAt, triesxb +* accountResetToken : data, uid, createdAt + +Returns: + +* resolves with: + * an object `{}` +* rejects with: + * `error.duplicate()` if a token already exists with the same `tokenId` + * any error from the underlying storage system (wrapped in `error.wrap()` + +Note: for some tokens there should only ever be one row per `uid`. This applies to `accountResetTokens`, +`passwordForgotTokens` and `passwordChangeTokens`. In the MySql driver we currently use `REPLACE INTO ...` so you +should do something equivalent with your storage backend. + +### .sessionToken(tokenId) ### +### .keyFetchToken(tokenId) ### +### .passwordChangeToken(tokenId) ### +### .passwordForgotToken(tokenId) ### +### .accountResetToken(tokenId) ### + +Parameters: + +* `tokenId` - (Buffer32) the id of the token to retrieve + +Returns: + +* resolves with: + * an object `{ ... }` with the relevant field (see below) +* rejects with: + * `error.notFound()` if this token does not exist + * any error from the underlying storage system (wrapped in `error.wrap()` + +Each token returns different fields. These fields are represented as `t.*` for a field +from the token and `a.*` for a field from the corresponding account. + +* sessionToken : t.tokenData, t.uid, t.createdAt, a.emailVerified, a.email, a.emailCode, a.verifierSetAt +* keyFetchToken : t.authKey, t.uid, t.keyBundle, t.createdAt, a.emailVerified, a.verifierSetAt +* passwordChangeToken : t.tokenData, t.uid, t.createdAt, a.verifierSetAt +* passwordForgotToken : t.tokenData, t.uid, t.createdAt, t.passCode, t.tries, a.email, a.verifierSetAt +* accountResetToken : t.uid, t.tokenData, t.createdAt, a.verifierSetAt + +### .deleteSessionToken(tokenId) ### +### .deleteKeyFetchToken(tokenId) ### +### .deletePasswordChangeToken(tokenId) ### +### .deletePasswordForgotToken(tokenId) ### +### .deleteAccountResetToken(tokenId) ### + +Will delete the token of the correct type designated by the given `tokenId`. + +## .updatePasswordForgotToken(tokenId, token) ## + +An extra function for `passwordForgotTokens`. Just updates the `tries` field of the token. + +Parameters. + +* tokenId : (Buffer32) the unique id for this token +* token : (Object) - + * tries : (number) + +Returns: + +* resolves with: + * an object `{}` (whether a row was updated or not, ie. even if `tokenId` does not exist.) +* rejects with: + * any error from the underlying storage system (wrapped in `error.wrap()` + +## .forgotPasswordVerified(tokenId, accountResetToken) ## + +An extra function for `passwordForgotTokens`. This performs three operations: + +1. deletes the `passwordForgotToken` corresponding to the `tokenId` +2. creates an `accountResetToken` corresponding to the fields specified in `accountResetToken` +3. sets the `emailVerified` fields of `accounts` to true specified by the `uid` in the `accountResetToken` + +Parameters: + +* tokenId : (Buffer32) the unique id for this token +* accountResetToken: (object) + * tokenId + * data + * uid + * createdA + +(Ends) diff --git a/fxa-auth-db-server/docs/Developing_with_Backend_Repos.md b/fxa-auth-db-server/docs/Developing_with_Backend_Repos.md new file mode 100644 index 0000000..dc6d963 --- /dev/null +++ b/fxa-auth-db-server/docs/Developing_with_Backend_Repos.md @@ -0,0 +1,99 @@ +# Developing with Backend Repos # + +The FxA project currently has three repos related to the database backend. This repo (fxa-auth-db-server) holds the +common server and common tests that each storage backend uses. The current (two) storage backends that use this +repo are: + +* fxa-auth-db-mem (generally for testing purposes) +* fxa-auth-db-mysql (for development and production) + +(Where 'development' here means for these three repos, not necessarily for the fxa-auth-server.) + +## New Features ## + +There is a reasonably close relationship between these three repos, so when a new feature needs to be added to +the `fxa-auth-db-server`, `fxa-auth-db-mem` and `fxa-auth-db-mysql` it can be tricky to figure out the best +way of proceeding. The following instructions provide an example of how this can be achieved (but not specifically +the _only_ way this can be achieved). + +## Assumptions # + +From here, we're going to assume that you have: + +1. all three repos checked out into three directories (named after themselves) +2. the ability to run the `npm test` command in all three repos +3. the ability to run the `npm start` command in the storage repos + +## Creating your Branches # + +Assume we're going to create the feature "#1 - Add New Operation" (whatever that operation is). Let's branch in each +repo: + +```sh +$ git branch i1-add-new-operation +$ git checkout i1-add-new-operation +Switched to branch 'i1-add-new-operation' +``` + +Then, install any packages and test: + +```sh +$ npm install +... +$ npm test +ok +``` + +## Developing ## + +When developing, you are probably changing code in the server AND in each storage backend, so in both of the backend repos +you should point your `node_modules/fxa-auth-db-server` to the checked out version above. + +```sh +$ cd fxa-auth-db-/node_modules +$ rm -rf fxa-auth-db-server +$ ln -s ../../fxa-auth-db-server . +``` + +Once this has been done, you should only run `npm install` for the `fxa-auth-db-server` repo when in it's own +directory. Also, just run `npm install ` in the backend repos, rather than a plain `npm install`. + +## Updates to `package.json` (and therefore `npm-shrinkwrap.json`) ## + +Do not change the dependency url of the `fxa-auth-db-server` repo in `package.json` (for your storage repos) as you are +developing. Generally, because you have linked your development version here, you won't need to change this. + +If you need a new dependency in any repo, just add it to `package.json` as you normally would during development. + +## Finishing off the Branch ## + +When finishing off the branch, commit your final changes and only then should you re-create your `npm-shrinkwrap.json` +files. This should be done as a separate commit as the last commit of the branch. This just keeps these generated changes +separate to the rest of your changed (even though they will still show up in the pull request). + +You should regenerate the `fxa-auth-db-server/npm-shrinkwrap.json` file first, and the storage repos afterwards. + +The following commands allow you to have complete control over this regeneration. + +```sh +$ rm -rf node_modules/ +$ npm cache clean +$ rm npm-shrinkwrap.json +$ npm install +$ npm shrinkwrap --dev +``` + +When you have done that for each branch, you want Travis to pass when you send your Pull Request. Firstly, push the +branch for the `fxa-auth-db-server` (and create a PR), then set the `package.json` file in each storage backend to +reference this new branch. When these branches are made into a PR, they should use the correct `fxa-auth-db-server` +branch so that the test on Travis goes correctly. + +## Review and Merge ## + +When merging, the `fxa-auth-db-server` should be merged first, then the branches in each storage backend can be changed +back to point to the master branch of the db-server. At this point, they will still pass Travis on the branch and will +be fine once merged into master. + +Note: anytime `package.json` is changed, the above set of shrinkwrap commands should be performed. + +(Ends) diff --git a/fxa-auth-db-server/docs/Server_API.md b/fxa-auth-db-server/docs/Server_API.md new file mode 100644 index 0000000..841dafa --- /dev/null +++ b/fxa-auth-db-server/docs/Server_API.md @@ -0,0 +1,1434 @@ +# Server API + +The `fxa-auth-db-server` has the following API which the `fxa-auth-server` uses. + +# Overview + +All responses are of the form `application/json`. + +## URL Structure + +All requests ... + +## Request Format + +All requests conform to the following points: + +* the methods used are HEAD, GET, PUT, POST and DELETE +* the `Content-Type` header must be `application/json` +* all buffer-type parameters must be a hex encoded string +* the body is a JSON structure + +Some requests require you to substitute in a parameter as part of the path. For example, when creating an account +(e.g. for the uid 'ABCD') the path used will be documented as `/account/` and the path used will be +`/account/ABCD`. + +## Response Format + +All responses conform to the following: + +* the returned `Content-Type` is always `application/json` +* the body is a JSON structure + +## Data Types + +The following datatypes are used throughout this document: + +* epoch : the date in ms since epoch. eg. 1424819640738 such as that returned from `Date.now()` +* hex128 : a 128 bit value in hex encoding. ie. 32 chars long (16 bytes) +* hex256 : a 256 bit value in hex encoding. ie. 64 chars long (32 bytes) +* hex768 : a 768 bit value in hex encoding. ie. 192 chars long (96 bytes) +* string255 : a string up to 255 characters/bytes long + +# Operations + +## Operations ## + +* General: + * ping : `GET /` + * heartbeat : `GET /__heartbeat__` +* Account: + * account : `GET /account/:id` + * accountExists : `HEAD /emailRecord/:id` + * emailRecord : `GET /emailRecord/:id` + * createAccount : `PUT /account/:id` + * checkPassword : `POST /account/:id/checkPassword` + * resetAccount : `POST /account/:id/reset` + * deleteAccount : `DELETE /account/:id` + * verifyEmail : `POST /account/:id/verifyEmail` +* Session Tokens: + * accountDevices : `GET /account/:id/devices` + * sessionToken : `GET /sessionToken/:id` + * deleteSessionToken : `DEL /sessionToken/:id` + * createSessionToken : `PUT /sessionToken/:id` +* Account Reset Tokens: + * accountResetToken : `GET /accountResetToken/:id` + * deleteAccountResetToken : `DEL /accountResetToken/:id` + * createAccountResetToken : `PUT /accountResetToken/:id` +* Key Fetch Tokens: + * keyFetchToken : `GET /keyFetchToken/:id` + * deleteKeyFetchToken : `DEL /keyFetchToken/:id` + * createKeyFetchToken : `PUT /keyFetchToken/:id` +* Password Change Tokens: + * passwordChangeToken : `GET /passwordChangeToken/:id` + * deletePasswordChangeToken : `DEL /passwordChangeToken/:id` + * createPasswordChangeToken : `PUT /passwordChangeToken/:id` +* Password Forgot Tokens: + * passwordForgotToken : `GET /passwordForgotToken/:id` + * deletePasswordForgotToken : `DEL /passwordForgotToken/:id` + * createPasswordForgotToken : `PUT /passwordForgotToken/:id` + * updatePasswordForgotToken : `POST /passwordForgotToken/:id/update` + * forgotPasswordVerified : `POST /passwordForgotToken/:id/verified` + +## Ping : `GET /` + +### Request + +``` +curl -X GET http://localhost:8000/ +``` + +### Response + +``` +HTTP/1.1 200 OK + +{"version":"0.30.0"} +``` + +The server does not return any errors from this operation, except those generated by infrastructure +such as a timeout, or if your library cannot connect to the server. + +## Heartbeat : `GET /__heartbeat__` + +### Request + +``` +curl -X GET http://localhost:8000/__heartbeat__ +``` + +### Response + +``` +HTTP/1.1 200 OK + +{} +``` + +A failed request may be returned as: + +``` +HTTP/1.1 500 Internal Server Error + +{"message":"connect ECONNREFUSED"} +``` + +This may be due to the backend server not being able to ping it's datastore, or if there happens to +be any other reason the server isn't functioning correctly. + +## createAccount : `PUT /account/` + +### Example + +``` +curl \ + -v \ + -X PUT \ + -H "Content-Type: application/json" \ + -d '{ + "normalizedEmail" : "foo@example.com", + "email" : "foo@example.com", + "emailCode" : "9b4da6ccd05e7c24ce6a6c0d208bc7c9", + "emailVerified" : false, + "kA" : "5e1994b0159081921adb416236058d92bd0715a91c884654e4269c49d467a160", + "wrapWrapKb" : "a746589a4d3db2b0552476bae4fc8c9156d29499eeb0d6583ffd6ddcd7482097", + "authSalt" : "d870b1472524fcef2cfd512533b1fb19fe6cf1b555cb5d85d60a636cc5356aba", + "verifyHash" : "5791981c2f0685aa9400597b6bee51d04c59399798e9bcf3cdbeec3d8b50971f", + "verifierVersion" : 1, + "verifierSetAt" : 1424832691282, + "locale" : "en_US" + }' \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac +``` + +### Request + +* Method : PUT +* Path : `/account/` + * uid : hex128 +* Params: + * normalizedEmail : string255 + * email : string255 + * emailCode : hex128 + * emailVerified : boolean + * kA : hex256 + * wrapWrapKb : hex256 + * authSalt : hex256 + * verifierVersion : int8 + * verifyHash hex256 + * verifierSetAt : epoch + * locale : string255 + * createdAt : epoch + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 409 Conflict + * Conditions: if this account `uid` or `normalizedEmail` already exists + * Content-Type : 'application/json' + * Body : {"message":"Record already exists"} +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} + + +## GET /account/ + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac +``` + +### Request + +* Method : GET +* Path : `/account/` + * uid : hex128 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 564 + +{ + "normalizedEmail":"foo@example.com", + "email":"foo@example.com", + "emailCode":"9b4da6ccd05e7c24ce6a6c0d208bc7c9", + "emailVerified":false, + "kA":"5e1994b0159081921adb416236058d92bd0715a91c884654e4269c49d467a160", + "wrapWrapKb":"a746589a4d3db2b0552476bae4fc8c9156d29499eeb0d6583ffd6ddcd7482097", + "authSalt":"d870b1472524fcef2cfd512533b1fb19fe6cf1b555cb5d85d60a636cc5356aba", + "verifyHash":"5791981c2f0685aa9400597b6bee51d04c59399798e9bcf3cdbeec3d8b50971f", + "verifierVersion":1, + "verifierSetAt":1424993616858, + "locale":"en_US", + "createdAt":1424993616858, + "devices":{}, + "lockedAt":null +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{ ... ... }` +* Status Code : 404 Not Found + * Conditions: if this account `uid` or `normalizedEmail` already exists + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## accountExists : `HEAD /emailRecord/` + +### Example + +``` +curl \ + -v \ + -X HEAD \ + http://localhost:8000/emailRecord/foo@example.com +``` + +### Request + +* Method : HEAD +* Path : `/emailRecord/` + * email : string255 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 564 + +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : empty +* Status Code : 404 Not Found + * Conditions: if this email does not exist + * Content-Type : 'application/json' + * Body : empty +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : empty + + +## emailRecord : `GET /emailRecord/` + +Similar to `GET /account/` but using email address instead of uid. + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/emailRecord/foo@example.com +``` + +### Request + +* Method : GET +* Path : `/emailRecord/` + * email : string255 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 564 + +{ + "normalizedEmail":"foo@example.com", + "email":"foo@example.com", + "emailCode":"9b4da6ccd05e7c24ce6a6c0d208bc7c9", + "emailVerified":false, + "kA":"5e1994b0159081921adb416236058d92bd0715a91c884654e4269c49d467a160", + "wrapWrapKb":"a746589a4d3db2b0552476bae4fc8c9156d29499eeb0d6583ffd6ddcd7482097", + "authSalt":"d870b1472524fcef2cfd512533b1fb19fe6cf1b555cb5d85d60a636cc5356aba", + "verifyHash":"5791981c2f0685aa9400597b6bee51d04c59399798e9bcf3cdbeec3d8b50971f", + "verifierVersion":1, + "verifierSetAt":1424993616858, + "locale":"en_US", + "createdAt":1424993616858, + "devices":{}, + "lockedAt":null +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{ ... ... }` +* Status Code : 404 Not Found + * Conditions: if this account `uid` or `normalizedEmail` already exists + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + +## checkPassword : `POST /account//checkPassword` + +Returns back the same `uid` if correct. + +### Example + +``` +curl \ + -v \ + -X POST \ + -H "Content-Type: application/json" \ + -d '{ + "verifyHash":"5791981c2f0685aa9400597b6bee51d04c59399798e9bcf3cdbeec3d8b50971f" + }' \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac/checkPassword +``` + +### Request + +* Method : POST +* Path : `/account//checkPassword` + * verifyHash : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 90 + +{ + "uid":"6044486dd15b42e08b1fb9167415b9ac" +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{ ... ... }` +* Status Code : 400 Bad Request + * Conditions: if this account `uid` doesn't exist or the `password` is incorrect + * Content-Type : 'application/json' + * Body : `{"message":"Incorrect password"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + +## resetAccount : `POST /account//reset` +## deleteAccount : `DELETE /account/` +## verifyEmail : `POST /account//verifyEmail` + +``` +curl \ + -v \ + -X POST \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac/verifyEmail +``` + +### Request + +* Method : POST +* Path : `/account//verifyEmail` + * uid : hex128 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + +Note: if the account `uid` is not found, a `200 OK` is returned anyway. + + +## createSessionToken : `PUT /sessionToken/` + +### Example + +``` +curl \ + -v \ + -X PUT \ + -H "Content-Type: application/json" \ + -d '{ + "uid" : "6044486dd15b42e08b1fb9167415b9ac", + "data" : "e2c3a8f73e826b9176e54e0f6ecb34b60b1e1979d254638f6b61d721c069d576", + "createdAt" : 1425004396952 + }' \ + http://localhost:8000/sessionToken/522c251a1623e1f1db1f4fe68b9594d26772d6e77e04cb68e110c58600f97a77 +``` + +### Request + +* Method : PUT +* Path : `/sessionToken/` + * tokenId : hex256 +* Params: + * uid : hex128 + * data : hex256 + * createdAt : epoch + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 409 Conflict + * Conditions: if this `tokenId` already exists + * Content-Type : 'application/json' + * Body : {"message":"Record already exists"} +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} + + +## accountDevices : `GET /account//devices` + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac/devices +``` + +### Request + +* Method : GET +* Path : `/account//devices` + * uid : hex128 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 564 + +[ + { + "data":"e2c3a8f73e826b9176e54e0f6ecb34b60b1e1979d254638f6b61d721c069d576", + "uid":"6044486dd15b42e08b1fb9167415b9ac", + "createdAt":1425004396952, + "id":"522c251a1623e1f1db1f4fe68b9594d26772d6e77e04cb68e110c58600f97a77" + } +] +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this account `uid` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## sessionToken : `GET /sessionToken/` + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/sessionToken/522c251a1623e1f1db1f4fe68b9594d26772d6e77e04cb68e110c58600f97a77 +``` + +### Request + +* Method : GET +* Path : `/sessionToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 285 + +{ + "data":"e2c3a8f73e826b9176e54e0f6ecb34b60b1e1979d254638f6b61d721c069d576", + "uid":"6044486dd15b42e08b1fb9167415b9ac", + "createdAt":1425004396952, + "id":"522c251a1623e1f1db1f4fe68b9594d26772d6e77e04cb68e110c58600f97a77" +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## deleteSessionToken : `DEL /sessionToken/` + +This operation is idempotent. If you delete a `tokenId` twice, the same result occurs. In fact, if you delete a +`tokenId` that doesn't exist, it also returns the same `200 OK` result (since it is already not there). + +### Example + +``` +curl \ + -v \ + -X DELETE \ + http://localhost:8000/sessionToken/522c251a1623e1f1db1f4fe68b9594d26772d6e77e04cb68e110c58600f97a77 +``` + +### Request + +* Method : DELETE +* Path : `/sessionToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## createAccountResetToken : `PUT /accountResetToken/` + +Since only one `accountResetToken` is allowed for each account at any time, any subsequent new token will delete the +old one. + +### Example + +``` +curl \ + -v \ + -X PUT \ + -H "Content-Type: application/json" \ + -d '{ + "uid" : "6044486dd15b42e08b1fb9167415b9ac", + "data" : "b034061cc2886a3c3c08bd4e9bbc8afc4bc3fc9bca12d5b5d0aa7e0a7f78b9ce", + "createdAt" : 1425004396952 + }' \ + http://localhost:8000/accountResetToken/da7e3b59fc6021836ed205d2176c11819932c9554bec5a40a1f4178b7f08194d +``` + +### Request + +* Method : PUT +* Path : `/accountResetToken/` + * tokenId : hex256 +* Params: + * uid : hex128 + * data : hex256 + * createdAt : epoch + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 409 Conflict + * Conditions: if this `tokenId` already exists + * Content-Type : 'application/json' + * Body : {"message":"Record already exists"} +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + + +## accountResetToken : `GET /accountResetToken/` + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/accountResetToken/da7e3b59fc6021836ed205d2176c11819932c9554bec5a40a1f4178b7f08194d +``` + +### Request + +* Method : GET +* Path : `/accountResetToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 177 + +{ + "tokenData":"b034061cc2886a3c3c08bd4e9bbc8afc4bc3fc9bca12d5b5d0aa7e0a7f78b9ce", + "uid":"6044486dd15b42e08b1fb9167415b9ac", + "createdAt":1425004396952, + "verifierSetAt":1424993616858 +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## deleteAccountResetToken : `DEL /accountResetToken/` + +This operation is idempotent. If you delete a `tokenId` twice, the same result occurs. In fact, if you delete a +`tokenId` that doesn't exist, it also returns the same `200 OK` result (since it is already not there). + +### Example + +``` +curl \ + -v \ + -X DELETE \ + http://localhost:8000/accountResetToken/da7e3b59fc6021836ed205d2176c11819932c9554bec5a40a1f4178b7f08194d +``` + +### Request + +* Method : DELETE +* Path : `/accountResetToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## createKeyFetchToken : `PUT /keyFetchToken/` + +### Example + +``` +curl \ + -v \ + -X PUT \ + -H "Content-Type: application/json" \ + -d '{ + "uid" : "6044486dd15b42e08b1fb9167415b9ac", + "authKey" : "b034061cc2886a3c3c08bd4e9bbc8afc4bc3fc9bca12d5b5d0aa7e0a7f78b9ce", + "keyBundle" : "83333269c64eb43219f8b5807d37ac2391fc77295562685a5239674e2b0215920c45e2295c0d92fa7d69cb58d1e3c6010e1281f6d6c0df694b134815358110ae22a7b4c348a4f426bef3783b0493b3a531b649c0e2f19848d9563a61cd0f7eb8", + "createdAt" : 1425004396952 + }' \ + http://localhost:8000/keyFetchToken/4c17443c1bcf5e509bc90904905ea1974900120d3dd34e7061f182cb063f976a +``` + + +### Request + +* Method : PUT +* Path : `/keyFetchToken/` + * tokenId : hex256 +* Params: + * uid : hex128 + * authKey : hex256 + * keyBundle : hex768 + * createdAt : epoch + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 409 Conflict + * Conditions: if this `tokenId` already exists + * Content-Type : 'application/json' + * Body : {"message":"Record already exists"} +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + +## keyFetchToken : `GET /keyFetchToken/` + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/keyFetchToken/4c17443c1bcf5e509bc90904905ea1974900120d3dd34e7061f182cb063f976a +``` + +### Request + +* Method : GET +* Path : `/keyFetchToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 399 + +{ + "authKey":"b034061cc2886a3c3c08bd4e9bbc8afc4bc3fc9bca12d5b5d0aa7e0a7f78b9ce", + "uid":"6044486dd15b42e08b1fb9167415b9ac", + "keyBundle":"83333269c64eb43219f8b5807d37ac2391fc77295562685a5239674e2b0215920c45e2295c0d92fa7d69cb58d1e3c6010e1281f6d6c0df694b134815358110ae22a7b4c348a4f426bef3783b0493b3a531b649c0e2f19848d9563a61cd0f7eb8", + "createdAt":1425004396952, + "emailVerified":false, + "verifierSetAt":1425263030609 +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## deleteKeyFetchToken : `DEL /keyFetchToken/` + +This operation is idempotent. If you delete a `tokenId` twice, the same result occurs. In fact, if you delete a +`tokenId` that doesn't exist, it also returns the same `200 OK` result (since it is already not there). + +### Example + +``` +curl \ + -v \ + -X DELETE \ + http://localhost:8000/keyFetchToken/4c17443c1bcf5e509bc90904905ea1974900120d3dd34e7061f182cb063f976a +``` + +### Request + +* Method : DELETE +* Path : `/keyFetchToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## createPasswordChangeToken : `PUT /passwordChangeToken/` + +### Example + +``` +curl \ + -v \ + -X PUT \ + -H "Content-Type: application/json" \ + -d '{ + "uid" : "6044486dd15b42e08b1fb9167415b9ac", + "data" : "bbfe036d84cc1ae9b5eecc503ff9106c61d25961d5680669d2065c6bb7a5530d", + "createdAt" : 1425004396952 + }' \ + http://localhost:8000/passwordChangeToken/20f751b2cc61129d9bc631d70c994129a35da6bf324456e4bdb82a0381ca76ec +``` + +### Request + +* Method : PUT +* Path : `/passwordChangeToken/` + * tokenId : hex256 +* Params: + * uid : hex128 + * data : hex256 + * createdAt : epoch + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 409 Conflict + * Conditions: if this `tokenId` already exists + * Content-Type : 'application/json' + * Body : {"message":"Record already exists"} +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + +## passwordChangeToken : `GET /passwordChangeToken/` + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/passwordChangeToken/20f751b2cc61129d9bc631d70c994129a35da6bf324456e4bdb82a0381ca76ec +``` + +### Request + +* Method : GET +* Path : `/passwordChangeToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 177 + +{ + "tokenData":"bbfe036d84cc1ae9b5eecc503ff9106c61d25961d5680669d2065c6bb7a5530d", + "uid":"6044486dd15b42e08b1fb9167415b9ac", + "createdAt":1425004396952, + "verifierSetAt":1425263030609 +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## deletePasswordChangeToken : `DEL /passwordChangeToken/` + +This operation is idempotent. If you delete a `tokenId` twice, the same result occurs. In fact, if you delete a +`tokenId` that doesn't exist, it also returns the same `200 OK` result (since it is already not there). + +### Example + +``` +curl \ + -v \ + -X DELETE \ + http://localhost:8000/passwordChangeToken/20f751b2cc61129d9bc631d70c994129a35da6bf324456e4bdb82a0381ca76ec +``` + +### Request + +* Method : DELETE +* Path : `/passwordChangeToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## createPasswordForgotToken : `PUT /passwordForgotToken/` + +### Example + +``` +curl \ + -v \ + -X PUT \ + -H "Content-Type: application/json" \ + -d '{ + "uid" : "6044486dd15b42e08b1fb9167415b9ac", + "data" : "958266599bdc7218277a349f2675ebf38d8542eb784e01d1332f87fb98a970c3", + "passCode" : "95c0fab6a666b1a5cbf2db4700a6a779", + "tries" : 1, + "createdAt" : 1425004396952 + }' \ + http://localhost:8000/passwordForgotToken/266fd690895c8b0086bb2c83e4b3b41c128746125f28b5429938765279673d62 +``` + +### Request + +* Method : PUT +* Path : `/passwordForgotToken/` + * tokenId : hex256 +* Params: + * uid : hex128 + * data : hex256 + * passCode : hex128 + * tries : int + * createdAt : epoch + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 409 Conflict + * Conditions: if this `tokenId` already exists + * Content-Type : 'application/json' + * Body : {"message":"Record already exists"} +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + +## passwordForgotToken : `GET /passwordForgotToken/` + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/passwordForgotToken/266fd690895c8b0086bb2c83e4b3b41c128746125f28b5429938765279673d62 +``` + +### Request + +* Method : GET +* Path : `/passwordChangeToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 259 + +{ + "tokenData":"958266599bdc7218277a349f2675ebf38d8542eb784e01d1332f87fb98a970c3", + "uid":"6044486dd15b42e08b1fb9167415b9ac", + "passCode":"95c0fab6a666b1a5cbf2db4700a6a779", + "tries":1, + "createdAt":1425004396952, + "email":"foo@example.com", + "verifierSetAt":1425263030609 +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + +## deletePasswordForgotToken : `DEL /passwordForgotToken/` + +This operation is idempotent. If you delete a `tokenId` twice, the same result occurs. In fact, if you delete a +`tokenId` that doesn't exist, it also returns the same `200 OK` result (since it is already not there). + +### Example + +``` +curl \ + -v \ + -X DELETE \ + http://localhost:8000/passwordForgotToken/266fd690895c8b0086bb2c83e4b3b41c128746125f28b5429938765279673d62 +``` + +### Request + +* Method : DELETE +* Path : `/passwordForgotToken/` + * tokenId : hex256 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `{}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## updatePasswordForgotToken : `POST /passwordForgotToken//update` + +This just updates the number of tries for a particular token. + +### Example + +``` +curl \ + -v \ + -X POST \ + -H "Content-Type: application/json" \ + -d '{ + "tries" : 2 + }' \ + http://localhost:8000/passwordForgotToken/266fd690895c8b0086bb2c83e4b3b41c128746125f28b5429938765279673d62/update +``` + +### Request + +* Method : PUT +* Path : `/passwordForgotToken//update` + * tokenId : hex256 +* Params: + * tries : int + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + + +## forgotPasswordVerified : `POST /passwordForgotToken//verified` + +This method should: + +* delete the passwordForgotToken designated by +* create a new accountResetToken as given in JSON +* verify the email address for this account +* unlock the account (if already locked) + +### Example + +This request sends a new `accountResetToken` and receives back + +``` +curl \ + -v \ + -X POST \ + -H "Content-Type: application/json" \ + -d '{ + "uid" : "6044486dd15b42e08b1fb9167415b9ac", + "data" : "cad0306bd6505df67d5fff2264e59a9eabdbfd4e441ac2272bda2d1e8c740072", + "createdAt" : 1425004396952 + }' \ + http://localhost:8000/passwordForgotToken/266fd690895c8b0086bb2c83e4b3b41c128746125f28b5429938765279673d62/verified +``` + +### Request + +* Method : PUT +* Path : `/passwordForgotToken//update` + * tokenId : hex256 +* Params: + * tries : int + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + +## lockAccount : `POST /account//lock` ## + +This method should: + +* set `lockedAt` for the account specified +* store the `unlockCode` for this account + +### Example + +``` +curl \ + -v \ + -X POST \ + -H "Content-Type: application/json" \ + -d '{ + "unlockCode" : "4aa3ca42fbc2e4d64e634ab92c5a607b", + "lockedAt" : 1425004396952 + }' \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac/lock +``` + +### Request + +* Method : POST +* Path : `/account//lock` + * uid : hex128 +* Params: + * unlockCode : hex128 + * lockedAt : epoch + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 404 Not Found + * Conditions: if this account `uid` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + +## unlockCode : `GET /account//unlockCode` ## + +### Example + +``` +curl \ + -v \ + -X GET \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac/unlockCode +``` + +### Request + +* Method : GET +* Path : `/account/uid>` + * uid : hex128 +* Params: none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 90 + +{ + "uid":"6044486dd15b42e08b1fb9167415b9ac", + "unlockCode":"4aa3ca42fbc2e4d64e634ab92c5a607b" +} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : `[ ... ...]` +* Status Code : 404 Not Found + * Conditions: if this session `tokenId` doesn't exist + * Content-Type : 'application/json' + * Body : `{"message":"Not Found"}` +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : `{"code":"InternalError","message":"......"}` + + +## unlockAccount : `POST /account//unlock` ## + +This operation should: + +* unset `lockedAt` (e.g. null in a database) +* delete the `unlockCode` for this account + +This operation is idempotent. If you delete an unlockCode twice or an unlockCode that doesn't exist then the operation +will still succeed. + +### Example + +``` +curl \ + -v \ + -X POST \ + -H "Content-Type: application/json" \ + -d '{}' \ + http://localhost:8000/account/6044486dd15b42e08b1fb9167415b9ac/unlock +``` + +### Request + +* Method : POST +* Path : `/account//unlock` + * uid : hex128 +* Params: + * none + +### Response + +``` +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 2 + +{} +``` + +* Status Code : 200 OK + * Content-Type : 'application/json' + * Body : {} +* Status Code : 500 Internal Server Error + * Conditions: if something goes wrong on the server + * Content-Type : 'application/json' + * Body : {"code":"InternalError","message":"......"} +* `` + +(Ends) diff --git a/fxa-auth-db-server/grunttasks/bump.js b/fxa-auth-db-server/grunttasks/bump.js new file mode 100644 index 0000000..fd2a61e --- /dev/null +++ b/fxa-auth-db-server/grunttasks/bump.js @@ -0,0 +1,26 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// takes care of bumping the version number in package.json + +module.exports = function (grunt) { + 'use strict' + + grunt.config('bump', { + options: { + files: ['package.json'], + bumpVersion: true, + commit: true, + commitMessage: 'Release v%VERSION%', + commitFiles: ['package.json', 'CHANGELOG'], + createTag: true, + tagName: 'v%VERSION%', + tagMessage: 'Version %VERSION%', + push: false, + pushTo: 'origin', + gitDescribeOptions: '--tags --always --abrev=1 --dirty=-d' + } + }) +} + diff --git a/fxa-auth-db-server/grunttasks/copyright.js b/fxa-auth-db-server/grunttasks/copyright.js new file mode 100644 index 0000000..928238c --- /dev/null +++ b/fxa-auth-db-server/grunttasks/copyright.js @@ -0,0 +1,26 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +module.exports = function (grunt) { + 'use strict' + + grunt.config('copyright', { + app: { + src: [ + '{,lib/,scripts/}*.js' + ], + options: { + pattern: 'This Source Code Form is subject to the terms of the Mozilla Public' + } + }, + tests: { + src: [ + 'test/{local,backend}/*.js' + ], + options: { + pattern: 'Any copyright is dedicated to the Public Domain.' + } + } + }) +} diff --git a/fxa-auth-db-server/grunttasks/eslint.js b/fxa-auth-db-server/grunttasks/eslint.js new file mode 100644 index 0000000..dcf1537 --- /dev/null +++ b/fxa-auth-db-server/grunttasks/eslint.js @@ -0,0 +1,19 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +module.exports = function (grunt) { + 'use strict' + + grunt.config('eslint', { + options: { + eslintrc: '.eslintrc' + }, + files: [ + '{,grunttasks/,lib/,scripts/,test/,test/backend/,test/local/}*.js' + ] + }) + + // Let's make a sneaky alias for ESLint and call it `jshint`. + grunt.registerTask('jshint', ['eslint']) +} diff --git a/fxa-auth-db-server/grunttasks/version.js b/fxa-auth-db-server/grunttasks/version.js new file mode 100644 index 0000000..4246c34 --- /dev/null +++ b/fxa-auth-db-server/grunttasks/version.js @@ -0,0 +1,31 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// +// A task to stamp a new version. +// +// Before running this task you should update CHANGELOG with the +// changes for this release. Protip: you only need to make changes +// to CHANGELOG; this task will add and commit for you. +// +// * version is updated in package.json +// * git tag with version name is created. +// * git commit with updated package.json created. +// +// NOTE: This task will not push this commit for you. +// + +module.exports = function (grunt) { + 'use strict' + + grunt.registerTask('version', [ + 'bump-only:minor', + 'bump-commit' + ]) + + grunt.registerTask('version:patch', [ + 'bump-only:patch', + 'bump-commit' + ]) +} diff --git a/fxa-auth-db-server/index.js b/fxa-auth-db-server/index.js new file mode 100644 index 0000000..bb9222a --- /dev/null +++ b/fxa-auth-db-server/index.js @@ -0,0 +1,118 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var restify = require('restify') +var bufferize = require('./lib/bufferize') +var version = require('./package.json').version + +function createServer(db) { + + function reply(fn) { + return function (req, res, next) { + fn.call(db, req.params.id, req.body) + .then( + function (result) { + api.emit( + 'success', + { + code: 200, + route: req.route.name, + method: req.method, + path: req.url, + t: Date.now() - req.time() + } + ) + if (Array.isArray(result)) { + res.send(result.map(bufferize.unbuffer)) + } + else { + res.send(bufferize.unbuffer(result || {})) + } + }, + function (err) { + if (typeof err !== 'object') { + err = { message: err || 'none' } + } + var statusCode = err.code || 500 + api.emit( + 'failure', + { + code: statusCode, + route: req.route.name, + method: req.method, + path: req.url, + err: err, + t: Date.now() - req.time(), + } + ) + + res.send(statusCode, err) + } + ) + .done(next, next) + } + } + var api = restify.createServer() + api.use(restify.bodyParser()) + api.use(bufferize.bufferizeRequest) + + api.get('/account/:id', reply(db.account)) + api.del('/account/:id', reply(db.deleteAccount)) + api.put('/account/:id', reply(db.createAccount)) + api.get('/account/:id/devices', reply(db.accountDevices)) + api.post('/account/:id/checkPassword', reply(db.checkPassword)) + api.post('/account/:id/reset', reply(db.resetAccount)) + api.post('/account/:id/verifyEmail', reply(db.verifyEmail)) + api.post('/account/:id/locale', reply(db.updateLocale)) + api.post('/account/:id/lock', reply(db.lockAccount)) + api.post('/account/:id/unlock', reply(db.unlockAccount)) + api.get('/account/:id/unlockCode', reply(db.unlockCode)) + + api.get('/sessionToken/:id', reply(db.sessionToken)) + api.del('/sessionToken/:id', reply(db.deleteSessionToken)) + api.put('/sessionToken/:id', reply(db.createSessionToken)) + + api.get('/keyFetchToken/:id', reply(db.keyFetchToken)) + api.del('/keyFetchToken/:id', reply(db.deleteKeyFetchToken)) + api.put('/keyFetchToken/:id', reply(db.createKeyFetchToken)) + + api.get('/accountResetToken/:id', reply(db.accountResetToken)) + api.del('/accountResetToken/:id', reply(db.deleteAccountResetToken)) + api.put('/accountResetToken/:id', reply(db.createAccountResetToken)) + + api.get('/passwordChangeToken/:id', reply(db.passwordChangeToken)) + api.del('/passwordChangeToken/:id', reply(db.deletePasswordChangeToken)) + api.put('/passwordChangeToken/:id', reply(db.createPasswordChangeToken)) + + api.get('/passwordForgotToken/:id', reply(db.passwordForgotToken)) + api.del('/passwordForgotToken/:id', reply(db.deletePasswordForgotToken)) + api.put('/passwordForgotToken/:id', reply(db.createPasswordForgotToken)) + api.post('/passwordForgotToken/:id/update', reply(db.updatePasswordForgotToken)) + api.post('/passwordForgotToken/:id/verified', reply(db.forgotPasswordVerified)) + + api.get('/emailRecord/:id', reply(db.emailRecord)) + api.head('/emailRecord/:id', reply(db.accountExists)) + + api.get('/__heartbeat__', reply(db.ping)) + + api.get( + '/', + function (req, res, next) { + res.send({ version: version }) + next() + } + ) + + var memInterval = setInterval(function() { + api.emit('mem', process.memoryUsage()) + }, 15000) + memInterval.unref() + + return api +} + +module.exports = { + createServer: createServer, + errors: require('./lib/error') +} diff --git a/fxa-auth-db-server/lib/bufferize.js b/fxa-auth-db-server/lib/bufferize.js new file mode 100644 index 0000000..4b17197 --- /dev/null +++ b/fxa-auth-db-server/lib/bufferize.js @@ -0,0 +1,39 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var HEX_STRING = /^(?:[a-fA-F0-9]{2})+$/ + +function unbuffer(object) { + var keys = Object.keys(object) + for (var i = 0; i < keys.length; i++) { + var x = object[keys[i]] + if (Buffer.isBuffer(x)) { + object[keys[i]] = x.toString('hex') + } + } + return object +} + +function bufferize(object) { + var keys = Object.keys(object) + for (var i = 0; i < keys.length; i++) { + var x = object[keys[i]] + if (typeof(x) === 'string' && HEX_STRING.test(x)) { + object[keys[i]] = Buffer(x, 'hex') + } + } + return object +} + +function bufferizeRequest(req, res, next) { + if (req.body) { req.body = bufferize(req.body) } + if (req.params) { req.params = bufferize(req.params) } + next() +} + +module.exports = { + unbuffer: unbuffer, + bufferize: bufferize, + bufferizeRequest: bufferizeRequest +} diff --git a/fxa-auth-db-server/lib/error.js b/fxa-auth-db-server/lib/error.js new file mode 100644 index 0000000..9eb46cc --- /dev/null +++ b/fxa-auth-db-server/lib/error.js @@ -0,0 +1,65 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var inherits = require('util').inherits + +function AppError(options) { + this.message = options.message + this.errno = options.errno + this.error = options.error + this.code = options.code + if (options.stack) this.stack = options.stack +} +inherits(AppError, Error) + +AppError.prototype.toString = function () { + return 'Error: ' + this.message +} + +AppError.duplicate = function () { + return new AppError( + { + code: 409, + error: 'Conflict', + errno: 101, + message: 'Record already exists' + } + ) +} + +AppError.notFound = function () { + return new AppError( + { + code: 404, + error: 'Not Found', + errno: 116, + message: 'Not Found' + } + ) +} + +AppError.incorrectPassword = function () { + return new AppError( + { + code: 400, + error: 'Bad request', + errno: 103, + message: 'Incorrect password' + } + ) +} + +AppError.wrap = function (err) { + return new AppError( + { + code: 500, + error: 'Internal Server Error', + errno: err.errno, + message: err.code, + stack: err.stack + } + ) +} + +module.exports = AppError diff --git a/fxa-auth-db-server/lib/promise.js b/fxa-auth-db-server/lib/promise.js new file mode 100644 index 0000000..6e99510 --- /dev/null +++ b/fxa-auth-db-server/lib/promise.js @@ -0,0 +1,5 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +module.exports = require('bluebird') diff --git a/fxa-auth-db-server/package.json b/fxa-auth-db-server/package.json new file mode 100644 index 0000000..681cf1f --- /dev/null +++ b/fxa-auth-db-server/package.json @@ -0,0 +1,38 @@ +{ + "name": "fxa-auth-db-server", + "version": "0.39.0", + "description": "Firefox Accounts DB Server", + "main": "index.js", + "scripts": { + "test": "grunt && ./scripts/tap-coverage.js test/local", + "outdated": "npm outdated --depth 0" + }, + "repository": { + "type": "git", + "url": "https://github.com/mozilla/fxa-auth-db-server" + }, + "author": "Mozilla (https://mozilla.org/)", + "license": "MPL-2.0", + "bugs": { + "url": "https://github.com/mozilla/fxa-auth-db-server/issues" + }, + "homepage": "https://github.com/mozilla/fxa-auth-db-server", + "dependencies": { + "restify": "2.8.2" + }, + "devDependencies": { + "ass": "git://github.com/jrgm/ass.git#5be99ee", + "bluebird": "1.2.2", + "eslint-config-fxa": "1.2.0", + "grunt": "0.4.5", + "grunt-bump": "0.3.0", + "grunt-copyright": "0.2.0", + "grunt-eslint": "14.0.0", + "load-grunt-tasks": "0.6.0", + "tap": "0.4.12" + }, + "keywords": [], + "engines": { + "node": "0.10.x" + } +} diff --git a/fxa-auth-db-server/scripts/tap-coverage.js b/fxa-auth-db-server/scripts/tap-coverage.js new file mode 100755 index 0000000..953157b --- /dev/null +++ b/fxa-auth-db-server/scripts/tap-coverage.js @@ -0,0 +1,38 @@ +#!/usr/bin/env node + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +if (!process.env.NO_COVERAGE) { + var ass = require('ass').enable( { + // exclude files in /client/ and /test/ from code coverage + exclude: [ '/client/', '/test' ] + }) +} + +var path = require('path'), + spawn = require('child_process').spawn, + fs = require('fs') + +var p = spawn(path.join(path.dirname(__dirname), 'node_modules', '.bin', 'tap'), + process.argv.slice(2), { stdio: 'inherit' }) + +p.on('close', function(code) { + if (!process.env.NO_COVERAGE) { + ass.report('json', function(err, r) { + console.log('code coverage:', r.percent + '%') + process.stdout.write('generating coverage.html: ') + var start = new Date() + ass.report('html', function(err, html) { + fs.writeFileSync(path.join(path.dirname(__dirname), 'coverage.html'), + html) + process.stdout.write('complete in ' + + ((new Date() - start) / 1000.0).toFixed(1) + 's\n') + process.exit(code) + }) + }) + } else { + process.exit(code) + } +}) diff --git a/fxa-auth-db-server/test/backend/db_tests.js b/fxa-auth-db-server/test/backend/db_tests.js new file mode 100644 index 0000000..2d4deb9 --- /dev/null +++ b/fxa-auth-db-server/test/backend/db_tests.js @@ -0,0 +1,887 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +var test = require('../ptaptest') +var crypto = require('crypto') + +var zeroBuffer16 = Buffer('00000000000000000000000000000000', 'hex') +var zeroBuffer32 = Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex') + +function newUuid() { + return crypto.randomBytes(16) +} + +var now = Date.now() +var ACCOUNT = { + uid: newUuid(), + email: ('' + Math.random()).substr(2) + '@bar.com', + emailCode: zeroBuffer16, + emailVerified: false, + verifierVersion: 1, + verifyHash: zeroBuffer32, + authSalt: zeroBuffer32, + kA: zeroBuffer32, + wrapWrapKb: zeroBuffer32, + verifierSetAt: now, + createdAt: now, + locale : 'en_US', +} +// set normalizedEmail, since the fxa-auth-server should do that for us! +ACCOUNT.normalizedEmail = ACCOUNT.email.toLowerCase() + +function hex(len) { + return Buffer(crypto.randomBytes(len).toString('hex'), 'hex') +} +function hex16() { return hex(16) } +function hex32() { return hex(32) } +// function hex64() { return hex(64) } +function hex96() { return hex(96) } + +var SESSION_TOKEN_ID = hex32() +var SESSION_TOKEN = { + data : hex32(), + uid : ACCOUNT.uid, + createdAt: now + 1 +} + +var KEY_FETCH_TOKEN_ID = hex32() +var KEY_FETCH_TOKEN = { + authKey : hex32(), + uid : ACCOUNT.uid, + keyBundle : hex96(), + createdAt: now + 2 +} + +var PASSWORD_FORGOT_TOKEN_ID = hex32() +var PASSWORD_FORGOT_TOKEN = { + data : hex32(), + uid : ACCOUNT.uid, + passCode : hex16(), + tries : 1, + createdAt: now + 3 +} + +var PASSWORD_CHANGE_TOKEN_ID = hex32() +var PASSWORD_CHANGE_TOKEN = { + data : hex32(), + uid : ACCOUNT.uid, + createdAt: now + 4 +} + +var ACCOUNT_RESET_TOKEN_ID = hex32() +var ACCOUNT_RESET_TOKEN = { + data : hex32(), + uid : ACCOUNT.uid, + createdAt: now + 5 +} + +// To run these tests from a new backend, pass the config and an already created +// DB API for them to be run against. +module.exports = function(config, DB) { + DB.connect(config) + .then( + function (db) { + + test( + 'ping', + function (t) { + t.plan(1) + return db.ping() + .then(function(account) { + t.pass('Got the ping ok') + }, function(err) { + t.fail('Should not have arrived here') + }) + } + ) + + test( + 'account creation and password checking', + function (t) { + t.plan(42) + var emailBuffer = Buffer(ACCOUNT.email) + return db.accountExists(emailBuffer) + .then(function(exists) { + t.fail('account should not yet exist for this email address') + }, function(err) { + t.pass('ok, account could not be found') + }) + .then(function() { + return db.createAccount(ACCOUNT.uid, ACCOUNT) + }) + .then(function(account) { + t.deepEqual(account, {}, 'Returned an empty object on account creation') + var emailBuffer = Buffer(ACCOUNT.email) + return db.accountExists(emailBuffer) + }) + .then(function(exists) { + t.ok(exists, 'account exists for this email address') + }) + .then(function() { + t.pass('Retrieving account using uid') + return db.account(ACCOUNT.uid) + }) + .then(function(account) { + t.deepEqual(account.uid, ACCOUNT.uid, 'uid') + t.equal(account.email, ACCOUNT.email, 'email') + t.deepEqual(account.emailCode, ACCOUNT.emailCode, 'emailCode') + t.equal(!!account.emailVerified, ACCOUNT.emailVerified, 'emailVerified') + t.deepEqual(account.kA, ACCOUNT.kA, 'kA') + t.deepEqual(account.wrapWrapKb, ACCOUNT.wrapWrapKb, 'wrapWrapKb') + t.deepEqual(account.verifyHash, ACCOUNT.verifyHash, 'verifyHash') + t.deepEqual(account.authSalt, ACCOUNT.authSalt, 'authSalt') + t.equal(account.verifierVersion, ACCOUNT.verifierVersion, 'verifierVersion') + t.equal(account.createdAt, ACCOUNT.createdAt, 'createdAt') + t.equal(account.verifierSetAt, account.createdAt, 'verifierSetAt has been set to the same as createdAt') + t.equal(account.locale, ACCOUNT.locale, 'locale') + t.equal(account.lockedAt, null, 'lockedAt is not set to anything') + }) + .then(function() { + t.pass('Checking bad password') + return db.checkPassword(ACCOUNT.uid, {verifyHash: Buffer(crypto.randomBytes(32))}) + }) + .then(function() { + t.fail('password check should fail') + }, function(err) { + t.ok(err, 'incorrect password produces an error') + t.equal(err.code, 400, 'error code') + t.equal(err.errno, 103, 'error errno') + t.equal(err.message, 'Incorrect password', 'message') + t.equal(err.error, 'Bad request', 'error') + }) + .then(function() { + t.pass('Checking password') + return db.checkPassword(ACCOUNT.uid, {verifyHash: zeroBuffer32}) + }) + .then(function(account) { + t.deepEqual(account.uid, ACCOUNT.uid, 'uid') + t.equal(Object.keys(account).length, 1, 'Only one field (uid) was returned, nothing else') + }) + .then(function() { + t.pass('Retrieving account using email') + var emailBuffer = Buffer(ACCOUNT.email) + return db.emailRecord(emailBuffer) + }) + .then(function(account) { + t.deepEqual(account.uid, ACCOUNT.uid, 'uid') + t.equal(account.email, ACCOUNT.email, 'email') + t.deepEqual(account.emailCode, ACCOUNT.emailCode, 'emailCode') + t.equal(!!account.emailVerified, ACCOUNT.emailVerified, 'emailVerified') + t.deepEqual(account.kA, ACCOUNT.kA, 'kA') + t.deepEqual(account.wrapWrapKb, ACCOUNT.wrapWrapKb, 'wrapWrapKb') + t.deepEqual(account.verifyHash, ACCOUNT.verifyHash, 'verifyHash') + t.deepEqual(account.authSalt, ACCOUNT.authSalt, 'authSalt') + t.equal(account.verifierVersion, ACCOUNT.verifierVersion, 'verifierVersion') + t.equal(account.verifierSetAt, ACCOUNT.verifierSetAt, 'verifierSetAt') + // locale not returned with .emailRecord() (unlike .account() when it is) + }) + // and we piggyback some duplicate query error handling here... + .then(function() { + return db.createAccount(ACCOUNT.uid, ACCOUNT) + }) + .then( + function() { + t.fail('this should have resulted in a duplicate account error') + }, + function(err) { + t.ok(err, 'trying to create the same account produces an error') + t.equal(err.code, 409, 'error code') + t.equal(err.errno, 101, 'error errno') + t.equal(err.message, 'Record already exists', 'message') + t.equal(err.error, 'Conflict', 'error') + } + ) + } + ) + + test( + 'session token handling', + function (t) { + t.plan(10) + return db.createSessionToken(SESSION_TOKEN_ID, SESSION_TOKEN) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on session token creation') + return db.sessionToken(SESSION_TOKEN_ID) + }) + .then(function(token) { + // tokenId is not returned from db.sessionToken() + t.deepEqual(token.tokenData, SESSION_TOKEN.data, 'token data matches') + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.equal(token.createdAt, SESSION_TOKEN.createdAt, 'createdAt is correct') + t.equal(!!token.emailVerified, ACCOUNT.emailVerified, 'token emailVerified is same as account emailVerified') + t.equal(token.email, ACCOUNT.email, 'token email same as account email') + t.deepEqual(token.emailCode, ACCOUNT.emailCode, 'token emailCode same as account emailCode') + t.equal(token.verifierSetAt, ACCOUNT.verifierSetAt, 'verifierSetAt is correct') + }) + .then(function() { + return db.deleteSessionToken(SESSION_TOKEN_ID) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on forgot key fetch token deletion') + return db.sessionToken(SESSION_TOKEN_ID) + }) + .then(function(token) { + t.fail('Session Token should no longer exist') + }, function(err) { + t.pass('Session Token deleted successfully') + }) + } + ) + + test( + 'key fetch token handling', + function (t) { + t.plan(8) + return db.createKeyFetchToken(KEY_FETCH_TOKEN_ID, KEY_FETCH_TOKEN) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on key fetch token creation') + return db.keyFetchToken(KEY_FETCH_TOKEN_ID) + }) + .then(function(token) { + // tokenId is not returned + t.deepEqual(token.authKey, KEY_FETCH_TOKEN.authKey, 'authKey matches') + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.equal(token.createdAt, KEY_FETCH_TOKEN.createdAt, 'createdAt is ok') + t.equal(!!token.emailVerified, ACCOUNT.emailVerified, 'emailVerified is correct') + // email is not returned + // emailCode is not returned + t.equal(token.verifierSetAt, ACCOUNT.verifierSetAt, 'verifierSetAt is correct') + }) + .then(function() { + return db.deleteKeyFetchToken(KEY_FETCH_TOKEN_ID) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on forgot key fetch token deletion') + return db.keyFetchToken(KEY_FETCH_TOKEN_ID) + }) + .then(function(token) { + t.fail('Key Fetch Token should no longer exist') + }, function(err) { + t.pass('Key Fetch Token deleted successfully') + }) + } + ) + + test( + 'forgot password token handling', + function (t) { + t.plan(25) + + var token + var THROWAWAY_PASSWORD_FORGOT_TOKEN_ID = hex32() + var THROWAWAY_PASSWORD_FORGOT_TOKEN = { + data : hex32(), + uid : ACCOUNT.uid, // same account uid + passCode : hex16(), + tries : 1, + createdAt: Date.now() + } + + return db.createPasswordForgotToken(PASSWORD_FORGOT_TOKEN_ID, PASSWORD_FORGOT_TOKEN) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on forgot password token creation') + return db.passwordForgotToken(PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(newToken) { + token = newToken + // tokenId is not returned + t.deepEqual(token.tokenData, PASSWORD_FORGOT_TOKEN.data, 'token data matches') + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.equal(token.createdAt, PASSWORD_FORGOT_TOKEN.createdAt, 'createdAt same') + t.deepEqual(token.passCode, PASSWORD_FORGOT_TOKEN.passCode, 'token passCode same') + t.equal(token.tries, PASSWORD_FORGOT_TOKEN.tries, 'Tries is correct') + t.equal(token.email, ACCOUNT.email, 'token email same as account email') + t.equal(token.verifierSetAt, ACCOUNT.verifierSetAt, 'verifierSetAt is set correctly') + }) + .then(function() { + return db.passwordForgotToken(PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(newToken) { + token = newToken + // tokenId is not returned + t.deepEqual(token.tokenData, PASSWORD_FORGOT_TOKEN.data, 'token data matches') + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.equal(token.createdAt, PASSWORD_FORGOT_TOKEN.createdAt, 'createdAt is correct') + t.deepEqual(token.passCode, PASSWORD_FORGOT_TOKEN.passCode, 'token passCode same') + t.equal(token.tries, PASSWORD_FORGOT_TOKEN.tries, 'Tries is correct') + t.equal(token.email, ACCOUNT.email, 'token email same as account email') + t.equal(token.verifierSetAt, ACCOUNT.verifierSetAt, 'verifierSetAt is correct') + }) + .then(function() { + // just update the tries + token.tries = 9 + return db.updatePasswordForgotToken(PASSWORD_FORGOT_TOKEN_ID, token) + }) + .then(function(result) { + t.deepEqual(result, {}, 'The returned object from the token update is empty') + // re-fetch the updated token + return db.passwordForgotToken(PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(newToken) { + t.deepEqual(newToken.uid, ACCOUNT.uid, 'token belongs to this account') + t.equal(newToken.tries, 9, 'token now has had 9 tries') + return db.deletePasswordForgotToken(PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on forgot password token deletion') + return db.passwordForgotToken(PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(newToken /* unused */) { + t.fail('Password Forgot Token should no longer exist') + }, function(err) { + t.pass('Password Forgot Token deleted successfully') + }) + .then(function() { + // insert a throwaway token + return db.createPasswordForgotToken(THROWAWAY_PASSWORD_FORGOT_TOKEN_ID, THROWAWAY_PASSWORD_FORGOT_TOKEN) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on forgot password token creation') + // and we should be able to retrieve it as usual + return db.passwordForgotToken(THROWAWAY_PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(token) { + // just check that the tokenData is what we expect (complete tests are above) + t.deepEqual(token.tokenData, THROWAWAY_PASSWORD_FORGOT_TOKEN.data, 'token data matches') + // now, let's insert a different passwordForgotToken with the same uid + return db.createPasswordForgotToken(PASSWORD_FORGOT_TOKEN_ID, PASSWORD_FORGOT_TOKEN) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on forgot password token creation (when overwriting another)') + // if we retrieve the throwaway one, we should fail + return db.passwordForgotToken(THROWAWAY_PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(newToken /* unused */) { + t.fail('Throwaway Password Forgot Token should no longer exist') + }, function(err) { + t.pass('Throwaway Password Forgot Token deleted successfully') + // but the new one is still there + return db.passwordForgotToken(PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(token) { + // just check that the tokenData is what we expect (complete tests are above) + t.deepEqual(token.tokenData, PASSWORD_FORGOT_TOKEN.data, 'token data matches') + }, function(err) { + t.fail('We should have been able to retrieve the new password forgot token') + }) + } + ) + + test( + 'change password token handling', + function (t) { + t.plan(12) + + var THROWAWAY_PASSWORD_CHANGE_TOKEN_ID = hex32() + var THROWAWAY_PASSWORD_CHANGE_TOKEN = { + data : hex32(), + uid : ACCOUNT.uid, // same account uid + createdAt: Date.now() + } + + return db.createPasswordChangeToken(PASSWORD_CHANGE_TOKEN_ID, PASSWORD_CHANGE_TOKEN) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on change password token creation') + return db.passwordChangeToken(PASSWORD_CHANGE_TOKEN_ID) + }) + .then(function(token) { + // tokenId is not returned + t.deepEqual(token.tokenData, PASSWORD_CHANGE_TOKEN.data, 'token data matches') + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.equal(token.createdAt, PASSWORD_CHANGE_TOKEN.createdAt, 'createdAt is correct') + t.equal(token.verifierSetAt, ACCOUNT.verifierSetAt, 'verifierSetAt is set correctly') + }) + .then(function() { + return db.deletePasswordChangeToken(PASSWORD_CHANGE_TOKEN_ID) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on forgot password change deletion') + return db.passwordChangeToken(PASSWORD_CHANGE_TOKEN_ID) + }) + .then(function(token) { + t.fail('Password Change Token should no longer exist') + }, function(err) { + t.pass('Password Change Token deleted successfully') + }) + .then(function() { + // insert a throwaway token + return db.createPasswordChangeToken(THROWAWAY_PASSWORD_CHANGE_TOKEN_ID, THROWAWAY_PASSWORD_CHANGE_TOKEN) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on change password token creation') + // and we should be able to retrieve it as usual + return db.passwordChangeToken(THROWAWAY_PASSWORD_CHANGE_TOKEN_ID) + }) + .then(function(token) { + // just check that the tokenData is what we expect (complete tests are above) + t.deepEqual(token.tokenData, THROWAWAY_PASSWORD_CHANGE_TOKEN.data, 'token data matches') + // now, let's insert a different passwordChangeToken with the same uid + return db.createPasswordChangeToken(PASSWORD_CHANGE_TOKEN_ID, PASSWORD_CHANGE_TOKEN) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on change password token creation (when overwriting another)') + // if we retrieve the throwaway one, we should fail + return db.passwordChangeToken(THROWAWAY_PASSWORD_CHANGE_TOKEN_ID) + }) + .then(function(newToken /* unused */) { + t.fail('Throwaway Password Change Token should no longer exist') + }, function(err) { + t.pass('Throwaway Password Change Token deleted successfully') + // but the new one is still there + return db.passwordChangeToken(PASSWORD_CHANGE_TOKEN_ID) + }) + .then(function(token) { + // just check that the tokenData is what we expect (complete tests are above) + t.deepEqual(token.tokenData, PASSWORD_CHANGE_TOKEN.data, 'token data matches') + }, function(err) { + t.fail('We should have been able to retrieve the new password change token') + }) + } + ) + + test( + 'email verification and locale change', + function (t) { + t.plan(6) + + var emailBuffer = Buffer(ACCOUNT.email) + return db.emailRecord(emailBuffer) + .then(function(emailRecord) { + return db.verifyEmail(emailRecord.uid) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object email verification') + return db.account(ACCOUNT.uid) + }) + .then(function(account) { + t.ok(account.emailVerified, 'account should now be emailVerified (truthy)') + t.equal(account.emailVerified, 1, 'account should now be emailVerified (1)') + + account.locale = 'en_NZ' + return db.updateLocale(ACCOUNT.uid, account) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object for updateLocale') + return db.account(ACCOUNT.uid) + }) + .then(function(account) { + t.equal(account.locale, 'en_NZ', 'account should now have new locale') + + // test verifyEmail for a non-existant account + return db.verifyEmail(newUuid()) + }) + .then(function(res) { + t.deepEqual(res, {}, 'No matter what happens, we get an empty object back') + }, function(err) { + t.fail('We should not have failed this .verifyEmail() request') + }) + } + ) + + test( + 'locked accounts', + function (t) { + t.plan(7) + + var lockedAt = Date.now() + var unlockCode = hex16() + var uid = ACCOUNT.uid + var email = Buffer(ACCOUNT.email) + + // set lockedAt + return db.lockAccount(uid, { lockedAt: lockedAt, unlockCode: unlockCode }) + .then(null, function(err) { + t.fail('We should not have failed this .lockAccount() request') + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object for lockAccount') + return db.account(uid) + }) + .then(function(account) { + t.equal(account.lockedAt, lockedAt, 'account should now be locked') + return db.emailRecord(email) + }) + .then(function(emailRecord) { + t.equal(emailRecord.lockedAt, lockedAt, 'emailRecord should show the account as locked') + + return db.unlockCode(uid) + }) + .then(function (_unlockCode) { + t.deepEqual(_unlockCode.unlockCode, unlockCode, 'unlockCode should be set') + + // try to unlock the account + return db.unlockAccount(uid) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object for unlockAccount') + // get this account back out + return db.account(uid) + }, function(err) { + t.fail('We should not have failed this .unlockAccount() request') + }) + .then(function(account) { + t.equal(account.lockedAt, null, 'account should now be unlocked') + // now check it's been saved + return db.emailRecord(email) + }) + .then(function(emailRecord) { + t.equal(emailRecord.lockedAt, null, 'emailRecord should now show the account as unlocked') + }) + } + ) + + test( + 'account reset token handling', + function (t) { + t.plan(14) + + // create a second accountResetToken + var accountResetTokenId = hex32() + var accountResetToken = { + data : hex32(), + uid : ACCOUNT.uid, + createdAt: Date.now() + } + + return db.createAccountResetToken(ACCOUNT_RESET_TOKEN_ID, ACCOUNT_RESET_TOKEN) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on account reset token creation') + return db.accountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(token) { + // tokenId is not returned + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.deepEqual(token.tokenData, ACCOUNT_RESET_TOKEN.data, 'token data matches') + t.equal(token.createdAt, ACCOUNT_RESET_TOKEN.createdAt, 'createdAt is correct') + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + }) + .then(function() { + return db.deleteAccountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on account reset deletion') + return db.accountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(token) { + t.fail('Account Reset Token should no longer exist') + }, function(err) { + t.pass('Account Reset Token deleted successfully') + }) + .then(function() { + // Now add back in the original token + return db.createAccountResetToken(ACCOUNT_RESET_TOKEN_ID, ACCOUNT_RESET_TOKEN) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on account reset token creation (for the 2nd time)') + // get this back out + return db.accountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(token) { + // tokenId is not returned + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.deepEqual(token.tokenData, ACCOUNT_RESET_TOKEN.data, 'token data matches') + // replace this token with a new one + return db.createAccountResetToken(accountResetTokenId, accountResetToken) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on second account reset token creation') + // now retrieve this one + return db.accountResetToken(accountResetTokenId) + }) + .then(function(token) { + // check a couple of fields + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.deepEqual(token.tokenData, accountResetToken.data, 'token data matches') + // now check that the original token no longer exists + return db.accountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(token) { + t.fail('Original Account Reset Token should no longer exist') + }, function(err) { + t.pass('Original Account Reset Token is no longer there') + }) + } + ) + + test( + 'db.forgotPasswordVerified', + function (t) { + t.plan(18) + // for this test, we are creating a new account with a different email address + // so that we can check that emailVerified turns from false to true (since + // we already set it to true earlier) + var now = Date.now() + var ACCOUNT = { + uid: newUuid(), + email: ('' + Math.random()).substr(2) + '@bar.com', + emailCode: zeroBuffer16, + emailVerified: false, + verifierVersion: 1, + verifyHash: zeroBuffer32, + authSalt: zeroBuffer32, + kA: zeroBuffer32, + wrapWrapKb: zeroBuffer32, + verifierSetAt: now, + createdAt: now, + locale: 'en_GB', + } + ACCOUNT.normalizedEmail = ACCOUNT.email.toLowerCase() + var PASSWORD_FORGOT_TOKEN_ID = hex32() + var PASSWORD_FORGOT_TOKEN = { + data : hex32(), + uid : ACCOUNT.uid, + passCode : hex16(), + tries : 1, + createdAt: now + 1 + } + var ACCOUNT_RESET_TOKEN_ID = hex32() + var ACCOUNT_RESET_TOKEN = { + tokenId : ACCOUNT_RESET_TOKEN_ID, + data : hex32(), + uid : ACCOUNT.uid, + createdAt: now + 2 + } + var THROWAWAY_ACCOUNT_RESET_TOKEN_ID = hex32() + var THROWAWAY_ACCOUNT_RESET_TOKEN = { + tokenId : ACCOUNT_RESET_TOKEN_ID, + data : hex32(), + uid : ACCOUNT.uid, + createdAt: now + 3 + } + var ACCOUNT_UNLOCK_CODE = hex16() + + return db.createAccount(ACCOUNT.uid, ACCOUNT) + .then(function() { + // let's add a throwaway accountResetToken, which should be overwritten when + // we call passwordForgotToken() later. + return db.createAccountResetToken(THROWAWAY_ACCOUNT_RESET_TOKEN_ID, THROWAWAY_ACCOUNT_RESET_TOKEN) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on account reset token creation (the throwaway one)') + // let's get it back out to make sure it is there + return db.accountResetToken(THROWAWAY_ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(token) { + // check a couple of fields + t.deepEqual(token.uid, ACCOUNT.uid, 'token belongs to this account') + t.deepEqual(token.tokenData, THROWAWAY_ACCOUNT_RESET_TOKEN.data, 'token data matches') + // get this account out using emailRecord + var emailBuffer = Buffer(ACCOUNT.email) + return db.emailRecord(emailBuffer) + }) + .then(function(result) { + t.pass('.emailRecord() did not error') + return db.createPasswordForgotToken(PASSWORD_FORGOT_TOKEN_ID, PASSWORD_FORGOT_TOKEN) + }) + .then(function(passwordForgotToken) { + t.pass('.createPasswordForgotToken() did not error') + // let's also lock the account here so we can check it is unlocked after the createPasswordForgotToken() + return db.lockAccount(ACCOUNT.uid, { lockedAt: Date.now(), unlockCode: ACCOUNT_UNLOCK_CODE }) + }) + .then(function(passwordForgotToken) { + t.pass('.lockAccount() did not error') + return db.forgotPasswordVerified(PASSWORD_FORGOT_TOKEN_ID, ACCOUNT_RESET_TOKEN) + }) + .then(function() { + t.pass('.forgotPasswordVerified() did not error') + // now check that the forgotPasswordVerified also reset the lockedAt + return db.emailRecord(Buffer(ACCOUNT.email)) + }) + .then(function(account) { + t.equal(account.lockedAt, null, 'account should now be unlocked') + return db.forgotPasswordVerified(PASSWORD_FORGOT_TOKEN_ID, ACCOUNT_RESET_TOKEN) + }) + .then(function() { + t.pass('.forgotPasswordVerified() did not error') + // let's try and get the throwaway accountResetToken (shouldn't exist any longer) + return db.accountResetToken(THROWAWAY_ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(token) { + t.fail('Throwaway Account Reset Token should no longer exist') + }, function(err) { + t.pass('Throwaway Account Reset Token deleted during forgotPasswordVerified') + // retrieve passwordForgotToken (shouldn't exist now) + return db.passwordForgotToken(PASSWORD_FORGOT_TOKEN_ID) + }) + .then(function(token) { + t.fail('Password Forgot Token should no longer exist') + }, function(err) { + t.pass('Password Forgot Token deleted successfully') + }) + .then(function() { + return db.accountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(accountResetToken) { + t.pass('.accountResetToken() did not error') + // tokenId is not returned + t.deepEqual(accountResetToken.uid, ACCOUNT.uid, 'token belongs to this account') + t.deepEqual(accountResetToken.tokenData, ACCOUNT_RESET_TOKEN.data, 'token data matches') + t.equal(accountResetToken.verifierSetAt, ACCOUNT.verifierSetAt, 'verifierSetAt is set correctly') + }) + .then(function() { + return db.account(ACCOUNT.uid) + }) + .then(function(account) { + t.ok(account.emailVerified, 'account should now be emailVerified (truthy)') + t.equal(account.emailVerified, 1, 'account should now be emailVerified (1)') + }) + .then(function() { + return db.deleteAccountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object on account reset deletion') + return db.accountResetToken(ACCOUNT_RESET_TOKEN_ID) + }) + .then(function(token) { + t.fail('Account Reset Token should no longer exist') + }, function(err) { + t.pass('Account Reset Token deleted successfully') + }) + } + ) + + test( + 'db.accountDevices', + function (t) { + t.plan(3) + var anotherSessionTokenId = hex32() + var anotherSessionToken = { + data : hex32(), + uid : ACCOUNT.uid, + createdAt: Date.now(), + } + db.createSessionToken(SESSION_TOKEN_ID, SESSION_TOKEN) + .then(function(sessionToken) { + return db.createSessionToken(anotherSessionTokenId, anotherSessionToken) + }) + .then(function() { + return db.accountDevices(ACCOUNT.uid) + }) + .then(function(devices) { + t.equal(devices.length, 2, 'Account devices should be two') + return devices[0] + }) + .then(function(sessionToken) { + return db.deleteSessionToken(SESSION_TOKEN_ID) + }) + .then(function(sessionToken) { + return db.accountDevices(ACCOUNT.uid) + }) + .then(function(devices) { + t.equal(devices.length, 1, 'Account devices should be one') + return devices[0] + }) + .then(function(sessionToken) { + return db.deleteSessionToken(anotherSessionTokenId) + }) + .then(function(sessionToken) { + return db.accountDevices(ACCOUNT.uid) + }) + .then(function(devices) { + t.equal(devices.length, 0, 'Account devices should be zero') + }) + } + ) + + test( + 'db.resetAccount', + function (t) { + t.plan(9) + var uid = ACCOUNT.uid + var lockedAt = Date.now() + var unlockCode = hex16() + + return db.createSessionToken(SESSION_TOKEN_ID, SESSION_TOKEN) + .then(function(sessionToken) { + t.pass('.createSessionToken() did not error') + return db.createAccountResetToken(ACCOUNT_RESET_TOKEN_ID, ACCOUNT_RESET_TOKEN) + }) + .then(function() { + t.pass('.createAccountResetToken() did not error') + // lock the account to ensure the unlockCode is deleted + return db.lockAccount(uid, { lockedAt: lockedAt, unlockCode: unlockCode }) + }) + .then(function() { + t.pass('.lockAccount() did not error') + return db.unlockCode(uid) + }) + .then(function(unlockCode) { + t.ok(unlockCode.unlockCode, 'unlockCode is correctly returned') + return db.resetAccount(uid, ACCOUNT) + }) + .then(function(sessionToken) { + t.pass('.resetAccount() did not error') + return db.accountDevices(uid) + }) + .then(function(devices) { + t.pass('.accountDevices() did not error') + t.equal(devices.length, 0, 'The devices length should be zero') + }) + .then(function() { + // account should STILL exist for this email address + var emailBuffer = Buffer(ACCOUNT.email) + return db.accountExists(emailBuffer) + }) + .then(function(exists) { + t.ok(exists, 'account still exists ok') + return db.unlockCode(uid) + }, function(err) { + t.fail('the account for this email address should still exist') + }) + .then(function(unlockCode) { + t.fail('an unlockCode should no longer exist for this uid') + }, function(err) { + t.pass('unlockCode is deleted for this uid') + }) + } + ) + + test( + 'account deletion', + function (t) { + t.plan(3) + var uid = ACCOUNT.uid + var lockedAt = Date.now() + var unlockCode = hex16() + // lock the account to ensure the unlockCode is deleted + return db.lockAccount(uid, { lockedAt: lockedAt, unlockCode: unlockCode }) + .then(function() { + return db.deleteAccount(uid) + }) + .then(function() { + // account should no longer exist for this email address + var emailBuffer = Buffer(ACCOUNT.email) + return db.accountExists(emailBuffer) + }) + .then(function(exists) { + t.fail('account should no longer exist for this email address') + }, function(err) { + t.pass('account no longer exists for this email address') + return db.unlockCode(uid) + }) + .then(function(unlockCode) { + t.fail('an unlockCode should no longer exist for this uid') + }, function(err) { + t.pass('unlockCode is deleted for this uid') + + // try to unlock the account + return db.unlockAccount(uid) + }) + .then(function(result) { + t.deepEqual(result, {}, 'Returned an empty object for unlockAccount') + }, function(err) { + t.fail('We should not have failed this .unlockAccount() request') + }) + } + ) + + test( + 'teardown', + function (t) { + return db.close() + } + ) + + } + ) +} diff --git a/fxa-auth-db-server/test/backend/index.js b/fxa-auth-db-server/test/backend/index.js new file mode 100644 index 0000000..bb6c9a3 --- /dev/null +++ b/fxa-auth-db-server/test/backend/index.js @@ -0,0 +1,7 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +module.exports = { + dbTests: require('./db_tests'), + remote: require('./remote'), +} diff --git a/fxa-auth-db-server/test/backend/remote.js b/fxa-auth-db-server/test/backend/remote.js new file mode 100644 index 0000000..3a87f7d --- /dev/null +++ b/fxa-auth-db-server/test/backend/remote.js @@ -0,0 +1,556 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +var test = require('tap').test + +var crypto = require('crypto') +var fake = require('../fake') +var P = require('../../lib/promise') +var clientThen = require('../client-then') + +function emailToHex(email) { + return Buffer(email).toString('hex') +} + +// Helper function that performs two tests: +// +// (1) checks that the response is a 200 +// (2) checks that the content-type header is correct +// +// Takes the test object (t) and the response object (r). +function respOk(t, r) { + t.equal(r.res.statusCode, 200, 'returns a 200') + t.equal(r.res.headers['content-type'], 'application/json', 'json is returned') +} + +// Helper function that performs three tests: +// +// (1) checks that the response is a 200 +// (2) checks that the content-type header is correct +// (3) checks that the response was an empty object +// +// Takes the test object (t) and the response object (r). +function respOkEmpty(t, r) { + t.equal(r.res.statusCode, 200, 'returns a 200') + t.equal(r.res.headers['content-type'], 'application/json', 'json is returned') + t.deepEqual(r.obj, {}, 'Returned object is empty') +} + +// Helper function that performs two tests: +// +// (1) checks that the response is a 404 +// (2) checks that the error body for a 404 is consistent +// +// Takes the test object (t) and the error object (err). +function testNotFound(t, err) { + t.equal(err.statusCode, 404, 'returns a 404') + t.deepEqual(err.body, { message : 'Not Found' }, 'Object contains no other fields') +} + +// To run these tests from a new backend, create a DB instance, start a test server +// and pass the config containing the connection params to this function. The tests +// will run against that server. +module.exports = function(cfg) { + + var d = P.defer() + + console.log(cfg) + var client = clientThen({ url : 'http://' + cfg.hostname + ':' + cfg.port }) + console.log({ url : 'http://' + cfg.hostname + ':' + cfg.port }) + + test( + 'heartbeat', + function (t) { + client.getThen('/__heartbeat__') + .then(function (r) { + t.deepEqual(r.obj, {}, 'Heartbeat contains an empty object and nothing unexpected') + t.end() + }) + } + ) + + test( + 'account not found', + function (t) { + t.plan(2) + client.getThen('/account/hello-world') + .then(function(r) { + t.fail('This request should have failed (instead it suceeded)') + t.end() + }, function(err) { + testNotFound(t, err) + t.end() + }) + } + ) + + test( + 'add account, check password, retrieve it, delete it', + function (t) { + t.plan(35) + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then(function(r) { + respOkEmpty(t, r) + var randomPassword = Buffer(crypto.randomBytes(32)).toString('hex') + return client.postThen('/account/' + user.accountId + '/checkPassword', {'verifyHash': randomPassword}) + }) + .then(function(r) { + t.fail('should not be here, password isn\'t valid') + }, function(err) { + t.ok(err, 'incorrect password produces an error') + return client.postThen('/account/' + user.accountId + '/checkPassword', {'verifyHash': user.account.verifyHash}) + }) + .then(function(r) { + respOk(t, r) + var account = r.obj + t.equal(account.uid, user.accountId) + return client.getThen('/account/' + user.accountId) + }) + .then(function(r) { + respOk(t, r) + + var account = r.obj + var fields = 'accountId,email,emailCode,kA,verifierVersion,verifyHash,authSalt'.split(',') + fields.forEach(function(f) { + t.equal(user.account[f], account[f], 'Both Fields ' + f + ' are the same') + }) + t.equal(user.account.emailVerified, !!account.emailVerified, 'Both fields emailVerified are the same') + }, function(err) { + t.fail('Error for some reason:' + err) + }) + .then(function() { + return client.headThen('/emailRecord/' + emailToHex(user.account.email)) + }) + .then(function(r) { + respOkEmpty(t, r) + return client.getThen('/emailRecord/' + emailToHex(user.account.email)) + }) + .then(function(r) { + respOk(t, r) + var account = r.obj + var fields = 'accountId,email,emailCode,kA,verifierVersion,verifyHash,authSalt'.split(',') + fields.forEach(function(f) { + t.equal(user.account[f], account[f], 'Both Fields ' + f + ' are the same') + }) + t.equal(user.account.emailVerified, !!account.emailVerified, 'Both fields emailVerified are the same') + }) + .then(function() { + return client.delThen('/account/' + user.accountId) + }) + .then(function(r) { + respOk(t, r) + // now make sure this record no longer exists + return client.headThen('/emailRecord/' + emailToHex(user.account.email)) + }) + .then(function(r) { + t.fail('Should not be here, since this account no longer exists') + }, function(err) { + t.equal(err.toString(), 'NotFoundError', 'Account not found (no body due to being a HEAD request') + t.deepEqual(err.body, {}, 'Body contains nothing since this is a HEAD request') + t.deepEqual(err.statusCode, 404, 'Status Code is 404') + }) + .done(function() { + t.end() + }, function(err) { + t.fail(err) + t.end() + }) + } + ) + + test( + 'session token handling', + function (t) { + t.plan(14) + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then(function() { + return client.getThen('/sessionToken/' + user.sessionTokenId) + }) + .then(function(r) { + t.fail('A non-existant session token should not have returned anything') + }, function(err) { + t.pass('No session token exists yet') + return client.putThen('/sessionToken/' + user.sessionTokenId, user.sessionToken) + }) + .then(function(r) { + respOk(t, r) + return client.getThen('/sessionToken/' + user.sessionTokenId) + }) + .then(function(r) { + var token = r.obj + + // tokenId is not returned from db.sessionToken() + t.deepEqual(token.tokenData, user.sessionToken.data, 'token data matches') + t.deepEqual(token.uid, user.accountId, 'token belongs to this account') + t.ok(token.createdAt, 'Got a createdAt') + t.equal(!!token.emailVerified, user.account.emailVerified, 'emailVerified same as account emailVerified') + t.equal(token.email, user.account.email, 'token.email same as account email') + t.deepEqual(token.emailCode, user.account.emailCode, 'token emailCode same as account emailCode') + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + + // now delete it + return client.delThen('/sessionToken/' + user.sessionTokenId) + }) + .then(function(r) { + respOk(t, r) + // now make sure the token no longer exists + return client.getThen('/sessionToken/' + user.sessionTokenId) + }) + .then(function(r) { + t.fail('Fetching the non-existant sessionToken should have failed') + t.end() + }, function(err) { + testNotFound(t, err) + t.end() + }) + } + ) + + test( + 'key fetch token handling', + function (t) { + t.plan(13) + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then(function() { + return client.getThen('/keyFetchToken/' + user.keyFetchTokenId) + }) + .then(function(r) { + t.fail('A non-existant session token should not have returned anything') + }, function(err) { + t.pass('No session token exists yet') + return client.putThen('/keyFetchToken/' + user.keyFetchTokenId, user.keyFetchToken) + }) + .then(function(r) { + respOk(t, r) + return client.getThen('/keyFetchToken/' + user.keyFetchTokenId) + }) + .then(function(r) { + var token = r.obj + + // tokenId is not returned from db.keyFetchToken() + t.deepEqual(token.uid, user.accountId, 'token belongs to this account') + t.deepEqual(token.authKey, user.keyFetchToken.authKey, 'authKey matches') + t.deepEqual(token.keyBundle, user.keyFetchToken.keyBundle, 'keyBundle matches') + t.ok(token.createdAt, 'Got a createdAt') + t.equal(!!token.emailVerified, user.account.emailVerified) + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + + // now delete it + return client.delThen('/keyFetchToken/' + user.keyFetchTokenId) + }) + .then(function(r) { + respOk(t, r) + // now make sure the token no longer exists + return client.getThen('/keyFetchToken/' + user.keyFetchTokenId) + }) + .then(function(r) { + t.fail('Fetching the non-existant keyFetchToken should have failed') + t.end() + }, function(err) { + testNotFound(t, err) + t.end() + }) + } + ) + + test( + 'account reset token handling', + function (t) { + t.plan(11) + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then(function() { + return client.getThen('/accountResetToken/' + user.accountResetTokenId) + }) + .then(function(r) { + t.fail('A non-existant session token should not have returned anything') + }, function(err) { + t.pass('No session token exists yet') + return client.putThen('/accountResetToken/' + user.accountResetTokenId, user.accountResetToken) + }) + .then(function(r) { + respOk(t, r) + return client.getThen('/accountResetToken/' + user.accountResetTokenId) + }) + .then(function(r) { + var token = r.obj + + // tokenId is not returned from db.accountResetToken() + t.deepEqual(token.uid, user.accountId, 'token belongs to this account') + t.deepEqual(token.tokenData, user.accountResetToken.data, 'token data matches') + t.ok(token.createdAt, 'Got a createdAt') + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + + // now delete it + return client.delThen('/accountResetToken/' + user.accountResetTokenId) + }) + .then(function(r) { + respOk(t, r) + // now make sure the token no longer exists + return client.getThen('/accountResetToken/' + user.accountResetTokenId) + }) + .then(function(r) { + t.fail('Fetching the non-existant accountResetToken should have failed') + t.end() + }, function(err) { + testNotFound(t, err) + t.end() + }) + } + ) + + test( + 'password change token handling', + function (t) { + t.plan(11) + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then(function() { + return client.getThen('/passwordChangeToken/' + user.passwordChangeTokenId) + }) + .then(function(r) { + t.fail('A non-existant session token should not have returned anything') + }, function(err) { + t.pass('No session token exists yet') + return client.putThen('/passwordChangeToken/' + user.passwordChangeTokenId, user.passwordChangeToken) + }) + .then(function(r) { + respOk(t, r) + return client.getThen('/passwordChangeToken/' + user.passwordChangeTokenId) + }) + .then(function(r) { + var token = r.obj + + // tokenId is not returned from db.passwordChangeToken() + t.deepEqual(token.tokenData, user.passwordChangeToken.data, 'token data matches') + t.deepEqual(token.uid, user.accountId, 'token belongs to this account') + t.ok(token.createdAt, 'Got a createdAt') + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + + // now delete it + return client.delThen('/passwordChangeToken/' + user.passwordChangeTokenId) + }) + .then(function(r) { + respOk(t, r) + // now make sure the token no longer exists + return client.getThen('/passwordChangeToken/' + user.passwordChangeTokenId) + }) + .then(function(r) { + t.fail('Fetching the non-existant passwordChangeToken should have failed') + t.end() + }, function(err) { + testNotFound(t, err) + t.end() + }) + } + ) + + test( + 'password forgot token handling', + function (t) { + t.plan(19) + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then(function() { + return client.getThen('/passwordForgotToken/' + user.passwordForgotTokenId) + }) + .then(function(r) { + t.fail('A non-existant session token should not have returned anything') + }, function(err) { + t.pass('No session token exists yet') + return client.putThen('/passwordForgotToken/' + user.passwordForgotTokenId, user.passwordForgotToken) + }) + .then(function(r) { + respOk(t, r) + return client.getThen('/passwordForgotToken/' + user.passwordForgotTokenId) + }) + .then(function(r) { + var token = r.obj + + // tokenId is not returned from db.passwordForgotToken() + t.deepEqual(token.tokenData, user.passwordForgotToken.data, 'token data matches') + t.deepEqual(token.uid, user.accountId, 'token belongs to this account') + t.ok(token.createdAt, 'Got a createdAt') + t.deepEqual(token.passCode, user.passwordForgotToken.passCode) + t.equal(token.tries, user.passwordForgotToken.tries, 'Tries is correct') + t.equal(token.email, user.account.email) + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + + // now update this token (with extra tries) + user.passwordForgotToken.tries += 1 + return client.postThen('/passwordForgotToken/' + user.passwordForgotTokenId + '/update', user.passwordForgotToken) + }) + .then(function(r) { + respOk(t, r) + + // re-fetch this token + return client.getThen('/passwordForgotToken/' + user.passwordForgotTokenId) + }) + .then(function(r) { + var token = r.obj + + // tokenId is not returned from db.passwordForgotToken() + t.deepEqual(token.tokenData, user.passwordForgotToken.data, 'token data matches') + t.deepEqual(token.uid, user.accountId, 'token belongs to this account') + t.ok(token.createdAt, 'Got a createdAt') + t.deepEqual(token.passCode, user.passwordForgotToken.passCode) + t.equal(token.tries, user.passwordForgotToken.tries, 'Tries is correct (now incremented)') + t.equal(token.email, user.account.email) + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + + // now delete it + return client.delThen('/passwordForgotToken/' + user.passwordForgotTokenId) + }) + .then(function(r) { + respOk(t, r) + // now make sure the token no longer exists + return client.getThen('/passwordForgotToken/' + user.passwordForgotTokenId) + }) + .then(function(r) { + t.fail('Fetching the non-existant passwordForgotToken should have failed') + t.end() + }, function(err) { + testNotFound(t, err) + t.end() + }) + } + ) + + test( + 'password forgot token verified', + function (t) { + t.plan(16) + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then(function(r) { + respOk(t, r) + return client.putThen('/passwordForgotToken/' + user.passwordForgotTokenId, user.passwordForgotToken) + }) + .then(function(r) { + respOk(t, r) + // now, verify the password (which inserts the accountResetToken) + user.accountResetToken.tokenId = user.accountResetTokenId + return client.postThen('/passwordForgotToken/' + user.passwordForgotTokenId + '/verified', user.accountResetToken) + }) + .then(function(r) { + respOk(t, r) + // check the accountResetToken exists + return client.getThen('/accountResetToken/' + user.accountResetTokenId) + }) + .then(function(r) { + var token = r.obj + + // tokenId is not returned from db.accountResetToken() + t.deepEqual(token.uid, user.accountId, 'token belongs to this account') + t.deepEqual(token.tokenData, user.accountResetToken.data, 'token data matches') + t.ok(token.createdAt, 'Got a createdAt') + t.ok(token.verifierSetAt, 'verifierSetAt is set to a truthy value') + + // make sure then passwordForgotToken no longer exists + return client.getThen('/passwordForgotToken/' + user.passwordForgotTokenId) + }) + .then(function(r) { + t.fail('Fetching the non-existant passwordForgotToken should have failed') + }, function(err) { + testNotFound(t, err) + // and check that the account has been verified + return client.getThen('/emailRecord/' + emailToHex(user.account.email)) + }) + .then(function(r) { + respOk(t, r) + var account = r.obj + t.equal(true, !!account.emailVerified, 'emailVerified is now true') + }) + .then(function(r) { + t.pass('All password forgot token verified tests passed') + t.end() + }, function(err) { + t.fail(err) + t.end() + }) + } + ) + + test( + 'locale', + function (t) { + var user = fake.newUserDataHex() + client.putThen('/account/' + user.accountId, user.account) + .then( + function (r) { + respOk(t, r) + return client.putThen('/sessionToken/' + user.sessionTokenId, user.sessionToken) + } + ) + .then( + function (r) { + respOk(t, r) + return client.postThen('/account/' + user.accountId + '/locale', { locale: 'en-US'}) + } + ) + .then( + function (r) { + respOk(t, r) + return client.getThen('/sessionToken/' + user.sessionTokenId) + } + ) + .done( + function (r) { + respOk(t, r) + t.equal('en-US', r.obj.locale, 'locale was set properly') + t.end() + } + ) + } + ) + + test( + 'add account, lock it, unlock it', + function (t) { + var user = fake.newUserDataHex() + var unlockCode = user.unlockCode + client.putThen('/account/' + user.accountId, user.account) + .then( + function (r) { + respOk(t, r) + return client.postThen('/account/' + user.accountId + '/lock', { lockedAt: Date.now(), unlockCode: unlockCode }) + } + ) + .then( + function (r) { + respOk(t, r) + return client.getThen('/account/' + user.accountId + '/unlockCode') + } + ) + .then( + function (r) { + respOk(t, r) + + t.equal(r.obj.unlockCode, unlockCode, 'unlockCode was set properly') + + return client.postThen('/account/' + user.accountId + '/unlock') + } + ) + .then( + function (r) { + respOk(t, r) + t.end() + } + ) + } + ) + + test( + 'teardown', + function (t) { + d.resolve() + t.end() + } + ) + + return d.promise + +} diff --git a/fxa-auth-db-server/test/client-then.js b/fxa-auth-db-server/test/client-then.js new file mode 100644 index 0000000..8cfc823 --- /dev/null +++ b/fxa-auth-db-server/test/client-then.js @@ -0,0 +1,31 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +var restify = require('restify') +var P = require('../lib/promise.js') + +var ops = [ 'head', 'get', 'post', 'put', 'del' ] + +module.exports = function createClient(cfg) { + cfg.agent = false + cfg.headers = { + connection : 'close', + } + var client = restify.createJsonClient(cfg) + + // create a thenable version of each operation + ops.forEach(function(name) { + client[name + 'Then'] = function() { + var p = P.defer() + var args = Array.prototype.slice.call(arguments, 0) + args.push(function(err, req, res, obj) { + if (err) return p.reject(err) + p.resolve({ req: req, res: res, obj: obj }) + }) + client[name].apply(this, args) + return p.promise + } + }) + + return client +} diff --git a/fxa-auth-db-server/test/fake.js b/fxa-auth-db-server/test/fake.js new file mode 100644 index 0000000..d64c7d3 --- /dev/null +++ b/fxa-auth-db-server/test/fake.js @@ -0,0 +1,154 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +var crypto = require('crypto') + +function hex(len) { + return crypto.randomBytes(len).toString('hex') +} +function hex16() { return hex(16) } +function hex32() { return hex(32) } +// function hex64() { return hex(64) } +function hex96() { return hex(96) } + +function buf(len) { + return Buffer(crypto.randomBytes(len)) +} +function buf16() { return buf(16) } +function buf32() { return buf(32) } +// function buf64() { return buf(64) } +function buf96() { return buf(96) } + +module.exports.newUserDataHex = function() { + var data = {} + + // account + data.accountId = hex16() + data.account = { + email: hex16() + '@example.com', + emailCode: hex16(), + emailVerified: false, + verifierVersion: 1, + verifyHash: hex32(), + authSalt: hex32(), + kA: hex32(), + wrapWrapKb: hex32(), + verifierSetAt: Date.now(), + createdAt: Date.now(), + } + data.account.normalizedEmail = data.account.email.toLowerCase() + + // sessionToken + data.sessionTokenId = hex32() + data.sessionToken = { + data : hex32(), + uid : data.accountId, + createdAt: Date.now() + } + + // keyFetchToken + data.keyFetchTokenId = hex32() + data.keyFetchToken = { + authKey : hex32(), + uid : data.accountId, + keyBundle : hex96(), + createdAt: Date.now() + } + + // accountResetToken + data.accountResetTokenId = hex32() + data.accountResetToken = { + data : hex32(), + uid : data.accountId, + createdAt: Date.now() + } + + // passwordChangeToken + data.passwordChangeTokenId = hex32() + data.passwordChangeToken = { + data : hex32(), + uid : data.accountId, + createdAt: Date.now() + } + + // passwordForgotToken + data.passwordForgotTokenId = hex32() + data.passwordForgotToken = { + data : hex32(), + uid : data.accountId, + passCode : hex16(), + tries : 1, + createdAt: Date.now() + } + + data.unlockCode = hex16() + + return data +} + +module.exports.newUserDataBuffer = function() { + var data = {} + + // account + data.accountId = buf16() + data.account = { + email: buf16() + '@example.com', + emailCode: buf16(), + emailVerified: false, + verifierVersion: 1, + verifyHash: buf32(), + authSalt: buf32(), + kA: buf32(), + wrapWrapKb: buf32(), + verifierSetAt: Date.now(), + createdAt: Date.now(), + } + data.account.normalizedEmail = data.account.email.toLowerCase() + + // sessionToken + data.sessionTokenId = buf32() + data.sessionToken = { + data : buf32(), + uid : data.accountId, + createdAt: Date.now() + } + + // keyFetchToken + data.keyFetchTokenId = buf32() + data.keyFetchToken = { + authKey : buf32(), + uid : data.accountId, + keyBundle : buf96(), + createdAt: Date.now() + } + + // accountResetToken + data.accountResetTokenId = buf32() + data.accountResetToken = { + data : buf32(), + uid : data.accountId, + createdAt: Date.now() + } + + // passwordChangeToken + data.passwordChangeTokenId = buf32() + data.passwordChangeToken = { + data : buf32(), + uid : data.accountId, + createdAt: Date.now() + } + + // passwordForgotToken + data.passwordForgotTokenId = buf32() + data.passwordForgotToken = { + data : buf32(), + uid : data.accountId, + passCode : buf16(), + tries : 1, + createdAt: Date.now() + } + + data.unlockCode = buf16() + + return data +} diff --git a/fxa-auth-db-server/test/local/error.js b/fxa-auth-db-server/test/local/error.js new file mode 100644 index 0000000..a2b4ada --- /dev/null +++ b/fxa-auth-db-server/test/local/error.js @@ -0,0 +1,46 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +require('ass') +var test = require('../ptaptest') + +test( + 'error module', + function (t) { + t.plan(22) + var error = require('../../lib/error') + t.type(error, 'function', 'error module returns a function') + + var duplicate = error.duplicate() + t.type(duplicate, 'object', 'duplicate returns an object') + t.ok(duplicate instanceof error, 'is an instance of error') + t.equals(duplicate.code, 409) + t.equals(duplicate.errno, 101) + t.equals(duplicate.message, 'Record already exists') + t.equals(duplicate.error, 'Conflict') + t.equals(duplicate.toString(), 'Error: Record already exists') + + var notFound = error.notFound() + t.type(notFound, 'object', 'notFound returns an object') + t.ok(notFound instanceof error, 'is an instance of error') + t.equals(notFound.code, 404) + t.equals(notFound.errno, 116) + t.equals(notFound.message, 'Not Found') + t.equals(notFound.error, 'Not Found') + t.equals(notFound.toString(), 'Error: Not Found') + + var err = new Error('Something broke.') + err.code = 'ER_QUERY_INTERRUPTED' + err.errno = 1317 + var wrap = error.wrap(err) + t.type(wrap, 'object', 'wrap returns an object') + t.ok(wrap instanceof error, 'is an instance of error') + t.equals(wrap.code, 500) + t.equals(wrap.errno, 1317) + t.equals(wrap.message, 'ER_QUERY_INTERRUPTED') + t.equals(wrap.error, 'Internal Server Error') + t.equals(wrap.toString(), 'Error: ER_QUERY_INTERRUPTED') + + t.end() + } +) diff --git a/fxa-auth-db-server/test/ptaptest.js b/fxa-auth-db-server/test/ptaptest.js new file mode 100644 index 0000000..347dc0f --- /dev/null +++ b/fxa-auth-db-server/test/ptaptest.js @@ -0,0 +1,55 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * A promise-ified version of tap.test. + * + * This module provides a 'test' function that operates just like tap.test, but + * will properly close a promise if the test returns one. This makes it easier + * to ensure that any unhandled errors cause the test to fail. Use like so: + * + * var test = require('./ptap') + * + * test( + * 'an example test', + * function (t) { + * return someAPI.thingThatReturnsPromise() + * .then(function(result) { + * t.assertEqual(result, 42) + * }) + * } + * ) + * + * Because the test function returns a promise, we get the following for free: + * + * * wait for the promise to resolve, and call t.end() when it does + * * check for unhandled errors and fail the test if they occur + * + */ + +// support code coverage +// require('ass'); + +var tap = require('tap') + +module.exports = function(name, testfunc) { + var wrappedtestfunc = function(t) { + var res = testfunc(t) + if (typeof res !== 'undefined') { + if (typeof res.done === 'function') { + res.done( + function() { + t.end() + }, + function(err) { + console.error(err.stack) + t.fail(err.message || err.error || err) + t.end() + } + ) + } + } + } + return tap.test(name, wrappedtestfunc) +} diff --git a/index.js b/index.js index 6593832..0e49a70 100644 --- a/index.js +++ b/index.js @@ -6,7 +6,7 @@ var config = require('./config') var dbServer = require('fxa-auth-db-server') var error = dbServer.errors var logger = require('./lib/logging')('bin.server') -var DB = require('./lib/db/mysql')(logger, error) +var DB = require('./lib/db/mem')(logger, error) module.exports = function () { return DB.connect(config) diff --git a/lib/db/mem.js b/lib/db/mem.js new file mode 100644 index 0000000..a1d0c3c --- /dev/null +++ b/lib/db/mem.js @@ -0,0 +1,518 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var P = require('bluebird') + +// our data stores +var accounts = {} +var uidByNormalizedEmail = {} +var sessionTokens = {} +var keyFetchTokens = {} +var accountResetTokens = {} +var passwordChangeTokens = {} +var passwordForgotTokens = {} +var accountUnlockCodes = {} + +module.exports = function (log, error) { + + function Memory(db) {} + + // CREATE + Memory.prototype.createAccount = function (uid, data) { + uid = uid.toString('hex') + + data.devices = {} + + data.lockedAt = null + + if ( accounts[uid] ) { + return P.reject(error.duplicate()) + } + + if ( uidByNormalizedEmail[data.normalizedEmail] ) { + return P.reject(error.duplicate()) + } + + accounts[uid.toString('hex')] = data + uidByNormalizedEmail[data.normalizedEmail] = uid + + return P.resolve({}) + } + + Memory.prototype.createSessionToken = function (tokenId, sessionToken) { + sessionToken.id = tokenId + tokenId = tokenId.toString('hex') + + if ( sessionTokens[tokenId] ) { + return P.reject(error.duplicate()) + } + + sessionTokens[tokenId] = { + data: sessionToken.data, + uid: sessionToken.uid, + createdAt: sessionToken.createdAt, + } + + var account = accounts[sessionToken.uid.toString('hex')] + account.devices[tokenId] = sessionToken + + return P.resolve({}) + } + + Memory.prototype.createKeyFetchToken = function (tokenId, keyFetchToken) { + tokenId = tokenId.toString('hex') + + if ( keyFetchTokens[tokenId] ) { + return P.reject(error.duplicate()) + } + + keyFetchTokens[tokenId] = { + authKey: keyFetchToken.authKey, + uid: keyFetchToken.uid, + keyBundle: keyFetchToken.keyBundle, + createdAt: keyFetchToken.createdAt, + } + + return P.resolve({}) + } + + Memory.prototype.createPasswordForgotToken = function (tokenId, passwordForgotToken) { + tokenId = tokenId.toString('hex') + + if ( passwordForgotTokens[tokenId] ) { + return P.reject(error.duplicate()) + } + + // Delete any passwordForgotTokens for this uid (since we're only + // allowed one at a time). + deleteByUid(passwordForgotToken.uid.toString('hex'), passwordForgotTokens) + + passwordForgotTokens[tokenId] = { + tokenData: passwordForgotToken.data, + uid: passwordForgotToken.uid, + passCode: passwordForgotToken.passCode, + tries: passwordForgotToken.tries, + createdAt: passwordForgotToken.createdAt, + } + + return P.resolve({}) + } + + Memory.prototype.createPasswordChangeToken = function (tokenId, passwordChangeToken) { + tokenId = tokenId.toString('hex') + + if ( passwordChangeTokens[tokenId] ) { + return P.reject(error.duplicate()) + } + + // Delete any passwordChangeTokens for this uid (since we're only + // allowed one at a time). + deleteByUid(passwordChangeToken.uid.toString('hex'), passwordChangeTokens) + + passwordChangeTokens[tokenId] = { + tokenData: passwordChangeToken.data, + uid: passwordChangeToken.uid, + createdAt: passwordChangeToken.createdAt, + } + + return P.resolve({}) + } + + Memory.prototype.createAccountResetToken = function (tokenId, accountResetToken) { + tokenId = tokenId.toString('hex') + + if ( accountResetTokens[tokenId] ) { + return P.reject(error.duplicate()) + } + + // Delete any accountResetTokens for this uid (since we're only + // allowed one at a time). + deleteByUid(accountResetToken.uid.toString('hex'), accountResetTokens) + + accountResetTokens[tokenId] = { + tokenData: accountResetToken.data, + uid: accountResetToken.uid, + createdAt: accountResetToken.createdAt, + } + + return P.resolve({}) + } + + // DELETE + + // The lazy way + // uid is a hex string (not a buffer) + function deleteByUid(uid, collection) { + Object.keys(collection).forEach(function(key) { + var item = collection[key] + + if (!item.uid) { + throw new Error('No "uid" property in collection item') + } + + if (item.uid.toString('hex') === uid) { + delete collection[key] + } + }) + } + + Memory.prototype.deleteSessionToken = function (tokenId) { + tokenId = tokenId.toString('hex') + + if ( !sessionTokens[tokenId] ) { + return P.resolve({}) + } + + var sessionToken = sessionTokens[tokenId] + delete sessionTokens[tokenId] + + var account = accounts[sessionToken.uid.toString('hex')] + delete account.devices[tokenId] + return P.resolve({}) + } + + Memory.prototype.deleteKeyFetchToken = function (tokenId) { + delete keyFetchTokens[tokenId.toString('hex')] + return P.resolve({}) + } + + Memory.prototype.deleteAccountResetToken = function (tokenId) { + delete accountResetTokens[tokenId.toString('hex')] + return P.resolve({}) + } + + Memory.prototype.deletePasswordForgotToken = function (tokenId) { + delete passwordForgotTokens[tokenId.toString('hex')] + return P.resolve({}) + } + + Memory.prototype.deletePasswordChangeToken = function (tokenId) { + delete passwordChangeTokens[tokenId.toString('hex')] + return P.resolve({}) + } + + // READ + + Memory.prototype.accountExists = function (email) { + email = email.toString('utf8').toLowerCase() + if ( uidByNormalizedEmail[email] ) { + return P.resolve({}) + } + return P.reject(error.notFound()) + } + + Memory.prototype.checkPassword = function (uid, hash) { + + return this.account(uid) + .then(function(account) { + if(account.verifyHash.toString('hex') === hash.verifyHash.toString('hex')) { + return P.resolve({uid: uid}) + } + else { + return P.reject(error.incorrectPassword()) + } + }, function() { + return P.reject(error.incorrectPassword()) + }) + } + + Memory.prototype.accountDevices = function (uid) { + return this.account(uid) + .then(function(account) { + var devices = Object.keys(account.devices).map( + function (id) { + return account.devices[id] + } + ) + return P.resolve(devices) + }) + } + + // account(): + // + // Takes: + // - uid - a Buffer() + // + // Returns: + // - the account if found + // - throws 'notFound' if not found + Memory.prototype.account = function (uid) { + uid = uid.toString('hex') + if ( accounts[uid] ) { + return P.resolve(accounts[uid]) + } + return P.reject(error.notFound()) + } + + // emailRecord(): + // + // Takes: + // - email - a string of hex encoded characters + // + // Returns: + // - the account if found + // - throws 'notFound' if not found + Memory.prototype.emailRecord = function (email) { + email = email.toString('utf8').toLowerCase() + if ( uidByNormalizedEmail[email] ) { + return P.resolve(accounts[uidByNormalizedEmail[email]]) + } + return P.reject(error.notFound()) + } + + // sessionToken() + // + // Takes: + // - id - a string of hex chars + Memory.prototype.sessionToken = function (id) { + id = id.toString('hex') + + if ( !sessionTokens[id] ) { + return P.reject(error.notFound()) + } + + var item = {} + + item.tokenData = sessionTokens[id].data + item.uid = sessionTokens[id].uid + item.createdAt = sessionTokens[id].createdAt + + var accountId = sessionTokens[id].uid.toString('hex') + var account = accounts[accountId] + item.emailVerified = account.emailVerified + item.email = account.email + item.emailCode = account.emailCode + item.verifierSetAt = account.verifierSetAt + item.locale = account.locale + + return P.resolve(item) + } + + Memory.prototype.keyFetchToken = function (id) { + id = id.toString('hex') + + if ( !keyFetchTokens[id] ) { + return P.reject(error.notFound()) + } + + var item = {} + + var token = keyFetchTokens[id] + item.authKey = token.authKey + item.uid = token.uid + item.keyBundle = token.keyBundle + item.createdAt = token.createdAt + + var accountId = token.uid.toString('hex') + var account = accounts[accountId] + item.emailVerified = account.emailVerified + item.verifierSetAt = account.verifierSetAt + + return P.resolve(item) + } + + Memory.prototype.passwordForgotToken = function (id) { + id = id.toString('hex') + + if ( !passwordForgotTokens[id] ) { + return P.reject(error.notFound()) + } + + var item = {} + + var token = passwordForgotTokens[id] + item.tokenData = token.tokenData + item.uid = token.uid + item.passCode = token.passCode + item.tries = token.tries + item.createdAt = token.createdAt + + var accountId = token.uid.toString('hex') + var account = accounts[accountId] + item.email = account.email + item.verifierSetAt = account.verifierSetAt + + return P.resolve(item) + } + + Memory.prototype.passwordChangeToken = function (id) { + id = id.toString('hex') + + if ( !passwordChangeTokens[id] ) { + return P.reject(error.notFound()) + } + + var item = {} + + var token = passwordChangeTokens[id] + item.tokenData = token.tokenData + item.uid = token.uid + item.createdAt = token.createdAt + + var accountId = token.uid.toString('hex') + var account = accounts[accountId] + item.verifierSetAt = account.verifierSetAt + + return P.resolve(item) + } + + Memory.prototype.accountResetToken = function (id) { + id = id.toString('hex') + + if ( !accountResetTokens[id] ) { + return P.reject(error.notFound()) + } + + var item = {} + + var token = accountResetTokens[id] + item.tokenData = token.tokenData + item.uid = token.uid + item.createdAt = token.createdAt + + var accountId = token.uid.toString('hex') + var account = accounts[accountId] + item.verifierSetAt = account.verifierSetAt + + return P.resolve(item) + } + + // BATCH + Memory.prototype.verifyEmail = function (uid) { + return this.account(uid) + .then( + function (account) { + account.emailVerified = 1 + return {} + }, + function (err) { + return {} + } + ) + } + + Memory.prototype.forgotPasswordVerified = function (tokenId, accountResetToken) { + return P.all([ + this.deletePasswordForgotToken(tokenId), + this.createAccountResetToken(accountResetToken.tokenId, accountResetToken), + this.verifyEmail(accountResetToken.uid), + this.unlockAccount(accountResetToken.uid) + ]) + } + + Memory.prototype.resetAccount = function (uid, data) { + return this.account(uid) + .then( + function (account) { + uid = uid.toString('hex') + deleteByUid(uid, sessionTokens) + deleteByUid(uid, keyFetchTokens) + deleteByUid(uid, accountResetTokens) + deleteByUid(uid, passwordChangeTokens) + deleteByUid(uid, passwordForgotTokens) + deleteByUid(uid, accountUnlockCodes) + + account.verifyHash = data.verifyHash + account.authSalt = data.authSalt + account.wrapWrapKb = data.wrapWrapKb + account.verifierSetAt = data.verifierSetAt + account.verifierVersion = data.verifierVersion + account.devices = {} + return [] + } + ) + } + + Memory.prototype.deleteAccount = function (uid) { + return this.account(uid) + .then( + function (account) { + uid = uid.toString('hex') + deleteByUid(uid, sessionTokens) + deleteByUid(uid, keyFetchTokens) + deleteByUid(uid, accountResetTokens) + deleteByUid(uid, passwordChangeTokens) + deleteByUid(uid, passwordForgotTokens) + deleteByUid(uid, accountUnlockCodes) + + delete uidByNormalizedEmail[account.normalizedEmail] + delete accounts[uid] + return [] + } + ) + } + + Memory.prototype.updateLocale = function (uid, data) { + return this.account(uid) + .then( + function (account) { + account.locale = data.locale + return {} + } + ) + } + + Memory.prototype.lockAccount = function (uid, data) { + return this.account(uid) + .then( + function (account) { + account.lockedAt = data.lockedAt + accountUnlockCodes[uid] = { + uid: uid, + unlockCode: data.unlockCode + } + return {} + } + ) + } + + Memory.prototype.unlockAccount = function (uid) { + return this.account(uid) + .then( + function (account) { + account.lockedAt = null + delete accountUnlockCodes[uid] + return {} + }, + function(err) { + // The only error from this.account(uid) could be a 404 Not Found. We're masking + // this since the auth server firstly checks for an account prior to calling this + // so if we have stumbled here (without an account) we probably don't mind. + return {} + } + ) + } + + Memory.prototype.unlockCode = function (uid) { + var unlockCode = accountUnlockCodes[uid] + if (! unlockCode) { + return P.reject(error.notFound()) + } + + return P.resolve(unlockCode) + } + + Memory.prototype.updatePasswordForgotToken = function (id, data) { + var token = passwordForgotTokens[id.toString('hex')] + if (!token) { return P.reject(error.notFound()) } + token.tries = data.tries + return P.resolve({}) + } + + // UTILITY FUNCTIONS + + Memory.prototype.ping = function () { + return P.resolve({}) + } + + Memory.prototype.close = function () { + return P.resolve({}) + } + + Memory.connect = function(options) { + return P.resolve(new Memory()) + } + + return Memory +} diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index abf6c87..cd2a641 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -4,7 +4,7 @@ "dependencies": { "ass": { "version": "1.0.0", - "from": "git://github.com/jrgm/ass.git#5be99ee7abc9fcf63f9ebcc37b151b9c822146d1", + "from": "git://github.com/jrgm/ass.git#5be99ee", "resolved": "git://github.com/jrgm/ass.git#5be99ee7abc9fcf63f9ebcc37b151b9c822146d1", "dependencies": { "async": { @@ -262,9 +262,9 @@ } }, "fxa-auth-db-server": { - "version": "0.42.0", - "from": "git://github.com/mozilla/fxa-auth-db-server.git#3d5f649de3324be6c9c37076ea094b2fe3b7bdcd", - "resolved": "git://github.com/mozilla/fxa-auth-db-server.git#3d5f649de3324be6c9c37076ea094b2fe3b7bdcd", + "version": "0.39.0", + "from": "fxa-auth-db-server", + "resolved": "file:fxa-auth-db-server", "dependencies": { "restify": { "version": "2.8.2", @@ -273,7 +273,7 @@ "dependencies": { "assert-plus": { "version": "0.1.5", - "from": "assert-plus@>=0.1.5 <0.2.0", + "from": "assert-plus@0.1.5", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.1.5.tgz" }, "backoff": { @@ -440,7 +440,7 @@ }, "keep-alive-agent": { "version": "0.0.1", - "from": "keep-alive-agent@>=0.0.1 <0.0.2", + "from": "keep-alive-agent@0.0.1", "resolved": "https://registry.npmjs.org/keep-alive-agent/-/keep-alive-agent-0.0.1.tgz" }, "lru-cache": { @@ -509,7 +509,7 @@ }, "dtrace-provider": { "version": "0.2.8", - "from": "dtrace-provider@>=0.2.8 <0.3.0", + "from": "dtrace-provider@0.2.8", "resolved": "https://registry.npmjs.org/dtrace-provider/-/dtrace-provider-0.2.8.tgz" } } @@ -594,7 +594,7 @@ "dependencies": { "inherits": { "version": "2.0.1", - "from": "inherits@>=2.0.1 <2.1.0", + "from": "inherits@>=2.0.1 <3.0.0", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" }, "typedarray": { @@ -734,7 +734,7 @@ "dependencies": { "inherits": { "version": "2.0.1", - "from": "inherits@>=2.0.1 <2.1.0", + "from": "inherits@>=2.0.1 <3.0.0", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" }, "typedarray": { @@ -1124,7 +1124,7 @@ }, "exit": { "version": "0.1.2", - "from": "exit@>=0.1.0 <0.2.0", + "from": "exit@>=0.1.1 <0.2.0", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz" }, "htmlparser2": { @@ -1319,7 +1319,7 @@ "dependencies": { "lru-cache": { "version": "2.6.5", - "from": "lru-cache@>=2.0.0 <3.0.0", + "from": "lru-cache@>=2.5.0 <3.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.6.5.tgz" }, "sigmund": { @@ -1367,7 +1367,7 @@ "dependencies": { "lru-cache": { "version": "2.6.5", - "from": "lru-cache@>=2.0.0 <3.0.0", + "from": "lru-cache@>=2.5.0 <3.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.6.5.tgz" }, "sigmund": { @@ -1413,7 +1413,7 @@ "dependencies": { "ansi-regex": { "version": "0.2.1", - "from": "ansi-regex@>=0.2.0 <0.3.0", + "from": "ansi-regex@>=0.2.1 <0.3.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-0.2.1.tgz" } } @@ -1425,7 +1425,7 @@ "dependencies": { "ansi-regex": { "version": "0.2.1", - "from": "ansi-regex@>=0.2.0 <0.3.0", + "from": "ansi-regex@>=0.2.1 <0.3.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-0.2.1.tgz" } } @@ -1554,7 +1554,7 @@ }, "inherits": { "version": "2.0.1", - "from": "inherits@*", + "from": "inherits@>=2.0.0 <3.0.0", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" }, "minimatch": { @@ -1655,7 +1655,7 @@ }, "mkdirp": { "version": "0.5.1", - "from": "mkdirp@>=0.5.0 <0.6.0", + "from": "mkdirp@>=0.3.0 <0.4.0||>=0.4.0 <0.5.0||>=0.5.0 <0.6.0", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "dependencies": { "minimist": { @@ -1752,7 +1752,7 @@ }, "node-uuid": { "version": "1.4.3", - "from": "node-uuid@>=1.4.0 <1.5.0", + "from": "node-uuid@>=1.4.1 <2.0.0", "resolved": "https://registry.npmjs.org/node-uuid/-/node-uuid-1.4.3.tgz" }, "qs": { @@ -1892,7 +1892,7 @@ }, "escape-regexp-component": { "version": "1.0.2", - "from": "escape-regexp-component@1.0.2", + "from": "escape-regexp-component@>=1.0.2 <2.0.0", "resolved": "https://registry.npmjs.org/escape-regexp-component/-/escape-regexp-component-1.0.2.tgz" }, "formidable": { @@ -2030,7 +2030,7 @@ }, "glob": { "version": "3.2.11", - "from": "glob@>=3.2.1 <3.3.0", + "from": "glob@>=3.2.9 <3.3.0", "resolved": "https://registry.npmjs.org/glob/-/glob-3.2.11.tgz", "dependencies": { "minimatch": { @@ -2054,7 +2054,7 @@ }, "inherits": { "version": "2.0.1", - "from": "inherits@*", + "from": "inherits@>=2.0.0 <3.0.0", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" }, "mkdirp": { diff --git a/package.json b/package.json index cec34a7..e9f04d4 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "bluebird": "2.1.3", "clone": "0.2.0", "convict": "0.4.2", - "fxa-auth-db-server": "git://github.com/mozilla/fxa-auth-db-server.git", + "fxa-auth-db-server": "file:fxa-auth-db-server", "fxa-jwtool": "0.4.0", "mozlog": "2.0.0", "mysql": "2.3.2", @@ -44,5 +44,12 @@ "restify": "2.8.1", "tap": "0.4.13" }, - "keywords": [ "fxa", "firefox", "firefox-accounts", "backend", "storage", "mysql" ] + "keywords": [ + "fxa", + "firefox", + "firefox-accounts", + "backend", + "storage", + "mysql" + ] }