diff --git a/src/handlers/http/demo_data.rs b/src/handlers/http/demo_data.rs index 2df4d8373..c018d1883 100644 --- a/src/handlers/http/demo_data.rs +++ b/src/handlers/http/demo_data.rs @@ -168,3 +168,45 @@ fn execute_demo_script( Ok(()) } + +#[cfg(test)] +mod auth_tests { + use actix_web::{App, http::StatusCode, test as actix_test, web}; + + use crate::handlers::http::base_path; + use crate::handlers::http::modal::server::Server; + + /// `GET /api/v1/demodata` is registered by the main and query servers + /// without any authentication layer, yet it runs server-side actions with + /// the deployment's own root credentials. An unauthenticated caller must + /// be rejected before the handler runs. + /// + /// The query string deliberately uses an unsupported action, so a request + /// that reaches the handler answers 400 without spawning the demo script. + #[actix_web::test] + async fn demodata_requires_authentication() { + // The handler reads PARSEABLE.options before matching the action. + crate::parseable::install_default_test_parseable(); + + let app = actix_test::init_service( + App::new().service(web::scope(&base_path()).service(Server::get_demo_data_webscope())), + ) + .await; + + let request = actix_test::TestRequest::get() + .uri("/api/v1/demodata?action=unsupported") + .to_request(); + // A rejection arrives as an Err from the test service, not as a + // response, so read the status from either form. + let status = match actix_test::try_call_service(&app, request).await { + Ok(response) => response.status(), + Err(error) => error.as_response_error().status_code(), + }; + + assert_eq!( + status, + StatusCode::UNAUTHORIZED, + "an unauthenticated demodata request must not reach the handler" + ); + } +} diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index ea8242371..b91d43ad3 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -241,6 +241,14 @@ pub async fn setup_otel_stream( ); let tenant_id = get_tenant_id_from_request(req)?; + // The OTLP endpoints authorize `Action::Ingest` against the header stream, + // and `check_auth` matches any stream-scoped permission against internal + // streams, so refuse them here exactly like the `/api/v1/ingest` and + // `/api/v1/logstream/{name}` handlers do. + let internal_stream_names = PARSEABLE.streams.list_internal_streams(&tenant_id); + if internal_stream_names.contains(&stream_name) { + return Err(PostError::InternalStream(stream_name)); + } PARSEABLE .create_stream_if_not_exists( &stream_name, @@ -1365,3 +1373,140 @@ mod header_error_tests { assert_eq!(other.status_code(), StatusCode::INTERNAL_SERVER_ERROR); } } + +#[cfg(test)] +mod otel_internal_stream_tests { + use std::sync::Arc; + + use actix_web::test::TestRequest; + + use super::*; + use crate::metadata::LogStreamMetadata; + use crate::option::Mode; + use crate::parseable::{DEFAULT_TENANT, Stream}; + + /// Registers an internal stream in the live server state, as `pmeta` and + /// `pstats` exist in a real deployment. + fn register_internal_stream(name: &str) { + let staging = tempfile::tempdir_in(concat!(env!("CARGO_MANIFEST_DIR"), "/target")) + .expect("a temporary staging directory") + .keep(); + let options = Arc::new(crate::cli::Options { + local_staging_path: staging, + mode: Mode::All, + ..crate::cli::Options::default() + }); + let metadata = LogStreamMetadata { + stream_type: StreamType::Internal, + // A pre-existing non-OTEL log source, so the OTLP handler's + // log-source compatibility check passes and the write would + // proceed past it. + log_source: vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + ..LogStreamMetadata::default() + }; + let stream = Stream::new(options, name, metadata, None, &None); + PARSEABLE + .streams + .write() + .unwrap() + .entry(DEFAULT_TENANT.to_owned()) + .or_default() + .insert(name.to_owned(), stream); + } + + /// `POST /v1/logs`, `/v1/metrics` and `/v1/traces` all stage their writes + /// through `setup_otel_stream`, which must refuse internal streams exactly + /// like the `/api/v1/ingest` and `/api/v1/logstream/{name}` handlers do. + #[tokio::test] + async fn otel_ingestion_rejects_internal_streams() { + crate::parseable::install_default_test_parseable(); + register_internal_stream("pmeta"); + assert!( + PARSEABLE + .streams + .list_internal_streams(&None) + .contains(&"pmeta".to_owned()), + "the internal stream fixture must be registered" + ); + + let req = TestRequest::default() + .insert_header((STREAM_NAME_HEADER_KEY, "pmeta")) + .to_http_request(); + + let result = setup_otel_stream( + &req, + LogSource::OtelLogs, + &OTEL_LOG_KNOWN_FIELD_LIST, + TelemetryType::Logs, + vec![], + vec![], + ) + .await; + + assert!( + matches!(result, Err(PostError::InternalStream(ref name)) if name == "pmeta"), + "ingesting into an internal stream via the OTLP endpoints must be rejected, got {result:?}" + ); + } + + /// Documents the enabling half of the finding: `check_auth` treats any + /// stream-scoped permission as a match for an internal stream (the clause + /// was added for *reading* internal datasets in upstream commit 651f067c, + /// but it applies to every action, including Ingest). This is why the + /// ingestion handlers must refuse internal streams themselves, and why a + /// role scoped to a single user stream must never be the only protection. + #[test] + fn check_auth_matches_stream_scoped_permissions_against_internal_streams() { + use crate::rbac::map::{ + ROLES, Roles, SESSIONS, SessionKey, Sessions, USER_GROUPS, USERS, UserGroups, + mut_roles, mut_users, sessions, + }; + use crate::rbac::role::ParseableResourceType; + use crate::rbac::role::model::{DefaultPrivilege, Role}; + use crate::rbac::user::{Basic, User, UserType}; + use parking_lot::RwLock; + use ulid::Ulid; + + crate::parseable::install_default_test_parseable(); + register_internal_stream("pmeta"); + + let _serial = crate::rbac::map::TEST_SERIAL.blocking_lock(); + USERS.get_or_init(|| RwLock::new(crate::rbac::map::Users::default())); + SESSIONS.get_or_init(|| RwLock::new(Sessions::default())); + USER_GROUPS.get_or_init(|| RwLock::new(UserGroups::default())); + ROLES.get_or_init(|| RwLock::new(Roles::default())); + mut_roles() + .entry(DEFAULT_TENANT.to_owned()) + .or_default() + .insert( + "scoped-ingester".to_owned(), + Role::create_user_role(vec![DefaultPrivilege::Ingestor { + resource: Some(ParseableResourceType::Stream("app-logs".to_owned())), + }]), + ); + + let user = User { + ty: UserType::Native(Basic { + username: format!("scoped-{}", Ulid::new()).to_lowercase(), + password_hash: "unused-in-this-test".to_owned(), + email: None, + }), + roles: HashSet::from(["scoped-ingester".to_owned()]), + user_groups: HashSet::new(), + tenant: None, + protected: false, + }; + mut_users().insert(user.clone()); + let key = SessionKey::SessionId(Ulid::new()); + crate::rbac::Users.new_session(&user, key.clone(), chrono::TimeDelta::minutes(5)); + + let response = + sessions().check_auth(&key, crate::rbac::role::Action::Ingest, Some("pmeta"), None); + + assert_eq!( + response, + Some(crate::rbac::Response::Authorized), + "documents the over-grant: a role scoped to `app-logs` authorizes ingest on the internal stream `pmeta`" + ); + } +} diff --git a/src/handlers/http/middleware.rs b/src/handlers/http/middleware.rs index 9f5ce104a..0718320a7 100644 --- a/src/handlers/http/middleware.rs +++ b/src/handlers/http/middleware.rs @@ -271,16 +271,29 @@ where let key: Result = extract_session_key(&mut req); - // if action is ingestion, check if tenant is correct for basic auth user + // if action is ingestion, the client-supplied tenant header must match + // the tenant the credential itself belongs to if self.action.eq(&Action::Ingest) && let Ok(key) = &key - && let SessionKey::BasicAuth { username, password } = &key && let (_, Some(tenant)) = &user_and_tenant_id - && !Users.validate_basic_user_tenant_id(username, password, tenant) { - header_error = Some(actix_web::Error::from(PostError::Header( - crate::utils::header_parsing::ParseHeaderError::InvalidTenantId, - ))); + // Basic credentials are verified against the users of that tenant. + // Every other credential is a tracked session (cookie, forwarded + // or API-key) already bound to the tenant it was issued in, so the + // claimed tenant must be the session's own. + let tenant_matches = match &key { + SessionKey::BasicAuth { username, password } => { + Users.validate_basic_user_tenant_id(username, password, tenant) + } + session @ SessionKey::SessionId(_) => Users + .get_userid_from_session(session) + .is_some_and(|(_, session_tenant)| session_tenant.eq(tenant)), + }; + if !tenant_matches { + header_error = Some(actix_web::Error::from(PostError::Header( + crate::utils::header_parsing::ParseHeaderError::InvalidTenantId, + ))); + } } let auth_result: Result<_, Error> = (self.auth_method)(&mut req, self.action); @@ -476,15 +489,20 @@ fn insert_api_key_tenant_header( } /// Unit tests cannot initialize `PARSEABLE`, which parses the process arguments, -/// so they exercise the middleware in single-tenant mode. +/// so they exercise the middleware in single-tenant mode. Tests that need the +/// multi-tenant branches flip the test-only `TEST_MULTI_TENANT` flag while +/// holding the RBAC serial lock, so no other middleware test observes the change. #[cfg(not(test))] fn is_multi_tenant() -> bool { PARSEABLE.options.is_multi_tenant() } +#[cfg(test)] +static TEST_MULTI_TENANT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + #[cfg(test)] fn is_multi_tenant() -> bool { - false + TEST_MULTI_TENANT.load(std::sync::atomic::Ordering::Relaxed) } /// Resolve an incoming API key value to its backing `UserType::ApiKey` user. @@ -2284,3 +2302,164 @@ mod api_key_auth_tests { assert!(obs_text_cases.load(Ordering::SeqCst) > 0); } } + +/// The ingest routes resolve the target tenant from the client-supplied +/// `x-p-tenant` header. Basic credentials are checked against that tenant, but +/// a session cookie is not: a user whose session belongs to tenant A must not +/// be able to ingest as tenant B just by claiming B's header. +#[cfg(test)] +mod ingest_tenant_binding_tests { + use std::collections::HashSet; + use std::sync::atomic::Ordering; + + use actix_web::{ + App, HttpResponse, dev::ServiceResponse, http::StatusCode, test as actix_test, web, + }; + use chrono::TimeDelta; + use parking_lot::RwLock; + use ulid::Ulid; + + use super::*; + use crate::rbac::map::{ + ROLES, Roles, SESSIONS, Sessions, USER_GROUPS, USERS, UserGroups, mut_roles, mut_users, + }; + use crate::rbac::role::ParseableResourceType; + use crate::rbac::role::model::{DefaultPrivilege, Role}; + use crate::rbac::user::{Basic, User, UserType}; + + const STREAM: &str = "shared-stream"; + + /// Runs with the middleware's multi-tenant answer enabled, restoring it + /// on scope exit (including on panic). + struct MultiTenant; + impl MultiTenant { + fn enable() -> Self { + TEST_MULTI_TENANT.store(true, Ordering::SeqCst); + MultiTenant + } + } + impl Drop for MultiTenant { + fn drop(&mut self) { + TEST_MULTI_TENANT.store(false, Ordering::SeqCst); + } + } + + fn unique_tenant(prefix: &str) -> String { + format!("{prefix}-{}", Ulid::new()).to_lowercase() + } + + async fn auth_state() -> tokio::sync::MutexGuard<'static, ()> { + let serial = crate::rbac::map::TEST_SERIAL.lock().await; + USERS.get_or_init(|| RwLock::new(crate::rbac::map::Users::default())); + SESSIONS.get_or_init(|| RwLock::new(Sessions::default())); + USER_GROUPS.get_or_init(|| RwLock::new(UserGroups::default())); + ROLES.get_or_init(|| RwLock::new(Roles::default())); + serial + } + + /// A native user in `tenant` whose only role grants `Ingest` on `STREAM`, + /// plus a tracked cookie session for them. + fn scoped_session_user(tenant: &str) -> SessionKey { + let role_name = format!("scoped-ingester-{}", Ulid::new()).to_lowercase(); + mut_roles().entry(tenant.to_owned()).or_default().insert( + role_name.clone(), + Role::create_user_role(vec![DefaultPrivilege::Ingestor { + resource: Some(ParseableResourceType::Stream(STREAM.to_owned())), + }]), + ); + let user = User { + ty: UserType::Native(Basic { + username: format!("scoped-{}", Ulid::new()).to_lowercase(), + password_hash: "unused-in-this-test".to_owned(), + email: None, + }), + roles: HashSet::from([role_name]), + user_groups: HashSet::new(), + tenant: Some(tenant.to_owned()), + protected: false, + }; + mut_users().insert(user.clone()); + let key = SessionKey::SessionId(Ulid::new()); + crate::rbac::Users.new_session(&user, key.clone(), TimeDelta::minutes(5)); + key + } + + /// A POST route wrapped exactly like the ingest routes: `Auth` with + /// `Action::Ingest` and the resource-context decision. The stub handler + /// records the tenant header it was reached with. + async fn call_ingest_route( + session: &SessionKey, + claimed_tenant: &str, + ) -> (StatusCode, Option) { + let seen_tenant = std::sync::Arc::new(std::sync::Mutex::new(None)); + let handler_tenant = std::sync::Arc::clone(&seen_tenant); + let route = web::post() + .to(move |req: actix_web::HttpRequest| { + let tenant = req + .headers() + .get(TENANT_ID) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + *handler_tenant.lock().unwrap() = tenant; + async { HttpResponse::Ok().finish() } + }) + .wrap(Auth { + action: Action::Ingest, + method: auth_resource_context, + }); + let app = actix_test::init_service(App::new().route("/", route)).await; + + let SessionKey::SessionId(id) = session else { + unreachable!("the fixture tracks a cookie session"); + }; + let request = actix_test::TestRequest::post() + .insert_header(("cookie", format!("session={id}"))) + .insert_header((TENANT_ID, claimed_tenant)) + .insert_header((STREAM_NAME_HEADER_KEY, STREAM)) + .to_request(); + let response: ServiceResponse = match actix_test::try_call_service(&app, request).await { + Ok(response) => response, + Err(error) => { + let status = error.as_response_error().status_code(); + return (status, None); + } + }; + let status = response.status(); + let body = actix_web::body::to_bytes(response.into_body()) + .await + .expect("buffered body"); + assert!(body.is_empty(), "the stub returns an empty body"); + (status, seen_tenant.lock().unwrap().clone()) + } + + #[actix_web::test] + async fn session_ingest_is_bound_to_the_sessions_tenant() { + // `check_auth` resolves the context stream through `PARSEABLE`. + crate::parseable::install_default_test_parseable(); + let _state = auth_state().await; + let _multi = MultiTenant::enable(); + + let tenant_a = unique_tenant("tenant-a"); + let tenant_b = unique_tenant("tenant-b"); + let session = scoped_session_user(&tenant_a); + + // The session belongs to tenant A; claiming tenant B's header must be + // rejected before the handler, like a Basic credential of another + // tenant already is. + let (status, seen) = call_ingest_route(&session, &tenant_b).await; + assert_eq!( + status, + StatusCode::BAD_REQUEST, + "a session of tenant {tenant_a} must not ingest as {tenant_b}" + ); + assert!( + seen.is_none(), + "the request must be rejected before the handler sees the tenant header" + ); + + // Control: claiming the session's own tenant still ingests. + let (status, seen) = call_ingest_route(&session, &tenant_a).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(seen.as_deref(), Some(tenant_a.as_str())); + } +} diff --git a/src/handlers/http/modal/server.rs b/src/handlers/http/modal/server.rs index d19af4d5f..78e498ebc 100644 --- a/src/handlers/http/modal/server.rs +++ b/src/handlers/http/modal/server.rs @@ -293,7 +293,8 @@ impl Server { } pub fn get_demo_data_webscope() -> Scope { - web::scope("/demodata").service(web::resource("").route(web::get().to(get_demo_data))) + web::scope("/demodata") + .service(web::resource("").route(web::get().to(get_demo_data).authenticate())) } pub fn get_otel_generator_webscope() -> Scope { diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 1192f613c..332ae6681 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -31,7 +31,7 @@ use tracing::{error, instrument, warn}; use crate::{ event::{ - FORMAT_KEY, SOURCE_IP_KEY, USER_AGENT_KEY, commit_ingested_schemas, + DEFAULT_TIMESTAMP_KEY, FORMAT_KEY, SOURCE_IP_KEY, USER_AGENT_KEY, commit_ingested_schemas, error::EventError, format::{EventFormat, LogSource, json}, }, @@ -59,6 +59,15 @@ use crate::{ }; const IGNORE_HEADERS: [&str; 3] = [STREAM_NAME_HEADER_KEY, LOG_SOURCE_KEY, EXTRACT_LOG_KEY]; +// Fields the server fills in for every record. `x-p-` headers must not set them: +// `x-p-p_timestamp` would inject a second `p_timestamp` column next to the +// server's, and `x-p-p_src_ip` would replace the recorded source address. +const RESERVED_CUSTOM_FIELD_KEYS: [&str; 4] = [ + DEFAULT_TIMESTAMP_KEY, + USER_AGENT_KEY, + SOURCE_IP_KEY, + FORMAT_KEY, +]; const MAX_CUSTOM_FIELDS: usize = 10; const MAX_FIELD_VALUE_LENGTH: usize = 100; @@ -583,7 +592,14 @@ pub fn get_custom_fields_from_header(req: &HttpRequest) -> HashMap MAX_FIELD_VALUE_LENGTH { warn!( @@ -595,11 +611,6 @@ pub fn get_custom_fields_from_header(req: &HttpRequest) -> HashMap` headers become custom fields. The fields the server records + // itself must not be settable that way: a client could otherwise forge the + // source address or add a second `p_timestamp` column. + #[test] + fn reserved_headers_cannot_replace_server_fields() { + let req = TestRequest::default() + .peer_addr("192.0.2.1:8080".parse().unwrap()) + .insert_header((USER_AGENT, "real-agent")) + .insert_header(("x-p-p_src_ip", "10.0.0.1")) + .insert_header(("x-p-p_user_agent", "fake-agent")) + .insert_header(("x-p-p_format", "fake-format")) + .insert_header(("x-p-p_timestamp", "1700000000000")) + .insert_header(("x-p-team", "payments")) + .to_http_request(); + + let custom_fields = get_custom_fields_from_header(&req); + + assert_eq!(custom_fields.get(SOURCE_IP_KEY).unwrap(), "192.0.2.1"); + assert_eq!(custom_fields.get(USER_AGENT_KEY).unwrap(), "real-agent"); + assert!(!custom_fields.contains_key(FORMAT_KEY)); + assert!(!custom_fields.contains_key(DEFAULT_TIMESTAMP_KEY)); + assert_eq!(custom_fields.get("team").unwrap(), "payments"); + } } diff --git a/src/parseable/mod.rs b/src/parseable/mod.rs index a757afc99..235458309 100644 --- a/src/parseable/mod.rs +++ b/src/parseable/mod.rs @@ -157,6 +157,39 @@ fn resolve_telemetry_type( #[cfg(test)] pub(crate) static CONTRACT_PARSEABLE_FACTORY: OnceCell Parseable> = OnceCell::new(); +/// Test-only: install a factory-backed `PARSEABLE` backed by a temporary +/// local store, so tests can exercise code that reads the global without the +/// process command line being parsed. A factory installed by another test +/// wins (the cell is set once), which is fine: the tests that use this only +/// need *a* server context, never a specific one. +#[cfg(test)] +pub(crate) fn install_default_test_parseable() { + fn factory() -> Parseable { + use crate::storage::object_storage::ObjectStorageProvider; + // Kept for the life of the test process: the global outlives every test + let root = tempfile::tempdir().expect("a temporary directory").keep(); + let provider = Arc::new(crate::storage::FSConfig { root }); + let storage = provider.construct_client(); + let metastore = Arc::new( + crate::metastore::metastores::object_store_metastore::ObjectStoreMetastore { + storage: storage.clone(), + }, + ); + Parseable::new( + crate::cli::Options::default(), + #[cfg(feature = "kafka")] + ::parse_from([ + "contract", + ]), + provider, + metastore, + storage, + ) + } + let _ = CONTRACT_PARSEABLE_FACTORY.set(factory); + Lazy::force(&PARSEABLE); +} + /// Shared state of the Parseable server. pub static PARSEABLE: Lazy = Lazy::new(|| { #[cfg(test)] diff --git a/src/validator.rs b/src/validator.rs index 0f3e80494..9436600eb 100644 --- a/src/validator.rs +++ b/src/validator.rs @@ -76,6 +76,17 @@ pub fn stream_name( Ok(()) } +/// Names the server itself ingests into. A user-created stream with one of +/// these names would capture those internal writes into a caller-owned +/// stream, so `new_stream_name` refuses to create one. Existing streams with +/// these names still load (see `stream_name`), keeping old deployments +/// startable; the stream-metadata migration classifies `pmeta` as internal. +const INTERNAL_STREAM_NAMES: &[&str] = &[ + crate::handlers::http::cluster::PMETA_STREAM_NAME, + crate::handlers::http::cluster::BILLING_METRICS_STREAM_NAME, + crate::storage::field_stats::DATASET_STATS_STREAM_NAME, +]; + /// Validates the name of a stream being created. On top of [`stream_name`], /// it must be ASCII: object stores percent-encode other characters in keys, /// and the storage layer doesn't handle the encoded form everywhere, so such @@ -89,6 +100,10 @@ pub fn new_stream_name( if !name.is_ascii() { return Err(StreamNameValidationError::NonAsciiName(name.to_owned())); } + // Creation only: never let a user stream shadow an internal one. + if stream_type != StreamType::Internal && INTERNAL_STREAM_NAMES.contains(&name) { + return Err(StreamNameValidationError::ReservedName(name.to_owned())); + } Ok(()) } @@ -281,4 +296,27 @@ mod tests { matches!(err, StreamNameValidationError::ReservedName(name) if name == DEFAULT_TENANT) ); } + + /// The server writes its own bookkeeping into the internal streams; a user + /// creating a stream with the same name would capture those writes, and + /// the internal machinery would then run on a user-owned stream. + #[test] + fn new_stream_names_cannot_shadow_internal_streams() { + for name in [ + crate::handlers::http::cluster::PMETA_STREAM_NAME, + crate::handlers::http::cluster::BILLING_METRICS_STREAM_NAME, + crate::storage::field_stats::DATASET_STATS_STREAM_NAME, + ] { + assert!( + matches!( + new_stream_name(name, StreamType::UserDefined), + Err(StreamNameValidationError::ReservedName(rejected)) if rejected == name + ), + "creating a user stream named {name} must be refused" + ); + // A stream that already exists under such a name still loads; + // refusing it here would make the server unstartable. + assert!(stream_name(name, StreamType::UserDefined).is_ok(), "{name}"); + } + } }