Skip to content

Commit

Permalink
Merge pull request #1962 from trade-tariff/GL-919
Browse files Browse the repository at this point in the history
GL-919: Implement throttling GL api
  • Loading branch information
rasikasri authored Sep 4, 2024
2 parents 053e890 + 6f1e92e commit 209cce3
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,6 @@ group :test do
end

group :production do
gem 'rack-attack'
gem 'rack-timeout'
end
3 changes: 3 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,8 @@ GEM
activesupport (>= 2.3.14)
racc (1.8.0)
rack (3.1.7)
rack-attack (6.7.0)
rack (>= 1.0, < 4)
rack-protection (4.0.0)
base64 (>= 0.1.0)
rack (>= 3.0.0, < 4)
Expand Down Expand Up @@ -501,6 +503,7 @@ DEPENDENCIES
pry-rails
puma
rabl
rack-attack
rack-timeout
rails (~> 7.1)
redis (>= 5.0.6)
Expand Down
17 changes: 17 additions & 0 deletions config/initializers/rack_attack.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
if Rails.env.production?
class Rack::Attack
Rack::Attack.cache.store = ActiveSupport::Cache::RedisCacheStore.new(url: ENV['REDIS_URL'])

API_KEY_LIMITS = JSON.parse(ENV['GREEN_LANES_API_KEYS'])

if API_KEY_LIMITS.present?
API_KEY_LIMITS['api_keys'].each do |api_key, config|
throttle(api_key.to_s, limit: config['limit'], period: config['period'].to_i.hour) do |req|
req.path.start_with?('/green_lanes/goods_nomenclatures') && req.env['HTTP_X_API_KEY'] == api_key
end
end
end
end
else
logger.info 'Rack::Attack is disabled in Dev env.'
end
25 changes: 25 additions & 0 deletions docs/green_lanes_api_keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
### API Key Management

To access GL endpoints in the production environment, clients must provide a valid API key. These API keys are
securely stored in AWS Secrets Manager under the secret name backend-green-lanes-api-keys as a JSON blob.

When authorizing a new API client, you should update the JSON file in Secrets Manager by adding the client’s API key
along with their details and the appropriate throttling limits. This ensures that each client has the correct permissions
and rate limits when interacting with the GL endpoints. Throttling limit is set per number of hours specified in period.

```
{
"api_keys": {
"<secret>": {
"name": "Descartes Labs",
"description": "Descartes Labs integration key",
"client_id": "dev",
"client_contact": "[email protected]",
"client_secret": "<secret>",
"t&c_accepted": true,
"limit": 100,
"period": 1
}
}
}
```

0 comments on commit 209cce3

Please sign in to comment.