### Elasticsearch Version

Tested against 8.6.0

### Installed Plugins

_No response_

### Java Version

_bundled_

### OS Version

Ubuntu

### Problem Description

When `search.allow_expensive_queries` is set to `false` some queries may fail since they are considered expensive. Typically there is an obvious connection between the action you are performing and any errors raised due to expensive queries. For example, if you explicitly issue a [prefix query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html) and  `search.allow_expensive_queries` is set to `false` there is a natural correlation between your request and the error. 

It has been found that when the following conditions are met 

* The API key or role has application level privileges
* One of the application level privileges has a trailing wildcard in the application name (i.e. `myapp*`) 
* The API key or role  is not cached 

then authentication will fail due to an error [1] related to the expensive query. This because internally the code issues a prefix query to for the application name. The end result is the API key can longer be used for authentication for any action. 

Workaround include : 
* set `search.allow_expensive_queries` is set to `true`
* remove the `*` from the application privilege name

It is also possible to set  `search.allow_expensive_queries` to  `true` make a call with the API key or user with the role so that it gets cached, then set `search.allow_expensive_queries` back to `false` . That will cause the API key or role to be cached, and it will work after that, but it can also start to fail again at what would seem a random time if ever evicted from the cache or the node gets restarted. For this reason, that work around is not suggested. 

[1] Example exception. Note - other similar exceptions can occur but they all reference `search.allow_expensive_queries` and the `.security-*` index 
```
Caused by: [.security-7/9mbNjDCNRzSzrDtj2YEeKQ] org.elasticsearch.index.query.QueryShardException: failed to create query: [prefix] queries cannot be executed when 'search.allow_expensive_queries' is set to false. For optimised prefix queries on text fields please enable [index_prefixes].
	at org.elasticsearch.index.query.SearchExecutionContext.toQuery(SearchExecutionContext.java:548)
	at org.elasticsearch.index.query.SearchExecutionContext.toQuery(SearchExecutionContext.java:531)
	at org.elasticsearch.search.SearchService.parseSource(SearchService.java:1174)
	at org.elasticsearch.search.SearchService.createContext(SearchService.java:986)
	at org.elasticsearch.search.SearchService.executeQueryPhase(SearchService.java:630)
	at org.elasticsearch.search.SearchService.lambda$executeQueryPhase$2(SearchService.java:495)
	at org.elasticsearch.action.ActionRunnable$2.accept(ActionRunnable.java:50)
	at org.elasticsearch.action.ActionRunnable$2.accept(ActionRunnable.java:47)
	at org.elasticsearch.action.ActionRunnable$3.doRun(ActionRunnable.java:72)
	at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingAbstractRunnable.doRun(ThreadContext.java:917)
	at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
	at java.lang.Thread.run(Thread.java:1589)
```

### Steps to Reproduce

```
PUT _cluster/settings
{
    "persistent": {
        "search.allow_expensive_queries": "false"
    }
}

POST _security/api_key
{
  "name": "my_api_key",
  "role_descriptors": {
    "role1": {
      "cluster": ["all"],
      "indices": [
        {
          "names": ["test"],
          "privileges": ["write"]
        }
      ],
      "applications": [
        {
          "application": "app*",
          "privileges": ["read", "write"],
          "resources": ["*"]
        }
      ]
    }
  },
  "expiration": "1d"
}

using API key just created...

POST _bulk 
{ "index" : { "_index" : "test", "_id" : "4" } }
{ "field1" : "value1" }

```

EDIT: Updated text to suggest this can happen with an API key or a custom role
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/Security.java
components.add(realms);
        components.add(reservedRealm);
        systemIndices.getMainIndexManager().addStateListener(nativeRoleMappingStore::onSecurityIndexStateChange);
        final CacheInvalidatorRegistry cacheInvalidatorRegistry = new CacheInvalidatorRegistry();
        cacheInvalidatorRegistry.registerAlias("service", Set.of("file_service_account_token", "index_service_account_token"));
        components.add(cacheInvalidatorRegistry);
        systemIndices.getMainIndexManager().addStateListener(cacheInvalidatorRegistry::onSecurityIndexStateChange);
        final NativePrivilegeStore privilegeStore = new NativePrivilegeStore(
            settings,
            client,
            systemIndices.getMainIndexManager(),
            cacheInvalidatorRegistry
        );
        components.add(privilegeStore);
        dlsBitsetCache.set(new DocumentSubsetBitsetCache(settings, threadPool));
        final FieldPermissionsCache fieldPermissionsCache = new FieldPermissionsCache(settings);
        final FileRolesStore fileRolesStore = new FileRolesStore(
            settings,
            environment,
            resourceWatcherService,
            getLicenseState(),
            xContentRegistry
        );
        final NativeRolesStore nativeRolesStore = new NativeRolesStore(
            settings,
            client,
            getLicenseState(),
            systemIndices.getMainIndexManager(),
            clusterService
        );