What Is an API Key in Elasticsearch?

What Is an API Key in Elasticsearch?

A complete, plain-English guide to the credential that lets programs talk to Elasticsearch without sharing a password: how a key is made, how it is checked, how its permissions are limited, and how to run keys safely in production.

Think about a hotel. When you check in, the front desk does not hand you the master key that opens every door in the building. It gives you a plastic card that opens only your room, works only for the days you booked, and can be switched off at the desk in a few seconds if you lose it. Nobody has to change the locks. Nobody else’s card is affected.

An API key in Elasticsearch is that plastic card. Without it, a program that wants to read or write data would need a real person’s username and password, which is like handing a stranger the master key. With it, each program gets its own small, limited, replaceable credential. In this guide we start from zero, look at what happens inside the cluster each time a key is used, and finish with the practices, the traps, and the numbers that matter when you run keys in production.

1What an API Key Actually Is

Three ideas, put together: authentication, credential, and limited access. Once each is clear, the rest follows naturally.

Elasticsearch is a search and data engine. Programs talk to it over the network to store documents and to ask questions. Because the data is valuable, Elasticsearch has to answer two questions for every request. The first is authentication: “who are you?” The second is authorization: “are you allowed to do this particular thing?” A credential is the proof you show in answer to the first question. A username with a password is one kind of credential. An API key is another kind.

An API key is a credential that Elasticsearch itself creates and remembers. When you ask for one, Elasticsearch generates a random secret, gives the key an identifier, records the key in its own security storage, and shows you the secret one time. From then on, any program that presents the id and the secret together is recognized as holding that key. The program does not need a username, and it does not need anyone’s password.

The most useful part is the third idea: limited access. When you create a key, you can describe exactly what it may do, such as “write documents into the logs indexes and nothing else.” You can also give it an expiry time. And later you can cancel just that one key without touching anything else.

Everyday Analogy

Think of a valet key for a car. It starts the engine and opens the driver’s door, but it does not open the glove box or the trunk. A family member holds the full key. The valet holds a limited one, and if the valet loses it, you cancel that one key and the family’s keys keep working. An Elasticsearch API key is that valet key for your data.

Once
the secret part is shown only at the moment of creation
Scoped
each key can be limited to exactly the access it needs
Revocable
one key can be cancelled without affecting any other
A good API key is small, specific, and easy to throw away.

What a key is made of

Part

The id

A public identifier of the key. It is safe to look at and is used to find the key later, for example to cancel it.

Part

The secret

A long random value that proves you hold the key. Treat it like a password. It is shown only once, and Elasticsearch does not keep it in readable form.

Part

The name

A human-friendly label you choose, such as “orders-service-logs-writer”, to help you recognize the key later.

Optional

Permissions and expiry

Optional limits: a description of allowed actions, a time after which the key stops working, and free-form notes called metadata.

i
Do Not Mix Up the Names

The words “API key” appear in many products. Elastic Cloud, the hosting service, has its own API keys for managing deployments, and that is a different thing from the Elasticsearch API keys in this guide, which authenticate requests to the data engine itself. Also, the API keys of other companies are unrelated. This guide is only about the keys that Elasticsearch creates and checks.

The one-sentence version

If you remember one line from this chapter, make it this: an Elasticsearch API key is a revocable, optionally expiring, permission-limited credential, created and verified by Elasticsearch itself, that lets a program authenticate without using anyone’s password.

2Why It Exists: The Problem With Sharing Passwords

Every security feature is born from a painful situation. Here is the one that produced API keys.

Picture a company with fifty small programs that all need Elasticsearch: a website search box, an order tracker, three log shippers, a nightly report, and many more. The quick way to connect them is to create one user and give every program the same username and password. It works on day one, and then the trouble begins.

  • Too much power. That shared user often has broad rights, because it must satisfy the needs of every program. Each program therefore holds far more power than it uses.
  • No way to tell them apart. When something odd happens in the logs, every program looks like the same user. You cannot tell which one did it.
  • Painful rotation. If the password leaks, you must change it, and then every single program breaks at once until each is updated.
  • Tied to a person. Sometimes the password belongs to an actual employee. When that person leaves, or is forced to change the password, production stops.
  • No expiry. Passwords live until someone remembers to change them, which in practice means years.

API keys solve these problems together. Each program gets its own key with only the rights it needs. Each key has its own id, so logs show which key did what. A leaked key is cancelled by itself, and the other forty-nine programs carry on. A key can be given an end date at birth, so forgotten credentials clean themselves up.

Everyday Analogy

An office where everyone shares one master key has an easy first week and a terrible first year. When one person loses it, all the locks must be changed and all the keys re-issued. An office with a key card for each person can cancel one card in a moment and everyone else walks in as usual.

A short history

1

Early days: user accounts only

Elasticsearch security began with users, passwords, and roles. Applications had to pretend to be users.

2

Around version 6.7: API keys appear

The API key service arrived, at first as a preview, to give programs their own revocable credentials.

3

Version 7 era: maturity

The feature settled in and became the recommended choice for programs and agents that write or read data.

4

Later releases: better management

Ways to update an existing key, to update many keys at once, and to search through keys were added, along with special keys for cross-cluster work. Before, changing a key often meant replacing it.

5

Today: the default for programs

Elastic’s own tools, such as the agents and shippers, commonly use API keys, and security guidance for applications points to them.

The exact release for each step is worth double-checking in the release notes of your version. The direction of travel is what matters: from “programs borrow a person’s identity” toward “programs carry their own small, limited identity.”

Why not just make a new user for every program?

You can, and some teams do. A user needs a password, a role, and a home in some authentication system, and creating many of them is heavy work. API keys are lighter. They can be created by a program, in seconds, on demand, with permissions attached at creation. They fit the way modern systems create and destroy small workers all the time.

Three small stories about shared passwords

These stories are invented, but every security team has seen something like them.

The departing engineer. A developer sets up the nightly reporting job using her own account, because it is the quickest way to start. Two years later she moves to another company. Her account is disabled as part of the normal exit process, and the next morning every report is empty. It takes a day to find out why, because nobody remembers that the job was using her login.

The noisy neighbor. Ten services share one user. One of them has a bug and starts deleting documents it should not touch. The logs show only the shared user name, so the team spends hours checking each service in turn. If each service had its own key, the log would have named the guilty one at once.

The leaked configuration. A configuration file with a shared password is copied into a public code repository by mistake. Changing the password would break all ten services, so the team hesitates for two days while they prepare every service for the change. During those two days, the leaked password is still valid. With separate keys, only the one exposed key would have needed to be cancelled, in seconds.

3Core Concepts You Need First

A dozen words explain nearly everything about API keys. Learn them here and the later chapters will read like common sense.

Security

Authentication

Proving who you are. For an API key request, the proof is the key itself.

Security

Authorization

Deciding what you are allowed to do after you are identified. Keys carry their limits into this step.

Security

Credential

Whatever you present to prove identity: a password, a token, a certificate, or an API key.

Security

Realm

A source of identities that Elasticsearch trusts, such as its own user store, a directory service, or a single sign-on provider.

Access

Privilege

One permitted kind of action, such as reading from an index, writing to it, or viewing cluster health.

Access

Role and role descriptor

A role is a named bundle of privileges. A role descriptor is the same idea written out inside a key, to describe that key’s limits.

Ownership

Owner

The user who created the key. The key can never do more than its owner is allowed to do.

Lifecycle

Expiration

An optional time after which a key stops working by itself.

Lifecycle

Invalidation

Cancelling a key on purpose so that it can no longer be used.

Extras

Metadata

Free-form notes stored with a key, such as which team owns it and why it exists.

Storage

Security index

Elasticsearch’s own protected internal index where key records are kept.

Format

Encoded value

The id and the secret joined together and encoded as text, ready to place in a request header.

Authentication versus authorization, in one story

