1
0
mirror of https://github.com/bitwarden/server synced 2026-01-06 10:34:01 +00:00

Run formatting (#2230)

This commit is contained in:
Justin Baur
2022-08-29 16:06:55 -04:00
committed by GitHub
parent 9b7aef0763
commit 7f5f010e1e
1205 changed files with 73813 additions and 75022 deletions

View File

@@ -8,99 +8,98 @@ using Bit.Events.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Bit.Events.Controllers
namespace Bit.Events.Controllers;
[Route("collect")]
[Authorize("Application")]
public class CollectController : Controller
{
[Route("collect")]
[Authorize("Application")]
public class CollectController : Controller
private readonly ICurrentContext _currentContext;
private readonly IEventService _eventService;
private readonly ICipherRepository _cipherRepository;
private readonly IOrganizationRepository _organizationRepository;
public CollectController(
ICurrentContext currentContext,
IEventService eventService,
ICipherRepository cipherRepository,
IOrganizationRepository organizationRepository)
{
private readonly ICurrentContext _currentContext;
private readonly IEventService _eventService;
private readonly ICipherRepository _cipherRepository;
private readonly IOrganizationRepository _organizationRepository;
_currentContext = currentContext;
_eventService = eventService;
_cipherRepository = cipherRepository;
_organizationRepository = organizationRepository;
}
public CollectController(
ICurrentContext currentContext,
IEventService eventService,
ICipherRepository cipherRepository,
IOrganizationRepository organizationRepository)
[HttpPost]
public async Task<IActionResult> Post([FromBody] IEnumerable<EventModel> model)
{
if (model == null || !model.Any())
{
_currentContext = currentContext;
_eventService = eventService;
_cipherRepository = cipherRepository;
_organizationRepository = organizationRepository;
return new BadRequestResult();
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] IEnumerable<EventModel> model)
var cipherEvents = new List<Tuple<Cipher, EventType, DateTime?>>();
var ciphersCache = new Dictionary<Guid, Cipher>();
foreach (var eventModel in model)
{
if (model == null || !model.Any())
switch (eventModel.Type)
{
return new BadRequestResult();
}
var cipherEvents = new List<Tuple<Cipher, EventType, DateTime?>>();
var ciphersCache = new Dictionary<Guid, Cipher>();
foreach (var eventModel in model)
{
switch (eventModel.Type)
{
// User events
case EventType.User_ClientExportedVault:
await _eventService.LogUserEventAsync(_currentContext.UserId.Value, eventModel.Type, eventModel.Date);
break;
// Cipher events
case EventType.Cipher_ClientAutofilled:
case EventType.Cipher_ClientCopiedHiddenField:
case EventType.Cipher_ClientCopiedPassword:
case EventType.Cipher_ClientCopiedCardCode:
case EventType.Cipher_ClientToggledCardCodeVisible:
case EventType.Cipher_ClientToggledHiddenFieldVisible:
case EventType.Cipher_ClientToggledPasswordVisible:
case EventType.Cipher_ClientViewed:
if (!eventModel.CipherId.HasValue)
{
continue;
}
Cipher cipher = null;
if (ciphersCache.ContainsKey(eventModel.CipherId.Value))
{
cipher = ciphersCache[eventModel.CipherId.Value];
}
else
{
cipher = await _cipherRepository.GetByIdAsync(eventModel.CipherId.Value,
_currentContext.UserId.Value);
}
if (cipher == null)
{
continue;
}
if (!ciphersCache.ContainsKey(eventModel.CipherId.Value))
{
ciphersCache.Add(eventModel.CipherId.Value, cipher);
}
cipherEvents.Add(new Tuple<Cipher, EventType, DateTime?>(cipher, eventModel.Type, eventModel.Date));
break;
case EventType.Organization_ClientExportedVault:
if (!eventModel.OrganizationId.HasValue)
{
continue;
}
var organization = await _organizationRepository.GetByIdAsync(eventModel.OrganizationId.Value);
await _eventService.LogOrganizationEventAsync(organization, eventModel.Type, eventModel.Date);
break;
default:
// User events
case EventType.User_ClientExportedVault:
await _eventService.LogUserEventAsync(_currentContext.UserId.Value, eventModel.Type, eventModel.Date);
break;
// Cipher events
case EventType.Cipher_ClientAutofilled:
case EventType.Cipher_ClientCopiedHiddenField:
case EventType.Cipher_ClientCopiedPassword:
case EventType.Cipher_ClientCopiedCardCode:
case EventType.Cipher_ClientToggledCardCodeVisible:
case EventType.Cipher_ClientToggledHiddenFieldVisible:
case EventType.Cipher_ClientToggledPasswordVisible:
case EventType.Cipher_ClientViewed:
if (!eventModel.CipherId.HasValue)
{
continue;
}
}
Cipher cipher = null;
if (ciphersCache.ContainsKey(eventModel.CipherId.Value))
{
cipher = ciphersCache[eventModel.CipherId.Value];
}
else
{
cipher = await _cipherRepository.GetByIdAsync(eventModel.CipherId.Value,
_currentContext.UserId.Value);
}
if (cipher == null)
{
continue;
}
if (!ciphersCache.ContainsKey(eventModel.CipherId.Value))
{
ciphersCache.Add(eventModel.CipherId.Value, cipher);
}
cipherEvents.Add(new Tuple<Cipher, EventType, DateTime?>(cipher, eventModel.Type, eventModel.Date));
break;
case EventType.Organization_ClientExportedVault:
if (!eventModel.OrganizationId.HasValue)
{
continue;
}
var organization = await _organizationRepository.GetByIdAsync(eventModel.OrganizationId.Value);
await _eventService.LogOrganizationEventAsync(organization, eventModel.Type, eventModel.Date);
break;
default:
continue;
}
if (cipherEvents.Any())
{
foreach (var eventsBatch in cipherEvents.Batch(50))
{
await _eventService.LogCipherEventsAsync(eventsBatch);
}
}
return new OkResult();
}
if (cipherEvents.Any())
{
foreach (var eventsBatch in cipherEvents.Batch(50))
{
await _eventService.LogCipherEventsAsync(eventsBatch);
}
}
return new OkResult();
}
}

View File

@@ -1,21 +1,20 @@
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Mvc;
namespace Bit.Events.Controllers
{
public class InfoController : Controller
{
[HttpGet("~/alive")]
[HttpGet("~/now")]
public DateTime GetAlive()
{
return DateTime.UtcNow;
}
namespace Bit.Events.Controllers;
[HttpGet("~/version")]
public JsonResult GetVersion()
{
return Json(CoreHelpers.GetVersion());
}
public class InfoController : Controller
{
[HttpGet("~/alive")]
[HttpGet("~/now")]
public DateTime GetAlive()
{
return DateTime.UtcNow;
}
[HttpGet("~/version")]
public JsonResult GetVersion()
{
return Json(CoreHelpers.GetVersion());
}
}

View File

@@ -1,12 +1,11 @@
using Bit.Core.Enums;
namespace Bit.Events.Models
namespace Bit.Events.Models;
public class EventModel
{
public class EventModel
{
public EventType Type { get; set; }
public Guid? CipherId { get; set; }
public DateTime Date { get; set; }
public Guid? OrganizationId { get; set; }
}
public EventType Type { get; set; }
public Guid? CipherId { get; set; }
public DateTime Date { get; set; }
public Guid? OrganizationId { get; set; }
}

View File

@@ -1,40 +1,39 @@
using Bit.Core.Utilities;
using Serilog.Events;
namespace Bit.Events
namespace Bit.Events;
public class Program
{
public class Program
public static void Main(string[] args)
{
public static void Main(string[] args)
{
Host
.CreateDefaultBuilder(args)
.ConfigureCustomAppConfiguration(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureLogging((hostingContext, logging) =>
logging.AddSerilog(hostingContext, e =>
Host
.CreateDefaultBuilder(args)
.ConfigureCustomAppConfiguration(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureLogging((hostingContext, logging) =>
logging.AddSerilog(hostingContext, e =>
{
var context = e.Properties["SourceContext"].ToString();
if (context.Contains("IdentityServer4.Validation.TokenValidator") ||
context.Contains("IdentityServer4.Validation.TokenRequestValidator"))
{
var context = e.Properties["SourceContext"].ToString();
if (context.Contains("IdentityServer4.Validation.TokenValidator") ||
context.Contains("IdentityServer4.Validation.TokenRequestValidator"))
{
return e.Level > LogEventLevel.Error;
}
return e.Level > LogEventLevel.Error;
}
if (e.Properties.ContainsKey("RequestPath") &&
!string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) &&
(context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer")))
{
return false;
}
if (e.Properties.ContainsKey("RequestPath") &&
!string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) &&
(context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer")))
{
return false;
}
return e.Level >= LogEventLevel.Error;
}));
})
.Build()
.Run();
}
return e.Level >= LogEventLevel.Error;
}));
})
.Build()
.Run();
}
}

View File

@@ -6,113 +6,112 @@ using Bit.Core.Utilities;
using Bit.SharedWeb.Utilities;
using IdentityModel;
namespace Bit.Events
namespace Bit.Events;
public class Startup
{
public class Startup
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
public Startup(IWebHostEnvironment env, IConfiguration configuration)
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
Configuration = configuration;
Environment = env;
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment Environment { get; set; }
public void ConfigureServices(IServiceCollection services)
{
// Options
services.AddOptions();
// Settings
var globalSettings = services.AddGlobalSettingsServices(Configuration, Environment);
// Repositories
services.AddSqlServerRepositories(globalSettings);
// Context
services.AddScoped<ICurrentContext, CurrentContext>();
// Identity
services.AddIdentityAuthenticationServices(globalSettings, Environment, config =>
{
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
Configuration = configuration;
Environment = env;
config.AddPolicy("Application", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application", "external");
policy.RequireClaim(JwtClaimTypes.Scope, "api");
});
});
// Services
var usingServiceBusAppCache = CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) &&
CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName);
if (usingServiceBusAppCache)
{
services.AddSingleton<IApplicationCacheService, InMemoryServiceBusApplicationCacheService>();
}
else
{
services.AddSingleton<IApplicationCacheService, InMemoryApplicationCacheService>();
}
services.AddScoped<IEventService, EventService>();
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString))
{
services.AddSingleton<IEventWriteService, AzureQueueEventWriteService>();
}
else
{
services.AddSingleton<IEventWriteService, RepositoryEventWriteService>();
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment Environment { get; set; }
public void ConfigureServices(IServiceCollection services)
// Mvc
services.AddMvc(config =>
{
// Options
services.AddOptions();
config.Filters.Add(new LoggingExceptionHandlerFilterAttribute());
});
// Settings
var globalSettings = services.AddGlobalSettingsServices(Configuration, Environment);
// Repositories
services.AddSqlServerRepositories(globalSettings);
// Context
services.AddScoped<ICurrentContext, CurrentContext>();
// Identity
services.AddIdentityAuthenticationServices(globalSettings, Environment, config =>
{
config.AddPolicy("Application", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application", "external");
policy.RequireClaim(JwtClaimTypes.Scope, "api");
});
});
// Services
var usingServiceBusAppCache = CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) &&
CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName);
if (usingServiceBusAppCache)
{
services.AddSingleton<IApplicationCacheService, InMemoryServiceBusApplicationCacheService>();
}
else
{
services.AddSingleton<IApplicationCacheService, InMemoryApplicationCacheService>();
}
services.AddScoped<IEventService, EventService>();
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString))
{
services.AddSingleton<IEventWriteService, AzureQueueEventWriteService>();
}
else
{
services.AddSingleton<IEventWriteService, RepositoryEventWriteService>();
}
// Mvc
services.AddMvc(config =>
{
config.Filters.Add(new LoggingExceptionHandlerFilterAttribute());
});
if (usingServiceBusAppCache)
{
services.AddHostedService<Core.HostedServices.ApplicationCacheHostedService>();
}
}
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
IHostApplicationLifetime appLifetime,
GlobalSettings globalSettings)
if (usingServiceBusAppCache)
{
app.UseSerilog(env, appLifetime, globalSettings);
// Add general security headers
app.UseMiddleware<SecurityHeadersMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Default Middleware
app.UseDefaultMiddleware(env, globalSettings);
// Add routing
app.UseRouting();
// Add Cors
app.UseCors(policy => policy.SetIsOriginAllowed(o => CoreHelpers.IsCorsOriginAllowed(o, globalSettings))
.AllowAnyMethod().AllowAnyHeader().AllowCredentials());
// Add authentication and authorization to the request pipeline.
app.UseAuthentication();
app.UseAuthorization();
// Add current context
app.UseMiddleware<CurrentContextMiddleware>();
// Add MVC to the request pipeline.
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
services.AddHostedService<Core.HostedServices.ApplicationCacheHostedService>();
}
}
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
IHostApplicationLifetime appLifetime,
GlobalSettings globalSettings)
{
app.UseSerilog(env, appLifetime, globalSettings);
// Add general security headers
app.UseMiddleware<SecurityHeadersMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Default Middleware
app.UseDefaultMiddleware(env, globalSettings);
// Add routing
app.UseRouting();
// Add Cors
app.UseCors(policy => policy.SetIsOriginAllowed(o => CoreHelpers.IsCorsOriginAllowed(o, globalSettings))
.AllowAnyMethod().AllowAnyHeader().AllowCredentials());
// Add authentication and authorization to the request pipeline.
app.UseAuthentication();
app.UseAuthorization();
// Add current context
app.UseMiddleware<CurrentContextMiddleware>();
// Add MVC to the request pipeline.
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}