Laravel POST Attempts/timer, limits the request number stopping retries and interacting with time. I use RateLimiter and get the APP_KEY retrieved during installation, it is normal to use UserId, CompanyId, Projetc, etc.
It is very critical that the request reaches the destination and handle errors. Secure request are managed by Limits and Quotas with RateLimiter in a combination using throttle and middleware, that let us custom actions.
- Simple, fast POST request with Guzzle.
- Command Artisan using parameters.
- Multiple Errors Exception and validations.
- Real-time events and Log files.
- Application Cache to save the limit data.
After Fork Laravel repository, I redefined the origin remote to be associated and be able to push changes to my own fork. For this project I will use Guzzle with latest version 6.x to use POST request
Modify the composer.json file to apply installation for component.
{ "require": { "guzzlehttp/guzzle": "~6.3.3" } }
The install command reads the composer.json file from the current directory, resolves the dependencies, and installs them into vendor.
composer install
Copy .env.example to .env file
copy .\.env.example .env
Include in .env file the APP_KEY
php artisan key:generate
After Key generated, I configured the extra app information adding to .env file parameters as below:
API_URL=http://jsonplaceholder.typicode.com/posts POST_LIMITER_SECONDS=60 POST_LIMITER_RETRIES=3
IMPORTANT. The last two parameters are used to limit the request number stopping retries and interacting with time. I use RateLimiter and get the APP_KEY retrieved during installation, it is normal to use UserId, CompanyId, Projetc, etc.
Then new Artisan console command is configured.
php artisan make:command Post
Added POST Class Command to use and configure parameters as below:
timeout = 2.0 http_errors = false max = 10, // allow at most 10 redirects. strict = true, // use "strict" RFC compliant redirects. referer = true, // add a Referer header protocols = ['https'], // only allow https URLs track_redirects = true
Created new exception and handle error, if environment is production don’t show error details and record errors in Log.
php artisan make:exception PostNotFoundException
Review of the environment
try{
...POST
} catch (\Exception $e) {
\Log::error("Incfile---l--".$e);
if(env('APP_ENV')!='production')
return back()->withError($e->getMessage())->withInput();
}
The RateLimiter uses a cache store to put two things:
- A **key** that holds the number attempts, and another key which holds the window of time to register new attempts.
- The latter just appends **timer** to the original key.
Limit Attempts and Time aims to provide POST request protection and can be modified as the implementation is required.
//Init limiter
$limiter = app(RateLimiter::class);
//Get Key App
$key = env('APP_KEY');
$header = ["Attempts", "Retries Left", 'Available time (Sec)'];
//Calculate values to show in table
$info = [
[
"attempts"=>(string) ($limiter->attempts($key)+1)
,
"retries_left" => (string) ($limiter->retriesLeft($key, 3)<0)?0:$limiter->retriesLeft($key, env('POST_LIMITER_RETRIES'))
,
"available_time" => (string) ($limiter->availableIn($key)<0)?((int)env('POST_LIMITER_SECONDS')):($limiter->availableIn($key))
],
];
//show table
$this->table($header, $info);
when it is needed to increase values in Limiter
//charge attempt
$limiter->hit($key, ((int)env('POST_LIMITER_SECONDS')));
The methods:
- attempts(): Shows you how many attempts the user has been done.
- retriesLeft(): The number of retries left.
- availableIn(): How much time must pass to retry.
php artisan help Incfile:POST
Incfile:POST + Description: Send a simple POST request to external URL. + Usage: Incfile:POST [options] + Options: -U, --URL_POST[=URL_POST] [default: "Incfile_defined"] -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --env[=ENV] The environment the command should run under -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
The application will validate if POST is acceptable, handle corresponding errors Log and manage Limits of Attempts per Time defined, Limit Attempts and Time aims to provide POST request protection and can be modified as the implementation is required.
php artisan Incfile:POST
without parameters will request to Incfile default information as below:
API_URL=https://atomic.incfile.com/fakepost POST_LIMITER_SECONDS=60 POST_LIMITER_RETRIES=3 (can be 100K requests)
Attempts, Retries and Timeout are managed even if errors exists.
+----------+--------------+----------------------+ | Attempts | Retries Left | Available time (Sec) | +----------+--------------+----------------------+ | 1 | 3 | 60 | +----------+--------------+----------------------+ URL: https://atomic.incfile.com/fakepost Unable to connect. The url is not valid or you do not have permission to the site.
php artisan Incfile:POST -U http://jsonplaceholder.typicode.com/posts
will request using URL input in parameter and manage Attempts, Retries and Timeout as well.
+----------+--------------+----------------------+ | Attempts | Retries Left | Available time (Sec) | +----------+--------------+----------------------+ | 1 | 3 | 60 | +----------+--------------+----------------------+ URL: http://jsonplaceholder.typicode.com/posts POST sent correctly
You can use –verbose parameter to show Headers and Json Response details
php artisan Incfile:POST -U http://jsonplaceholder.typicode.com/posts --verbose
+----------+--------------+----------------------+ | Attempts | Retries Left | Available time (Sec) | +----------+--------------+----------------------+ | 1 | 3 | 60 | +----------+--------------+----------------------+ URL: http://jsonplaceholder.typicode.com/posts POST sent correctly HTTP/1.0 200 OK Cache-Control: no-cache, private Content-Type: application/json Date: Tue, 12 Nov 2019 04:17:24 GMT {"POST":"Completed"} Response:{ "Parm1": "Parm1", "id": 101 }
Thank you for considering contributing to the Laravel framework!
If you discover a security vulnerability within this project, please send an e-mail to Hector Alonso via [email protected]. All security vulnerabilities will be promptly addressed.
The Laravel framework is open-source software licensed under the MIT license. Then... this project too!