At an airport, you show your passport at the check-in desk. That is authentication: the desk learns who you are. Then the agent looks at your ticket and decides whether you may board this flight, sit in this class, and enter the lounge. That is authorization. Two separate checks, done one after the other. An API key does both jobs in a special way. Presenting the key answers the first question. The limits written into the key answer the second.

Everyday Analogy

A concert wristband works like this. The guard at the gate looks at the wristband and knows you are a real ticket holder. That is the identity check. The color of the wristband then decides whether you may enter the backstage area, the seated area, or only the standing area. That is the permission check. An API key is a wristband whose color you get to choose when it is created.

The owner rule: a key cannot outgrow its maker

This is the most important safety rule to learn early. A key is always created by an authenticated user, its owner. The key may be given fewer permissions than the owner has, but never more. If a user can only read the sales indexes, any key that user creates can, at most, read the sales indexes. This prevents someone with modest rights from creating a super-powerful key and using it to climb higher.

Two things a key is not

  • A key is not a user. It does not have a password, it does not show up in the user list, and it cannot log in to Kibana as a person.
  • A key is not a session. It does not expire after a short idle time. It stays valid until it reaches its expiry time, if any, or until someone cancels it.
!
Common Trap

Because a key without an expiry lives indefinitely, forgotten keys are a classic source of long-term risk. Chapter 14 explains how to keep them under control.

Quick glossary

WordPlain meaning
Bearer credentialAnyone who holds it can use it, like cash. No extra proof of who they are is asked.
Least privilegeGiving only the permissions that are truly needed and nothing more.
HashingTurning a secret into a scrambled fingerprint that can be compared but not turned back into the original.
RotationReplacing an old credential with a new one on a regular schedule.
Blast radiusHow much damage is possible if one credential leaks.
System indexAn internal Elasticsearch index that holds its own management data and is protected from normal access.
TLSThe encryption that protects data traveling over the network, used by HTTPS.

4Architecture and Components

Where does the key check happen in a real cluster, and which parts work together to make it possible?

Every request that reaches Elasticsearch first meets the security layer. That layer looks at the request’s headers to find out how the caller is proving their identity. If the header says the caller is using an API key, the request is handed to the API key service. Otherwise it goes through the chain of realms, such as the native user store or a single sign-on provider. Once identity is settled, the request moves on to the authorization step and only then to the actual data work.

flowchart TB
    App["Application or agent holding an API key"] -->|HTTPS request with Authorization header| GW["Elasticsearch HTTP layer"]
    GW --> AUTH["Authentication service"]
    AUTH --> AK{"Header scheme is ApiKey?"}
    AK -- Yes --> AKS["API key service: check cache, then security index"]
    AK -- No --> RLM["Realm chain: native, directory, single sign-on, and others"]
    AKS --> VER["Verify secret, expiry, and invalidation"]
    RLM --> VER2["Verify password or token"]
    VER --> AUTHZ["Authorization: key role descriptors and owner snapshot"]
    VER2 --> AUTHZ2["Authorization: roles of the user"]
    AUTHZ --> ACT["Requested action runs on the data"]
    AUTHZ2 --> ACT
    
Figure 1: A request carrying an API key is recognized at the header, verified by the API key service, and then authorized.

Read the picture from top to bottom. The application sends its request over an encrypted connection, adding an authorization header that names the scheme and carries the encoded key. The authentication service reads the scheme. For an API key, it asks the API key service, which first looks in an in-memory cache and, if needed, in the security index, and then verifies that the secret matches, the key has not expired, and the key has not been cancelled. Only then does the request proceed to authorization, which combines the limits stored in the key with the permissions of its owner to decide what is allowed.

The main components

Front door

HTTP layer with TLS

Receives the request over an encrypted connection. Keys should only ever travel over encrypted links.

Identity

Authentication service

Reads the header, decides which mechanism applies, and produces an authenticated identity or a refusal.

Keys

API key service

Creates keys, verifies them, applies expiry and cancellation, and manages the in-memory cache of recent successful checks.

Storage

Security index

A protected internal index holding each key’s record: id, name, owner, hashed secret, role descriptors, expiry, and metadata.

Access

Authorization service

Turns roles or role descriptors into a decision for each action and each index.

Management

Key management endpoints

Operations to create, inspect, search, update, and cancel keys, also available through the Kibana interface.

Records

Audit logging

An optional log of security events, including which key was used. Availability depends on the subscription level.

Outside

Secret store

Where your own systems keep the secret safely, such as a secrets manager. Not part of Elasticsearch, but essential.

Walking one request through the machine

1

The program reads its key from a safe place

It fetches the encoded key from an environment secret or a secrets manager, never from source code.

2

It sends the request over HTTPS

The authorization header names the scheme, followed by the encoded key.

3

The node decodes the key

It splits the encoded value back into the id and the secret.

4

The cache is checked first

If this exact key was verified moments ago, the stored result saves the costly comparison. Otherwise the record is fetched from the security index.

5

The key is verified

The secret is compared against the stored fingerprint. The expiry time is checked. The record is checked for cancellation.

6

Permissions are worked out

The key’s own limits are combined with the owner’s permissions to find what this key may do.

7

The action runs or is refused

If the request is within the allowed permissions, it proceeds. If not, the caller receives an “unauthorized” answer.

i
Why This Matters for Troubleshooting

Failures in this journey have two very different meanings. If the caller is refused at the authentication step, the key is unknown, expired, cancelled, or malformed. If the caller is refused at the authorization step, the key is fine but lacks permission for that specific action. Chapter 15 shows how to tell them apart quickly.

5Internal Working: What Happens When a Key Is Made and Used

Now we open the box. Two short stories explain everything: the birth of a key and the daily life of using it.

Story one: creating a key

1

An authenticated user asks for a key

The request is made through the key creation operation or the Kibana screen. The user must hold the right to manage API keys, either all keys or only their own.

2

Elasticsearch generates an id and a secret

Both are random. The secret is long enough that guessing it is not realistic.

3

The secret is turned into a fingerprint

Elasticsearch runs the secret through a deliberately slow, salted hashing method and stores only the result. The original secret is not kept.

4

A record is written to the security index

The record holds the id, the name, the owner, the fingerprint, the role descriptors, the expiry, the metadata, and a snapshot of the owner’s permissions.

5

The response returns the pieces, once

The caller receives the id, the name, the secret, and the ready-to-use encoded value. This is the only time the secret can be seen.

Everyday Analogy

A locksmith cuts a key and gives it to you. The hotel keeps only a record of the lock’s pattern, not a copy of your key in a drawer. If you lose it, the hotel cannot hand it back; it can only cut a new one and cancel the lost one.

Story two: using a key

Each time a program sends a request, the process described in Chapter 4 runs from start to finish. The interesting internal details are these.

Why the secret is hashed slowly

If a thief managed to read the security index, a plain-text secret would be an instant disaster. That is why only a fingerprint is stored. The fingerprint is made with a method that is intentionally slow, so that trying billions of guesses would take unreasonably long. The price is that every verification costs real processor time. For that reason Elasticsearch remembers successful verifications for a while, in memory.

The cache

Suppose one application sends a thousand requests per second with the same key. Running a slow hash comparison a thousand times per second would waste a great deal of effort. So each node keeps a cache of recently verified keys. On the first request the node does the full check and stores the outcome. Later requests find the key in the cache and skip the costly step. The cache has a time-to-live and a size limit, both configurable. When a key is cancelled, the cluster arranges for the cached results to be discarded quickly, so that a cancelled key does not keep working for long.

How permissions are computed

Authorization does not simply trust the key’s own description. It combines two sets. The first is the set of role descriptors stored in the key, which say what the key should be allowed to do. The second is a snapshot of the owner’s permissions, which say what the owner was allowed to do when the key was created or last updated. The key’s effective permissions are the overlap of the two. Anything outside either set is denied.

