use of io.dropwizard.auth.chained.ChainedAuthFilter in project fallout by datastax.
the class FalloutServiceBase method runServer.
private void runServer(FC conf, Environment environment, CreateAbortableTestRunExecutorFactory createTestRunExecutorFactory, SchemaMode schemaMode) throws Exception {
final LifecycleManager m = new LifecycleManager(environment);
final ResourceReservationLocks resourceReservationLocks = new ResourceReservationLocks();
cassandraDriverManager = m.manage(new CassandraDriverManager(conf.getCassandraHost(), conf.getCassandraPort(), conf.getKeyspace(), schemaMode, preCreateSchemaCallback));
SecurityUtil securityUtil = new SecurityUtil(conf.getSecureRandomAlgorithm());
final var userGroupMapper = createUserGroupMapper();
UserDAO userDAO = m.manage(new UserDAO(cassandraDriverManager, securityUtil, conf.getAdminUserCreds(), userGroupMapper));
TestRunDAO testRunDAO = m.manage(new TestRunDAO(cassandraDriverManager));
TestDAO testDAO = m.manage(new TestDAO(cassandraDriverManager, testRunDAO));
PerformanceReportDAO reportDAO = m.manage(new PerformanceReportDAO(cassandraDriverManager));
ActiveTestRunFactory activeTestRunFactory = createActiveTestRunFactory(conf);
UserMessenger mailer = HtmlMailUserMessenger.create(conf);
UserCredentialsFactory userCredentialsFactory = (testRun) -> {
User user = userDAO.getUser(testRun.getOwner());
if (user == null) {
throw new RuntimeException(String.format("Couldn't find User with email '%s'", testRun.getOwner()));
}
return new UserCredentials(user, userDAO.getCIUserByUser(user));
};
QueuingTestRunner testRunner = m.manageStartOnly(new QueuingTestRunner(testRunDAO::update, testDAO::updateLastRunAt, new PersistentPendingQueue(testRunDAO::getQueued), userCredentialsFactory, createTestRunExecutorFactory.create(conf, m, mailer, testDAO, testRunDAO, activeTestRunFactory), testRun -> activeTestRunFactory.getResourceRequirements(testRun, userCredentialsFactory), resourceReservationLocks, conf.getResourceLimits(), conf.getStartPaused()));
// monitor queue metrics
QueueMetricsManager.registerMetrics(environment.metrics(), testRunDAO);
runningTestRunsCount = testRunner::getRunningTestRunsCount;
// Make sure the performance_reports dir exists
FileUtils.createDirs(Paths.get(conf.getArtifactPath(), "performance_reports"));
final HashedWheelTimer timer = m.manage(new HashedWheelTimer(new NamedThreadFactory("ServiceTimer")), HashedWheelTimer::stop);
Path artifactPath = Paths.get(conf.getArtifactPath());
final var runningTaskLock = new ReentrantLock();
ArtifactScrubber artifactScrubber = m.manage(new ArtifactScrubber(conf.getStartPaused(), timer, runningTaskLock, Duration.hours(0), Duration.hours(24), artifactPath, testRunDAO, userDAO));
ArtifactCompressor artifactCompressor = m.manage(new ArtifactCompressor(conf.getStartPaused(), timer, runningTaskLock, Duration.hours(12), Duration.hours(24), artifactPath, testRunDAO, testDAO));
TestRunReaper testRunReaper = m.manage(new TestRunReaper(conf.getStartPaused(), timer, runningTaskLock, Duration.hours(18), Duration.days(7), testRunDAO, reportDAO, testDAO, mailer, SlackUserMessenger.create(conf.getSlackToken(), m.manage(FalloutClientBuilder.forComponent(SlackUserMessenger.class).build(), Client::close)), conf.getExternalUrl()));
QueueAdminTask queueAdminTask = new QueueAdminTask(testRunner, List.of(artifactScrubber, artifactCompressor, testRunReaper));
environment.admin().addTask(queueAdminTask);
final var artifactUsageAdminTask = new ArtifactUsageAdminTask(testRunDAO);
environment.admin().addTask(artifactUsageAdminTask);
environment.admin().addTask(new ArtifactCompressorAdminTask(artifactCompressor));
environment.admin().addTask(new ShutdownTask(this::shutdown));
truncateTrailingSlashesInUrls(conf);
final RewriteHandler rewriteHandler = new RewriteHandler();
conf.getServerFactory().insertHandler(rewriteHandler);
addArtifactServlet(conf, environment, rewriteHandler);
// Add CORS headers so that fallout API can be consumed from other than the main URL
// The `CrossOriginFilter` comes with the required default settings: allow any origin
environment.servlets().addFilter("CORS", CrossOriginFilter.class).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
// Register our exception mappers: note that we must use concrete (i.e. non-generic) classes, otherwise
// the convoluted exception mapping code in Jersey will fail with an HTTP 500 error.
// Dropwizard registers several helpful exception mappers on server start in its ExceptionMapperBinder; one of
// these provides a helper logging method for detecting a particular developer error when POSTing
// forms. Unfortunately, this intercepts _all_ IllegalStateExceptions. We insert our IllegalStateException
// mapper here to pre-empt it, whilest keeping the helper logic.
environment.jersey().register(new FalloutExceptionMapper<IllegalStateException>() {
private final IllegalStateExceptionMapper dropWizardIllegalStateExceptionMapper = new IllegalStateExceptionMapper();
/**
* If the helper code in {@link IllegalStateExceptionMapper} applies, use that
*/
@Override
public Response toResponse(IllegalStateException exception) {
if (LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR().equals(exception.getMessage())) {
return dropWizardIllegalStateExceptionMapper.toResponse(exception);
}
return super.toResponse(exception);
}
});
// This is our default exception mapper.
environment.jersey().register(new FalloutExceptionMapper<>() {
});
environment.jersey().register(new AuthDynamicFeature(new ChainedAuthFilter(getAuthFilters(conf, userDAO))));
// Enable @RolesAllowed annotations
environment.jersey().register(new RolesAllowedDynamicFeature());
// If you want to use @Auth to inject a custom Principal type into your resource
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
final ComponentResource componentResource = new ComponentResource(conf, componentFactory);
MainView mainView = new MainView(componentResource.getComponentTypes(), testRunner, addVersionedAssetsRewriteRule(rewriteHandler), conf::hideDisplayedEmailDomains);
componentResource.setMainView(mainView);
CommandExecutor commandExecutor = new LocalCommandExecutor();
environment.jersey().register(new StatusResource(testRunner));
environment.jersey().register(new HomeResource(conf, userDAO, testRunDAO, testRunner, conf.getResourceLimits(), mainView, userGroupMapper));
environment.jersey().register(new AdminResource(testRunner, queueAdminTask, artifactUsageAdminTask, mainView));
environment.jersey().register(new AccountResource(userDAO, conf, mailer, mainView, securityUtil, userGroupMapper));
environment.jersey().register(new TestResource(conf, testDAO, testRunDAO, activeTestRunFactory, userCredentialsFactory, reportDAO, testRunner, mainView, userGroupMapper));
environment.jersey().register(componentResource);
environment.jersey().register(new PerformanceToolResource(testDAO, testRunDAO, reportDAO, conf.getArtifactPath(), mainView, userGroupMapper));
registerOptionalResources(conf, environment, testRunDAO, commandExecutor);
// Using SSE (which is what LiveResource uses) doesn't work unless we prevent the
// GZIP output filter from flushing-on-demand (if we don't do this, data is queued up until the
// GZIP implementation decides it's a good time to flush: see java.util.zip.Deflater#SYNC_FLUSH).
((DefaultServerWithHandlerFactory) conf.getServerFactory()).getGzipFilterFactory().setSyncFlush(true);
final ArtifactWatcher artifactWatcher = new ArtifactWatcher(Paths.get(conf.getArtifactPath()), timer, conf.getArtifactWatcherCoalescingIntervalSeconds());
environment.lifecycle().manage(artifactWatcher);
final ServerSentEvents serverSentEvents = m.manageStartOnly(new ServerSentEvents(timer, conf.getServerSentEventsHeartBeatIntervalSeconds()));
environment.jersey().register(new LiveResource(testRunDAO, artifactWatcher, serverSentEvents));
setShutdownHandler(environment, testRunner, serverSentEvents);
}
use of io.dropwizard.auth.chained.ChainedAuthFilter in project consent by DataBiosphere.
the class ConsentApplication method run.
@Override
public void run(ConsentConfiguration config, Environment env) {
try {
initializeLiquibase(config);
} catch (LiquibaseException | SQLException e) {
LOGGER.error("Exception initializing liquibase: " + e);
}
// TODO: Update all services to use an injector.
// Previously, this code was working around a dropwizard+Guice issue with singletons and JDBI.
final Injector injector = Guice.createInjector(new ConsentModule(config, env));
// Clients
final HttpClientUtil clientUtil = new HttpClientUtil();
final GCSStore googleStore = injector.getProvider(GCSStore.class).get();
// Services
final ApprovalExpirationTimeService approvalExpirationTimeService = injector.getProvider(ApprovalExpirationTimeService.class).get();
final ConsentService consentService = injector.getProvider(ConsentService.class).get();
final DarCollectionService darCollectionService = injector.getProvider(DarCollectionService.class).get();
final DacService dacService = injector.getProvider(DacService.class).get();
final DataAccessRequestService dataAccessRequestService = injector.getProvider(DataAccessRequestService.class).get();
final DatasetAssociationService datasetAssociationService = injector.getProvider(DatasetAssociationService.class).get();
final DatasetService datasetService = injector.getProvider(DatasetService.class).get();
final ElectionService electionService = injector.getProvider(ElectionService.class).get();
final EmailNotifierService emailNotifierService = injector.getProvider(EmailNotifierService.class).get();
final GCSService gcsService = injector.getProvider(GCSService.class).get();
final InstitutionService institutionService = injector.getProvider(InstitutionService.class).get();
final MetricsService metricsService = injector.getProvider(MetricsService.class).get();
final PendingCaseService pendingCaseService = injector.getProvider(PendingCaseService.class).get();
final UserService userService = injector.getProvider(UserService.class).get();
final VoteService voteService = injector.getProvider(VoteService.class).get();
final AuditService auditService = injector.getProvider(AuditService.class).get();
final SummaryService summaryService = injector.getProvider(SummaryService.class).get();
final ReviewResultsService reviewResultsService = injector.getProvider(ReviewResultsService.class).get();
final UseRestrictionValidator useRestrictionValidator = injector.getProvider(UseRestrictionValidator.class).get();
final MatchService matchService = injector.getProvider(MatchService.class).get();
final OAuthAuthenticator authenticator = injector.getProvider(OAuthAuthenticator.class).get();
final LibraryCardService libraryCardService = injector.getProvider(LibraryCardService.class).get();
final SamService samService = injector.getProvider(SamService.class).get();
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
configureCors(env);
// Health Checks
env.healthChecks().register(GCS_CHECK, new GCSHealthCheck(gcsService));
env.healthChecks().register(ES_CHECK, new ElasticSearchHealthCheck(config.getElasticSearchConfiguration()));
env.healthChecks().register(ONTOLOGY_CHECK, new OntologyHealthCheck(clientUtil, config.getServicesConfiguration()));
env.healthChecks().register(SAM_CHECK, new SamHealthCheck(clientUtil, config.getServicesConfiguration()));
env.healthChecks().register(SG_CHECK, new SendGridHealthCheck(clientUtil, config.getMailConfiguration()));
final StoreOntologyService storeOntologyService = new StoreOntologyService(googleStore, config.getStoreOntologyConfiguration().getBucketSubdirectory(), config.getStoreOntologyConfiguration().getConfigurationFileName());
final ResearcherService researcherService = injector.getProvider(ResearcherService.class).get();
final NihService nihService = injector.getProvider(NihService.class).get();
final IndexOntologyService indexOntologyService = new IndexOntologyService(config.getElasticSearchConfiguration());
final IndexerService indexerService = new IndexerServiceImpl(storeOntologyService, indexOntologyService);
// Custom Error handling. Expand to include other codes when necessary
final ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "/error/404");
env.getApplicationContext().setErrorHandler(errorHandler);
env.jersey().register(ResponseServerFilter.class);
env.jersey().register(ErrorResource.class);
// Register standard application resources.
env.jersey().register(new ApprovalExpirationTimeResource(approvalExpirationTimeService, userService));
env.jersey().register(new DataAccessRequestResourceVersion2(dataAccessRequestService, emailNotifierService, gcsService, userService, matchService));
env.jersey().register(new DataAccessRequestResource(dataAccessRequestService, userService, consentService, electionService));
env.jersey().register(new DatasetResource(consentService, datasetService, userService, dataAccessRequestService));
env.jersey().register(new DatasetAssociationsResource(datasetAssociationService));
env.jersey().register(new ConsentResource(auditService, userService, consentService, matchService, useRestrictionValidator));
env.jersey().register(new ConsentAssociationResource(consentService, userService));
env.jersey().register(new ConsentElectionResource(consentService, dacService, emailNotifierService, voteService, electionService));
env.jersey().register(new ConsentManageResource(consentService));
env.jersey().register(new ConsentVoteResource(emailNotifierService, electionService, voteService));
env.jersey().register(new ConsentCasesResource(electionService, pendingCaseService, summaryService));
env.jersey().register(new DacResource(dacService, userService));
env.jersey().register(new DACUserResource(userService));
env.jersey().register(new DarCollectionResource(dataAccessRequestService, darCollectionService, userService));
env.jersey().register(new DataRequestElectionResource(dataAccessRequestService, emailNotifierService, summaryService, voteService, electionService));
env.jersey().register(new DataRequestVoteResource(dataAccessRequestService, datasetAssociationService, emailNotifierService, voteService, datasetService, electionService, userService));
env.jersey().register(new DataRequestCasesResource(electionService, pendingCaseService, summaryService));
env.jersey().register(new DataRequestReportsResource(dataAccessRequestService));
env.jersey().register(new DataUseLetterResource(auditService, googleStore, userService, consentService));
env.jersey().register(new ElectionResource(voteService, electionService));
env.jersey().register(new ElectionReviewResource(dataAccessRequestService, consentService, electionService, reviewResultsService));
env.jersey().register(new EmailNotifierResource(emailNotifierService));
env.jersey().register(new IndexerResource(indexerService, googleStore));
env.jersey().register(new InstitutionResource(userService, institutionService));
env.jersey().register(new LibraryCardResource(userService, libraryCardService));
env.jersey().register(new MatchResource(matchService));
env.jersey().register(new MetricsResource(metricsService));
env.jersey().register(new NihAccountResource(nihService, userService));
env.jersey().register(new ResearcherResource(researcherService));
env.jersey().register(new SamResource(samService));
env.jersey().register(new SwaggerResource(config.getGoogleAuthentication()));
env.jersey().register(new StatusResource(env.healthChecks()));
env.jersey().register(new UserResource(researcherService, samService, userService));
env.jersey().register(new TosResource(samService));
env.jersey().register(injector.getInstance(VersionResource.class));
env.jersey().register(new VoteResource(userService, voteService));
// Authentication filters
final UserRoleDAO userRoleDAO = injector.getProvider(UserRoleDAO.class).get();
AuthFilter defaultAuthFilter = new DefaultAuthFilter.Builder<AuthUser>().setAuthenticator(new DefaultAuthenticator()).setRealm(" ").buildAuthFilter();
List<AuthFilter> filters = Lists.newArrayList(defaultAuthFilter, new BasicCustomAuthFilter(new BasicAuthenticator(config.getBasicAuthentication())), new OAuthCustomAuthFilter(authenticator, userRoleDAO));
env.jersey().register(new AuthDynamicFeature(new ChainedAuthFilter(filters)));
env.jersey().register(RolesAllowedDynamicFeature.class);
env.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthUser.class));
}
Aggregations