Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(logs): reject tokens that cannot be a project API key (#76501)

Frank Hamand61a146617b8a
diff --git a/rust/capture-logs/README.md b/rust/capture-logs/README.md
index 42a82b2ea1a8..d792e8afe925 100644
--- a/rust/capture-logs/README.md
+++ b/rust/capture-logs/README.md
@@ -18,9 +18,12 @@ The service is configured using environment variables:
| Variable | Default | Description |
|----------|---------|-------------|
-| HOST | 0.0.0.0 | Host to bind the HTTP server |
-| PORT | 8000 | Port for the HTTP server |
-| JWT_SECRET | posthog_default_jwt_secret | Secret key for JWT validation |
+| BIND_HOST | :: | Host to bind the HTTP server |
+| BIND_PORT | 4318 | Port for the HTTP server |
+| MANAGEMENT_BIND_HOST | :: | Host to bind the health check and metrics server |
+| MANAGEMENT_BIND_PORT | 8080 | Port for the health check and metrics server |
+| MAX_REQUEST_BODY_SIZE_BYTES | 2097152 | Rejects larger request bodies, before and after gzip decompression |
+| DROP_EVENTS_BY_TOKEN | (none) | Comma-separated tokens to drop |
## Authentication
@@ -40,6 +43,30 @@ POST /v1/logs?token=your-project-token
The token is your PostHog project token.
+## Response codes
+
+| Status | Meaning | Client behavior |
+|--------|---------|-----------------|
+| 200 | Accepted | — |
+| 400 | Body could not be decoded as OTLP protobuf or JSON | Permanent |
+| 401 | No token, or a token that cannot be a project API key (for example a `phx_` personal API key) | Permanent, so the client stops and surfaces the misconfiguration |
+| 413 | Body over `MAX_REQUEST_BODY_SIZE_BYTES` | Permanent |
+
+The 401 covers shape only: empty, over 64 characters, non-ASCII, containing a null byte, or
+prefixed `phx_`. None of those can be a project API key, so answering 200 and dropping the
+records downstream only hides the misconfiguration from whoever is sending the data. This is
+the same check, and the same status, that event capture applies to the same input.
+
+One misconfiguration is still answered 200: a well-formed token that belongs to no project.
+Resolving a token to a team needs Postgres, which this service does not have, so those records
+are still dropped by the ingestion consumer. Event capture does not validate this at the edge
+either.
+
+A project over its billing quota is also still answered 200 and dropped by the consumer.
+
+Rejections are counted on `capture_logs_requests_rejected_total{reason, signal}`, where `reason`
+is one of `missing_token`, `dropped_token` or `invalid_token`.
+
## Running the Service
### From Source
diff --git a/rust/capture-logs/src/authorizer.rs b/rust/capture-logs/src/authorizer.rs
new file mode 100644
index 000000000000..2ebce97d92ab
--- /dev/null
+++ b/rust/capture-logs/src/authorizer.rs
@@ -0,0 +1,243 @@
+//! The single gate every ingest handler passes a request through.
+//!
+//! Token handling used to be copy-pasted into each handler, which made it possible for a check
+//! to reach some endpoints and not others. Resolving the token is only available here, together
+//! with the checks, so a handler cannot obtain a token without having been authorized.
+
+use std::sync::Arc;
+
+use axum::http::{HeaderMap, StatusCode};
+use axum::response::Json;
+use capture::token::validate_token;
+use limiters::token_dropper::TokenDropper;
+use metrics::counter;
+use serde_json::json;
+use tracing::error;
+
+const REJECTED_COUNTER: &str = "capture_logs_requests_rejected_total";
+
+/// The `(status, body)` pair the handlers already return, so a rejection needs no new plumbing.
+type Rejection = (StatusCode, Json<serde_json::Value>);
+
+/// The OTLP signal a request carries, used to label rejections so a spike can be attributed to
+/// one signal rather than to capture-logs as a whole.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Signal {
+ Logs,
+ Metrics,
+ Traces,
+}
+
+impl Signal {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::Logs => "logs",
+ Self::Metrics => "metrics",
+ Self::Traces => "traces",
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct Authorizer {
+ token_dropper: Arc<TokenDropper>,
+}
+
+impl Authorizer {
+ pub fn new(token_dropper: Arc<TokenDropper>) -> Self {
+ Self { token_dropper }
+ }
+
+ /// Resolve the project token from `Authorization: Bearer <token>`, falling back to the
+ /// `token` query parameter, then authorize it for `signal`.
+ pub fn authorize<'a>(
+ &self,
+ headers: &'a HeaderMap,
+ query_token: Option<&'a str>,
+ signal: Signal,
+ ) -> Result<&'a str, Rejection> {
+ let token = resolve_token(headers, query_token)
+ .map_err(|rejection| self.reject(signal, "missing_token", rejection))?;
+ self.authorize_token(token, signal)?;
+ Ok(token)
+ }
+
+ /// Authorize a token that the caller resolved itself. The Datadog endpoint accepts the token
+ /// in a path segment and in a bare `Authorization` value, so it cannot use `authorize`.
+ pub fn authorize_token(&self, token: &str, signal: Signal) -> Result<(), Rejection> {
+ if self.token_dropper.should_drop(token, "") {
+ return Err(self.reject(signal, "dropped_token", unauthorized("Invalid token")));
+ }
+
+ // Shape validation only rules out tokens that cannot be a project API key at all, such
+ // as a personal API key pasted into an exporter. A well-formed token belonging to no
+ // team still gets a 200 here and is dropped by the consumer, because resolving a token
+ // to a team needs Postgres, which this service does not have.
+ if let Err(reason) = validate_token(token) {
+ error!("Rejecting request with an invalid project API key: {reason}");
+ return Err(self.reject(
+ signal,
+ "invalid_token",
+ unauthorized(format!(
+ "Invalid project API key ({reason}). Use your project API key, which you can find in your PostHog project settings."
+ )),
+ ));
+ }
+
+ Ok(())
+ }
+
+ fn reject(&self, signal: Signal, reason: &'static str, rejection: Rejection) -> Rejection {
+ counter!(REJECTED_COUNTER, "reason" => reason, "signal" => signal.as_str()).increment(1);
+ rejection
+ }
+}
+
+fn unauthorized(message: impl Into<String>) -> Rejection {
+ (
+ StatusCode::UNAUTHORIZED,
+ Json(json!({ "error": message.into() })),
+ )
+}
+
+/// Bearer header first, `?token=` second, matching what the handlers did individually.
+fn resolve_token<'a>(
+ headers: &'a HeaderMap,
+ query_token: Option<&'a str>,
+) -> Result<&'a str, Rejection> {
+ let missing = || {
+ error!("No token provided");
+ unauthorized("No token provided")
+ };
+
+ if let Some(value) = headers.get("Authorization") {
+ return value
+ .to_str()
+ .unwrap_or("")
+ .split("Bearer ")
+ .last()
+ .filter(|token| !token.is_empty())
+ .ok_or_else(missing);
+ }
+
+ query_token
+ .filter(|token| !token.is_empty())
+ .ok_or_else(missing)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn authorizer() -> Authorizer {
+ Authorizer::new(Arc::new(TokenDropper::default()))
+ }
+
+ fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ for (name, value) in pairs {
+ headers.insert(
+ axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
+ value.parse().unwrap(),
+ );
+ }
+ headers
+ }
+
+ #[test]
+ fn a_personal_api_key_is_rejected_instead_of_silently_accepted() {
+ // Pasting a personal API key into an exporter is the misconfiguration that used to be
+ // answered 200 forever while every record was dropped downstream.
+ let (status, _) = authorizer()
+ .authorize_token("phx_personal_api_key", Signal::Logs)
+ .expect_err("a personal API key should not be accepted");
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ }
+
+ #[test]
+ fn structurally_impossible_tokens_are_rejected() {
+ let too_long = "a".repeat(65);
+
+ for token in [too_long.as_str(), "tokenwith\0nullbyte", "🦀", ""] {
+ let (status, _) = authorizer()
+ .authorize_token(token, Signal::Logs)
+ .expect_err("expected rejection");
+ assert_eq!(status, StatusCode::UNAUTHORIZED, "{token:?}");
+ }
+ }
+
+ #[test]
+ fn a_well_formed_token_is_accepted() {
+ assert!(authorizer()
+ .authorize_token("phc_well_formed", Signal::Logs)
+ .is_ok());
+ }
+
+ struct TokenSourceCase {
+ name: &'static str,
+ auth_header: Option<&'static str>,
+ query_token: Option<&'static str>,
+ expected: Option<&'static str>,
+ }
+
+ #[test]
+ fn token_comes_from_the_bearer_header_then_the_query_param() {
+ let cases = [
+ TokenSourceCase {
+ name: "bearer header",
+ auth_header: Some("Bearer phc_header"),
+ query_token: None,
+ expected: Some("phc_header"),
+ },
+ TokenSourceCase {
+ name: "header wins over query param",
+ auth_header: Some("Bearer phc_header"),
+ query_token: Some("phc_query"),
+ expected: Some("phc_header"),
+ },
+ TokenSourceCase {
+ name: "query param fallback",
+ auth_header: None,
+ query_token: Some("phc_query"),
+ expected: Some("phc_query"),
+ },
+ TokenSourceCase {
+ name: "nothing provided",
+ auth_header: None,
+ query_token: None,
+ expected: None,
+ },
+ TokenSourceCase {
+ name: "empty query param",
+ auth_header: None,
+ query_token: Some(""),
+ expected: None,
+ },
+ TokenSourceCase {
+ name: "bearer with no token",
+ auth_header: Some("Bearer "),
+ query_token: None,
+ expected: None,
+ },
+ ];
+
+ for case in cases {
+ let request_headers = match case.auth_header {
+ Some(value) => headers(&[("Authorization", value)]),
+ None => HeaderMap::new(),
+ };
+ let result = authorizer().authorize(&request_headers, case.query_token, Signal::Logs);
+
+ match case.expected {
+ Some(token) => assert_eq!(result.ok(), Some(token), "{}", case.name),
+ None => assert_eq!(
+ result.expect_err(case.name).0,
+ StatusCode::UNAUTHORIZED,
+ "{}",
+ case.name
+ ),
+ }
+ }
+ }
+}
diff --git a/rust/capture-logs/src/endpoints/datadog.rs b/rust/capture-logs/src/endpoints/datadog.rs
index c52074221d87..f3a5ee82e6e3 100644
--- a/rust/capture-logs/src/endpoints/datadog.rs
+++ b/rust/capture-logs/src/endpoints/datadog.rs
@@ -1,3 +1,4 @@
+use crate::authorizer::Signal;
use crate::log_record::{override_timestamp, KafkaLogRow};
use crate::service::{decode_body_if_gzip_magic, Service};
use axum::{
@@ -315,12 +316,8 @@ pub async fn export_datadog_logs_http(
},
};
- if service.token_dropper.should_drop(&token, "") {
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "Invalid token"})),
- ));
- }
+ // Datadog agents ship logs, so this shares the logs signal.
+ service.authorizer.authorize_token(&token, Signal::Logs)?;
tracing::Span::current().record("token", &token);
diff --git a/rust/capture-logs/src/lib.rs b/rust/capture-logs/src/lib.rs
index c200d8158e60..9467fb0e6695 100644
--- a/rust/capture-logs/src/lib.rs
+++ b/rust/capture-logs/src/lib.rs
@@ -1,4 +1,5 @@
pub mod auth;
+pub mod authorizer;
pub mod avro_schema;
pub mod config;
pub mod endpoints;
diff --git a/rust/capture-logs/src/main.rs b/rust/capture-logs/src/main.rs
index 0642ae96aae8..96f0cb851cc7 100644
--- a/rust/capture-logs/src/main.rs
+++ b/rust/capture-logs/src/main.rs
@@ -3,6 +3,7 @@ use std::time::Duration;
use axum::{extract::DefaultBodyLimit, http::Method, routing::get, routing::post, Router};
use capture::metrics_middleware::track_metrics;
+use capture_logs::authorizer::Authorizer;
use capture_logs::config::Config;
use capture_logs::endpoints::datadog;
use capture_logs::kafka::KafkaSink;
@@ -117,20 +118,15 @@ async fn main() {
.expect("could not bind management port");
let token_dropper = TokenDropper::new(&config.drop_events_by_token.unwrap_or_default());
- let token_dropper_arc = Arc::new(token_dropper);
- let logs_service = match Service::new(
- kafka_sink,
- token_dropper_arc,
- config.max_request_body_size_bytes,
- )
- .await
- {
- Ok(service) => service,
- Err(e) => {
- error!("Failed to initialize log service: {}", e);
- panic!("Could not start log capture service: {e}");
- }
- };
+ let authorizer = Authorizer::new(Arc::new(token_dropper));
+ let logs_service =
+ match Service::new(kafka_sink, authorizer, config.max_request_body_size_bytes).await {
+ Ok(service) => service,
+ Err(e) => {
+ error!("Failed to initialize log service: {}", e);
+ panic!("Could not start log capture service: {e}");
+ }
+ };
let http_bind = format!("{}:{}", config.host, config.port);
info!("Listening on {}", http_bind);
let http_listener = tokio::net::TcpListener::bind(http_bind)
diff --git a/rust/capture-logs/src/service.rs b/rust/capture-logs/src/service.rs
index 432a638946a7..4a3072167144 100644
--- a/rust/capture-logs/src/service.rs
+++ b/rust/capture-logs/src/service.rs
@@ -1,3 +1,4 @@
+use crate::authorizer::{Authorizer, Signal};
use crate::log_record::KafkaLogRow;
use crate::metric_record::{flatten_metric, KafkaMetricRow};
use crate::trace_record::KafkaTraceRow;
@@ -9,7 +10,6 @@ use axum::{
};
use bytes::Bytes;
use common_compression::{decompress_gzip_capped, has_gzip_magic_header, CompressionError};
-use limiters::token_dropper::TokenDropper;
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
@@ -18,7 +18,6 @@ use serde::Deserialize;
use serde_json::{json, Value};
use std::fs::File;
use std::io::Write;
-use std::sync::Arc;
use crate::kafka::KafkaSink;
@@ -303,7 +302,7 @@ pub fn parse_otel_message(json_bytes: &Bytes) -> Result<ExportLogsServiceRequest
#[derive(Clone)]
pub struct Service {
pub(crate) sink: KafkaSink,
- pub(crate) token_dropper: Arc<TokenDropper>,
+ pub(crate) authorizer: Authorizer,
pub(crate) max_request_body_size_bytes: usize,
}
@@ -315,12 +314,12 @@ pub struct QueryParams {
impl Service {
pub async fn new(
kafka_sink: KafkaSink,
- token_dropper: Arc<TokenDropper>,
+ authorizer: Authorizer,
max_request_body_size_bytes: usize,
) -> Result<Self, anyhow::Error> {
Ok(Self {
sink: kafka_sink,
- token_dropper,
+ authorizer,
max_request_body_size_bytes,
})
}
@@ -373,49 +372,10 @@ pub async fn export_logs_http(
headers: HeaderMap,
body: Bytes,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- // The project token must be passed in as a Bearer token in the Authorization header
- if !headers.contains_key("Authorization") && query_params.token.is_none() {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": format!("No token provided")})),
- ));
- }
-
- let token = if headers.contains_key("Authorization") {
- match headers["Authorization"]
- .to_str()
- .unwrap_or("")
- .split("Bearer ")
- .last()
- {
- Some(token) if !token.is_empty() => token,
- _ => {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": format!("No token provided")})),
- ));
- }
- }
- } else {
- match query_params.token {
- Some(ref token) if !token.is_empty() => token,
- _ => {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": format!("No token provided")})),
- ));
- }
- }
- };
- if service.token_dropper.should_drop(token, "") {
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": format!("Invalid token")})),
- ));
- }
+ let token =
+ service
+ .authorizer
+ .authorize(&headers, query_params.token.as_deref(), Signal::Logs)?;
tracing::Span::current().record("token", token);
@@ -563,49 +523,10 @@ pub async fn export_traces_http(
headers: HeaderMap,
body: Bytes,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- if !headers.contains_key("Authorization") && query_params.token.is_none() {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "No token provided"})),
- ));
- }
-
- let token = if headers.contains_key("Authorization") {
- match headers["Authorization"]
- .to_str()
- .unwrap_or("")
- .split("Bearer ")
- .last()
- {
- Some(token) if !token.is_empty() => token,
- _ => {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "No token provided"})),
- ));
- }
- }
- } else {
- match query_params.token {
- Some(ref token) if !token.is_empty() => token,
- _ => {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "No token provided"})),
- ));
- }
- }
- };
-
- if service.token_dropper.should_drop(token, "") {
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "Invalid token"})),
- ));
- }
+ let token =
+ service
+ .authorizer
+ .authorize(&headers, query_params.token.as_deref(), Signal::Traces)?;
tracing::Span::current().record("token", token);
@@ -740,49 +661,10 @@ pub async fn export_metrics_http(
headers: HeaderMap,
body: Bytes,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- if !headers.contains_key("Authorization") && query_params.token.is_none() {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "No token provided"})),
- ));
- }
-
- let token = if headers.contains_key("Authorization") {
- match headers["Authorization"]
- .to_str()
- .unwrap_or("")
- .split("Bearer ")
- .last()
- {
- Some(token) if !token.is_empty() => token,
- _ => {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "No token provided"})),
- ));
- }
- }
- } else {
- match query_params.token {
- Some(ref token) if !token.is_empty() => token,
- _ => {
- error!("No token provided");
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "No token provided"})),
- ));
- }
- }
- };
-
- if service.token_dropper.should_drop(token, "") {
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "Invalid token"})),
- ));
- }
+ let token =
+ service
+ .authorizer
+ .authorize(&headers, query_params.token.as_deref(), Signal::Metrics)?;
tracing::Span::current().record("token", token);