flowchart LR
    O["Owner's permissions: snapshot at creation or last update"] --> X(("Overlap"))
    K["Key's role descriptors: what you asked for"] --> X
    X --> E["Effective permissions of the key"]
    
Figure 2: The key’s effective permissions are the overlap of what was requested and what the owner could do.
Everyday Analogy

A manager writes a permission slip for an intern: “may enter rooms A, B, and C.” But the manager herself can only enter A, B, and D. The intern can then enter only A and B, because those are the rooms that appear on both lists. The slip cannot grant more than the manager holds, and the manager chose to limit it further.

If a key is created without any role descriptors of its own, it receives the owner’s permissions as they were at that time. In current versions, the way owner changes are reflected in existing keys depends on the version and on whether the key is later updated, so confirm the behavior in the documentation of the version you run, and test it before you rely on it.

Where the data lives

Keys are stored in the protected security index. This has two consequences. First, keys are as durable as that index, which is replicated like other indexes and can be included in snapshots of the cluster’s security data. Second, key operations depend on that index being available, which Chapter 13 discusses.

What expiry and cancellation really do

Expiry is checked when a key is used, comparing the stored time to the current time. Cancellation marks the record so that it can no longer authenticate. Neither removes the record immediately. Expired and cancelled keys are kept for a retention period and then removed by a regular cleanup job, which keeps recent history available for investigation while stopping the security index from growing forever. The exact retention and cleanup timing are configurable.

Version notes and upgrade checks

The way keys are stored, updated, and reported has grown over several releases. Some operations, such as updating a key in place, searching through keys, and cross-cluster keys, exist only in newer versions. The default values for cache and cleanup settings can also differ. Before an upgrade, read the release notes for security changes, confirm that existing keys still authenticate on a test cluster, and check that any automation that reads or creates keys still understands the response format. After the upgrade, run a small test with a real key from each critical application, before declaring the work done.

i
A Simple Habit

Keep one low-risk test key for each environment, with a harmless permission. Use it as a canary after upgrades and configuration changes. If the canary fails, you learn about a problem before a real application does.

6Data Flow and Lifecycle of a Key

A key is born, used, changed, replaced, and eventually removed. Knowing this life story helps you plan for each stage instead of being surprised by it.

flowchart LR
    C["Create: id and secret issued, secret shown once"] --> U["In use: applications authenticate"]
    U --> P{"What changes?"}
    P -- "Permissions or notes" --> UP["Update the key"]
    UP --> U
    P -- "Time to rotate" --> N["Create a new key and deploy it"]
    N --> I["Invalidate the old key"]
    P -- "Expiry time reached" --> E["Key expires"]
    E --> R["Kept for a retention period"]
    I --> R
    R --> D["Removed by automatic cleanup"]
    
Figure 3: The life of an API key, from creation to automatic removal.

The stages in order

1

Plan

Decide what the key is for, which indexes it touches, which actions it needs, and how long it should live. Write this down in the key’s name and metadata.

2

Create

Generate the key with narrow role descriptors and, where possible, an expiry. Capture the encoded value at once, because the secret will not be shown again.

3

Deliver

Place the key in a secrets manager or a protected setting of the target system. Avoid email, chat messages, and shared documents.

4

Use

The program includes the key in each request. Watch for authentication failures that signal expiry or cancellation.

5

Update

When a program needs slightly different access, newer versions can change the key’s role descriptors or metadata in place, so the secret does not have to change.

6

Rotate

On a regular schedule, or after any suspicion of leakage, create a replacement, roll it out, confirm that traffic uses it, and only then cancel the old one.

7

Retire

Cancel keys that are no longer needed. Expired keys stop working by themselves. After the retention period, the records disappear.

Everyday Analogy

A building manager tracks key cards through their whole life: issued at hiring, limited to certain floors, replaced when worn out, cancelled when the person leaves. A card with no record of who holds it, and no end date, is a security hole waiting to be found.

The rotation dance

The safest way to replace a key is to make the new one before removing the old one. If you cancel first, the application fails until the new secret arrives. If you create first, both keys work for a short overlap, the application switches at its own pace, and you cancel the old key once you see the new one in use. This is the same idea as a relay race: the second runner starts moving before the first hands over the baton.

What happens when the owner changes

A key is linked to the user who created it. That link has consequences. If the owner’s account is removed, or the owner’s roles change, existing keys may behave differently from what you expect, depending on your version. For this reason, many organizations create long-lived keys under a dedicated service user, not under a person’s account, so that keys do not quietly break when an employee changes jobs. Test this behavior in your version before you rely on it.

The security index and upgrades

Because keys live in the cluster’s internal security data, they travel with it during ordinary maintenance, such as rolling restarts and upgrades. They are lost if you rebuild a cluster from scratch without restoring that data. Plan for this in disaster recovery: either restore the security data from a snapshot, or be ready to re-issue keys to every application.

!
Do Not Rely on Memory

If the only copy of a key’s secret is on a laptop, then when the laptop is lost, so is the key. Store the secret in a managed secrets system from the very first day, and record which system holds it.

7Permissions: Role Descriptors and Effective Access

The real strength of an API key is not that it identifies a program, but that it limits that program. Here is how the limits are written and how they combine.

When you create a key, you can include one or more role descriptors. A role descriptor is a small description of allowed access. It has the same ingredients as a role in Elasticsearch, but it lives inside the key. It can name three kinds of things.

Ingredient 1

Cluster privileges

Actions that affect the whole cluster, such as viewing health or monitoring. Most application keys need few or none.

Ingredient 2

Index privileges

Actions on specific indexes, named by exact name or by pattern: reading, writing, creating, viewing metadata, and so on.

Ingredient 3

Extra restrictions

On some subscription levels, limits on which fields or which documents a key may see. Availability depends on your license.

Effective permissions: the overlap rule

As Chapter 5 showed, what the key can actually do is the overlap between its role descriptors and the snapshot of its owner’s permissions. This produces a comforting property: whatever mistakes you make when writing role descriptors, the key can never exceed the owner. It also produces a common surprise: if your key seems too weak, the reason may be that the owner never had the permission in the first place.

Everyday Analogy

Think of two sieves stacked on top of each other. Only the grains small enough to fall through both sieves reach the bowl. The upper sieve is the owner’s permissions, the lower sieve is the key’s own description. What reaches the bowl is the key’s effective access.

Typical permission sets, in words

Use caseSuggested accessKeep out
Log shipper writing to log indexesCreate and write on the log index pattern only, plus a small monitoring right if the shipper needs itReading other data, changing settings, deleting indexes
Website search boxRead on the product index or alias onlyWrite, delete, any cluster privilege
Nightly reporting jobRead on the reporting indexesWrite, cluster privileges
Data import jobWrite and create on the destination index, perhaps index management for that indexReading unrelated indexes, security management
Monitoring scriptCluster monitoring privilege onlyAll index access
Administrator automationThe exact management actions required, for a short timeBroad superuser rights, long lifetimes

Use aliases and patterns thoughtfully

Index privileges can name a pattern such as “logs-” followed by a star. That is convenient, since new daily indexes automatically fall under the key’s permissions. But a broad star can also cover more than you intended. Review each pattern: would a new index that matches it be something this program should touch? Where possible, grant access to an alias that points at the right indexes, so that your access description stays short and clear.

Start from nothing and add

The most reliable way to write role descriptors is to start with no permissions and add only what the program demonstrably needs. The opposite habit, which is to start with a powerful set and remove things, tends to leave surplus rights behind. If a program breaks because a permission is missing, the “unauthorized” answer names the action that was refused, and you add just that one privilege.

Keys with no role descriptors

If you do not include role descriptors, the key simply carries the owner’s permissions. This is convenient and dangerous. If the owner is an administrator, every such key becomes an administrator key. Even if it is fast to create, this habit undoes the main benefit of the feature. Treat “no role descriptors” as an exception, not a default.

i
A Test That Pays Off

