Skip to content

[feature] Support rate limiting through policy_effect extension #1672

@hsluoyz

Description

@hsluoyz

It would be great if Casbin could support rate limiting natively by extending the policy_effect expression and implementing a custom Effector.

The idea is to introduce a new rate_limit function in policy_effect like this:

[policy_effect]
e = rate_limit(10, minute, allow, sub)

This means "allow at most 10 requests per minute, only count allowed requests, and bucket by subject". The four parameters are:

  • max: maximum request count within the time window
  • unit: time window unit, could be second, minute, hour, or day
  • count_type: either allow (only count allowed requests) or all (count all requests including denied ones, useful for preventing brute-force attacks)
  • bucket: the field(s) to group by, such as all, sub, obj, act

A RateLimitEffector implementing the Effector interface would parse this expression, maintain internal bucket states (counters and window timestamps), and decide whether to allow or deny based on current count. The bucket key is generated from the request context according to the bucket type, for example sub:alice when bucket is sub.

To implement this, we need to extend the policy_effect expression parser to recognize the rate_limit function, create a new RateLimitEffector that implements the Effector interface with internal state management, and make sure the enforce context (sub, obj, act) is passed to the effector so it can generate proper bucket keys.

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions