---
setup:
  - skip:
      features: headers

  - do:
      cluster.health:
        wait_for_status: yellow
  - do:
      ingest.put_pipeline:
        id: "my_pipeline"
        body:  >
          {
            "processors": [
              {
                "set_security_user" : {
                  "field" : "user"
                }
              }
            ]
          }

---
teardown:
  - do:
      ingest.delete_pipeline:
        id: "my_pipeline"
        ignore: 404

---
"Test set security user ingest processor works for API keys":
  - do:
      security.create_api_key:
        body:  >
          {
            "name": "with-metadata",
            "metadata": {
              "string": "hello",
              "number": 42,
              "complex": { "foo": "bar", "values": [1, 3, 5] }
            }
          }
  - set: { id: id_with_metadata }
  - transform_and_set: { login_creds: "#base64EncodeCredentials(id,api_key)" }

  - do:
      headers:
        Authorization: ApiKey ${login_creds}
      index:
        index: index
        id: "1"
        pipeline: "my_pipeline"
        body: >
          {
            "message": "should have api key metadata"
          }

  - do:
      security.create_api_key:
        body:  >
          {
            "name": "no-metadata"
          }
  - set: { id: id_no_metadata }
  - transform_and_set: { login_creds: "#base64EncodeCredentials(id,api_key)" }

  - do:
      headers:
        Authorization: ApiKey ${login_creds}
      index:
        index: index
        id: "2"
        pipeline: "my_pipeline"
        body: >
          {
            "message": "should not have api key metadata"
          }

  - do:
      security.create_api_key:
        body:  >
          {
            "name": "empty-metadata",
            "metadata": { }
          }
  - set: { id: id_empty_metadata }
  - transform_and_set: { login_creds: "#base64EncodeCredentials(id,api_key)" }

  - do:
      headers:
        Authorization: ApiKey ${login_creds}
      index:
        index: index
        id: "3"
        pipeline: "my_pipeline"
        body: >
          {
            "message": "should not have api key metadata either"
          }

  - do:
      indices.refresh:
        index: index

  - do:
      get:
        index: index
        id: "1"
  - match: { _source.user.api_key.name: "with-metadata" }
  - match: { _source.user.api_key.id: $id_with_metadata }
  - match: { _source.user.api_key.metadata: { "string": "hello", "number": 42, "complex": {"foo": "bar", "values": [1, 3, 5]} } }

  - do:
      get:
        index: index
        id: "2"
  - match: { _source.user.api_key.name: "no-metadata" }
  - match: { _source.user.api_key.id: $id_no_metadata }
  - is_false: _source.user.api_key.metadata

  - do:
      get:
        index: index
        id: "3"
  - match: { _source.user.api_key.name: "empty-metadata" }
  - match: { _source.user.api_key.id: $id_empty_metadata }
  - is_false: _source.user.api_key.metadata