After creating a key, use it to try both something it should be able to do and something it should not. Confirm that the first works and the second is refused. A permission that has never been tested to fail is only a hope.

Who may create keys

Creating keys is itself a privilege. One cluster privilege lets a user manage every key in the cluster, and a narrower one lets a user manage only their own keys. Hand out the narrow one whenever you can. A person or a tool that can create keys with any permission and any owner can quietly build a long-lived back door, so this privilege deserves the same care as a master password.

Limiting fields and documents (license-dependent)

Beyond index names and actions, some subscription levels let a role descriptor limit which fields a key may see and which documents it may read. This is called field-level and document-level security. It is very useful when you must share part of an index. For example, a vendor may read a product index but see only the public fields, and only the documents that belong to that vendor. Because these features depend on the license, check what your subscription allows before designing around them.

Everyday Analogy

Imagine a filing cabinet where a visitor may open only the drawers for their own company, and may read only the front page of each file. The cabinet is shared, but each visitor sees a different slice of it. Field and document limits are the drawer locks and the black-out marker.

Do not treat these limits as a substitute for good data design. If a whole category of data must never be visible to a certain program, keeping it in a separate index that the key cannot touch is simpler and easier to prove than a filter on a shared index.

8Creating and Managing Keys

A short tour of the operations you will use, and the habits that keep a growing collection of keys understandable.

OperationWhat it doesWho may do it
CreateMakes a new key and returns the id, the secret, and the encoded value onceA user with permission to manage keys
Get or queryLists keys, and in newer versions supports searching by name, owner, expiry, and metadataManagers of all keys, or an owner for their own keys
UpdateChanges role descriptors, metadata, or expiry of an existing key, in newer versionsOwner, or a manager of all keys
InvalidateCancels one or more keys so they can no longer authenticateOwner, or a manager of all keys
Clear cacheDiscards cached verification results on nodes, useful after urgent changesUsers with the right security privileges
Grant on behalf of a userLets a trusted service create a key for another user using that user’s credentialsA tightly limited privilege for special services

These operations are available through the Elasticsearch security interface and through the Kibana management screens, where you can see a list of keys, their owners, and their status, and create or cancel them with a few clicks. For repeatable work, such as onboarding a new application, scripting the creation is better than clicking, because the script documents what was done.

Give every key a good name

The name is not required to be unique, which means it is easy to end up with twenty keys called “test.” A good naming convention includes the application, the purpose, and sometimes the environment. For instance, a key named “checkout-service-prod-orders-writer” tells you a lot at a glance. When you review keys six months later, names like that save real time.

Use metadata as a label

Metadata is a free-form set of notes stored with the key. Use it to record things a future reader will need: the owning team, a contact address, a ticket reference, the date the key was reviewed, and the reason it exists. Never place secrets in metadata, because metadata is visible to anyone who can read the key’s details.

Everyday Analogy

A hotel’s key log lists every card with a room number, a guest name, and an end date. A card with no label in the log is a mystery, and mysteries are what security audits are made to find.

Set an expiry when you can

An expiry turns forgotten credentials into self-cleaning ones. For temporary work, such as a one-off migration, an expiry of days is natural. For long-running services, an expiry of a few months combined with a rotation process is better than a key that lives forever, because the rotation process is regularly tested and the key never gets old enough to be forgotten. Remember that an expiry can cause an outage when it arrives, so calendar the rotation before it happens and alert on keys nearing their end date.

Keys created by tools

Many Elastic tools, such as the agents and shippers, can create or use keys for you as part of their setup. These keys are real keys and appear in the same list. Their names often reveal the tool that made them. Avoid cancelling a key you do not recognize before you find out who owns it, since it may be feeding a live pipeline.

Cleaning up

Once a quarter, review the list of keys. Ask of each one: does the owner still exist, is the application still running, is the access still the smallest that works, and is the expiry sensible? Cancel what fails the review. This ten-minute habit prevents the slow buildup of unused, powerful credentials that later becomes a serious finding in a security audit.

!
Never Cancel Blindly

Cancelling a key that a live system depends on is an instant outage. Before cancelling an unfamiliar key, check when it was last used, in audit logs if you have them, and ask the team named in its metadata.

Automating key creation safely

As the number of applications grows, creating keys by hand does not scale, and people start copying old keys “just this once.” A better answer is a small provisioning process that creates keys on request. A good version of it has these properties.

  • It runs under a narrow account. The account holds only the right to manage its own keys, not the right to manage all keys.
  • It uses templates. Each application type has an approved permission template, such as “log writer” or “read-only search,” so that people request a type, not free-form access.
  • It records who asked. The requester, the team, and the reason go into the metadata.
  • It delivers the secret directly to a secrets manager. The secret never appears in tickets, chat messages, or build logs.
  • It sets the expiry itself. The requester cannot choose “never.”

Continuous integration systems deserve special mention. Build logs are widely readable and often kept for a long time. If a script prints the response of the creation operation, the secret ends up in the logs. Configure such scripts to send the secret straight to the secrets system and to mask it in output.

9Using Keys in Clients and Tools

Creating a key is half the job. Presenting it correctly, from every kind of client, is the other half.

The header format

Requests carry an authorization header. For an API key, the header’s value is the word ApiKey, a space, and then the encoded value that Elasticsearch returned when the key was created. That encoded value is simply the id and the secret, joined by a colon, and turned into text using a standard encoding. If you only saved the id and the secret separately, you can rebuild the encoded value yourself, but using the ready-made value avoids mistakes.

!
Common Trap

Some people paste the id alone, or the secret alone, or use the wrong word before the value. Any of these produces an “unable to authenticate” answer. Another mistake is to send the key over plain, unencrypted HTTP, which exposes the secret to anyone who can watch the network.

Official client libraries

The official Elasticsearch libraries for languages such as Java, Python, JavaScript, Go, and others let you configure a key once, when you create the client. After that, every request carries the header automatically. Read the key from an environment variable or a secrets system when the program starts, and never hard-code it in source files.

Shippers, agents, and pipelines

Tools that send data to Elasticsearch, such as Beats, Elastic Agent, and Logstash, can be configured to authenticate with a key, usually in their output settings. Where a tool asks for the key in a combined form, it commonly expects the id and the secret joined by a colon. Read the tool’s documentation, because the accepted format differs. Use one key per shipper or per group of shippers with the same job, not one key for the whole fleet, so that a single compromised machine does not force you to replace every credential.

Everyday Analogy

Giving each delivery driver their own building card means that when one driver’s card is stolen, you cancel one card. Giving all drivers the same card means the theft forces you to reissue cards to everyone.

Proxies and load balancers

Some proxies and gateways strip or rewrite authorization headers, especially those that apply their own authentication. If a key works when you contact a node directly but not through the gateway, look at how the gateway handles that header. Also make sure that every hop from your program to the cluster uses encryption.

Keys in browsers and mobile apps

A key placed in a web page or a mobile app is visible to anyone who looks. It is therefore not a secret at all. If a browser must talk to Elasticsearch directly, then that key should be as weak as possible: read access to a single alias, no write or management rights, and a short expiry. A safer design puts a small backend service in between. The service holds the real key and exposes only the specific searches the browser is allowed to run, so that the key never leaves your servers.

Checking who you are

Elasticsearch has a small operation that answers the question “who am I?” for whatever credential you send. When called with an API key, it reports that the authentication type is an API key and shows the key’s id and name. It is the fastest way to confirm that the right key is in use and that it is recognized, before you start debugging permissions.

1

Store the encoded value in a secrets system

Not in a code repository, a chat message, or a wiki.

2

Load it at startup

Read it into the client’s configuration from an environment secret or a mounted secret.

3

Confirm identity

Ask the cluster who it thinks you are, and check the key’s name.

4

Run a harmless allowed action and a forbidden one

Confirm the first succeeds and the second is refused.

5

Log failures without logging the key

Record the key’s id or name in logs, never the secret.

