| name | langfuse-security-basics |
| description | Implement Langfuse security best practices for API keys and data privacy.
Use when securing Langfuse integration, protecting API keys,
or implementing data privacy controls for LLM observability.
Trigger with phrases like "langfuse security", "langfuse API key security",
"langfuse data privacy", "secure langfuse", "langfuse PII".
|
| allowed-tools | Read, Write, Edit |
| version | 1.0.0 |
| license | MIT |
| author | Jeremy Longshore <jeremy@intentsolutions.io> |
Langfuse Security Basics
Overview
Security best practices for Langfuse API keys, data privacy, and compliance.
Prerequisites
- Langfuse SDK installed
- Understanding of API key management
- Knowledge of data privacy requirements (GDPR, etc.)
Instructions
Step 1: Secure API Key Management
echo '.env*' >> .gitignore
echo '!.env.example' >> .gitignore
cat > .env.example << 'EOF'
LANGFUSE_PUBLIC_KEY=pk-lf-your-public-key
LANGFUSE_SECRET_KEY=sk-lf-your-secret-key
LANGFUSE_HOST=https://cloud.langfuse.com
EOF
git log --all --full-history -- '*/.env*' '*.env'
Step 2: Use Environment-Specific Keys
interface LangfuseConfig {
publicKey: string;
secretKey: string;
host: string;
enabled: boolean;
}
function getLangfuseConfig(): LangfuseConfig {
const env = process.env.NODE_ENV || "development";
const configs: Record<string, LangfuseConfig> = {
development: {
publicKey: process.env.LANGFUSE_PUBLIC_KEY_DEV!,
secretKey: process.env.LANGFUSE_SECRET_KEY_DEV!,
host: process.env.LANGFUSE_HOST_DEV || "https://cloud.langfuse.com",
enabled: true,
},
staging: {
publicKey: process.env.LANGFUSE_PUBLIC_KEY_STAGING!,
secretKey: process.env.LANGFUSE_SECRET_KEY_STAGING!,
host: process.env.LANGFUSE_HOST_STAGING || "https://cloud.langfuse.com",
enabled: ,
},
: {
: process..!,
: process..!,
: process.. || ,
: ,
},
};
configs[env] || configs.;
}
Step 3: Implement PII Scrubbing
interface ScrubConfig {
patterns: RegExp[];
replacement: string;
}
const DEFAULT_SCRUB_CONFIG: ScrubConfig = {
patterns: [
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,
/\b\d{3}-\d{2}-\d{4}\b/g,
/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,
/\b(sk|pk|api|key|token|secret)[-_]?[a-zA-Z0-9]{20,}\b/gi,
/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
],
replacement: "[REDACTED]",
};
function scrubPII(data: any, config = DEFAULT_SCRUB_CONFIG): any {
if (typeof data === "string") {
let scrubbed = data;
for (const pattern of config.patterns) {
scrubbed = scrubbed.replace(pattern, config.replacement);
}
return scrubbed;
}
if (Array.isArray(data)) {
return data.map(() => (item, config));
}
( data === && data !== ) {
: <, > = {};
( [key, value] .(data)) {
(.(key)) {
scrubbed[key] = ;
} {
scrubbed[key] = (value, config);
}
}
scrubbed;
}
data;
}
trace = langfuse.({
: ,
: (userInput),
: (metadata),
});
Step 4: Create Secure Trace Wrapper
interface SecureTraceOptions {
scrubInputs?: boolean;
scrubOutputs?: boolean;
excludeFields?: string[];
allowedMetadataFields?: string[];
}
function createSecureLangfuse(
config: ConstructorParameters<typeof Langfuse>[0],
securityOptions: SecureTraceOptions = {}
) {
const langfuse = new Langfuse(config);
const {
scrubInputs = true,
scrubOutputs = true,
excludeFields = ["password", "token", "apiKey", "secret"],
allowedMetadataFields = ["userId", "sessionId", "environment"],
} = securityOptions;
function sanitize(data: any, shouldScrub: boolean): any {
if (!shouldScrub) return data;
if (typeof data === "object" && data !== null) {
const sanitized = { ...data };
for ( field excludeFields) {
sanitized[field];
}
(sanitized);
}
(data);
}
(): <, > {
: <, > = {};
( field allowedMetadataFields) {
(metadata[field] !== ) {
filtered[field] = metadata[field];
}
}
filtered;
}
{
() {
langfuse.({
...params,
: (params., scrubInputs),
: params. ? (params., scrubOutputs) : ,
: params.
? (params.)
: ,
});
},
: langfuse.(),
: langfuse.(),
};
}
Step 5: Implement Key Rotation
import { Langfuse } from "langfuse";
async function rotateKeys() {
console.log("1. Create new API keys in Langfuse dashboard");
console.log(" https://cloud.langfuse.com/settings/api-keys\n");
console.log("2. Update secrets in your environment:");
console.log(" - AWS Secrets Manager");
console.log(" - GCP Secret Manager");
console.log(" - HashiCorp Vault");
console.log(" - GitHub Secrets\n");
console.log("3. Deploy application with new keys\n");
const langfuse = new Langfuse({
publicKey: process.env.LANGFUSE_PUBLIC_KEY_NEW!,
secretKey: process.env.LANGFUSE_SECRET_KEY_NEW!,
});
trace = langfuse.({
: ,
: { : },
});
langfuse.();
.();
.();
.();
.();
}
().(.);
Output
- Secure API key management
- Environment-specific key separation
- PII scrubbing for inputs/outputs
- Secure trace wrapper
- Key rotation procedure
Security Checklist
| Item | Status | Notes |
|---|
| API keys in .gitignore | Required | Never commit keys |
| Environment separation | Required | Dev/staging/prod keys |
| PII scrubbing enabled | Recommended | Before sending traces |
| Secrets in secret manager | Required | Not in code/config |
| Key rotation schedule | Recommended | Quarterly minimum |
| Audit logging enabled | Recommended | Track API key usage |
Error Handling
| Issue | Cause | Solution |
|---|
| Key exposed in logs | Logging full requests | Scrub before logging |
| PII in traces | No scrubbing | Enable PII scrubbing |
| Key in git history | Committed .env | Rotate keys immediately |
| Cross-env data leak | Shared keys | Use separate keys per env |
Examples
Secrets Manager Integration
import { SecretsManager } from "@aws-sdk/client-secrets-manager";
const secretsManager = new SecretsManager({ region: "us-east-1" });
async function getLangfuseSecrets() {
const response = await secretsManager.getSecretValue({
SecretId: "langfuse/production",
});
const secrets = JSON.parse(response.SecretString!);
return {
publicKey: secrets.LANGFUSE_PUBLIC_KEY,
secretKey: secrets.LANGFUSE_SECRET_KEY,
};
}
const secrets = await getLangfuseSecrets();
const langfuse = new Langfuse(secrets);
Audit Key Usage
const trace = langfuse.trace({
name: "operation",
metadata: {
keyPrefix: process.env.LANGFUSE_PUBLIC_KEY?.slice(0, 10),
environment: process.env.NODE_ENV,
service: process.env.SERVICE_NAME,
},
});
Resources
Next Steps
For production readiness, see langfuse-prod-checklist.