Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor public api #80

Merged
merged 22 commits into from
Nov 8, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 129 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,143 @@ Completely and thoroughly test your Firebase security rules without connecting t
## Usage

All you need to do is supply the security rules and some mock data, then write tests describing the expected behavior of the rules. Targaryen will interpret the rules and run the tests.

Targaryen can be used in one of three ways: as a standalone command-line utility, as a set of custom matchers for [Jasmine](https://jasmine.github.io), or as a plugin for [Chai](http://chaijs.com). When a test fails, you get detailed debug information that explains why the read/write operation succeeded/failed.

```js
const assert = require('assert');
const targaryen = require('targaryen');

const rules = {
rules: {
foo: {
'.write': 'true'
}
}
};
const data = {foo: 1};
const auth = {uid: 'someuid'};

const database = targaryen.database(rules, data);
const {allowed, newDatabase, info} = database.as(auth).write('/foo', 2);

console.log('Rule evaluations:\n', info);
assert.ok(allowed);

assert.equal(newDatabase.rules, database.rules);
assert.equal(newDatabase.root.foo.$value(), 2);
assert.equal(newDatabase.auth, auth);
```

Targaryen provides three convenient ways to run tests:

- as a standalone command-line utility:

```bash
targaryen path/to/rules.json path/to/tests.json
```

- as a set of custom matchers for [Jasmine](https://jasmine.github.io):

```js
const targaryen = require('targaryen/plugins/jasmine');;

describe('my security rules', function() {

beforeEach(function() {
jasmine.addMatchers(targaryen.matchers);
targaryen.setFirebaseData(require(DATA_PATH));
targaryen.setFirebaseRules(require(RULES_PATH));
});

it('should allow authenticated used to rule all data', function() {
expect({uid: 'foo'}).canRead('/');
expect(null).cannotRead('/');
})

});
```

- or as a plugin for [Chai](http://chaijs.com).

```js
const chai = require('chai');
const targaryen = require('targaryen/plugins/chai');
const expect = chai.expect;

chai.use(targaryen);

describe('my security rules', function() {

before(function() {
targaryen.setFirebaseData(require(DATA_PATH)));
targaryen.setFirebaseRules(require(RULES_PATH));
});

it('should allow authenticated used to rule all data', function() {
expect({uid: 'foo'}).can.read.path('/');
expect(null).cannot.read.path('/');
})

});
```

When a test fails, you get detailed debug information that explains why the read/write operation succeeded/failed.

See [USAGE.md](https://github.com/goldibex/targaryen/blob/master/USAGE.md) for more information.


## How does Targaryen work?

Targaryen statically analyzes your security rules using [esprima](http://esprima.org). It then conducts two passes over the abstract syntax tree. The first pass, during the parsing process, checks the types of variables and the syntax of the rules for correctness. The second pass, during the testing process, evaluates the expressions in the security rules given a set of state variables (the RuleDataSnapshots, auth data, the present time, and any wildchildren).


## API

### `targaryen.database(rules: object|Ruleset, data: object|DataNode, now: null|number): Database`

Creates a set of rules and initial data to simulate read, write and update of operations.

The Database objects are immutable; to get an updated Database object with different the user auth data, rules, data or timestamp, use its `with(options)` method.


### `Database.prototype.with({rules: {rules: object}, data: any, auth: null|object, now: number}): Database`

Extends the database object with new rules, data, auth data, or time stamp.


### `Database.prototype.as(auth: null|object): Database`

Extends the database object with auth data.


### `Database.prototype.read(path: string, now: null|number): Result`

Simulates a read operation.


### `Database.prototype.write(path: string, value: any, priority: any, now: null|number): Result`

Simulates a write operation.


### `Database.prototype.update(path: string, patch: object, now: null|number): Result`

Simulates an update operation (including multi-location update).


### `Result: {allowed: boolean, info: string, database: Database, newDatabase: Database, newValue: any}`

It holds:

- `allowed`: the success status;
- `info`: the rule evaluation info;
- `database`: the original database.

For write and update operations, it also includes:

- `newDatabase`: the resulting database;
- `newValue`: the value written to the database.


## Why is it named Targaryen?

> There were trials. Of a sort. Lord Rickard demanded trial by combat, and the
Expand Down
4 changes: 2 additions & 2 deletions bin/targaryen
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ var stripJsonComments = require('strip-json-comments');
var path = require('path'),
Table = require('cli-table'),
colors = require('colors'),
helpers = require('../lib/test-helpers'),
TestJig = require('../lib/test-jig'),
helpers = require('../lib/util'),
TestJig = require('../lib/test-cmd'),
argv = require('minimist')(process.argv.slice(2), { boolean: true });

if (argv._.length < 2) {
Expand Down
23 changes: 12 additions & 11 deletions docs/chai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,21 @@
2. Create a new directory for your security tests, like, say, `test/security`.

3. Add a new *fixture JSON* for the state of your Firebase. Call this, say, `test/security/<firebase path>.json`. This file will describe the state of the Firebase data store for your tests, that is, what you can get via the `root` and `data` variables in the security rules.

4. Create a new file for your first set of tests, like `test/security/<firebase path>.js`.

5. Add the following content to the top of the new file:

```js
var chai = require('chai'),
targaryen = require('targaryen');
const chai = require('chai');
const targaryen = require('targaryen/plugins/chai');

chai.use(targaryen.chai);
chai.use(targaryen);

describe('my security rules', function() {

before(function() {
targaryen.setFirebaseData(require(path.join(__dirname, path.basename(__filename, '.js') + '.json')));
targaryen.setFirebaseData(require(DATA_PATH)));
targaryen.setFirebaseRules(require(RULES_PATH));
});

Expand All @@ -31,7 +31,7 @@ where `RULES_PATH` is the path to your security rules JSON file. If your securit

6. Write your security tests.

The subject of every assertion will be the authentication state (i.e., `auth`) of the user trying the operation, so for instance, `null` would be an unauthenticated user, or a Firebase Password Login user would look like `{ uid: 'password:500f6e96-92c6-4f60-ad5d-207253aee4d3', id: 1, provider: 'password' }`. There are symbolic versions of these in `targaryen.users`.
The subject of every assertion will be the authentication state (i.e., `auth`) of the user trying the operation, so for instance, `null` would be an unauthenticated user, or a Firebase Password Login user would look like `{ uid: 'password:500f6e96-92c6-4f60-ad5d-207253aee4d3', id: 1, provider: 'password' }`. There are symbolic versions of these in `targaryen.users`.

See the API section below for details, or take a look at the example files here.

Expand All @@ -49,14 +49,15 @@ mocha examples/<name of example>.js

## API

- `targaryen.chai`: The plugin object. Load this using `chai.use(targaryen.chai)` before running any tests.
- `targaryen.setFirebaseData(data)`: Set the mock data to be used as the existing Firebase data, i.e., `root` and `data`.
- `targaryen.setFirebaseRules(rules)`: Set the security rules to be tested against. Throws if there's a syntax error in your rules.
- `targaryen.users`: A set of authentication objects you can use as the subject of the assertions. Has the following keys:
- import with `require('targaryen/plugins/chai')`.
- `chaiTargaryen.chai`: The plugin object. Load this using `chai.use(chaiTargaryen.chai)` before running any tests.
- `chaiTargaryen.setFirebaseData(data)`: Set the mock data to be used as the existing Firebase data, i.e., `root` and `data`.
- `chaiTargaryen.setFirebaseRules(rules)`: Set the security rules to be tested against. Throws if there's a syntax error in your rules.
- `chaiTargaryen.users`: A set of authentication objects you can use as the subject of the assertions. Has the following keys:
- `unauthenticated`: an unauthenticated user, i.e., `auth === null`.
- `anonymous`: a user authenticated using Firebase anonymous sessions.
- `password`: a user authenticated using Firebase Password Login.
- `facebook`: a user authenticated by their Facebook account.
- `facebook`: a user authenticated by their Facebook account.
- `twitter`: a user authenticated by their Twitter account.
- `google`: a user authenticated by their Google account.
- `github`: a user authenticated by their Github account.
Expand Down
12 changes: 7 additions & 5 deletions docs/chai/examples/erroring.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use strict';

var chai = require('chai'),
targaryen = require('../../../index.js'), // in your app this would be require('targaryen')
expect = chai.expect,
users = targaryen.users;
// in your app this would be require('targaryen/plugins/chai')
const targaryen = require('../../../plugins/chai');
const chai = require('chai');
const expect = chai.expect;
const users = targaryen.users;

chai.use(targaryen.chai);
chai.use(targaryen);

describe('An invalid set of security rules', function() {

Expand Down
12 changes: 7 additions & 5 deletions docs/chai/examples/failing.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use strict';

var chai = require('chai'),
targaryen = require('../../../index.js'), // in your app this would be require('targaryen')
expect = chai.expect,
users = targaryen.users;
// in your app this would be require('targaryen/plugins/chai')
const targaryen = require('../../../plugins/chai');
const chai = require('chai');
const expect = chai.expect;
const users = targaryen.users;

chai.use(targaryen.chai);
chai.use(targaryen);

describe('A valid set of security rules and data', function() {

Expand Down
12 changes: 7 additions & 5 deletions docs/chai/examples/passing.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use strict';

var chai = require('chai'),
targaryen = require('../../../index.js'), // in your app this would be require('targaryen')
expect = chai.expect,
users = targaryen.users;
// in your app this would be require('targaryen/plugins/chai')
const targaryen = require('../../../plugins/chai');
const chai = require('chai');
const expect = chai.expect;
const users = targaryen.users;

chai.use(targaryen.chai);
chai.use(targaryen);

describe('A valid set of security rules and data', function() {

Expand Down
21 changes: 11 additions & 10 deletions docs/jasmine/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@
2. Create a new directory for your security tests. Jasmine likes your tests to live in the directory `spec`, so a good choice might be `spec/security`. Add this directory to `spec/support/jasmine.json`.

3. Add a new *fixture JSON* for the state of your Firebase. Call this `spec/security/<firebase path>.json`. This file will describe the state of the Firebase data store for your tests, that is, what you can get via the `root` and `data` variables in the security rules.

4. Create a new file for your first set of tests, like `spec/security/<firebase path>.js`.

5. Add the following content to the top of the new file:

```js
var path = require('path'),
targaryen = require('targaryen');
const targaryen = require('targaryen/plugins/jasmine');
const users = targaryen.users;

targaryen.setFirebaseData(require(path.join(__dirname, path.basename(__filename, '.js') + '.json')));
targaryen.setFirebaseRules(require(RULES_PATH));

describe('my security rules', function() {

beforeEach(function() {
jasmine.addMatchers(targaryen.jasmine.matchers);
jasmine.addMatchers(targaryen.matchers);
});

});
Expand All @@ -31,7 +31,7 @@ where `RULES_PATH` is the path to your security rules JSON file. If your securit

6. Write your security tests.

The subject of every assertion will be the authentication state (i.e., `auth`) of the user trying the operation, so for instance, `null` would be an unauthenticated user, or a Firebase Password Login user would look like `{ uid: 'password:500f6e96-92c6-4f60-ad5d-207253aee4d3', id: 1, provider: 'password' }`. There are symbolic versions of these in `targaryen.users`.
The subject of every assertion will be the authentication state (i.e., `auth`) of the user trying the operation, so for instance, `null` would be an unauthenticated user, or a Firebase Password Login user would look like `{ uid: 'password:500f6e96-92c6-4f60-ad5d-207253aee4d3', id: 1, provider: 'password' }`. There are symbolic versions of these in `targaryen.users`.

See the API section below for details, or take a look at the example files here.

Expand All @@ -48,14 +48,15 @@ jasmine spec/security/<name of example>.js

## API

- `targaryen.jasmine`: The plugin object. Load this using `jasmine.addMatchers(targaryen.jasmine.matchers)` before running any tests.
- `targaryen.setFirebaseData(data)`: Set the mock data to be used as the existing Firebase data, i.e., `root` and `data`.
- `targaryen.setFirebaseRules(rules)`: Set the security rules to be tested against. Throws if there's a syntax error in your rules.
- `targaryen.users`: A set of authentication objects you can use as the subject of the assertions. Has the following keys:
- import with `require('targaryen/plugins/jasmine')`.
- `jasmineTargaryen.matchers`: The plugin object. Load this using `jasmine.addMatchers(jasmineTargaryen.matchers)` before running any tests.
- `jasmineTargaryen.setFirebaseData(data)`: Set the mock data to be used as the existing Firebase data, i.e., `root` and `data`.
- `jasmineTargaryen.setFirebaseRules(rules)`: Set the security rules to be tested against. Throws if there's a syntax error in your rules.
- `jasmineTargaryen.users`: A set of authentication objects you can use as the subject of the assertions. Has the following keys:
- `unauthenticated`: an unauthenticated user, i.e., `auth === null`.
- `anonymous`: a user authenticated using Firebase anonymous sessions.
- `password`: a user authenticated using Firebase Password Login.
- `facebook`: a user authenticated by their Facebook account.
- `facebook`: a user authenticated by their Facebook account.
- `twitter`: a user authenticated by their Twitter account.
- `google`: a user authenticated by their Google account.
- `github`: a user authenticated by their Github account.
Expand Down
9 changes: 6 additions & 3 deletions docs/jasmine/examples/spec/security/erroring.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@

'use strict';

var targaryen = require('../../../../../index'), // in your app this would be require('targaryen')
users = targaryen.users;
// in your app this would be require('targaryen/plugins/jasmine')
const targaryen = require('../../../plugins/jasmine');

describe('An invalid set of security rules and data', function() {

beforeEach(function() {
jasmine.addMatchers(targaryen.matchers);
});

it('causes Targaryen to throw', function() {

targaryen.setFirebaseData(require('./data.json'));
Expand Down
8 changes: 4 additions & 4 deletions docs/jasmine/examples/spec/security/failing.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@

'use strict';

var targaryen = require('../../../../../index'), // in your app this would be require('targaryen')
users = targaryen.users;
// in your app this would be require('targaryen/plugins/jasmine')
const targaryen = require('../../../plugins/jasmine');
const users = targaryen.users;

targaryen.setFirebaseData(require('./data.json'));
targaryen.setFirebaseRules(require('./rules.json'));

describe('A valid set of security rules and data', function() {

beforeEach(function() {
jasmine.addMatchers(targaryen.jasmine.matchers);
jasmine.addMatchers(targaryen.matchers);
});

it('can have read errors', function() {
Expand Down
5 changes: 3 additions & 2 deletions docs/jasmine/examples/spec/security/passing.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

'use strict';

var targaryen = require('../../../../../index'), // in your app this would be require('targaryen')
users = targaryen.users;
// in your app this would be require('targaryen/plugins/jasmine')
const targaryen = require('../../../plugins/jasmine');
const users = targaryen.users;

targaryen.setFirebaseData(require('./data.json'));
targaryen.setFirebaseRules(require('./rules.json'));
Expand Down
Loading