Keys in containers and orchestration platforms

Modern applications often run in containers, and orchestration platforms offer built-in ways to hand secrets to them. The choices differ in safety.

Better

Mounted secret files

The platform places the secret in a file that only the application can read, and can update it in place when the key is rotated.

Better

Secrets manager integration

The application, or a helper next to it, fetches the key at start and refreshes it on a schedule, so rotation needs no redeployment.

Careful

Environment variables

Convenient and common, but they can show up in process listings, crash reports, and debug pages. Use with care, and never print them.

Avoid

Baked into the image

A key placed inside a container image travels wherever the image goes, and cannot be changed without rebuilding it.

Whichever way you choose, make sure the application can pick up a new key without restarting, or that a restart is cheap and safe. Rotation that needs a coordinated restart of many services will be postponed until the day it becomes an emergency.

10API Keys Versus Other Ways to Authenticate

API keys are one of several credentials. Choosing the right one for each situation is part of good design.

flowchart TD
    A["Who or what needs to authenticate?"] --> B{"A person using a browser or Kibana?"}
    B -- Yes --> C["Single sign-on or a user account"]
    B -- No --> D{"An Elastic component such as Kibana or Fleet Server?"}
    D -- Yes --> E["Service account token"]
    D -- No --> F{"An application, script, or pipeline?"}
    F -- Yes --> G["API key with least-privilege role descriptors"]
    F -- No --> H["Review the design and choose a matching realm"]
    
Figure 4: A simple decision path for choosing a credential type.
CredentialBest forStrengthsWeak points
Username and passwordPeople, and legacy toolsUniversal, easy to understandShared, hard to rotate, tied to a person
API keyApplications, scripts, shippers, pipelinesPer-purpose, scoped, expiring, individually revocableBearer secret, needs careful storage and cleanup
Service account tokenElastic’s own components that connect to ElasticsearchPurpose-built for services, fixed permissionsLimited to the built-in service accounts
Short-lived access tokenInteractive sessions that need refreshingExpires quicklyNeeds refresh logic in the client
Client certificateStrong machine identity in controlled networksVery strong, no shared secret on the wireHeavy to issue and manage
Single sign-on (SAML or OpenID)People using KibanaCentral control, multi-factor supportNot designed for headless programs
Everyday Analogy

A building has a front desk badge for employees, a visitor sticker for guests, a special pass for the maintenance company, and an electronic code for a delivery robot. Each fits a different kind of person or machine. Trying to give the robot an employee badge tied to a real person’s name would cause trouble the day that person leaves.

Choosing between an API key and a user account for a program

If the program is a long-lived service with a well-known job, both work, but keys let you split its access into small pieces and cancel them separately. If the program is a temporary task, a key with a short expiry is nearly always better. If a person is running a script from their own laptop for their own purposes, their own key, created under their own account and with a short expiry, avoids putting their password into a script.

API key versus service account token

Service account tokens exist for components that Elastic supplies, and they are tied to a fixed set of permissions defined for that component. Your own applications are not service accounts in this sense. For your own software, the flexible choice is the API key, which you shape to your needs.

Keys with third-party systems

When a third-party tool must call your cluster, give it a dedicated key with the narrowest access that lets it work, and a fixed expiry, so that a vendor problem never turns into a breach of your data. Record the vendor in the key’s metadata so that any reviewer knows why the key exists.

i
The Guiding Question

Ask, “If this credential leaked today, how bad would it be, and how fast could I cancel it?” The best credential for a program is the one with the smallest answer to the first half and the fastest answer to the second.

A path from a shared user to individual keys

Many teams start with one shared user and want to move to keys without breaking anything. A calm, step-by-step plan works better than a big-bang change.

1

List the programs that use the shared user

Use logs, network records, and configuration searches to find every one. There are always more than people remember.

2

Work out what each really needs

For each program, list the indexes it touches and the actions it performs.

3

Create a key per program

Write narrow role descriptors, set expiries, and store the secrets safely.

4

Switch programs one at a time

Change each to use its key, and watch for authorization refusals that reveal a missing permission.

5

Retire the shared user

When no program uses it any more, change its password, then disable it. Keep it disabled for a while before deleting.

11Performance and Scalability

Checking a key is a security step that runs on every request. How costly is it, and what keeps it from becoming a bottleneck?

Verifying an API key involves three pieces of work: finding the key’s record, checking the secret against its stored fingerprint, and working out the permissions. Of these, the secret check is the heaviest, because the fingerprint method is slow on purpose. If the system did this from scratch on every request, busy applications would burn a lot of processor time on security. That is why caching is central to how keys perform.

A numbers walkthrough

Let us use invented numbers to feel the difference. Suppose one full verification of a secret costs 20 milliseconds of processor time. An application sends 1,000 requests per second with the same key. If every request needed a full verification, that would be 20 seconds of processor time for each second on the clock, which is about 20 processor cores doing nothing but security.

Now imagine that each node remembers a successful verification for a while. The first request pays the 20 milliseconds. The next thousands find the answer in memory at almost no cost. The security work per second drops from about 20 cores to a tiny fraction of one core. The figures in real systems will differ, but the shape is what matters: without the cache, keys would be too expensive to use at scale, and with it, the cost is negligible.

Everyday Analogy

A night guard who inspects your badge closely with a magnifying glass the first time, and then simply nods when he sees you again during the same shift, is doing exactly what the cache does. A guard who used the magnifying glass at every pass would create a queue that reaches out the door.

What influences the cost

Cache

Time to live and size

Longer retention and a bigger cache mean fewer full verifications. Both are configurable, with defaults suited to most clusters. Check the documentation of your version for the exact values.

Hashing

Algorithm choice

Elasticsearch offers a choice of hashing methods for stored fingerprints. Stronger settings cost more per verification, which the cache offsets.

Variety

Number of distinct keys

Many different keys in use at the same time means more cache entries and more permission sets to build. It is fine at ordinary scale but worth knowing about at very large scale.

Storage

Security index reads

A cache miss needs a read from the security index. This is quick but adds up if the cache keeps missing.

Churn

Creating and cancelling often

Systems that mint a key for every tiny task create many records and clear caches often. Prefer fewer, longer-lived keys per role of program.

Connections

Client behavior

Clients that reuse connections and send larger batches make fewer requests, so there are fewer checks in total.

Scaling with the cluster

Each node keeps its own cache, so the cost of verification scales with the number of nodes handling requests. When a cluster grows, more nodes share the requests, and each node still remembers the keys it has seen. The first request for a key on a fresh node pays the full price, so a burst of new nodes joining, or a restart of many nodes at once, causes a short period with more processor use, as each node rebuilds its cache. It is a mild effect, but it is a good reason to restart nodes in a rolling way.

Cancellation and the cache

There is a balance between speed and revocation. A long cache lifetime means better performance but also that a cancelled key might, in theory, continue to work on a node until its cache entry is discarded. Elasticsearch handles this by clearing the relevant cache entries across the cluster when a key is cancelled, so that the delay is short in practice. For urgent cases, there is also an operation to clear the key cache on demand.

i
Measure, Do Not Guess

The best test of authentication cost is to look at the processor use of your nodes during a load test with realistic keys. If security shows up as a significant share, look at how many distinct keys are used and how often they change, before you touch any cache setting.

12Advantages, Disadvantages, and Trade-offs

No security mechanism is free. Here is the honest balance sheet.

Advantages

  • Each program has its own identity, so activity can be traced.
  • Permissions can be narrowed to exactly what is needed.
  • A leaked key is cancelled alone without disturbing others.
  • Optional expiry makes forgotten keys clean themselves up.
  • No person’s password is placed in scripts or configuration.
  • Created quickly, on demand, from a program or a screen.
  • Secrets are stored only as fingerprints inside the cluster.

