Blueprint
Search…
Policies
It is not uncommon to restrict access to different routes based on who is making the request. For example, you many want to restrict access to a route based a request's origin, IP address, or if the request has the correct authorizations.
Blueprint realizes this need through its policy framework. In this part of the tutorial, we will explore how to create a simple policy, attach it to a route, and then write a unit test to test the policy.

Defining a policy

Let's say we want to restrict access to GET /api/rentals to requests that only have the header Secret-Key and the value of the header is set to ssshhh.
This example is for demonstration purposes only. Please do not do anything this simple in a production environment when it comes to securing an API.
To do this, we are going to create a policy as shown below. As shown in the example, our policy is first placed in the /app/policies directory. We then organize our policy under the /rental directory since this policy pertains to the rental resource. Lastly, we place the policy in a file named getAll.js. This help us remember the policy is for getting all rentals (more on this later).
// app/policies/rental/getAll.js.js
1
const { Policy } = require ('@onehilltech/blueprint');
2
3
/**
4
* This is a simple demonstration of a policy.
5
*/
6
module.exports = Policy.extend ({
7
/// The failure code used when the policy fails.
8
failureCode: 'invalid_secret',
9
10
/// The human readable message that can be displayed on the
11
/// client-side when this policy fails.
12
failureMessage: 'The request has an invalid secret.',
13
14
/**
15
* Run the policy.
16
*
17
* @param req The Express request object.
18
*/
19
runCheck (req) {
20
// Check the Secret-Key request header, but do not use something like this in
21
// a production environment.
22
23
return req.get ('Secret-Key') === 'ssshhh';
24
}
25
});
26
Copied!
Each policy must implement the runCheck(req) method because this is the main entry point the framework uses to execute a policy. If the policy succeeds, it must return true. If the policy fails, it can return either false, or a failure object. The failure object is a hash that contains a failureCode and failureMessage property. As you see in the example above, the policy can also define a default failureCode and failureMessage at the top-level of the policy. The default failure code and failure message are used when the policy returns false.
In the example above, we are checking the request header for the value of the Secret-Key header. If the value is ssshhh, the policy returns true. If the value is not ssshhh, then the policy returns false.
Policies that return true are allowed to continue its routing process either to the next policy, or to the controller action for the route. Policies that return false stop the request handling, and return 403 to the client. The body of the response will contain the corresponding failureCode and failureMessage associated with the failed policy.

Attaching the policy to a route

Now that we have defined a policy, we need to attach (or bind) the policy to the correct route. We do this in the router specification.
Let's assume that we go back to the router we defined before we started using resources. This router is illustrated below. The router has a policy property that is used to define the policy for a route or an action. As shown below, we have specified the policy created above on the /rentals route defined below.
1
// app/routers/api/rental.js
2
3
const { Router } = require ('@onehilltech/blueprint');
4
5
module.exports = Router.extend ({
6
specification: {
7
'/rentals': {
8
// This policy applies to all requests /api/rentals regardless of the
9
// HTTP verb (or action) called.
10
policy: 'rentals.getAll',
11
12
get: {
13
// If we add the policy here, then it only applies to GET /api/rentals.
14
policy: 'rentals.getAll',
15
16
// This statement will bind this route to the get action in the
17
// rental controller. Now, GET /api/rentals can handle client requests.
18
19
}
20
}
21
}
22
});
Copied!

Policies for resources

The example above illustrated how to manually attach a policy to a route. This works when you manually bind routes to actions in a router specification. When we use resources, however, we have to use a different approach. Instead, the framework automatically attaches policies to resource routes. This is done by searching for a policy that matches resource name + action.
If you recall, we defined the policy for our example in a file named /app/policies/rental/getAll.js. We did this in preparation for replacing the manually specification of a policy with the automatic specification of a policy when using a resource. If we revert our design above back to the resource approach, then we do not have to manually specify the policies. Instead, the Blueprint framework will search for policies that match this resource for each inferred action of a resource, such as getOne, getAll, and update.
1
// app/routers/api/rental.js
2
3
const { Router } = require ('@onehilltech/blueprint');
4
5
module.exports = Router.extend ({
6
specification: {
7
'/rentals': {
8
resource: { controller: 'rental' }
9
}
10
}
11
});
Copied!
For the example above, the framework will search for the following optional policies in app/policies:
Policy
Location
Description
rental.create
rental/create.js
Policy for creating a resource.
rental.getOne
rental/getOne.js
Policy for getting a single resource.
rental.getAll
rental/getAll.js
Policy for getting many, or querying, a resource.
rental.update
rental/update.js
Policy for updating a resource.
rental.delete
rental/delete.js
Policy for deleting a resource.

Testing your policies

You unit test your policies the same way you unit test any route. The main difference is instead of expecting a 200 response, you are expecting a 403 response. You can also check the body of the response to make sure its returning the correct failure code and failure message. Below is an example of checking the policy we created above.
1
// tests/unit-tests/app/routers/rental.js
2
3
const { request } = require ('@onehilltech/blueprint-testing');
4
const { expect } = require ('chai');
5
6
describe ('app | routers | rental', function () {
7
context ('GET', function () {
8
it ('should get all the rentals', async function () {
9
// Send a mock request to the api, and wait for the response. This request
10
// succeeds because it has the correct value for Secret-Key header.
11
12
const res = await request ()
13
.get ('/api/rentals')
14
.set ('Secret-Key', 'ssshhh')
15
.expect (200);
16
17
// res.body has the text from the response.
18
// From here you can use chai to implement test oracle via assertions.
19
});
20
21
it ('should fail because it has invalid Secret-Key header', async function () {
22
// This reqeust will fail. We are checking the response code, and
23
// the text in the response.
24
25
await request ()
26
.get ('/api/rentals')
27
.set ('Secret-Key', 'This will fail!')
28
.expect (403, {
29
errors: [{
30
code: 'invalid_secret',
31
detail: 'The request has an invalid secret.',
32
status: '403'
33
}]});
34
});
35
});
36
});
Copied!