Implementing Authorization
1. Defining User Permissions
| Element | Example |
|---|---|
| Role | admin, user, guest |
| Scope | chat:read, chat:write |
| Resource | room:42 |
| Action | create, read, update, delete |
2. Checking Message Permissions
Example: Per-message check
ws.on("message", async (raw) => {
const m = JSON.parse(raw);
if (!can(ws.session.user, m.type, m.payload)) {
return ws.send(JSON.stringify({ "type":"err", "code":403, "id":m.id }));
}
handle(m);
});
| Layer | Check |
|---|---|
| Connect | Can use WS? |
| Subscribe | Can read topic? |
| Publish | Can write topic? |
| RPC | Can invoke method? |
3. Implementing Role-Based Access Control
| Role | Allows |
|---|---|
| guest | read public topics |
| member | read+write public |
| moderator | delete messages |
| admin | all |
4. Implementing Attribute-Based Access Control
Example: ABAC predicate
function canEdit(user, doc) {
return doc.ownerId === user.id
|| user.roles.includes("admin")
|| (doc.team && user.teams.includes(doc.team));
}
| Attribute | Source |
|---|---|
| User | id, roles, teams |
| Resource | owner, visibility, tags |
| Env | time, IP, geo |
| Action | read/write/admin |
5. Validating Topic Access
| Pattern | Rule |
|---|---|
public.* | Anyone |
user.{id}.* | Only that user |
team.{id}.* | Team members |
admin.* | Role: admin |
6. Implementing Resource Ownership
| Field | Use |
|---|---|
ownerId | Direct ownership |
parentId | Inherit from parent |
acl | Per-user permissions |
7. Handling Permission Denied
| Strategy | Detail |
|---|---|
| Reply error | {type:"err",code:403,id} |
| Silently drop | For abuse-prone endpoints |
| Close 4403 | Repeated violations |
| Audit log | Always record denials |
8. Implementing Dynamic Permissions
| Source | Detail |
|---|---|
| Policy engine | OPA / Cedar |
| Feature flags | LaunchDarkly, Unleash |
| Db lookup | Per-request ACL fetch (cache!) |
9. Auditing Authorization Events
| Field | Purpose |
|---|---|
| actor | Who |
| action | What |
| resource | On what |
| decision | allow/deny |
| reason | Policy rule |
| ts/ip/ua | Context |
10. Testing Authorization Logic
| Test | Detail |
|---|---|
| Allow matrix | Role × action × resource expected outcomes |
| Deny matrix | Same, asserting denial |
| Privilege escalation | Try forged tokens |
| IDOR | Other user's resource IDs |