Disadvantages

  • A key is a bearer secret: whoever holds it can use it.
  • Without expiry and review, keys pile up unnoticed.
  • The secret cannot be recovered, only replaced.
  • Keys are linked to their owner, so owner changes can cause surprises.
  • Keys live in one cluster and do not automatically work in another.
  • Wide use requires discipline: naming, metadata, rotation, audits.
  • Audit logging depends on the subscription level.
Trade-offLeaning toward convenienceLeaning toward safety
ExpiryNo expiry: never breaks, easy to forgetShort expiry: cleans itself up, needs a rotation process
PermissionsBroad rights: works for everything, big blast radiusNarrow rights: needs more effort, contained damage
Number of keysOne key for many programs: simple, one leak affects allOne key per program: more to manage, better isolation
Key ownerA person’s account: quick to start, breaks when they leaveA dedicated service account: extra setup, stable over time
Cache durationLong: faster requests, slightly slower effect of some changesShort: quicker effect, more verification work
Where the secret is storedEnvironment file: simple, easier to leakSecrets manager: extra service, proper controls
Everyday Analogy

A house with one key under the doormat is easy for everyone and terrible for security. A house with a keypad, individual codes, and a log of who came in is a little more work to run and very much safer. The right choice depends on what is inside the house.

How strict should you be?

SituationRecommended stance
Production service with valuable or personal dataStrict: narrow rights, one key per service, expiry with rotation, secrets manager, audit logs
Internal reporting jobModerate: read-only on named indexes, expiry of months
Temporary migrationShort-lived: expiry of days, cancelled when finished
Development sandbox with fake dataRelaxed, but still not shared with production
Anything reachable from browsers or mobile appsVery strict: read-only on one alias, short expiry, or use a backend in between

13High Availability and Reliability

Security that makes your system fragile is a bad trade. Here is how to keep key-based access dependable.

Keys depend on the security index

Every key record lives in the internal security index. That index is replicated like other data, so the loss of a single node does not lose keys. But if the index becomes unavailable, for example when the cluster is in a serious failure state, authentication that needs to read key records can fail. Results already stored in the cache may still let recently used keys keep working for a while, but you should not count on that. The practical lesson is that the health of the security index is part of the health of your applications.

Everyday Analogy

If the building’s key card database goes offline, cards that were recently used may still open the doors for a while because the reader remembers them, but new cards will not work and cancelled cards may not be refused. Keeping that database healthy is as important as keeping the doors themselves working.

Backups and disaster recovery

Snapshots of a cluster can include its security data, and this is what allows keys to survive a rebuild. When you plan disaster recovery, decide explicitly whether security data is part of the snapshots, test a restore in a safe environment, and confirm that keys still authenticate afterward. If you decide not to restore security data, write down the process for re-issuing every key to every application, and estimate how long it would take.

Multiple clusters

Keys exist inside one cluster. A key made in cluster A means nothing to cluster B. If you run several clusters, such as development, staging, and production, you will have separate keys in each, and you must never reuse a secret across them. For work that spans clusters, such as searching or replicating between them, newer versions provide a special type of key designed for cross-cluster access, which is scoped to that purpose. Check the documentation for the version you use.

Avoiding expiry outages

A key that expires on a Sunday night at midnight will stop the application on a Sunday night at midnight. That is the intended behavior, and also a common cause of surprise incidents. Prevent it with three habits.

1

Track expiry dates

Keep a list, or query the cluster for keys nearing their end date, and send reminders to their owners well in advance.

2

Rotate early

Replace keys at half of their lifetime, not at the last minute, so that you have time to fix problems.

3

Let programs reload keys

Design applications to pick up a new key without a restart, for example by re-reading it from a secrets system when authentication fails.

4

Alert on failures

A sudden rise in authentication failures from one application is the earliest sign of an expired or cancelled key.

Owner changes and continuity

People move teams and leave companies. If a key is owned by a person’s account, then the change of that person can quietly break or endanger the key. Prefer dedicated service users to own long-lived keys, keep the owner’s role stable, and record a contact team in the key’s metadata. When someone leaves, review the keys they created, and re-issue important ones under a stable owner.

Graceful behavior in the client

A well-built client treats an “unauthorized” answer as a distinct event. It logs the key’s name, never the secret, raises an alert, and tries to load a fresh key. It does not hammer the cluster with retries. Meanwhile it should keep any data it could not send in a safe local buffer, so that the outage costs delay, not loss.

!
Test the Failure

Once in a while, cancel a test key on purpose in a non-production environment and watch what the application does. It is much better to discover in a drill that the program crashes on an unauthorized answer than to discover it during a real incident.

A runbook for rebuilding a cluster

Suppose a cluster must be rebuilt from scratch. Keys are one of the things that are easiest to forget in the plan. A good runbook answers a few questions in advance.

  • Are security data and key records included in the snapshots, and has a restore been tested recently?
  • If not, where is the list of every application and the access it needs, so that new keys can be made quickly?
  • Who has the right to create keys in the rebuilt cluster, and how is the first administrator credential protected?
  • How will new secrets reach each application, and in what order should applications be reconnected?
  • How will you confirm that no old key from the previous cluster is still in use anywhere, since old secrets should not be reused?

Practicing this once in a test environment is far cheaper than discovering the gaps during a real outage.

14Security Considerations

An API key is a security tool, and it is also a security risk. Knowing where it can go wrong is what keeps it safe.

The key is a bearer secret

Anyone who holds the key can act as it, from anywhere, with nothing more to prove. There is no second factor and no check of the caller’s location built in. That makes the protection of the secret the most important task. Treat it with the same care as a password to a production database.

Where secrets leak

Source code

Repositories

Keys committed to code, even in private repositories, are copied into many places and remain in history. Use scanning tools to catch them.

Logs

Log files and error messages

Printing request headers or full configuration into logs spreads the secret to everyone who can read the logs.

Chat

Messages and tickets

Pasting a key into a chat or a ticket to “quickly help” leaves a permanent copy in a system with wide access.

Screens

Screenshots and recordings

The creation screen shows the secret once. A screenshot of it, shared for documentation, is a leak.

Front end

Browsers and mobile apps

Anything shipped to a user’s device can be read by the user, so it cannot be secret.

Network

Unencrypted connections

Sending a key over plain HTTP exposes it to anyone who can observe the network.

How the cluster protects the secret

Elasticsearch stores only a salted, deliberately slow fingerprint of each secret, so that reading the security index does not reveal usable keys. The secret is shown once and cannot be retrieved. Requests should travel over encrypted connections, and communication between the nodes themselves should also be encrypted. These are the foundations, and they only help if the security features are turned on and configured.

Least privilege and blast radius

The single most effective control is to make each key weak. A key that can only write to one index can leak without turning into a data breach. When you review key permissions, imagine an attacker holding the key and ask what they could do with it. If the answer is troubling, narrow the key.

Everyday Analogy

If a thief steals a key that opens only a bicycle shed, the loss is small. If the same thief steals the key to the whole warehouse, the loss is huge. You cannot always stop theft, but you can decide which keys are worth stealing.

Who can create keys

Anyone who can create keys with broad access, under an account with wide permissions, can create a long-lived credential that outlives their own employment. Limit key management to the people and automation that need it, prefer the narrower “own keys only” privilege, and review the list of users who can manage all keys regularly. Automation that creates keys should itself be tightly controlled and logged.

Auditing

Audit logging records security events, including which key was used to make a request, subject to the features of your subscription level. With audit logs you can answer questions such as “which key deleted this index?” and “is this old key still being used?” Without them, you rely on application logs and the key’s metadata. If your data is sensitive, plan for audit logging from the start, and keep the logs where the people you audit cannot change them.

When a key leaks: an incident playbook

1

Cancel immediately

Invalidate the key. Speed matters more than perfection. If urgency demands, also clear the key cache so that all nodes refuse it at once.

2

Issue a replacement

Create a new key with narrow rights and deliver it through the secrets system, so the application recovers quickly.

3

