EzRules
You can use EzRules to prevent unauthorized socket.io packets or HTTP requests from returning data to malicious users.
Setting a Rule
Each EzModel has EzRules which can be set with the following syntax
- Sample
- Full Sample
model.rules.for(RuleType.CREATE).check((req,event) => {
if (/** Your Condition here */) throw Boom.unauthorized()
})
import { EzBackend, EzModel, RuleType, Type } from "@ezbackend/common"
import { EzOpenAPI } from "@ezbackend/openapi"
import { EzDbUI } from "@ezbackend/db-ui"
import Boom from "@hapi/boom"
const app = new EzBackend()
//plugins
app.addApp(new EzOpenAPI())
app.addApp(new EzDbUI())
//Bank Transaction Example
const transactions = new EzModel("Transactions", {
receiver: Type.VARCHAR,
sender: Type.VARCHAR,
amount: Type.INT
})
transactions.rules.for(RuleType.CREATE).check((req,event) => {
//Don't allow creating a transaction unless the sender is the user
if (req.user.id !== event.entity.sender) throw Boom.unauthorized()
})
app.addApp(transactions, { prefix: "transactions" })
app.start()
In the rule, to prevent further execution of the code (e.g a HTTP reply being sent or a socket.io packet being sent), you need to throw an error.
Available Rule Types
You can add rules for multiple RuleTypes, for example:
model.rules.for(
RuleType.CREATE,
RuleType.READ,
RuleType.UPDATE,
RuleType.DELETE
).check((req, event) => {
if (/** Your Condition here */) throw Boom.unauthorized()
})
info
To prevent a user from receiving unauthorized socket.io packet updates, set the RuleType.READ
property
How it works
EzRules works using async local storage in order to save requests contexts through the call stack.
In the above example
- A HTTP Request is made
- A fastify preHandler sets
req.user
toBob
- This
req
is saved in the context - the HTTP Request handler calls
foo()
foo()
results in a database read- Entities are read from
CashTransactions
- The
entities
are saved in the context - Since there is a
req
context and aentity
context, the rules are checked to see if Bob has permission to read the transaction