elastic / terraform-provider-elasticstack

Terraform provider for Elastic Stack
https://registry.terraform.io/providers/elastic/elasticstack/latest/docs
Apache License 2.0
167 stars 91 forks source link

[Bug] Cannot authenticate with user apikey #415

Open pyranja opened 1 year ago

pyranja commented 1 year ago

Describe the bug

I'm trying to use the elasticstack_fleet_enrollment_tokens data source, when using an api key for authentication. Performing a terraform plan fails with a 401 Unauthorized status.

{"statusCode":401,"error":"Unauthorized","message":"[security_exception\n\tRoot causes:\n\t\tsecurity_exception: unable to authenticate with provided credentials and anonymous access is not allowed for this request]: unable to authenticate with provided credentials and anonymous access is not allowed for this request"}

To Reproduce Steps to reproduce the behavior:

provider "elasticstack" {
  fleet { # TODO inject
    endpoint = "https://replace-me.kb.eu-west-1.aws.found.io:443"
    api_key  = "REPLACE_ME_APIKEY"
  }
}

data "elasticstack_fleet_enrollment_tokens" "current" {
  policy_id = null # fetch all tokenss
}

Expected behavior Can use an apikey to authenticate with fleet.

Debug output Run terraform command with TF_LOG=trace and provide extended information on TF operations.

Additional context I verified that the apikey works when contacting the api directly. After checking the provider implementation, I suspect that the provider sends authorization headers with the Bearer prefix. Apikeys are expected to use the Apikey prefix though - https://www.elastic.co/guide/en/cloud/current/ec-api-authentication.html

pyranja commented 1 year ago

I think that's a duplicate of #364 actually.

xeivieni commented 7 months ago

@pyranja I think you close the issue too soon. I am facing the same issue and you were right on you supposition : here in the fleet client code we can see that the Authorization header is prefixed by the Bearer keyword instead of ApiKey https://github.com/elastic/terraform-provider-elasticstack/blob/main/internal/clients/fleet/client.go#L102

tobio commented 7 months ago

FWIW the correct link for the Kibana API is here. It's lacking some detail on how to use API key auth though. The conclusion is however still correct, i.e we need to use the ApiKey prefix, rather than Bearer.

The docs linked to in the original issue are for the ESS (Cloud) API which currently uses a different API key to Kibana/Elasticsearch.

daemitus commented 3 days ago

solved by #576