Review what the key did

Look at audit logs and application logs for use of the key from unexpected places or at unexpected times.

4

Find the cause

Work out how it leaked, whether through code, logs, chat, or a device, and close that path.

5

Look for siblings

If one key leaked through a habit, other keys probably did too. Rotate related keys and fix the habit.

!
Do Not Skip the Basics

Turn on authentication and encryption, even on clusters that seem internal. Many data exposures come from clusters that were “only internal” and had no protection.

Compliance and data protection

Many organizations must show auditors that access to sensitive data is controlled, limited, and reviewed. API keys can help you tell that story, because each key has an owner, a stated purpose, a narrow set of rights, and an end date. Auditors typically ask a handful of questions: who can create credentials, how are they stored, how often are they rotated, how quickly can access be withdrawn, and where is the evidence? Good answers are a written key policy, a list of keys with owners, records of rotations, and audit logs of key usage.

If the data in the cluster is personal or regulated, add two more habits. First, keep keys that can read that data to a minimum, and review them more often than the rest. Second, avoid giving any key access to more personal data than its task requires, because the amount of data reachable through a key is the measure of the harm if it leaks.

15Monitoring, Logging, and Metrics

You cannot manage what you cannot see. These are the signals to watch, and the questions that solve most problems.

What you can ask the cluster

  • Who am I? The authentication check shows whether the current credential is an API key, and gives its id and name.
  • What keys exist? The key listing shows names, owners, creation and expiry times, and whether each key is still active. It can be filtered to show only active keys.
  • Which keys are about to expire? In newer versions the key search operation can filter by expiry time, which powers a reminder job.
  • What are a key’s limits? The detailed view of a key can show the role descriptors and, optionally, the owner’s permission snapshot that limits it.
Metric or signalWhat it tells youWarning sign
Authentication failures per applicationExpired, cancelled, or wrong keysA sudden jump from one source
Authorization refusals per keyA key attempting things beyond its rightsNew refusals after a deployment, or many from an unexpected source
Number of active keysGrowth and sprawlSteady rise without matching applications
Keys with no expiryLong-lived exposureAny key of this type in a sensitive environment
Keys expiring soonUpcoming outagesExpiry within days without a rotation plan
Keys not used recentlyCandidates for cancellationPowerful keys idle for months
Key creation eventsWho is making new credentialsCreation at odd hours or by unexpected users
Security index healthAvailability of key storageAny unassigned shard on that index

Troubleshooting: 401 versus 403

The two most common problems have different answers, and telling them apart saves hours.

401

Unable to authenticate

The cluster does not accept the credential at all. Suspects: wrong header word, wrong or partial value, expired key, cancelled key, encoding mistake, a proxy stripping the header, or a different cluster than the one that issued the key.

403

Action is unauthorized

The key is fine, but the action is not allowed. Suspects: role descriptors too narrow, owner lacking the permission, wrong index name or pattern, or a needed cluster privilege missing. The message names the refused action.

1

Ask “who am I?” with the same credential

If this fails, the problem is authentication. If it works, the key is recognized and the problem is permissions.

2

Look up the key

Check that it is active and not expired, and that the owner is who you expect.

3

Compare the refused action with the role descriptors

Find the specific privilege that is missing. Add exactly that one, using the update operation or a new key.

4

Check the owner’s permissions

If the key’s description seems right but access is still denied, the owner may lack the permission.

5

Check the path

Confirm that proxies, gateways, and encryption settings are not altering the request.

Logging that helps

Log the key’s name or id in your application’s messages, never the secret. When something goes wrong, you can then match a failure to a specific key. In the cluster, audit logs, where available, record authentication successes and failures with the key’s details. Keep them long enough to investigate incidents, and protect them from tampering.

i
Alerts Worth Having

Alert on a sudden rise in authentication failures, on keys expiring within a set number of days, on the creation of keys outside your normal process, on keys with no expiry in production, and on the security index becoming unhealthy.

A monthly review checklist

1

List all active keys

Export the list with names, owners, creation dates, and expiry dates.

2

Flag the strange ones

Look for keys without an expiry, without metadata, with unfamiliar names, or created by unexpected owners.

3

Check the powerful ones first

Any key with write, delete, or management rights deserves a second look at its permissions and its recent use.

4

Confirm each owner team still exists

Ask the named contact whether the key is still needed and whether it should be narrower.

5

Cancel and record

Cancel what is not needed, note the changes in your records, and schedule rotation for keys nearing half of their lifetime.

16Design Patterns and Anti-patterns

Good habits make keys a strength. Bad habits turn them into the weakest link.

Patterns that work

1

One key per program and purpose

Each application, and each job within it, gets its own key. Logs show who did what, and a leak affects one thing only.

2

Narrow role descriptors, written from nothing

Begin with no access and add only what the program demonstrably needs.

3

A dedicated service owner

Long-lived keys are created under a stable service user, not a person, so staff changes do not break or endanger them.

4

Expiry plus automatic rotation

Keys live for weeks or months. A scheduled job creates the replacement, publishes it to the secrets system, and cancels the old one after a check.

5

Secrets in a managed store

Applications fetch the key at startup or on demand, never from source code.

6

Backend in front of untrusted clients

Browsers and mobile apps talk to a small service that holds the real key and offers only specific searches.

7

Regular review of the key list

A quarterly check for unused, unlabeled, over-powerful, or non-expiring keys.

Everyday Analogy

A well-run hotel issues a fresh card to each guest, limits it to their floor, sets its end date, and logs it. It does not keep a pile of unlabeled cards in a drawer that open every door. The habits are simple and boring, and that is why they work.

Anti-patterns to avoid

ANTI-PATTERN 01Avoid
What people do

They create one powerful key and share it among all applications, teams, and environments “to keep things simple.”

Why it hurts

Any leak exposes everything. Nobody can tell which program did what. Rotating it breaks every system at once, so it never gets rotated.

Better approach

Create a separate, narrowly scoped key for each program and environment, and name each one clearly.

ANTI-PATTERN 02Avoid
What people do

They create keys with no role descriptors while logged in as an administrator, so each key inherits full administrator rights.

Why it hurts

Every key becomes an administrator credential. The main benefit of the feature is thrown away.

Better approach

Always write explicit, narrow role descriptors, and create keys under an account whose own rights are already modest.

ANTI-PATTERN 03Avoid
What people do

They commit keys to source repositories, paste them into chat, or print them in logs.

Why it hurts

Secrets spread to places with wide access and long memories. Automated scanners find leaked keys very quickly.

Better approach

Keep secrets in a managed store, run secret scanning on repositories, and log only the key’s name or id.

ANTI-PATTERN 04Avoid
What people do

They create keys with no expiry and never look at them again.

Why it hurts

Forgotten keys outlive projects and people. Years later nobody knows what they open, and nobody dares to cancel them.

Better approach

Set expiries, record owners in metadata, and review the list on a schedule.

ANTI-PATTERN 05Avoid
What people do

They cancel the old key first and only then create and deploy the new one during a rotation.

Why it hurts

The application is unauthorized from the moment of cancellation until the new key is in place, which causes an avoidable outage.

Better approach

Create and deploy the new key first, confirm it is in use, and cancel the old one afterward.

ANTI-PATTERN 06Avoid
What people do

They place a key with write access into a web page or a mobile app, because “it is hidden in the code.”

Why it hurts

Anything delivered to a user’s device can be read by that user. The key is public from the first download.

Better approach

Put a backend service in between, or, if direct access is unavoidable, use a read-only, single-alias, short-lived key.

17Best Practices and Common Mistakes

A short list you could hand to a new teammate on their first day.

Best practices

Scope

Least privilege always

Grant the smallest access that works. Test both what should succeed and what should fail.

Identity

One key per purpose

Separate keys for separate programs and environments.

Lifetime

Expire and rotate

Use expiry, rotate before it arrives, and create the new key before cancelling the old.

