Skip to content

Commit

Permalink
Eliminate the anti-discovery pattern in Elasticsearch
Browse files Browse the repository at this point in the history
Fix #15133
  • Loading branch information
MikeAlhayek committed Jan 19, 2024
1 parent 95e3cc7 commit d08cfd2
Show file tree
Hide file tree
Showing 12 changed files with 302 additions and 136 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public class AdminController : Controller
private readonly INotifier _notifier;
private readonly ILogger _logger;
private readonly IOptions<TemplateOptions> _templateOptions;
private readonly ElasticConnectionOptions _elasticConnectionOptions;
private readonly IShapeFactory _shapeFactory;
private readonly ILocalizationService _localizationService;

Expand All @@ -71,6 +72,7 @@ public AdminController(
INotifier notifier,
ILogger<AdminController> logger,
IOptions<TemplateOptions> templateOptions,
IOptions<ElasticConnectionOptions> elasticConnectionOptions,
IShapeFactory shapeFactory,
ILocalizationService localizationService,
IStringLocalizer<AdminController> stringLocalizer,
Expand All @@ -90,6 +92,7 @@ public AdminController(
_notifier = notifier;
_logger = logger;
_templateOptions = templateOptions;
_elasticConnectionOptions = elasticConnectionOptions.Value;
_shapeFactory = shapeFactory;
_localizationService = localizationService;
S = stringLocalizer;
Expand All @@ -103,6 +106,11 @@ public async Task<IActionResult> Index(ContentOptions options, PagerParameters p
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return NotConfigured();
}

var indexes = (await _elasticIndexSettingsService.GetSettingsAsync())
.Select(i => new IndexViewModel { Name = i.IndexName })
.ToList();
Expand Down Expand Up @@ -150,13 +158,13 @@ public async Task<IActionResult> Index(ContentOptions options, PagerParameters p

[HttpPost, ActionName(nameof(Index))]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(AdminIndexViewModel model)
public IActionResult IndexFilterPOST(AdminIndexViewModel model)
=> RedirectToAction(nameof(Index), new RouteValueDictionary
{
{ _optionsSearch, model.Options.Search }
});

public async Task<ActionResult> Edit(string indexName = null)
public async Task<IActionResult> Edit(string indexName = null)
{
var IsCreate = string.IsNullOrWhiteSpace(indexName);
var settings = new ElasticIndexSettings();
Expand All @@ -166,6 +174,11 @@ public async Task<ActionResult> Edit(string indexName = null)
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return NotConfigured();
}

if (!IsCreate)
{
settings = await _elasticIndexSettingsService.GetSettingsAsync(indexName);
Expand Down Expand Up @@ -200,6 +213,11 @@ public async Task<ActionResult> EditPost(ElasticIndexSettingsViewModel model, st
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return BadRequest();
}

ValidateModel(model);

if (model.IsCreate)
Expand Down Expand Up @@ -295,6 +313,11 @@ public async Task<ActionResult> Reset(string id)
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return BadRequest();
}

if (!await _elasticIndexManager.ExistsAsync(id))
{
return NotFound();
Expand All @@ -316,6 +339,11 @@ public async Task<ActionResult> Rebuild(string id)
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return BadRequest();
}

if (!await _elasticIndexManager.ExistsAsync(id))
{
return NotFound();
Expand Down Expand Up @@ -349,6 +377,11 @@ public async Task<ActionResult> Delete(ElasticIndexSettingsViewModel model)
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return BadRequest();
}

if (!await _elasticIndexManager.ExistsAsync(model.IndexName))
{
await _notifier.SuccessAsync(H["Index not found on Elasticsearch server.", model.IndexName]);
Expand Down Expand Up @@ -378,6 +411,11 @@ public async Task<ActionResult> ForceDelete(ElasticIndexSettingsViewModel model)
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return BadRequest();
}

try
{
await _elasticIndexingService.DeleteIndexAsync(model.IndexName);
Expand Down Expand Up @@ -416,12 +454,19 @@ public async Task<IActionResult> SyncSettings()
return RedirectToAction(nameof(Index));
}

public Task<IActionResult> Query(string indexName, string query)
=> Query(new AdminQueryViewModel
public async Task<IActionResult> Query(string indexName, string query)
{
if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return NotConfigured();
}

return await Query(new AdminQueryViewModel
{
IndexName = indexName,
DecodedQuery = string.IsNullOrWhiteSpace(query) ? string.Empty : System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query))
});
}

[HttpPost]
public async Task<IActionResult> Query(AdminQueryViewModel model)
Expand All @@ -431,6 +476,11 @@ public async Task<IActionResult> Query(AdminQueryViewModel model)
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return BadRequest();
}

model.Indices = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray();

// Can't query if there are no indices.
Expand Down Expand Up @@ -496,6 +546,11 @@ public async Task<ActionResult> IndexPost(ContentOptions options, IEnumerable<st
return Forbid();
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return BadRequest();
}

