CodeIgniter4/libraries/throttler.html
2018-11-14 19:38:31 -08:00

430 lines
19 KiB
HTML

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Throttler &mdash; CodeIgniter4 4.0.0-alpha.2 documentation</title>
<link rel="shortcut icon" href="../_static/ci-icon.ico"/>
<link rel="stylesheet" href="../_static/css/citheme.css" type="text/css" />
<link rel="top" title="CodeIgniter4 4.0.0-alpha.2 documentation" href="../index.html"/>
<link rel="up" title="Library Reference" href="index.html"/>
<link rel="next" title="Dates and Times" href="time.html"/>
<link rel="prev" title="Session Library" href="sessions.html"/>
<script src="../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../index.html" class="icon icon-home"> CodeIgniter4
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../intro/index.html">Welcome to CodeIgniter4</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../installation/index.html">Installation</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../tutorial/index.html">Tutorial</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../concepts/index.html">CodeIgniter4 Overview</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../general/index.html">General Topics</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../incoming/index.html">Controllers and Routing</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../outgoing/index.html">Building Responses</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../database/index.html">Working With Databases</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../models/index.html">Modeling Data</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../dbmgmt/index.html">Managing Databases</a></li>
</ul>
<ul class="current">
<li class="toctree-l1 current"><a class="reference internal" href="index.html">Library Reference</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="caching.html">Caching Driver</a></li>
<li class="toctree-l2"><a class="reference internal" href="curlrequest.html">CURLRequest Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.html">Email Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="files.html">Working with Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="honeypot.html">Honeypot Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="images.html">Image Manipulation Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="pagination.html">Pagination</a></li>
<li class="toctree-l2"><a class="reference internal" href="security.html">Security Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="sessions.html">Session Library</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">Throttler</a></li>
<li class="toctree-l2"><a class="reference internal" href="time.html">Dates and Times</a></li>
<li class="toctree-l2"><a class="reference internal" href="typography.html">Typography</a></li>
<li class="toctree-l2"><a class="reference internal" href="uploaded_files.html">Working with Uploaded Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="uri.html">Working with URIs</a></li>
<li class="toctree-l2"><a class="reference internal" href="user_agent.html">User Agent Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="validation.html">Validation</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../helpers/index.html">Helpers</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../testing/index.html">Testing</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../cli/index.html">Command Line Usage</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../extending/index.html">Extending CodeIgniter</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../license.html">The MIT License (MIT)</a></li>
<li class="toctree-l1"><a class="reference internal" href="../changelog.html">Change Log</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">CodeIgniter4</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html">Docs</a> &raquo;</li>
<li><a href="index.html">Library Reference</a> &raquo;</li>
<li>Throttler</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="throttler">
<h1>Throttler<a class="headerlink" href="#throttler" title="Permalink to this headline"></a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#overview" id="id1">Overview</a></li>
<li><a class="reference internal" href="#rate-limiting" id="id2">Rate Limiting</a><ul>
<li><a class="reference internal" href="#the-code" id="id3">The Code</a></li>
<li><a class="reference internal" href="#applying-the-filter" id="id4">Applying the Filter</a></li>
</ul>
</li>
</ul>
</div>
<p>The Throttler class provides a very simple way to limit an activity to be performed to a certain number of attempts
within a set period of time. This is most often used for performing rate limiting on API&#8217;s, or restricting the number
of attempts a user can make against a form to help prevent brute force attacks. The class itself can be used
for anything that you need to throttle based on actions within a set time interval.</p>
<div class="section" id="overview">
<h2><a class="toc-backref" href="#id1">Overview</a><a class="headerlink" href="#overview" title="Permalink to this headline"></a></h2>
<p>The Throttler implements a simplified version of the <a class="reference external" href="https://en.wikipedia.org/wiki/Token_bucket">Token Bucket</a>
algorithm. This basically treats each action that you want as a bucket. When you call the <code class="docutils literal"><span class="pre">check()</span></code> method,
you tell it how large the bucket is, and how many tokens it can hold and the time interval. Each <code class="docutils literal"><span class="pre">check()</span></code> call uses
1 of the available tokens, by default. Let&#8217;s walk through an example to make this clear.</p>
<p>Let&#8217;s say we want an action to happen once every second. The first call to the Throttler would look like the following.
The first parameter is the bucket name, the second parameter the number of tokens the bucket holds, and
the third being the amount of time it takes the bucket to refill:</p>
<div class="highlight-ci"><div class="highlight"><pre><span></span><span class="nv">$throttler</span> <span class="o">=</span> <span class="nx">\Config\Services</span><span class="o">::</span><span class="na">throttler</span><span class="p">();</span>
<span class="nv">$throttler</span><span class="o">-&gt;</span><span class="na">check</span><span class="p">(</span><span class="nv">$name</span><span class="p">,</span> <span class="mi">60</span><span class="p">,</span> <span class="nx">MINUTE</span><span class="p">);</span>
</pre></div>
</div>
<p>Here we&#8217;re using one of the <a class="reference internal" href="../general/common_functions.html"><span class="doc">global constants</span></a> for the time, to make it a little
more readable. This says that the bucket allows 60 actions every minute, or 1 action every second.</p>
<p>Let&#8217;s say that a third-party script was trying to hit a URL repeatedly. At first, it would be able to use all 60
of those tokens in less than a second. However, after that the Throttler would only allow one action per second,
potentially slowing down the requests enough that they attack is no longer worth it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For the Throttler class to work, the Cache library must be setup to use a handler other than dummy.
For best performance, an in-memory cache, like Redis or Memcached, is recommended.</p>
</div>
</div>
<div class="section" id="rate-limiting">
<h2><a class="toc-backref" href="#id2">Rate Limiting</a><a class="headerlink" href="#rate-limiting" title="Permalink to this headline"></a></h2>
<p>The Throttler class does not do any rate limiting or request throttling on its own, but is the key to making
one work. An example <a class="reference internal" href="../incoming/filters.html"><span class="doc">Filter</span></a> is provided that implements very simple rate limiting at
one request per second per IP address. Here we will run through how it works, and how you could set it up and
start using it in your application.</p>
<div class="section" id="the-code">
<h3><a class="toc-backref" href="#id3">The Code</a><a class="headerlink" href="#the-code" title="Permalink to this headline"></a></h3>
<p>You can find this file at <strong>application/Filters/Throttle.php</strong> but the relevant method is reproduced here:</p>
<div class="highlight-ci"><div class="highlight"><pre><span></span><span class="k">public</span> <span class="k">function</span> <span class="nf">before</span><span class="p">(</span><span class="nx">RequestInterface</span> <span class="nv">$request</span><span class="p">)</span>
<span class="p">{</span>
<span class="nv">$throttler</span> <span class="o">=</span> <span class="nx">Services</span><span class="o">::</span><span class="na">throttler</span><span class="p">();</span>
<span class="c1">// Restrict an IP address to no more</span>
<span class="c1">// than 1 request per second across the</span>
<span class="c1">// entire site.</span>
<span class="k">if</span> <span class="p">(</span><span class="nv">$throttler</span><span class="o">-&gt;</span><span class="na">check</span><span class="p">(</span><span class="nv">$request</span><span class="o">-&gt;</span><span class="na">getIPAddress</span><span class="p">(),</span> <span class="mi">60</span><span class="p">,</span> <span class="nx">MINUTE</span><span class="p">)</span> <span class="o">===</span> <span class="k">false</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="nx">Services</span><span class="o">::</span><span class="na">response</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">setStatusCode</span><span class="p">(</span><span class="mi">429</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>When run, this method first grabs an instance of the throttler. Next it uses the IP address as the bucket name,
and sets things to limit them to one request per second. If the throttler rejects the check, returning false,
then we return a Response with the status code set to 429 - Too Many Attempts, and the script execution ends
before it ever hits the controller. This example will throttle based on a single IP address across all requests
made to the site, not per page.</p>
</div>
<div class="section" id="applying-the-filter">
<h3><a class="toc-backref" href="#id4">Applying the Filter</a><a class="headerlink" href="#applying-the-filter" title="Permalink to this headline"></a></h3>
<p>We don&#8217;t necessarily need to throttle every page on the site. For many web applications this makes the most sense
to apply only to POST requests, though API&#8217;s might want to limit every request made by a user. In order to apply
this to incoming requests, you need to edit <strong>/application/Config/Filters.php</strong> and first add an alias to the
filter:</p>
<div class="highlight-ci"><div class="highlight"><pre><span></span><span class="k">public</span> <span class="nv">$aliases</span> <span class="o">=</span> <span class="p">[</span>
<span class="s1">&#39;csrf&#39;</span> <span class="o">=&gt;</span> <span class="nx">\App\Filters\CSRF</span><span class="o">::</span><span class="na">class</span><span class="p">,</span>
<span class="s1">&#39;toolbar&#39;</span> <span class="o">=&gt;</span> <span class="nx">\App\Filters\DebugToolbar</span><span class="o">::</span><span class="na">class</span><span class="p">,</span>
<span class="s1">&#39;throttle&#39;</span> <span class="o">=&gt;</span> <span class="nx">\App\Filters\Throttle</span><span class="o">::</span><span class="na">class</span>
<span class="p">];</span>
</pre></div>
</div>
<p>Next, we assign it to all POST requests made on the site:</p>
<div class="highlight-ci"><div class="highlight"><pre><span></span><span class="k">public</span> <span class="nv">$methods</span> <span class="o">=</span> <span class="p">[</span>
<span class="s1">&#39;post&#39;</span> <span class="o">=&gt;</span> <span class="p">[</span><span class="s1">&#39;throttle&#39;</span><span class="p">,</span> <span class="s1">&#39;CSRF&#39;</span><span class="p">]</span>
<span class="p">];</span>
</pre></div>
</div>
<p>And that&#8217;s all there is to it. Now all POST requests made on the site will have be rate limited.</p>
<div class="section" id="class-reference">
<h4>Class Reference<a class="headerlink" href="#class-reference" title="Permalink to this headline"></a></h4>
<dl class="method">
<dt id="check">
<code class="descname">check</code><span class="sig-paren">(</span><em>string $key</em>, <em>int $capacity</em>, <em>int $seconds</em><span class="optional">[</span>, <em>int $cost = 1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#check" title="Permalink to this definition"></a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>$key</strong> (<em>string</em>) &#8211; The name of the bucket</li>
<li><strong>$capacity</strong> (<em>int</em>) &#8211; The number of tokens the bucket holds</li>
<li><strong>$seconds</strong> (<em>int</em>) &#8211; The number of seconds it takes for a bucket to completely fill</li>
<li><strong>$cost</strong> (<em>int</em>) &#8211; The number of tokens that are spent for this action</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first">TRUE if action can be performed, FALSE if not</p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Return type:</th><td class="field-body"><p class="first last">bool</p>
</td>
</tr>
</tbody>
</table>
<p>Checks to see if there are any tokens left within the bucket, or if too many have
been used within the allotted time limit. During each check the available tokens
are reduced by $cost if successful.</p>
</dd></dl>
<dl class="method">
<dt id="getTokentime">
<code class="descname">getTokentime</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#getTokentime" title="Permalink to this definition"></a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body">The number of seconds until another token should be available.</td>
</tr>
<tr class="field-even field"><th class="field-name">Return type:</th><td class="field-body">integer</td>
</tr>
</tbody>
</table>
<p>After <code class="docutils literal"><span class="pre">check()</span></code> has been run and returned FALSE, this method can be used
to determine the time until a new token should be available and the action can be
tried again. In this case the minimum enforced wait time is one second.</p>
</dd></dl>
</div>
</div>
</div>
</div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="time.html" class="btn btn-neutral float-right" title="Dates and Times" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="sessions.html" class="btn btn-neutral" title="Session Library" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
&copy; Copyright 2014-2018 British Columbia Institute of Technology.
Last updated on Nov 14, 2018.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'../',
VERSION:'4.0.0-alpha.2',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: false,
SOURCELINK_SUFFIX: ''
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html>