Storage

Use a secrets manager

Store the secret in a controlled system from the first day.

Labels

Name and describe

Clear names and metadata that state the team, purpose, and contact.

Ownership

Stable owners

Create long-lived keys under service accounts, not personal accounts.

Transport

Encrypt everything

Only ever send keys over encrypted connections.

Oversight

Review and alert

Regular reviews, plus alerts for failures, expiries, and unexpected key creation.

Common mistakes

  • Losing the secret. It is shown once. If you did not save it, you must create a new key.
  • Using the id where the encoded value is needed. The id alone is not a credential.
  • Assuming the key can exceed its owner. Effective access is always limited by the owner.
  • Forgetting the owner’s lifecycle. Keys under personal accounts can surprise you when that person moves on.
  • Reusing secrets across environments. A leak in development should never reach production.
  • Broad index patterns. A pattern with a star may cover indexes you never intended.
  • Ignoring expiry dates. A calendar-driven outage is entirely avoidable.
  • Treating metadata as private. Anyone who can view a key’s details can read its metadata.

Myths versus facts

MythFact
An API key is just a password for programs.It is a scoped, revocable, optionally expiring credential with its own identity and limits.
Keys never expire.By default they may not, but an expiry can be set, and it should be.
I can look up my secret later.The secret is shown once and only a fingerprint is stored.
A key can do more than the user who made it.Effective access is the overlap with the owner’s permissions.
Cancelling one key breaks the others.Each key is independent.
Keys are safe to embed in a web page.Anything sent to a browser is visible to its user.
A key from one cluster works in another.Keys are stored inside one cluster and belong to it.
!
A Golden Rule

Make each key small, specific, labeled, and temporary. If you cannot say in one sentence what a key is for, who owns it, and when it ends, it should not exist.

18Real-World and Industry Examples

Where do API keys quietly do their job?

Many well-known organizations have said publicly that Elasticsearch is part of their systems, including Wikipedia’s search, Netflix, Uber, and Stack Overflow. They rarely publish their security configurations, so the scenarios below are typical patterns for this kind of workload, not descriptions of anyone’s private setup.

Online store: the search service

A retailer of the size of Amazon or eBay runs a backend search service that answers queries from millions of shoppers. The service holds one key, limited to read access on the product alias. The website never talks to Elasticsearch directly, so the key is never shown to shoppers. Keys expire every few months, and a rotation job replaces them with an overlap period.

Fleet of log shippers

A streaming or ride-hailing company has thousands of servers sending logs. Each group of servers has a key that can only create and write to its own log index pattern. If a server is compromised, that group’s key is cancelled and replaced, and all other groups carry on undisturbed. Metadata records the team that owns each group.

Software-as-a-service with many customers

A support platform stores each customer’s tickets in separate indexes or with separate filters. The application uses narrow keys so that a bug in one feature cannot read the data of another. Cross-customer administration uses a different, tightly controlled key with a short life.

Kibana alerting in the background

Some Kibana features, such as alerting rules, run on a schedule after the person who set them up has gone home. They do this using API keys created from that person’s account and permissions. It shows the owner rule in action: the background job can do only what its creator was allowed to do, and if the creator’s rights change, the rule may need to be re-saved.

Deployment pipeline and data migrations

An automated release pipeline needs to create indexes and load data during a deployment. It receives a key with an expiry of a few hours, limited to the destination index. When the deployment ends, the key ends too. Nothing needs cleaning up.

Third-party analytics vendor

A company lets an outside vendor read a small set of aggregated indexes. It gives the vendor a read-only key on just those indexes, with an expiry that matches the contract period and a metadata note naming the contract. If the relationship ends, the key is cancelled in seconds.

i
The Common Thread

In every example, the winning ideas are the same: one key per purpose, the narrowest useful access, a stable owner, a defined end date, secrets kept safe, and a clear way to cancel and replace.

19Frequently Asked Questions

Short answers to the questions that come up most often.

Q1Is an API key the same as a password?
Not quite. Both are secrets, but a key has its own id, can be limited to specific actions, can expire, and can be cancelled on its own. It is designed for programs, not for people logging in.
Q2Can I recover a lost secret?
No. The secret is shown once, and only a fingerprint is stored. If it is lost, create a new key and cancel the old one.
Q3Do API keys expire by default?
A key does not expire unless you set an expiry when creating it. It is a good habit to set one.
Q4What is the difference between the id and the secret?
The id identifies the key and is safe to look at. The secret proves that you hold the key and must be protected. Together they are joined into the encoded value that requests use.
Q5Can a key have more permissions than its owner?
No. Effective access is the overlap of the key’s role descriptors and the owner’s permissions, so a key can never exceed its owner.
Q6What happens if I create a key without role descriptors?
It receives the owner’s permissions. If the owner is powerful, so is the key, which is why explicit role descriptors are recommended.
Q7Can one key have several role descriptors?
Yes. The privileges from all of its descriptors are combined, and the result is then limited by the owner’s permissions.
Q8Can I change a key’s permissions after creating it?
In newer versions there is an update operation for role descriptors and metadata. In older versions you must create a replacement key. Check the documentation for your version.
Q9How do I cancel a key?
Use the invalidate operation or the Kibana screen. The key stops working, and its record is later removed by automatic cleanup after a retention period.
Q10What header do I use to send a key?
The authorization header, with the word ApiKey, a space, and then the encoded value returned at creation.
Q11Do I need HTTPS?
Yes. A key sent over plain HTTP can be read by anyone watching the network. Modern secured setups enable encrypted connections by default, but always confirm.
Q12Can I use an API key to log in to Kibana?
Keys are meant for programs calling Elasticsearch. People sign in with user accounts or single sign-on. Kibana features may use keys behind the scenes for background tasks.
Q13What happens to keys when their owner leaves?
The behavior depends on the version and on what happens to the owner’s account and roles, so verify it in your version. The safe approach is to create long-lived keys under a stable service account and to review a departing person’s keys.
Q14Do keys work across clusters?
No. A key belongs to the cluster that created it. For cross-cluster features, newer versions offer a special type of key designed for that use.
Q15Are Elasticsearch API keys the same as Elastic Cloud API keys?
No. Elastic Cloud keys manage deployments in the hosting service. Elasticsearch keys authenticate requests to the data engine.
Q16Is the metadata secret?
No. Anyone who can view the key’s details can read it. Never store secrets there.
Q17How can I tell which key made a request?
Audit logging, where available in your subscription, records the key’s details. Application logs that record the key’s name can fill the gap.
Q18Do settings and defaults differ between versions?
The core ideas have been stable for many releases, but management features, defaults, and details change. Always confirm in the documentation for the exact version you run.

20Summary and Key Takeaways

If you skim only one part of this guide, make it this one.

An Elasticsearch API key is a small, purpose-made credential that lets a program prove who it is without borrowing anyone’s password. It can be limited to exactly the access the program needs, given an end date, and cancelled without disturbing anything else. Used with care, it makes systems safer and easier to run. Used carelessly, it becomes one more forgotten secret.

Key Takeaways

  • What it is: a credential created and checked by Elasticsearch, made of an id and a secret, shown once and stored only as a fingerprint.
  • Why it exists: to give each program its own limited, revocable identity instead of sharing a person’s username and password.
  • How permissions work: effective access is the overlap of the key’s role descriptors and its owner’s permissions, so a key can never exceed its owner.
  • How it is used: send the encoded value in the authorization header over an encrypted connection, from a secret loaded safely at startup.
  • How to keep it healthy: one key per purpose, narrow rights, stable owner, clear names and metadata, expiry, and rotation that creates the new key before cancelling the old.
  • How to keep it safe: never place secrets in code, logs, chats, or browsers, and treat a leak as an incident with a clear cancel-replace-review playbook.
  • How to watch it: alert on authentication failures, on keys nearing expiry, on unexpected key creation, and review the list of keys regularly.