if (itemIds?.Count() > 0)
{
var elasticIndexSettings = await _elasticIndexSettingsService.GetSettingsAsync();
Expand Down Expand Up @@ -540,7 +595,7 @@ public async Task<ActionResult> IndexPost(ContentOptions options, IEnumerable<st
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(options.BulkAction), "Unknown bulk action");
return BadRequest();
}
}

Expand Down Expand Up @@ -577,5 +632,8 @@ private async Task PopulateMenuOptionsAsync(ElasticIndexSettingsViewModel model)
model.Analyzers = _elasticSearchOptions.Analyzers
.Select(x => new SelectListItem { Text = x.Key, Value = x.Key });
}

private IActionResult NotConfigured()
=> View("NotConfigured");
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using OrchardCore.ContentManagement.Metadata.Models;
Expand All @@ -22,7 +21,7 @@ public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefiniti
{
return Initialize<ContentPickerFieldElasticEditorSettings>("ContentPickerFieldElasticEditorSettings_Edit", async model =>
{
partFieldDefinition.PopulateSettings<ContentPickerFieldElasticEditorSettings>(model);
partFieldDefinition.PopulateSettings(model);
model.Indices = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray();
}).Location("Editor");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Nest;
using OrchardCore.DisplayManagement.Entities;
using OrchardCore.DisplayManagement.Handlers;
Expand All @@ -30,20 +31,24 @@ public class ElasticSettingsDisplayDriver : SectionDisplayDriver<ISite, ElasticS
private readonly ElasticIndexSettingsService _elasticIndexSettingsService;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IAuthorizationService _authorizationService;
private readonly ElasticConnectionOptions _elasticConnectionOptions;
private readonly IElasticClient _elasticClient;

protected readonly IStringLocalizer S;

public ElasticSettingsDisplayDriver(
ElasticIndexSettingsService elasticIndexSettingsService,
IHttpContextAccessor httpContextAccessor,
IAuthorizationService authorizationService,
IOptions<ElasticConnectionOptions> elasticConnectionOptions,
IElasticClient elasticClient,
IStringLocalizer<ElasticSettingsDisplayDriver> stringLocalizer
)
{
_elasticIndexSettingsService = elasticIndexSettingsService;
_httpContextAccessor = httpContextAccessor;
_authorizationService = authorizationService;
_elasticConnectionOptions = elasticConnectionOptions.Value;
_elasticClient = elasticClient;
S = stringLocalizer;
}
Expand Down Expand Up @@ -73,6 +78,11 @@ public override async Task<IDisplayResult> UpdateAsync(ElasticSettings section,
return null;
}

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
return null;
}

if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, Permissions.ManageElasticIndexes))
{
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Threading.Tasks;
using Fluid.Values;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Nest;
using OrchardCore.Liquid;
using OrchardCore.Search.Abstractions;
Expand All @@ -25,6 +26,7 @@ public class ElasticsearchService : ISearchService
private readonly IElasticSearchQueryService _elasticsearchQueryService;
private readonly IElasticClient _elasticClient;
private readonly JavaScriptEncoder _javaScriptEncoder;
private readonly ElasticConnectionOptions _elasticConnectionOptions;
private readonly ILiquidTemplateManager _liquidTemplateManager;
private readonly ILogger _logger;

Expand All @@ -35,6 +37,7 @@ public ElasticsearchService(
IElasticSearchQueryService elasticsearchQueryService,
IElasticClient elasticClient,
JavaScriptEncoder javaScriptEncoder,
IOptions<ElasticConnectionOptions> elasticConnectionOptions,
ILiquidTemplateManager liquidTemplateManager,
ILogger<ElasticsearchService> logger
)
Expand All @@ -45,6 +48,7 @@ ILogger<ElasticsearchService> logger
_elasticsearchQueryService = elasticsearchQueryService;
_elasticClient = elasticClient;
_javaScriptEncoder = javaScriptEncoder;
_elasticConnectionOptions = elasticConnectionOptions.Value;
_liquidTemplateManager = liquidTemplateManager;
_logger = logger;
}
Expand All @@ -53,13 +57,20 @@ ILogger<ElasticsearchService> logger

public async Task<SearchResult> SearchAsync(string indexName, string term, int start, int pageSize)
{
var result = new SearchResult();

if (!_elasticConnectionOptions.IsFileConfigurationExists())
{
_logger.LogWarning("Elasticsearch: Couldn't execute search. The Elasticsearch has not yet been configured.");

return result;
}

var siteSettings = await _siteService.GetSiteSettingsAsync();
var searchSettings = siteSettings.As<ElasticSettings>();

var index = !string.IsNullOrWhiteSpace(indexName) ? indexName.Trim() : searchSettings.SearchIndex;

var result = new SearchResult();

if (index == null || !await _elasticIndexManager.ExistsAsync(index))
{
_logger.LogWarning("Elasticsearch: Couldn't execute search. The search index doesn't exist.");
Expand Down
Loading

0 comments on commit d08cfd2

Please sign in to comment.