Sikau

Security · Day 4 · about 40 min

Project: Authorization and rate limits

Who may do what (and stopping IDOR), plus a token-bucket limiter.

Logged in isn't allowed

The commonest real-world bug isn't clever crypto — it's GET /orders/1043 returning *someone else's* order because the code only checked that you're signed in. That's an IDOR. Check authorization on every object. And limit how fast anyone can try things, with a token bucket.

Rules and buckets

function canAccess(user, action, order) {
  if (!user) return false;
  if (user.role === "admin") return true;
  if (user.role === "staff") return action === "read";
  return order.owner === user.id && (action === "read" || action === "cancel"); // only your own
}

function createLimiter({ capacity, refillPerSecond }) {
  const buckets = new Map(); // key -> { tokens, at }
  return {
    allow(key, now) {
      const b = buckets.get(key) ?? { tokens: capacity, at: now };
      b.tokens = Math.min(capacity, b.tokens + ((now - b.at) / 1000) * refillPerSecond);
      b.at = now;
      buckets.set(key, b);
      if (b.tokens < 1) return false;
      b.tokens -= 1;
      return true;
    },
  };
}

The rest of this lesson

  • Authentication versus authorizationexplain
  • The token bucketexplain
  • Who may do what?match
  • Bucket after a burstpredict
  • canAccess and createLimiterchallenge
  • Badge quizquiz
  • Unit 1 completerecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 8 lessons of Security