elastic / elasticsearch-php

Official PHP client for Elasticsearch.
https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html
MIT License
5.27k stars 965 forks source link

Cannot add header 'es-security-runas-user' to impersonate another user #1321

Closed serlo89 closed 1 year ago

serlo89 commented 1 year ago

Cannot add header 'es-security-runas-user' to impersonate another user

I am trying to upgrade a PHP website from Elastic 7 to Elastic 8. This website use impersonation and this is not working if I upgrade to ES-PHP 8.

In ES-PHP 7 i used to build the query in this way:

 $params = [
    'client' => [
        'headers' => [
            'es-security-runas-user' => [$user]
        ]
    ],
    'body'=>[
        ...
    ]
];

$response = $my_conn->search($params);

I checked the breaking changes from ES7 to ES8 and i found the following:

We removed the special client parameter passed in $params endpoints. In details:

  • $params['client']['never_retry']
  • $params['client']['verbose']
  • $params['client']['port_in_header']
  • $params['client']['future'], you can set HTTP async using Client::setAsync(true)
  • $params['client']['ignore'], you can disable the Exception using Client::setResponseException(false)

https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/breaking_changes.html

So, how can I now add the header to impersonate another user? I'm sure that every setting in Elasticsearch is correct because if i send a request impersonating a user via curl or postman it works, but using the website i have the following Exception:

401 Unauthorized: 
{
  "error": {
    "root_cause": [
      {
        "type": "security_exception",
        "reason": "missing authentication credentials for REST request [/_search]",
        "header": {
          "WWW-Authenticate": [
            "Basic realm=\"security\" charset=\"UTF-8\"",
            "Bearer realm=\"security\"",
            "ApiKey"
          ]
        }
      }
    ],
    "type": "security_exception",
    "reason": "missing authentication credentials for REST request [/_search]",
    "header": {
      "WWW-Authenticate": [
        "Basic realm=\"security\" charset=\"UTF-8\"",
        "Bearer realm=\"security\"",
        "ApiKey"
      ]
    }
  },
  "status": 401
}

So, the custom header was not sent to the request. Thanks

serlo89 commented 1 year ago

I found that the authentication was not set correctly and caused the Error 401 Unauthorized. Fixing the problem made the query works but impersonation didn't work yet.

To impersonate i had to set the following code:

 $clientBuilder->setHttpClientOptions(['headers' => ['es-security-runas-user' => 'userToBeImpersonated']]);

and remove the 'client' parameter which is useless.