Files
server/src/Core/Services/Implementations/AmazonSqsBlockIpService.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

85 lines
2.7 KiB
C#
Raw Normal View History

2019-03-18 16:23:37 -04:00
using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.SQS;
using Bit.Core.Settings;
2019-03-18 16:23:37 -04:00
namespace Bit.Core.Services
{
public class AmazonSqsBlockIpService : IBlockIpService, IDisposable
{
private readonly IAmazonSQS _client;
2019-03-18 16:23:37 -04:00
private string _blockIpQueueUrl;
private string _unblockIpQueueUrl;
private bool _didInit = false;
private Tuple<string, bool, DateTime> _lastBlock;
public AmazonSqsBlockIpService(
GlobalSettings globalSettings)
: this(globalSettings, new AmazonSQSClient(
globalSettings.Amazon.AccessKeyId,
globalSettings.Amazon.AccessKeySecret,
RegionEndpoint.GetBySystemName(globalSettings.Amazon.Region))
)
{
}
public AmazonSqsBlockIpService(
GlobalSettings globalSettings,
IAmazonSQS amazonSqs)
2019-03-18 16:23:37 -04:00
{
if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeyId))
2019-03-18 16:23:37 -04:00
{
throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeyId));
}
if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeySecret))
2019-03-18 16:23:37 -04:00
{
throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeySecret));
}
if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.Region))
2019-03-18 16:23:37 -04:00
{
throw new ArgumentNullException(nameof(globalSettings.Amazon.Region));
}
_client = amazonSqs;
2019-03-18 16:23:37 -04:00
}
public void Dispose()
{
_client?.Dispose();
}
public async Task BlockIpAsync(string ipAddress, bool permanentBlock)
{
var now = DateTime.UtcNow;
if (_lastBlock != null && _lastBlock.Item1 == ipAddress && _lastBlock.Item2 == permanentBlock &&
2019-03-18 16:23:37 -04:00
(now - _lastBlock.Item3) < TimeSpan.FromMinutes(1))
{
// Already blocked this IP recently.
return;
}
_lastBlock = new Tuple<string, bool, DateTime>(ipAddress, permanentBlock, now);
await _client.SendMessageAsync(_blockIpQueueUrl, ipAddress);
if (!permanentBlock)
2019-03-18 16:23:37 -04:00
{
await _client.SendMessageAsync(_unblockIpQueueUrl, ipAddress);
}
}
private async Task InitAsync()
{
if (_didInit)
2019-03-18 16:23:37 -04:00
{
return;
}
var blockIpQueue = await _client.GetQueueUrlAsync("block-ip");
_blockIpQueueUrl = blockIpQueue.QueueUrl;
var unblockIpQueue = await _client.GetQueueUrlAsync("unblock-ip");
_unblockIpQueueUrl = unblockIpQueue.QueueUrl;
_didInit = true;
}
}
}