mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
feat(postgres): support COPY targets for OTLP logs and traces (#10449)
* feat(postgres): support COPY targets for OTLP logs and traces Signed-off-by: Ning Sun <sunning@greptime.com> * fix(postgres): guard OTLP COPY targets with catalog restriction and denial observability Address review findings on the OTLP COPY target feature: - Enforce the `disallow_cross_catalog_query` restriction for qualified OTLP COPY targets through the new `CopyInHandler::copy_in_validate_scope`, mirroring SQL INSERT and the csv format; it runs against the original session context before any data is transferred and before the user-provider scope check. - Meter and log `authorize_database` denials like startup authorization (`METRIC_AUTH_FAILURE` plus a scoped warn/error log). - Add an end-to-end denial test through COPY with a scoped user provider: cross-schema, cross-catalog, and `table_name`-override targets are rejected before ingestion, the OTLP handler is never reached, and the session scope stays usable afterwards. - Check the server's OTLP wiring before target errors, reword the metrics target rejection (no false 'with signal metrics' claim for the default signal), and avoid the second `OtlpOptions` clone in `new_otlp`. Signed-off-by: Ning Sun <sunning@greptime.com> * fix(postgres): surface OTLP COPY target denials as insufficient privilege Address review feedback: wrap the authorize_database failure with convert_err instead of PgWireError::ApiError, so a denied qualified COPY target returns SQLSTATE 42501 (insufficient privilege) rather than XX000 (internal error). The end-to-end authorization test now expects INSUFFICIENT_PRIVILEGE. Signed-off-by: Ning Sun <sunning@greptime.com> --------- Signed-off-by: Ning Sun <sunning@greptime.com>
This commit is contained in:
@@ -5795,6 +5795,73 @@ mod tests {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scope-targeted COPY formats (OTLP logs/traces) run the same
|
||||
/// cross-catalog restriction through `copy_in_validate_scope` before
|
||||
/// any data is streamed.
|
||||
#[tokio::test]
|
||||
async fn test_copy_in_validate_scope_cross_catalog_restriction() -> TestResult<()> {
|
||||
use catalog::memory::MemoryCatalogManager;
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
use servers::query_handler::CopyInHandler;
|
||||
|
||||
let catalog = MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
||||
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert(QueryOptions {
|
||||
disallow_cross_catalog_query: true,
|
||||
});
|
||||
let instance = test_instance_with_catalog_manager(
|
||||
catalog,
|
||||
test_table(1025, "target")?,
|
||||
plugins,
|
||||
None,
|
||||
executor,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let ctx = Arc::new(QueryContext::with(
|
||||
DEFAULT_CATALOG_NAME,
|
||||
DEFAULT_SCHEMA_NAME,
|
||||
));
|
||||
|
||||
// A target outside the session's catalog is rejected before any
|
||||
// data is streamed; a same-catalog schema is not.
|
||||
let err = instance
|
||||
.copy_in_validate_scope("other", DEFAULT_SCHEMA_NAME, ctx.clone())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
format!("{err:?}").contains("Illegal access to catalog"),
|
||||
"{err}"
|
||||
);
|
||||
instance
|
||||
.copy_in_validate_scope(DEFAULT_CATALOG_NAME, "other_schema", ctx.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Without the restriction every scope validates.
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert(QueryOptions {
|
||||
disallow_cross_catalog_query: false,
|
||||
});
|
||||
let catalog = MemoryCatalogManager::new_with_table(test_table(1026, "source")?);
|
||||
let instance = test_instance_with_catalog_manager(
|
||||
catalog.clone(),
|
||||
test_table(1027, "target")?,
|
||||
plugins,
|
||||
None,
|
||||
Arc::new(MockProcedureExecutor::new(catalog)),
|
||||
)
|
||||
.await?;
|
||||
instance
|
||||
.copy_in_validate_scope("other", DEFAULT_SCHEMA_NAME, ctx)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const NATIVE_PROMQL_OPTION: &str = "query.experimental_native_promql";
|
||||
|
||||
/// A frontend whose `public` schema holds two metric-engine logical tables, `cpu_usage` and
|
||||
|
||||
@@ -29,8 +29,36 @@ use table::metadata::TableInfoRef;
|
||||
|
||||
use crate::instance::Instance;
|
||||
|
||||
impl Instance {
|
||||
/// Whether cross-catalog access is disabled for this instance —
|
||||
/// mirrors SQL INSERT's catalog restriction (see `check_permission`).
|
||||
fn cross_catalog_restricted(&self) -> bool {
|
||||
self.plugins
|
||||
.get::<QueryOptions>()
|
||||
.map(|opts| opts.disallow_cross_catalog_query)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CopyInHandler for Instance {
|
||||
async fn copy_in_validate_scope(
|
||||
&self,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<()> {
|
||||
// Runs against the ORIGINAL session context — callers switch the
|
||||
// context to the target scope afterwards, so nothing downstream
|
||||
// would catch it.
|
||||
if self.cross_catalog_restricted() {
|
||||
validate_catalog_and_schema(catalog, schema, &query_ctx)
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExecuteQuerySnafu)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn copy_in_table(
|
||||
&self,
|
||||
catalog: &str,
|
||||
@@ -44,12 +72,7 @@ impl CopyInHandler for Instance {
|
||||
// query context — `begin_copy_in` switches the context to the
|
||||
// target catalog afterwards, so nothing downstream would catch
|
||||
// it.
|
||||
let disallow_cross_catalog_query = self
|
||||
.plugins
|
||||
.get::<QueryOptions>()
|
||||
.map(|opts| opts.disallow_cross_catalog_query)
|
||||
.unwrap_or_default();
|
||||
if disallow_cross_catalog_query {
|
||||
if self.cross_catalog_restricted() {
|
||||
validate_catalog_and_schema(catalog, schema, &query_ctx)
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExecuteQuerySnafu)?;
|
||||
|
||||
@@ -88,6 +88,38 @@ impl PgUserProviderSource {
|
||||
Self { user_provider }
|
||||
}
|
||||
|
||||
/// Authorizes a request that changes the connection's catalog/schema
|
||||
/// scope (a qualified COPY target). Denials are metered and logged
|
||||
/// like startup authorization, minus the client address which is not
|
||||
/// reachable here, and surface as their SQLSTATE-mapped pg error
|
||||
/// (`42501` insufficient privilege for access denials) instead of an
|
||||
/// internal error.
|
||||
pub(crate) async fn authorize_database(
|
||||
&self,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
user_info: &UserInfoRef,
|
||||
) -> PgWireResult<()> {
|
||||
match self
|
||||
.user_provider
|
||||
.authorize(catalog, schema, user_info)
|
||||
.await
|
||||
{
|
||||
Err(e) => {
|
||||
record_auth_failure(e.status_code());
|
||||
if e.status_code().should_log_error() {
|
||||
error!(e; user = user_info.username(), protocol = "postgres", catalog = %catalog,
|
||||
schema = %schema, reason = %e.status_code(), "COPY target authorization failed");
|
||||
} else {
|
||||
warn!(user = user_info.username(), protocol = "postgres", catalog = %catalog,
|
||||
schema = %schema, reason = %e.status_code(), "COPY target authorization denied");
|
||||
}
|
||||
Err(convert_err(AuthSnafu.into_error(e)))
|
||||
}
|
||||
Ok(()) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// (user, catalog, schema) of this login. Catalog/schema are parsed from
|
||||
/// the `database` startup parameter. Existence is checked after authorization.
|
||||
fn resolve(login: &WireLoginInfo<'_>) -> Option<(String, String, String)> {
|
||||
@@ -485,3 +517,30 @@ where
|
||||
send_error(client, PgErrorCode::Ec3D000.to_err_info(error)).await?;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_authorize_database() {
|
||||
let source = PgUserProviderSource::new(Arc::new(::auth::tests::MockUserProvider {
|
||||
catalog: "greptime".to_string(),
|
||||
schema: "allowed".to_string(),
|
||||
username: "greptime".to_string(),
|
||||
}));
|
||||
let user = userinfo_by_name(Some("greptime".to_string()));
|
||||
source
|
||||
.authorize_database("greptime", "allowed", &user)
|
||||
.await
|
||||
.unwrap();
|
||||
for (catalog, schema) in [("greptime", "denied"), ("other", "allowed")] {
|
||||
assert!(
|
||||
source
|
||||
.authorize_database(catalog, schema, &user)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,6 +454,15 @@ mod tests {
|
||||
|
||||
#[async_trait]
|
||||
impl CopyInHandler for Handler {
|
||||
async fn copy_in_validate_scope(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &str,
|
||||
_: QueryContextRef,
|
||||
) -> crate::error::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn copy_in_table(
|
||||
&self,
|
||||
_: &str,
|
||||
|
||||
@@ -73,7 +73,8 @@ pub(super) enum CopyFormat {
|
||||
/// pipeline the HTTP write endpoints use (one COPY statement is one
|
||||
/// ingestion request; streaming ingest is not supported).
|
||||
Influxdb(InfluxdbOptions),
|
||||
/// Table-less, **binary** OTLP: one `ExportMetricsServiceRequest`,
|
||||
/// **Binary** OTLP (optionally table-targeted for logs/traces):
|
||||
/// one `ExportMetricsServiceRequest`,
|
||||
/// `ExportTraceServiceRequest` or `ExportLogsServiceRequest`
|
||||
/// protobuf message, buffered whole and completed through the
|
||||
/// matching OTLP pipeline the OTLP/HTTP endpoints use. Advertises
|
||||
|
||||
@@ -394,12 +394,12 @@ impl CopyInState {
|
||||
/// State for the OTLP format: the whole binary payload is buffered
|
||||
/// and completed once at `CopyDone` through the matching OTLP
|
||||
/// pipeline. Binary: the advertised wire format code is 1.
|
||||
fn new_otlp(options: &OtlpOptions, query_ctx: QueryContextRef) -> Self {
|
||||
fn new_otlp(options: OtlpOptions, query_ctx: QueryContextRef) -> Self {
|
||||
Self {
|
||||
query_ctx,
|
||||
payload: Payload::Otlp {
|
||||
data: Vec::new(),
|
||||
options: options.clone(),
|
||||
options,
|
||||
},
|
||||
memory_guards: Vec::new(),
|
||||
granted_bytes: 0,
|
||||
@@ -790,20 +790,43 @@ impl PostgresServerHandlerInner {
|
||||
}
|
||||
CopyInState::new_influxdb(options, query_ctx)
|
||||
}
|
||||
// OTLP forbids a target table too — the payload's resource
|
||||
// metrics route to their own tables — and completes through
|
||||
// the OTLP metrics pipeline; the server must be wired.
|
||||
// OTLP metrics route to their own tables. Logs and traces
|
||||
// accept a destination without requiring it to exist yet.
|
||||
CopyFormat::Otlp(options) => {
|
||||
if !stmt.table.is_empty() {
|
||||
return Err(unsupported(format!(
|
||||
"format otlp routes each record to its own table; \"COPY {} FROM STDIN\" must not name one",
|
||||
stmt.table.join(".")
|
||||
)));
|
||||
if !stmt.columns.is_empty() {
|
||||
return Err(unsupported("format otlp does not support a column list"));
|
||||
}
|
||||
if self.otlp_handler.is_none() {
|
||||
return Err(unsupported("this server is not wired for the otlp format"));
|
||||
}
|
||||
CopyInState::new_otlp(options, query_ctx)
|
||||
let (options, target_ctx) =
|
||||
resolve_otlp_target(options, &stmt.table, query_ctx.clone())?;
|
||||
if target_ctx.current_catalog() != query_ctx.current_catalog()
|
||||
|| target_ctx.current_schema() != query_ctx.current_schema()
|
||||
{
|
||||
// The same cross-catalog restriction SQL INSERT and
|
||||
// the csv format enforce — must run against the
|
||||
// ORIGINAL session context, before the user-provider
|
||||
// scope check and before any data is transferred.
|
||||
self.copy_in_handler
|
||||
.copy_in_validate_scope(
|
||||
target_ctx.current_catalog(),
|
||||
&target_ctx.current_schema(),
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(convert_err)?;
|
||||
if let Some(source) = &self.auth_source {
|
||||
source
|
||||
.authorize_database(
|
||||
target_ctx.current_catalog(),
|
||||
&target_ctx.current_schema(),
|
||||
&query_ctx.current_user(),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
CopyInState::new_otlp(options, target_ctx)
|
||||
}
|
||||
// promwrite forbids a target table too — the body's series
|
||||
// carry their own metric names — and completes through the
|
||||
@@ -1148,6 +1171,32 @@ fn all_rejected_error(kind: &str, rejected: i64, reason: Option<&str>) -> PgWire
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves the SQL target's scope and supplies a fallback destination
|
||||
/// for logs/traces. The explicit WITH table_name option takes precedence
|
||||
/// over the SQL target's name, but does not override its catalog/schema.
|
||||
fn resolve_otlp_target(
|
||||
options: &OtlpOptions,
|
||||
parts: &[String],
|
||||
query_ctx: QueryContextRef,
|
||||
) -> PgWireResult<(OtlpOptions, QueryContextRef)> {
|
||||
let mut options = options.clone();
|
||||
if parts.is_empty() {
|
||||
return Ok((options, query_ctx));
|
||||
}
|
||||
let table_name = match &mut options.signal {
|
||||
OtlpSignal::Metrics { .. } => {
|
||||
return Err(unsupported(format!(
|
||||
"format otlp routes each metric to its own table; \"COPY {} FROM STDIN\" must not name one",
|
||||
parts.join(".")
|
||||
)));
|
||||
}
|
||||
OtlpSignal::Traces { table_name, .. } | OtlpSignal::Logs { table_name, .. } => table_name,
|
||||
};
|
||||
let (catalog, schema, table) = resolve_table_name(&query_ctx, parts)?;
|
||||
table_name.get_or_insert(table);
|
||||
Ok((options, adjust_query_context(query_ctx, &catalog, &schema)))
|
||||
}
|
||||
|
||||
fn adjust_query_context(
|
||||
query_ctx: QueryContextRef,
|
||||
catalog: &str,
|
||||
@@ -1302,6 +1351,69 @@ impl CopyHandler for PostgresServerHandlerInner {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_resolve_otlp_target() {
|
||||
for signal in ["logs", "traces"] {
|
||||
for (target, catalog, schema, expected_table) in [
|
||||
("", "greptime", "public", None),
|
||||
("my_table", "greptime", "public", Some("my_table")),
|
||||
("other.my_table", "greptime", "other", Some("my_table")),
|
||||
("cat.other.my_table", "cat", "other", Some("my_table")),
|
||||
(
|
||||
"\"Other\".\"MyTable\"",
|
||||
"greptime",
|
||||
"Other",
|
||||
Some("MyTable"),
|
||||
),
|
||||
] {
|
||||
for override_name in [None, Some("overridden")] {
|
||||
let override_option = override_name
|
||||
.map(|name| format!(", table_name '{name}'"))
|
||||
.unwrap_or_default();
|
||||
let stmt = copy_from_stdin_from_sql(&format!(
|
||||
"COPY {target} FROM STDIN WITH (FORMAT otlp, signal '{signal}'{override_option})"
|
||||
))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let CopyFormat::Otlp(options) = stmt.format else {
|
||||
panic!("expected OTLP");
|
||||
};
|
||||
let original_ctx = session::context::QueryContext::arc();
|
||||
let (resolved, ctx) =
|
||||
resolve_otlp_target(&options, &stmt.table, original_ctx.clone()).unwrap();
|
||||
let table_name = match resolved.signal {
|
||||
OtlpSignal::Logs { table_name, .. }
|
||||
| OtlpSignal::Traces { table_name, .. } => table_name,
|
||||
_ => panic!("expected logs or traces"),
|
||||
};
|
||||
assert_eq!(table_name.as_deref(), override_name.or(expected_table));
|
||||
assert_eq!(ctx.current_catalog(), catalog);
|
||||
assert_eq!(ctx.current_schema(), schema);
|
||||
// A qualified target must not change the session context.
|
||||
assert_eq!(original_ctx.current_catalog(), "greptime");
|
||||
assert_eq!(original_ctx.current_schema(), "public");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_otlp_metrics_target_rejected() {
|
||||
for signal in ["", ", signal 'metrics'"] {
|
||||
let stmt = copy_from_stdin_from_sql(&format!(
|
||||
"COPY my_metrics FROM STDIN WITH (FORMAT otlp{signal})"
|
||||
))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let CopyFormat::Otlp(options) = stmt.format else {
|
||||
panic!("expected OTLP");
|
||||
};
|
||||
let ctx = session::context::QueryContext::arc();
|
||||
let err = resolve_otlp_target(&options, &stmt.table, ctx).unwrap_err();
|
||||
assert!(err.to_string().contains("must not name one"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_copy_from_stdin_requires_format() {
|
||||
let err = copy_from_stdin_from_sql("COPY t FROM STDIN").unwrap_err();
|
||||
|
||||
@@ -18,8 +18,21 @@
|
||||
//!
|
||||
//! `COPY FROM STDIN WITH (FORMAT otlp [, signal 'traces'] [, <options>])`
|
||||
//! is a GreptimeDB-specific, **binary** format (wire format code 1).
|
||||
//! Like the influxdb format it is table-less and does not decode here:
|
||||
//! the whole payload is buffered until `CopyDone` — exactly like an
|
||||
//! Metrics are table-less; traces and logs also accept
|
||||
//! `COPY [catalog.][schema.]table FROM STDIN`. For those signals the
|
||||
//! destination precedence is `WITH (table_name ...)`, then the COPY
|
||||
//! target's table name, then the signal's default table. A qualified COPY
|
||||
//! target sets the catalog/schema even when `table_name` overrides its
|
||||
//! table name. Targets need not exist before ingestion. Column lists
|
||||
//! are not supported: the payload determines the ingested columns.
|
||||
//! A target that leaves the session's catalog/schema is subject to the
|
||||
//! same `disallow_cross_catalog_query` restriction as SQL INSERT and the
|
||||
//! csv format, and the user provider must authorize the target scope —
|
||||
//! the same `UserProvider::authorize` check a login to that database
|
||||
//! would run — before any data is transferred.
|
||||
//!
|
||||
//! This format does not decode here: the whole payload is buffered
|
||||
//! until `CopyDone` — exactly like an
|
||||
//! OTLP/HTTP request body — then decoded and completed through the
|
||||
//! frontend's `OpenTelemetryProtocolHandler`, the same path the
|
||||
//! `/v1/otlp/v1/{metrics,traces,logs}` endpoints use, under the
|
||||
|
||||
@@ -120,8 +120,8 @@ impl PostgresServer {
|
||||
self
|
||||
}
|
||||
|
||||
/// Wires the OTLP handler used by table-less
|
||||
/// `COPY FROM STDIN WITH (FORMAT otlp)` — the same handler the
|
||||
/// Wires the OTLP handler used by
|
||||
/// `COPY [table] FROM STDIN WITH (FORMAT otlp)` — the same handler the
|
||||
/// OTLP/HTTP endpoints use, so the payload runs through the
|
||||
/// identical pipeline. `with_metric_engine` carries the same flag
|
||||
/// the HTTP wiring passes from its options.
|
||||
|
||||
@@ -378,6 +378,19 @@ pub trait CopyInHandler: Send + Sync {
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<Option<TableInfoRef>>;
|
||||
|
||||
/// Validates that a COPY target's resolved catalog/schema is within
|
||||
/// the session's allowed scope, before any data is transferred.
|
||||
/// Enforces the `disallow_cross_catalog_query` restriction for
|
||||
/// targets that leave the session's catalog — the same restriction
|
||||
/// SQL INSERT and `copy_in_table` enforce. A no-op when the
|
||||
/// restriction is disabled.
|
||||
async fn copy_in_validate_scope(
|
||||
&self,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<()>;
|
||||
|
||||
/// Ingests Arrow batches through the same bulk path as Flight DoPut.
|
||||
/// The COPY transport owns framing and memory admission; implementations
|
||||
/// retain stream-level authorization and schema reconciliation.
|
||||
|
||||
@@ -49,6 +49,148 @@ mod mysql;
|
||||
mod postgres;
|
||||
mod prom_remote_write_v2_test;
|
||||
|
||||
/// An [`OpenTelemetryProtocolHandler`] test double that counts signal
|
||||
/// invocations and never ingests anything: flushed OTLP copies complete
|
||||
/// immediately, and tests can assert whether ingestion was reached at
|
||||
/// all.
|
||||
pub struct CountingOtlpHandler {
|
||||
calls: std::sync::atomic::AtomicUsize,
|
||||
pipeline_options: pipeline::PipelineOptions,
|
||||
}
|
||||
|
||||
impl CountingOtlpHandler {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
calls: std::sync::atomic::AtomicUsize::new(0),
|
||||
pipeline_options: pipeline::PipelineOptions::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calls(&self) -> usize {
|
||||
self.calls.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn invoked(&self) {
|
||||
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CountingOtlpHandler {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl servers::query_handler::PipelineHandler for CountingOtlpHandler {
|
||||
async fn insert(&self, _input: RowInsertRequests, _ctx: QueryContextRef) -> Result<Output> {
|
||||
unimplemented!("not part of this test double")
|
||||
}
|
||||
|
||||
async fn insert_all(
|
||||
&self,
|
||||
_inputs: Vec<(QueryContextRef, RowInsertRequests)>,
|
||||
) -> Result<Vec<Result<Output>>> {
|
||||
unimplemented!("not part of this test double")
|
||||
}
|
||||
|
||||
fn check_pipeline_query_permission(&self, _query_ctx: &QueryContextRef) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_pipeline(
|
||||
&self,
|
||||
_name: &str,
|
||||
_version: pipeline::PipelineVersion,
|
||||
_query_ctx: QueryContextRef,
|
||||
) -> Result<std::sync::Arc<pipeline::Pipeline>> {
|
||||
unimplemented!("not part of this test double")
|
||||
}
|
||||
|
||||
async fn insert_pipeline(
|
||||
&self,
|
||||
_name: &str,
|
||||
_content_type: &str,
|
||||
_pipeline: &str,
|
||||
_query_ctx: QueryContextRef,
|
||||
) -> Result<pipeline::PipelineInfo> {
|
||||
unimplemented!("not part of this test double")
|
||||
}
|
||||
|
||||
async fn delete_pipeline(
|
||||
&self,
|
||||
_name: &str,
|
||||
_version: pipeline::PipelineVersion,
|
||||
_query_ctx: QueryContextRef,
|
||||
) -> Result<Option<()>> {
|
||||
unimplemented!("not part of this test double")
|
||||
}
|
||||
|
||||
async fn get_table(
|
||||
&self,
|
||||
_table: &str,
|
||||
_query_ctx: &session::context::QueryContext,
|
||||
) -> std::result::Result<Option<std::sync::Arc<table::Table>>, catalog::error::Error> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn pipeline_options(&self) -> &pipeline::PipelineOptions {
|
||||
&self.pipeline_options
|
||||
}
|
||||
|
||||
fn build_pipeline(&self, _pipeline: &str) -> Result<pipeline::Pipeline> {
|
||||
unimplemented!("not part of this test double")
|
||||
}
|
||||
|
||||
async fn get_pipeline_str(
|
||||
&self,
|
||||
_name: &str,
|
||||
_version: pipeline::PipelineVersion,
|
||||
_query_ctx: QueryContextRef,
|
||||
) -> Result<(String, datatypes::timestamp::TimestampNanosecond)> {
|
||||
unimplemented!("not part of this test double")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl servers::query_handler::OpenTelemetryProtocolHandler for CountingOtlpHandler {
|
||||
async fn metrics(
|
||||
&self,
|
||||
_request: otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest,
|
||||
_ctx: QueryContextRef,
|
||||
_memory_limiter: Option<(servers::request_memory_limiter::ServerMemoryLimiter, u64)>,
|
||||
) -> Result<servers::query_handler::MetricsIngestOutcome> {
|
||||
self.invoked();
|
||||
Ok(Default::default())
|
||||
}
|
||||
|
||||
async fn traces(
|
||||
&self,
|
||||
_pipeline_handler: servers::query_handler::PipelineHandlerRef,
|
||||
_request: opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest,
|
||||
_pipeline: pipeline::PipelineWay,
|
||||
_pipeline_params: pipeline::GreptimePipelineParams,
|
||||
_table_name: String,
|
||||
_ctx: QueryContextRef,
|
||||
) -> Result<servers::query_handler::TraceIngestOutcome> {
|
||||
self.invoked();
|
||||
Ok(Default::default())
|
||||
}
|
||||
|
||||
async fn logs(
|
||||
&self,
|
||||
_pipeline_handler: servers::query_handler::PipelineHandlerRef,
|
||||
_request: opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest,
|
||||
_pipeline: pipeline::PipelineWay,
|
||||
_pipeline_params: pipeline::GreptimePipelineParams,
|
||||
_table_name: String,
|
||||
_ctx: QueryContextRef,
|
||||
) -> Result<Vec<Output>> {
|
||||
self.invoked();
|
||||
Ok(vec![Output::new_with_affected_rows(0)])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DummyInstance {
|
||||
query_engine: QueryEngineRef,
|
||||
}
|
||||
@@ -81,6 +223,17 @@ impl RecordingCopyInHandler {
|
||||
|
||||
#[async_trait]
|
||||
impl CopyInHandler for RecordingCopyInHandler {
|
||||
// The catalog restriction is an Instance concern; this test double
|
||||
// records writes and accepts every scope.
|
||||
async fn copy_in_validate_scope(
|
||||
&self,
|
||||
_catalog: &str,
|
||||
_schema: &str,
|
||||
_query_ctx: QueryContextRef,
|
||||
) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn copy_in_table(
|
||||
&self,
|
||||
catalog: &str,
|
||||
|
||||
@@ -31,8 +31,11 @@ use common_base::secrets::ExposeSecret;
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
use common_runtime::Builder as RuntimeBuilder;
|
||||
use common_runtime::runtime::BuilderBuild;
|
||||
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
|
||||
use opentelemetry_proto::tonic::logs::v1::ResourceLogs;
|
||||
use pgwire::api::Type;
|
||||
use postgres_types::FromSql;
|
||||
use prost::Message;
|
||||
use rand::Rng;
|
||||
use rustls::client::danger::{ServerCertVerified, ServerCertVerifier};
|
||||
use rustls::{Error, SignatureScheme};
|
||||
@@ -40,6 +43,7 @@ use rustls_pki_types::{CertificateDer, ServerName};
|
||||
use servers::error::Result;
|
||||
use servers::install_default_crypto_provider;
|
||||
use servers::postgres::PostgresServer;
|
||||
use servers::query_handler::OpenTelemetryProtocolHandlerRef;
|
||||
use servers::server::Server;
|
||||
use servers::tls::{ReloadableTlsServerConfig, TlsOption};
|
||||
use table::TableRef;
|
||||
@@ -229,13 +233,14 @@ fn create_postgres_server_with_user_provider(
|
||||
tls: TlsOption,
|
||||
user_provider: Option<UserProviderRef>,
|
||||
) -> Result<Box<dyn Server>> {
|
||||
create_postgres_server_inner(table, tls, user_provider).map(|(server, _)| server)
|
||||
create_postgres_server_inner(table, tls, user_provider, None).map(|(server, _)| server)
|
||||
}
|
||||
|
||||
fn create_postgres_server_inner(
|
||||
table: TableRef,
|
||||
tls: TlsOption,
|
||||
user_provider: Option<UserProviderRef>,
|
||||
otlp_handler: Option<OpenTelemetryProtocolHandlerRef>,
|
||||
) -> Result<(Box<dyn Server>, Arc<crate::RecordingCopyInHandler>)> {
|
||||
let instance = Arc::new(create_testing_instance(table));
|
||||
let copy_in_handler = Arc::new(crate::RecordingCopyInHandler::new(
|
||||
@@ -252,19 +257,21 @@ fn create_postgres_server_inner(
|
||||
.expect("Failed to load certificates and keys"),
|
||||
);
|
||||
|
||||
Ok((
|
||||
Box::new(PostgresServer::new(
|
||||
instance,
|
||||
copy_in_handler.clone(),
|
||||
tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
io_runtime,
|
||||
user_provider,
|
||||
None,
|
||||
)),
|
||||
copy_in_handler,
|
||||
))
|
||||
let mut server = PostgresServer::new(
|
||||
instance,
|
||||
copy_in_handler.clone(),
|
||||
tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
io_runtime,
|
||||
user_provider,
|
||||
None,
|
||||
);
|
||||
if let Some(otlp_handler) = otlp_handler {
|
||||
server = server.with_otlp_handler(otlp_handler, false);
|
||||
}
|
||||
|
||||
Ok((Box::new(server), copy_in_handler))
|
||||
}
|
||||
|
||||
async fn start_test_server_with_user_provider(
|
||||
@@ -1331,7 +1338,8 @@ async fn start_copy_in_test_server(
|
||||
) -> Result<(Box<dyn Server>, u16, Arc<crate::RecordingCopyInHandler>)> {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let _ = install_default_crypto_provider();
|
||||
let (mut server, handler) = create_postgres_server_inner(table, Default::default(), None)?;
|
||||
let (mut server, handler) =
|
||||
create_postgres_server_inner(table, Default::default(), None, None)?;
|
||||
let listening = "127.0.0.1:0".parse::<SocketAddr>().unwrap();
|
||||
server.start(listening).await.unwrap();
|
||||
let port = server.bind_addr().unwrap().port();
|
||||
@@ -1368,6 +1376,80 @@ async fn feed_copy_in(
|
||||
sink.as_mut().finish().await
|
||||
}
|
||||
|
||||
/// A scoped provider denies every COPY target outside `greptime.public`:
|
||||
/// qualified OTLP targets must be rejected before any data transfers,
|
||||
/// without reaching the OTLP handler and without disturbing the
|
||||
/// session's scope.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_copy_in_otlp_target_authorization() -> Result<()> {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let _ = install_default_crypto_provider();
|
||||
|
||||
let otlp_handler = Arc::new(crate::CountingOtlpHandler::new());
|
||||
let table = MemTable::default_numbers_table();
|
||||
let (server, server_port) = {
|
||||
let mut postgres_server = create_postgres_server_inner(
|
||||
table,
|
||||
Default::default(),
|
||||
// The mock provider authorizes only greptime.public for
|
||||
// user greptime, exactly like a scoped login database.
|
||||
Some(Arc::new(MockUserProvider::default())),
|
||||
Some(otlp_handler.clone()),
|
||||
)?
|
||||
.0;
|
||||
let listening = "127.0.0.1:0".parse::<SocketAddr>().unwrap();
|
||||
postgres_server.start(listening).await.unwrap();
|
||||
let port = postgres_server.bind_addr().unwrap().port();
|
||||
(postgres_server, port)
|
||||
};
|
||||
|
||||
let client = create_plain_connection_with_credentials(server_port, "greptime", "greptime")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Both cross-schema and cross-catalog targets are denied — the
|
||||
// table_name override keeps the target's scope, so it is denied too.
|
||||
for sql in [
|
||||
"COPY denied_schema.dest FROM STDIN WITH (FORMAT otlp, signal 'logs')",
|
||||
"COPY other_catalog.public.dest FROM STDIN WITH (FORMAT otlp, signal 'traces')",
|
||||
"COPY denied_schema.ignored FROM STDIN WITH (FORMAT otlp, signal 'logs', table_name 'override')",
|
||||
] {
|
||||
let error = client.simple_query(sql).await.unwrap_err();
|
||||
let db_error = error
|
||||
.as_db_error()
|
||||
.unwrap_or_else(|| panic!("{sql}: {error}"));
|
||||
// The authorization failure surfaces as insufficient privilege
|
||||
// (SQLSTATE 42501), not an internal error.
|
||||
assert_eq!(
|
||||
db_error.code(),
|
||||
&SqlState::INSUFFICIENT_PRIVILEGE,
|
||||
"{sql}: {}",
|
||||
db_error.message()
|
||||
);
|
||||
}
|
||||
// Denied before ingestion: the handler was never reached.
|
||||
assert_eq!(otlp_handler.calls(), 0);
|
||||
|
||||
// The session scope is untouched: a table-less copy in the session's
|
||||
// own scope still ingests afterwards.
|
||||
let payload = ExportLogsServiceRequest {
|
||||
resource_logs: vec![ResourceLogs::default()],
|
||||
}
|
||||
.encode_to_vec();
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT otlp, signal 'logs')",
|
||||
vec![bytes::Bytes::from(payload)],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 0);
|
||||
assert_eq!(otlp_handler.calls(), 1);
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_copy_in_csv() -> Result<()> {
|
||||
let (server, port, handler) = start_copy_in_test_server(copy_in_test_table()).await?;
|
||||
|
||||
@@ -1271,6 +1271,21 @@ async fn test_postgres_copy_in_otlp_binary() {
|
||||
};
|
||||
let body = request.encode_to_vec();
|
||||
|
||||
// Metrics must remain table-less, both with the default signal and
|
||||
// with an explicitly selected metrics signal.
|
||||
for sql in [
|
||||
"COPY forbidden_metrics FROM STDIN WITH (FORMAT otlp)",
|
||||
"COPY forbidden_metrics FROM STDIN WITH (FORMAT otlp, signal 'metrics')",
|
||||
] {
|
||||
let error = client.simple_query(sql).await.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.as_db_error()
|
||||
.is_some_and(|e| e.message().contains("must not name one")),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
// Feed the binary payload in small chunks: the message spans CopyData
|
||||
// boundaries exactly like a large text payload would.
|
||||
let rows = feed_copy_in(
|
||||
@@ -1377,6 +1392,52 @@ async fn test_postgres_copy_in_otlp_traces() {
|
||||
.collect();
|
||||
assert_eq!(count, vec!["1".to_string()]);
|
||||
|
||||
client
|
||||
.simple_query("CREATE DATABASE trace_dest")
|
||||
.await
|
||||
.unwrap();
|
||||
for (target, override_option, destination) in [
|
||||
("", "", "opentelemetry_traces"),
|
||||
("copy_target_traces", "", "copy_target_traces"),
|
||||
(
|
||||
"ignored_traces",
|
||||
", table_name 'override_traces'",
|
||||
"override_traces",
|
||||
),
|
||||
(
|
||||
"trace_dest.qualified_traces",
|
||||
"",
|
||||
"trace_dest.qualified_traces",
|
||||
),
|
||||
(
|
||||
"greptime.trace_dest.ignored",
|
||||
", table_name 'override_traces'",
|
||||
"trace_dest.override_traces",
|
||||
),
|
||||
] {
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
&format!("COPY {target} FROM STDIN WITH (FORMAT otlp, signal 'traces', pipeline_name 'greptime_trace_v2'{override_option})"),
|
||||
vec![Bytes::from(request.encode_to_vec())],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
let messages = client
|
||||
.simple_query(&format!(
|
||||
"SELECT count(*) FROM {destination} WHERE service_name = 'copy-svc'"
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
messages.iter().any(|m| matches!(
|
||||
m,
|
||||
tokio_postgres::SimpleQueryMessage::Row(row) if row.get(0) == Some("1")
|
||||
)),
|
||||
"destination: {destination}, messages: {messages:?}"
|
||||
);
|
||||
}
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
@@ -1409,6 +1470,16 @@ async fn test_postgres_copy_in_otlp_logs() {
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let error = client
|
||||
.simple_query("COPY copy_logs (body) FROM STDIN WITH (FORMAT otlp, signal 'logs')")
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.as_db_error()
|
||||
.is_some_and(|e| e.message().contains("does not support a column list"))
|
||||
);
|
||||
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT otlp, signal 'logs')",
|
||||
@@ -1431,6 +1502,48 @@ async fn test_postgres_copy_in_otlp_logs() {
|
||||
.collect();
|
||||
assert_eq!(count, vec!["1".to_string()]);
|
||||
|
||||
client
|
||||
.simple_query("CREATE DATABASE log_dest")
|
||||
.await
|
||||
.unwrap();
|
||||
for (target, override_option, destination) in [
|
||||
("", ", table_name 'option_only_logs'", "option_only_logs"),
|
||||
("copy_target_logs", "", "copy_target_logs"),
|
||||
(
|
||||
"ignored_logs",
|
||||
", table_name 'override_logs'",
|
||||
"override_logs",
|
||||
),
|
||||
("log_dest.qualified_logs", "", "log_dest.qualified_logs"),
|
||||
(
|
||||
"greptime.log_dest.ignored",
|
||||
", table_name 'override_logs'",
|
||||
"log_dest.override_logs",
|
||||
),
|
||||
] {
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
&format!("COPY {target} FROM STDIN WITH (FORMAT otlp, signal 'logs'{override_option})"),
|
||||
vec![Bytes::from(request.encode_to_vec())],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
let messages = client
|
||||
.simple_query(&format!(
|
||||
"SELECT count(*) FROM {destination} WHERE body = 'copied via postgres'"
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
messages.iter().any(|m| matches!(
|
||||
m,
|
||||
tokio_postgres::SimpleQueryMessage::Row(row) if row.get(0) == Some("1")
|
||||
)),
|
||||
"destination: {destination}, messages: {messages:?}"
|
||||
);
|
||||
}
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user