Security Best Practices
Most of what secures an LLM application is already in LLM4S: credentials that never appear in code or logs, guardrails on what goes in and comes out, encryption of what an agent stores, and limits on what its tools may touch. This page maps each concern to the component and the guide that covers it.
- API keys
- Untrusted input and output
- What tools may touch
- Data at rest and data retention
- Audit
- See also
API keys
Keep keys out of code and out of checked-in files. In order of preference:
- A file the platform mounts and rotates. A provider section’s
apiKeyFilenames a file holding the key; the client re-reads it when it changes, so a rotated key is used from the next request with no restart. Mount it with mode0400: a file readable by its group or others is logged as a warning. - Read from the secret store by llm4s.
VaultApiKeyProvider(llm4s-secrets-vault, HashiCorp Vault’s KV engine) andAwsSecretsManagerApiKeyProvider(llm4s-secrets-aws) fetch, cache and refresh the key over HTTP, with no vendor SDK; set one withwithApiKeyProvideron the provider config. For another secret store, implementApiKeyProvideryourself. - An environment variable, bound by the provider module’s
reference.conftollm4s.credentials.<id>.apiKey(for exampleOPENAI_API_KEY). Never read it withsys.envyourself.
1
2
3
4
5
llm4s.providers.openai-main {
provider = "openai"
model = "gpt-5.6-luna"
apiKeyFile = "/var/run/secrets/llm4s/openai-api-key" # instead of apiKey
}
Whichever ApiKeyProvider you use, it goes on the provider config the same way. A section is validated when it is
loaded, so Llm4sConfig.provider below still needs the section to resolve a key of its own (the apiKeyFile above, for
example); the provider you attach then supplies every key the client sends. When the secret store is the only
source, build the provider config in code instead
(Configuration in code) and attach the provider to that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import org.llm4s.config.Llm4sConfig
import org.llm4s.llmconnect.{ LLMClient, LLMConnect }
import org.llm4s.llmconnect.auth.ApiKeyProvider
import org.llm4s.model.ModelRegistryService
import org.llm4s.types.Result
import org.llm4s.types.ProviderModelTypes.ProviderName
// keys: for example, from llm4s-secrets-vault,
// VaultApiKeyProvider(VaultSettings("https://vault.internal:8200", Secret(vaultToken), "llm4s/openai", "apiKey"))
// which returns a Result[VaultApiKeyProvider]
def clientWithKeysFrom(keys: ApiKeyProvider): Result[LLMClient] = for {
registry <- Llm4sConfig.modelRegistryService()
given ModelRegistryService = registry
config <- Llm4sConfig.provider(ProviderName("openai-main")).flatMap(_.withApiKeyProvider(keys))
client <- LLMConnect.getClient(config)
} yield client
Keys are wrapped in ApiKey and Secret, whose toString is redacted, and llm4s’s errors never include them. Do not
log a key, or any part of one, yourself. The full rules, the Kubernetes, Vault Agent and CSI driver setups, and the
AWS example are in Production Deployment and
Rotating keys. A second account’s
section sets its own key; the config policy’s prod preset flags one that does not.
Creating a Secret registers its value process-wide, so that llm4s can remove it, by exact match, from the error
messages and logs it builds. Secret(value) is a configured credential and is never evicted; Secret.token(value)
is a short-lived one, and the oldest tokens are evicted once the registry holds more than 4096 values. A value under
8 characters is not registered, and there is no public way to forget one. So use Secret(...) for the fixed set of
long-lived credentials an application is configured with, and Secret.token(...) for a key you create per tenant
or per request: created with Secret(...), each distinct key stays registered until the process exits, and the
registry grows without bound (llm4s logs one warning when it passes 4096).
Untrusted input and output
Guardrails are set on the agent (withInputGuardrails, withOutputGuardrails); a block ends the turn
AgentStatus.Blocked and stores nothing of it. The built-in ones that matter for security:
| Concern | Guardrail |
|---|---|
| Prompt injection and jailbreak attempts in user input | PromptInjectionDetector (input) |
| Personal data in prompts or answers | PIIDetector to block, PIIMasker to mask (input and output) |
| A key, token or other secret in a prompt or answer | SecretLeakGuardrail (input and output) |
| Oversized input | LengthCheck |
| A judgement a pattern cannot make | LLMSafetyGuardrail |
1
2
3
4
5
6
7
8
9
10
import org.llm4s.agent.Agent
import org.llm4s.agent.guardrails.builtin.{ LengthCheck, PIIMasker, PromptInjectionDetector, SecretLeakGuardrail }
import org.llm4s.llmconnect.LLMClient
import org.llm4s.types.Result
def guardedAgent(client: LLMClient): Result[Agent] =
Agent.builder("assistant", client)
.withInputGuardrails(LengthCheck(1, 10000), PromptInjectionDetector(), PIIMasker())
.withOutputGuardrails(SecretLeakGuardrail(), PIIMasker())
.build()
Pattern-based detection is a filter, not a proof. Tool output is untrusted input too (indirect prompt injection), and the strongest defence is to give an agent only the tools and permissions its task needs. See Guardrails and the Security Reference.
What tools may touch
- Tool permissions:
PermissionMiddlewarewithPermissionRule.allow,denyandaskdecides per resource a tool call touches, and denies what no rule matches;asksuspends the turn for a person’s approval. See tool permissions and Human Review. - Commands and files: run them in the workspace container, whose command policy, confinement and egress rules are in Workspace Sandbox.
- HTTP and loaders: the HTTP tool and the URL loaders refuse private and link-local addresses by default; see SSRF.
Data at rest and data retention
- Encrypt what an agent stores.
EncryptingCheckpointer,EncryptingRunQueueandEncryptingLongTermStore(org.llm4s.agent.encryption, experimental) wrap any store with per-tenant keys. See encrypting what the store holds. - Delete on request.
Agent.forget(threadId)removes a thread; memories and vector stores delete by id or metadata filter.RetentionPolicyprunes old history. See deleting a user’s data. - Keep content out of telemetry. The default console tracer and the durable agent events carry no message content; see logging and tracing defaults.
Audit
A durable agent thread is an ordered log of its runs: model calls, tool executions, handoffs and guardrail blocks are stored as events (without content), with the checkpoints of each step. Together with tracing to Langfuse or OpenTelemetry, that is the audit trail; who asked is your application’s to record beside the thread id. See Streaming for the event types and Production Monitoring.
See also
- Data Protection: egress destinations, residency, personal data in prompts
- Security Reference
- Permission-based RAG: retrieval limited to what the asking user may see