mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 00:15:29 +00:00
fix(meta): honor user providers for admin endpoints (#10774)
* fix(meta): honor user providers for admin endpoints Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(meta): authorize admin operations through permission checker Signed-off-by: WenyXu <wenymedia@gmail.com> * test(meta): cover admin HTTP authentication from configuration Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(meta): enforce admin authorization on matched plugin routes Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: reject unregistered metasrv user providers Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
Generated
+2
@@ -8634,6 +8634,7 @@ version = "1.4.0-alpha.0"
|
||||
dependencies = [
|
||||
"api",
|
||||
"async-trait",
|
||||
"auth",
|
||||
"axum 0.8.4",
|
||||
"axum-macros",
|
||||
"chrono",
|
||||
@@ -11232,6 +11233,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"snafu 0.8.6",
|
||||
"standalone",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -458,6 +458,7 @@
|
||||
|
||||
| Key | Type | Default | Descriptions |
|
||||
| --- | -----| ------- | ----------- |
|
||||
| `user_provider` | String | Unset | User provider for admin authentication. Unset preserves anonymous admin access.<br/>When set, all `/admin/*` requests on both HTTP and legacy RPC listeners require<br/>valid credentials and permission for admin operations, including `/admin/health`.<br/>Static and watched-file providers allow default, rw, and wo users; ro users are denied.<br/>On the HTTP listener, /debug/* requires access to the selected database.<br/>Example: "static_user_provider:cmd:operator:rw=CHANGE_ME"<br/>Inline credentials are redacted in logs and serialized configuration.<br/>Existing anonymous scripts/probes must send credentials after enabling a provider.<br/>Protect admin credentials with TLS termination. |
|
||||
| `data_home` | String | `./greptimedb_data` | The working home directory. |
|
||||
| `store_addrs` | Array | -- | Store server address(es). The format depends on the selected backend.<br/><br/>For etcd: a list of "host:port" endpoints.<br/>e.g. ["192.168.1.1:2379", "192.168.1.2:2379"]<br/><br/>For PostgreSQL: a connection string in libpq format or URI.<br/>e.g.<br/>- "host=localhost port=5432 user=postgres password=<PASSWORD> dbname=postgres"<br/>- "postgresql://user:password@localhost:5432/mydb?connect_timeout=10"<br/>The detail see: https://docs.rs/tokio-postgres/latest/tokio_postgres/config/struct.Config.html<br/><br/>For mysql store, the format is a MySQL connection URL.<br/>e.g. "mysql://user:password@localhost:3306/greptime_meta?ssl-mode=VERIFY_CA&ssl-ca=/path/to/ca.pem" |
|
||||
| `store_key_prefix` | String | `""` | If it's not empty, the metasrv will store all data with this key prefix. |
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
## User provider for admin authentication. Unset preserves anonymous admin access.
|
||||
## When set, all `/admin/*` requests on both HTTP and legacy RPC listeners require
|
||||
## valid credentials and permission for admin operations, including `/admin/health`.
|
||||
## Static and watched-file providers allow default, rw, and wo users; ro users are denied.
|
||||
## On the HTTP listener, /debug/* requires access to the selected database.
|
||||
## Example: "static_user_provider:cmd:operator:rw=CHANGE_ME"
|
||||
## Inline credentials are redacted in logs and serialized configuration.
|
||||
## Existing anonymous scripts/probes must send credentials after enabling a provider.
|
||||
## Protect admin credentials with TLS termination.
|
||||
## @toml2docs:none-default
|
||||
#+ user_provider = "static_user_provider:file:/path/to/users"
|
||||
|
||||
## The working home directory.
|
||||
data_home = "./greptimedb_data"
|
||||
|
||||
|
||||
+2
-2
@@ -33,8 +33,8 @@ pub use common::{
|
||||
};
|
||||
pub use permission::{
|
||||
ALL_ACTIONS, AccessMode, COPY_TO, DASHBOARD_DELETE, DASHBOARD_QUERY, DASHBOARD_SAVE,
|
||||
DefaultPermissionChecker, INFLUXDB_WRITE, JAEGER_QUERY, LOG_QUERY, LOG_WRITE, OPENTSDB_WRITE,
|
||||
OTLP_WRITE, PIPELINE_DELETE, PIPELINE_INSERT, PIPELINE_QUERY, PROM_STORE_READ,
|
||||
DefaultPermissionChecker, INFLUXDB_WRITE, JAEGER_QUERY, LOG_QUERY, LOG_WRITE, METASRV_ADMIN,
|
||||
OPENTSDB_WRITE, OTLP_WRITE, PIPELINE_DELETE, PIPELINE_INSERT, PIPELINE_QUERY, PROM_STORE_READ,
|
||||
PROM_STORE_WRITE, PROMQL_QUERY, PermissionAction, PermissionChecker, PermissionReq,
|
||||
PermissionResp, PermissionTableTarget, PermissionTableTargets, SEMANTIC_GRAPH_QUERY,
|
||||
TableTargetPrecheck,
|
||||
|
||||
@@ -145,6 +145,9 @@ impl PermissionAction {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cluster administration, authorized independently of database access.
|
||||
pub const METASRV_ADMIN: PermissionAction = PermissionAction::write("metasrv.admin");
|
||||
|
||||
pub const COPY_TO: PermissionAction = PermissionAction::read("copy.to");
|
||||
pub const PROMQL_QUERY: PermissionAction = PermissionAction::read("promql.query");
|
||||
pub const LOG_QUERY: PermissionAction = PermissionAction::read("log.query");
|
||||
@@ -171,6 +174,7 @@ pub const SEMANTIC_GRAPH_QUERY: PermissionAction = PermissionAction::read("seman
|
||||
/// Downstream crates may define additional actions with [`PermissionAction::read`] and
|
||||
/// [`PermissionAction::write`].
|
||||
pub const ALL_ACTIONS: &[PermissionAction] = &[
|
||||
METASRV_ADMIN,
|
||||
COPY_TO,
|
||||
PROMQL_QUERY,
|
||||
LOG_QUERY,
|
||||
|
||||
@@ -19,6 +19,7 @@ use std::time::Duration;
|
||||
use async_trait::async_trait;
|
||||
use clap::Parser;
|
||||
use common_base::Plugins;
|
||||
use common_base::secrets::SecretString;
|
||||
use common_config::Configurable;
|
||||
use common_meta::distributed_time_constants::init_distributed_time_constants;
|
||||
use common_telemetry::logging::{DEFAULT_LOGGING_DIR, TracingOptions};
|
||||
@@ -164,6 +165,9 @@ pub struct StartCommand {
|
||||
http_addr: Option<String>,
|
||||
#[clap(long)]
|
||||
http_timeout: Option<u64>,
|
||||
/// User provider for admin authentication; authenticated users must have permission for admin operations.
|
||||
#[clap(long)]
|
||||
user_provider: Option<SecretString>,
|
||||
#[clap(long, default_value = "GREPTIMEDB_METASRV")]
|
||||
env_prefix: String,
|
||||
/// The working home directory of this metasrv instance.
|
||||
@@ -191,6 +195,7 @@ impl Debug for StartCommand {
|
||||
.field("enable_region_failover", &self.enable_region_failover)
|
||||
.field("http_addr", &self.http_addr)
|
||||
.field("http_timeout", &self.http_timeout)
|
||||
.field("user_provider", &self.user_provider)
|
||||
.field("env_prefix", &self.env_prefix)
|
||||
.field("data_home", &self.data_home)
|
||||
.field("store_key_prefix", &self.store_key_prefix)
|
||||
@@ -279,6 +284,10 @@ impl StartCommand {
|
||||
opts.enable_region_failover = enable_region_failover;
|
||||
}
|
||||
|
||||
if let Some(user_provider) = &self.user_provider {
|
||||
opts.user_provider = Some(user_provider.clone());
|
||||
}
|
||||
|
||||
if let Some(http_addr) = &self.http_addr {
|
||||
opts.http.addr.clone_from(http_addr);
|
||||
}
|
||||
@@ -451,6 +460,35 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_admin_user_provider_cli_redaction_and_precedence() {
|
||||
use common_base::secrets::ExposeSecret;
|
||||
let cmd = StartCommand::try_parse_from([
|
||||
"metasrv",
|
||||
"--user-provider",
|
||||
"static_user_provider:cmd:operator:rw=cli-secret",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(!format!("{cmd:?}").contains("cli-secret"));
|
||||
let mut opts = MetasrvOptions::default();
|
||||
opts.component.user_provider = Some(
|
||||
"static_user_provider:cmd:operator:rw=file-secret"
|
||||
.to_string()
|
||||
.into(),
|
||||
);
|
||||
cmd.merge_with_cli_options(&GlobalOptions::default(), &mut opts)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
opts.component
|
||||
.user_provider
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.expose_secret(),
|
||||
"static_user_provider:cmd:operator:rw=cli-secret"
|
||||
);
|
||||
assert!(!toml::to_string(&opts).unwrap().contains("cli-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_log_options_from_cli() {
|
||||
let cmd = StartCommand {
|
||||
|
||||
@@ -74,7 +74,9 @@ abstraction, election, key encoding, and the DDL manager live in `common-meta`;
|
||||
|
||||
Clients use the `meta-client` crate (`MetaClient`). On the server side the entry
|
||||
points are the gRPC services under `src/meta-srv/src/service/` and the HTTP admin
|
||||
API under `src/meta-srv/src/service/admin/`.
|
||||
API under `src/meta-srv/src/service/admin/`. Both HTTP and legacy RPC admin
|
||||
entry points require authentication and the `metasrv.admin` permission action when a user
|
||||
provider is configured; retain the cross-entry-point rejection/state tests.
|
||||
|
||||
## When you change X, also touch Y
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ workspace = true
|
||||
[dependencies]
|
||||
api.workspace = true
|
||||
async-trait.workspace = true
|
||||
auth.workspace = true
|
||||
axum.workspace = true
|
||||
axum-macros.workspace = true
|
||||
chrono.workspace = true
|
||||
|
||||
@@ -55,7 +55,7 @@ use crate::selector::round_robin::RoundRobinSelector;
|
||||
use crate::selector::weight_compute::RegionNumsBasedWeightCompute;
|
||||
use crate::selector::{Selector, SelectorType};
|
||||
use crate::service::admin;
|
||||
use crate::service::admin::admin_axum_router;
|
||||
use crate::service::admin::builtin_admin_router;
|
||||
use crate::utils::etcd::create_etcd_client_with_tls;
|
||||
use crate::{Result, error};
|
||||
|
||||
@@ -83,13 +83,20 @@ impl MetasrvInstance {
|
||||
let plugins = metasrv.plugins().clone();
|
||||
let metasrv = Arc::new(metasrv);
|
||||
|
||||
// Wire up the admin_axum_router as an extra router
|
||||
let extra_routers = admin_axum_router(metasrv.clone());
|
||||
let extra_routers = builtin_admin_router(metasrv.clone());
|
||||
|
||||
let mut builder = HttpServerBuilder::new(opts.http.clone())
|
||||
.with_metrics_handler(MetricsHandler)
|
||||
.with_greptime_config_options(opts.to_toml().context(error::TomlFormatSnafu)?);
|
||||
builder = builder.with_extra_router(extra_routers);
|
||||
if let Some(provider) = plugins.get::<auth::UserProviderRef>() {
|
||||
let checker = plugins
|
||||
.get::<auth::PermissionCheckerRef>()
|
||||
.unwrap_or_else(auth::DefaultPermissionChecker::arc);
|
||||
builder = builder
|
||||
.with_user_provider(provider)
|
||||
.with_admin_checker(checker);
|
||||
}
|
||||
|
||||
// put metasrv into plugins for later use
|
||||
plugins.insert::<Arc<Metasrv>>(metasrv.clone());
|
||||
|
||||
@@ -23,6 +23,7 @@ use api::v1::meta::{HeartbeatConfig, Role};
|
||||
use clap::ValueEnum;
|
||||
use common_base::Plugins;
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use common_base::secrets::SecretString;
|
||||
use common_config::{Configurable, DEFAULT_DATA_HOME};
|
||||
use common_event_recorder::EventRecorderOptions;
|
||||
use common_greptimedb_telemetry::GreptimeDBTelemetryTask;
|
||||
@@ -249,6 +250,9 @@ pub struct MetasrvOptions {
|
||||
pub grpc: GrpcOptions,
|
||||
/// The HTTP server options.
|
||||
pub http: HttpOptions,
|
||||
/// Provider for admin authentication. Inline credentials are redacted on serialization.
|
||||
#[serde(serialize_with = "auth::serialize_user_provider_option")]
|
||||
pub user_provider: Option<SecretString>,
|
||||
/// The logging options.
|
||||
pub logging: LoggingOptions,
|
||||
/// The procedure options.
|
||||
@@ -323,6 +327,7 @@ impl fmt::Debug for MetasrvOptions {
|
||||
)
|
||||
.field("grpc", &self.grpc)
|
||||
.field("http", &self.http)
|
||||
.field("user_provider", &self.user_provider)
|
||||
.field("logging", &self.logging)
|
||||
.field("procedure", &self.procedure)
|
||||
.field("failure_detector", &self.failure_detector)
|
||||
@@ -375,6 +380,7 @@ impl Default for MetasrvOptions {
|
||||
..Default::default()
|
||||
},
|
||||
http: HttpOptions::default(),
|
||||
user_provider: None,
|
||||
logging: LoggingOptions::default(),
|
||||
procedure: ProcedureConfig {
|
||||
max_retry_times: 12,
|
||||
@@ -1011,6 +1017,23 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::metasrv::MetasrvNodeInfo;
|
||||
|
||||
#[test]
|
||||
fn test_admin_provider_configuration_redaction() {
|
||||
use common_base::secrets::ExposeSecret;
|
||||
let opts: super::MetasrvOptions =
|
||||
toml::from_str(r#"user_provider = "static_user_provider:cmd:root:rw=admin-secret""#)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
opts.user_provider.as_ref().unwrap().expose_secret(),
|
||||
"static_user_provider:cmd:root:rw=admin-secret"
|
||||
);
|
||||
let serialized = toml::to_string(&opts).unwrap();
|
||||
assert!(!serialized.contains("admin-secret"));
|
||||
assert!(serialized.contains("user_provider = \"[REDACTED]\""));
|
||||
assert!(!format!("{opts:?}").contains("admin-secret"));
|
||||
assert!(super::MetasrvOptions::default().user_provider.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_store_addresses_are_redacted() {
|
||||
let address = "mysql://alice:store-secret@localhost/database?password=query-secret";
|
||||
|
||||
@@ -232,6 +232,23 @@ impl MetasrvBuilder {
|
||||
|
||||
let options = options.unwrap_or_default();
|
||||
options.gc.validate()?;
|
||||
if let Some(plugins) = &plugins
|
||||
&& plugins.get::<auth::UserProviderRef>().is_some()
|
||||
{
|
||||
ensure!(
|
||||
plugins.get::<auth::PermissionCheckerRef>().is_some(),
|
||||
error::InvalidArgumentsSnafu {
|
||||
err_msg: "A metasrv user provider requires a permission checker",
|
||||
}
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
options.user_provider.is_none(),
|
||||
error::InvalidArgumentsSnafu {
|
||||
err_msg: "No metasrv user provider registered for the configured user_provider",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let kv_backend = kv_backend.unwrap_or_else(|| Arc::new(MemoryKvBackend::new()));
|
||||
let in_memory = in_memory.unwrap_or_else(|| Arc::new(MemoryKvBackend::new()));
|
||||
@@ -852,6 +869,39 @@ pub struct DdlManagerConfigureContext {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_configured_user_provider_requires_registered_provider() {
|
||||
let options = MetasrvOptions {
|
||||
user_provider: Some("static_user_provider:cmd:user=secret".to_string().into()),
|
||||
..Default::default()
|
||||
};
|
||||
for builder in [
|
||||
MetasrvBuilder::new(),
|
||||
MetasrvBuilder::new().plugins(Plugins::new()),
|
||||
] {
|
||||
let result = builder.options(options.clone()).build().await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(error::Error::InvalidArguments { err_msg, .. })
|
||||
if err_msg == "No metasrv user provider registered for the configured user_provider"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_user_provider_requires_permission_checker() {
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<auth::UserProviderRef>(
|
||||
auth::user_provider_from_option("static_user_provider:cmd:user=secret").unwrap(),
|
||||
);
|
||||
let result = MetasrvBuilder::new().plugins(plugins).build().await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(error::Error::InvalidArguments { err_msg, .. })
|
||||
if err_msg == "A metasrv user provider requires a permission checker"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_migration_factory_is_resolved_during_construction() {
|
||||
use crate::procedure::region_migration::test_util::TestRegionFollowerMigrationProcedureFactory;
|
||||
|
||||
@@ -28,7 +28,9 @@ use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use axum::{Router as AxumRouter, routing};
|
||||
use auth::{DefaultPermissionChecker, PermissionCheckerRef, UserProviderRef};
|
||||
use axum::{Router as AxumRouter, middleware, routing};
|
||||
use servers::http::authorize::{AuthState, check_admin_auth, inner_admin_auth};
|
||||
use tonic::body::Body;
|
||||
use tonic::codegen::{BoxFuture, Service, http};
|
||||
use tonic::server::NamedService;
|
||||
@@ -95,7 +97,14 @@ pub fn make_admin_service(metasrv: Arc<Metasrv>) -> Admin {
|
||||
);
|
||||
let router = Router::nest("/admin", router);
|
||||
|
||||
Admin::new(router)
|
||||
Admin {
|
||||
router: Arc::new(router),
|
||||
user_provider: metasrv.plugins().get::<UserProviderRef>(),
|
||||
permission_checker: metasrv
|
||||
.plugins()
|
||||
.get::<PermissionCheckerRef>()
|
||||
.unwrap_or_else(DefaultPermissionChecker::arc),
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -114,12 +123,16 @@ where
|
||||
Self: Send,
|
||||
{
|
||||
router: Arc<Router>,
|
||||
user_provider: Option<UserProviderRef>,
|
||||
permission_checker: PermissionCheckerRef,
|
||||
}
|
||||
|
||||
impl Admin {
|
||||
pub fn new(router: Router) -> Self {
|
||||
Self {
|
||||
router: Arc::new(router),
|
||||
user_provider: None,
|
||||
permission_checker: DefaultPermissionChecker::arc(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,18 +152,32 @@ impl Service<http::Request<Body>> for Admin {
|
||||
|
||||
fn call(&mut self, req: http::Request<Body>) -> Self::Future {
|
||||
let router = self.router.clone();
|
||||
let query_params = req
|
||||
.uri()
|
||||
.query()
|
||||
.map(|q| {
|
||||
url::form_urlencoded::parse(q.as_bytes())
|
||||
.into_owned()
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let path = req.uri().path().to_owned();
|
||||
let method = req.method().clone();
|
||||
Box::pin(async move { router.call(&path, method, query_params).await })
|
||||
let user_provider = self.user_provider.clone();
|
||||
let permission_checker = self.permission_checker.clone();
|
||||
Box::pin(async move {
|
||||
if !router.handlers.contains_key(req.uri().path()) {
|
||||
return Ok(http::Response::builder()
|
||||
.status(http::StatusCode::NOT_FOUND)
|
||||
.body(Body::empty())
|
||||
.unwrap());
|
||||
}
|
||||
let req = match inner_admin_auth(user_provider, permission_checker, req).await {
|
||||
Ok(req) => req,
|
||||
Err(resp) => return Ok(resp.map(Body::new)),
|
||||
};
|
||||
let query_params = req
|
||||
.uri()
|
||||
.query()
|
||||
.map(|q| {
|
||||
url::form_urlencoded::parse(q.as_bytes())
|
||||
.into_owned()
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
router
|
||||
.call(req.uri().path(), req.method().clone(), query_params)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +259,13 @@ fn check_path(path: &str) {
|
||||
|
||||
/// Expose admin HTTP endpoints as an Axum router for the main HTTP server.
|
||||
pub fn admin_axum_router(metasrv: Arc<Metasrv>) -> AxumRouter {
|
||||
let auth_state = AuthState::new(metasrv.plugins().get::<UserProviderRef>())
|
||||
.with_permission_checker(metasrv.plugins().get::<PermissionCheckerRef>());
|
||||
builtin_admin_router(metasrv)
|
||||
.route_layer(middleware::from_fn_with_state(auth_state, check_admin_auth))
|
||||
}
|
||||
|
||||
pub(crate) fn builtin_admin_router(metasrv: Arc<Metasrv>) -> AxumRouter {
|
||||
let node_lease_handler = NodeLeaseHandler {
|
||||
meta_peer_client: metasrv.meta_peer_client().clone(),
|
||||
};
|
||||
@@ -678,6 +712,177 @@ mod axum_admin_tests {
|
||||
use crate::metasrv::builder::MetasrvBuilder;
|
||||
use crate::service::admin::sequencer::NextTableIdResponse;
|
||||
|
||||
struct RejectAdminChecker {
|
||||
error: Option<StatusCode>,
|
||||
}
|
||||
|
||||
impl auth::PermissionChecker for RejectAdminChecker {
|
||||
fn check_permission(
|
||||
&self,
|
||||
_: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
assert!(matches!(
|
||||
req,
|
||||
auth::PermissionReq::Action(auth::METASRV_ADMIN)
|
||||
));
|
||||
match self.error {
|
||||
None => Ok(auth::PermissionResp::Reject),
|
||||
Some(StatusCode::FORBIDDEN) => auth::error::PermissionDeniedSnafu.fail(),
|
||||
Some(StatusCode::INTERNAL_SERVER_ERROR) => auth::error::InternalStateSnafu {
|
||||
msg: "checker unavailable",
|
||||
}
|
||||
.fail(),
|
||||
Some(other) => panic!("unexpected test status {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
_: auth::UserInfoRef,
|
||||
_: auth::PermissionReq,
|
||||
_: auth::PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
panic!("Cluster administration has no table targets")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_admin_auth_on_both_listeners() {
|
||||
for configured in [false, true] {
|
||||
for (legacy, checker_mode) in [
|
||||
(false, 0),
|
||||
(true, 0),
|
||||
(false, 1),
|
||||
(true, 1),
|
||||
(false, 2),
|
||||
(true, 2),
|
||||
(false, 3),
|
||||
(true, 3),
|
||||
] {
|
||||
let plugins = common_base::Plugins::new();
|
||||
if configured {
|
||||
plugins.insert::<UserProviderRef>(auth::user_provider_from_option(
|
||||
"static_user_provider:cmd:root=secret,reader:ro=secret,writer:rw=secret,ingest:wo=secret",
|
||||
).unwrap());
|
||||
}
|
||||
if checker_mode != 0 {
|
||||
plugins.insert::<PermissionCheckerRef>(Arc::new(RejectAdminChecker {
|
||||
error: match checker_mode {
|
||||
2 => Some(StatusCode::FORBIDDEN),
|
||||
3 => Some(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
_ => None,
|
||||
},
|
||||
}));
|
||||
} else if configured {
|
||||
plugins.insert::<PermissionCheckerRef>(DefaultPermissionChecker::arc());
|
||||
}
|
||||
let metasrv = Arc::new(
|
||||
MetasrvBuilder::new()
|
||||
.options(MetasrvOptions::default())
|
||||
.kv_backend(Arc::new(MemoryKvBackend::new()))
|
||||
.plugins(plugins)
|
||||
.build()
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
let expected_status = |status| match (configured, checker_mode, status) {
|
||||
(false, _, _) => StatusCode::OK,
|
||||
(_, _, StatusCode::UNAUTHORIZED) => StatusCode::UNAUTHORIZED,
|
||||
(_, 0, _) => status,
|
||||
(_, 3, _) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
_ => StatusCode::FORBIDDEN,
|
||||
};
|
||||
for (header, authenticated_status) in [
|
||||
(None, StatusCode::UNAUTHORIZED),
|
||||
(Some("Basic cm9vdDpiYWQ="), StatusCode::UNAUTHORIZED),
|
||||
(Some("Basic cmVhZGVyOnNlY3JldA=="), StatusCode::FORBIDDEN),
|
||||
(Some("Basic d3JpdGVyOnNlY3JldA=="), StatusCode::OK),
|
||||
(Some("Basic aW5nZXN0OnNlY3JldA=="), StatusCode::OK),
|
||||
(Some("Basic cm9vdDpzZWNyZXQ="), StatusCode::OK),
|
||||
] {
|
||||
metasrv
|
||||
.runtime_switch_manager()
|
||||
.unset_maintenance_mode()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut request = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/admin/maintenance/enable");
|
||||
if let Some(header) = header {
|
||||
request = request.header("Authorization", header);
|
||||
}
|
||||
let status = if legacy {
|
||||
make_admin_service(metasrv.clone())
|
||||
.oneshot(request.body(tonic::body::Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
} else {
|
||||
admin_axum_router(metasrv.clone())
|
||||
.oneshot(request.body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
};
|
||||
let expected = expected_status(authenticated_status);
|
||||
assert_eq!(status, expected, "configured={configured}, legacy={legacy}");
|
||||
assert_eq!(
|
||||
metasrv
|
||||
.runtime_switch_manager()
|
||||
.maintenance_mode()
|
||||
.await
|
||||
.unwrap(),
|
||||
expected == StatusCode::OK,
|
||||
);
|
||||
}
|
||||
let unknown = Request::builder().uri("/admin/unknown");
|
||||
let status = if legacy {
|
||||
make_admin_service(metasrv.clone())
|
||||
.oneshot(unknown.body(tonic::body::Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
} else {
|
||||
admin_axum_router(metasrv.clone())
|
||||
.oneshot(unknown.body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
};
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
if configured {
|
||||
// Health is not an implicit exception to the admin policy.
|
||||
for (header, expected) in [
|
||||
(None, StatusCode::UNAUTHORIZED),
|
||||
(Some("Basic cmVhZGVyOnNlY3JldA=="), StatusCode::FORBIDDEN),
|
||||
(Some("Basic d3JpdGVyOnNlY3JldA=="), StatusCode::OK),
|
||||
] {
|
||||
let mut request = Request::builder().uri("/admin/health");
|
||||
if let Some(header) = header {
|
||||
request = request.header("Authorization", header);
|
||||
}
|
||||
let status = if legacy {
|
||||
make_admin_service(metasrv.clone())
|
||||
.oneshot(request.body(tonic::body::Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
} else {
|
||||
admin_axum_router(metasrv.clone())
|
||||
.oneshot(request.body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
};
|
||||
assert_eq!(status, expected_status(expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn setup_axum_app() -> AxumRouter {
|
||||
let kv_backend = Arc::new(MemoryKvBackend::new());
|
||||
let metasrv = MetasrvBuilder::new()
|
||||
|
||||
@@ -25,3 +25,6 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
snafu.workspace = true
|
||||
standalone.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio.workspace = true
|
||||
|
||||
@@ -12,11 +12,15 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use auth::{DefaultPermissionChecker, PermissionCheckerRef, UserProviderRef};
|
||||
use common_base::Plugins;
|
||||
use common_base::secrets::ExposeSecret;
|
||||
use common_error::ext::BoxedError;
|
||||
use meta_srv::bootstrap::MetasrvInstance;
|
||||
use meta_srv::error::Result;
|
||||
use meta_srv::error::{OtherSnafu, Result};
|
||||
use meta_srv::metasrv::MetasrvOptions;
|
||||
use meta_srv::metasrv::builder::MetasrvBuilder;
|
||||
use snafu::ResultExt;
|
||||
|
||||
use crate::options::PluginOptions;
|
||||
|
||||
@@ -28,8 +32,15 @@ use crate::options::PluginOptions;
|
||||
pub async fn setup_metasrv_plugins_pre_build(
|
||||
plugins: &mut Plugins,
|
||||
plugin_options: &[PluginOptions],
|
||||
_metasrv_opts: &MetasrvOptions,
|
||||
metasrv_opts: &MetasrvOptions,
|
||||
) -> Result<()> {
|
||||
if let Some(option) = &metasrv_opts.user_provider {
|
||||
let provider = auth::user_provider_from_option(option.expose_secret())
|
||||
.map_err(BoxedError::new)
|
||||
.context(OtherSnafu)?;
|
||||
plugins.insert::<UserProviderRef>(provider);
|
||||
plugins.insert::<PermissionCheckerRef>(DefaultPermissionChecker::arc());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -51,3 +62,43 @@ pub async fn setup_metasrv_plugins_post_build(
|
||||
pub async fn start_metasrv_plugins(_instance: &MetasrvInstance) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_admin_provider_registration() {
|
||||
let mut plugins = Plugins::new();
|
||||
let mut opts = MetasrvOptions::default();
|
||||
setup_metasrv_plugins_pre_build(&mut plugins, &[], &opts)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(plugins.get::<UserProviderRef>().is_none());
|
||||
opts.user_provider = Some(
|
||||
"static_user_provider:cmd:operator:ro=secret"
|
||||
.to_string()
|
||||
.into(),
|
||||
);
|
||||
setup_metasrv_plugins_pre_build(&mut plugins, &[], &opts)
|
||||
.await
|
||||
.unwrap();
|
||||
let user = plugins
|
||||
.get::<UserProviderRef>()
|
||||
.unwrap()
|
||||
.authenticate(
|
||||
auth::Identity::UserId("operator", None),
|
||||
auth::Password::PlainText("secret".to_string().into()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
plugins
|
||||
.get::<PermissionCheckerRef>()
|
||||
.unwrap()
|
||||
.check_permission(user, auth::PermissionReq::Action(auth::METASRV_ADMIN))
|
||||
.unwrap(),
|
||||
auth::PermissionResp::Reject
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,8 @@ provided through handler traits, mostly implemented by `frontend`.
|
||||
- gRPC wire changes start in `greptime-proto`; update builders and handlers here
|
||||
after bumping it.
|
||||
- Auth or `QueryContext` changes must cover HTTP, gRPC, MySQL, and PostgreSQL
|
||||
entry points.
|
||||
entry points. Admin HTTP authentication uses `http/authorize.rs` and requires
|
||||
the `metasrv.admin` permission action independently of database authorization.
|
||||
- A protocol handler that changes the `QueryContext` catalog or schema after
|
||||
authentication (HTTP `db` query/form parameters, MySQL `COM_INIT_DB`) calls
|
||||
`UserProvider::authorize` for the new scope before mutating the context. The
|
||||
|
||||
+54
-1
@@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex as StdMutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use auth::UserProviderRef;
|
||||
use auth::{PermissionCheckerRef, UserProviderRef};
|
||||
use axum::extract::{DefaultBodyLimit, Request, State};
|
||||
use axum::http::StatusCode as HttpStatusCode;
|
||||
use axum::middleware::Next;
|
||||
@@ -198,6 +198,7 @@ pub struct HttpServer {
|
||||
router: StdMutex<Router>,
|
||||
shutdown_tx: Mutex<Option<Sender<()>>>,
|
||||
user_provider: Option<UserProviderRef>,
|
||||
admin_checker: Option<PermissionCheckerRef>,
|
||||
memory_limiter: ServerMemoryLimiter,
|
||||
|
||||
// server configs
|
||||
@@ -656,6 +657,7 @@ pub struct HttpServerBuilder {
|
||||
batching_protocols: Vec<BatchingProtocol>,
|
||||
logical_batching_protocols: Vec<BatchingProtocol>,
|
||||
user_provider: Option<UserProviderRef>,
|
||||
admin_checker: Option<PermissionCheckerRef>,
|
||||
router: Router,
|
||||
memory_limiter: ServerMemoryLimiter,
|
||||
}
|
||||
@@ -667,6 +669,7 @@ impl HttpServerBuilder {
|
||||
batching_protocols: Vec::new(),
|
||||
logical_batching_protocols: Vec::new(),
|
||||
user_provider: None,
|
||||
admin_checker: None,
|
||||
router: Router::new(),
|
||||
memory_limiter: ServerMemoryLimiter::default(),
|
||||
}
|
||||
@@ -880,6 +883,12 @@ impl HttpServerBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the metasrv admin policy to matched routes in the admin namespace.
|
||||
pub fn with_admin_checker(mut self, checker: PermissionCheckerRef) -> Self {
|
||||
self.admin_checker = Some(checker);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_extra_router(self, router: Router) -> Self {
|
||||
Self {
|
||||
router: self.router.merge(router),
|
||||
@@ -907,6 +916,7 @@ impl HttpServerBuilder {
|
||||
batching_protocols: self.batching_protocols.clone(),
|
||||
logical_batching_protocols: self.logical_batching_protocols.clone(),
|
||||
user_provider: self.user_provider,
|
||||
admin_checker: self.admin_checker,
|
||||
shutdown_tx: Mutex::new(None),
|
||||
router: StdMutex::new(self.router),
|
||||
bind_addr: None,
|
||||
@@ -942,6 +952,7 @@ impl HttpServerBuilder {
|
||||
batching_protocols: self.batching_protocols.clone(),
|
||||
logical_batching_protocols: self.logical_batching_protocols.clone(),
|
||||
user_provider: self.user_provider.clone(),
|
||||
admin_checker: self.admin_checker.clone(),
|
||||
shutdown_tx: Mutex::new(None),
|
||||
router: StdMutex::new(self.router.clone()),
|
||||
bind_addr: None,
|
||||
@@ -961,6 +972,7 @@ impl HttpServerBuilder {
|
||||
batching_protocols: self.batching_protocols,
|
||||
logical_batching_protocols: self.logical_batching_protocols,
|
||||
user_provider: self.user_provider.clone(),
|
||||
admin_checker: self.admin_checker.clone(),
|
||||
shutdown_tx: Mutex::new(None),
|
||||
router: StdMutex::new(self.router),
|
||||
bind_addr: None,
|
||||
@@ -1041,6 +1053,15 @@ impl HttpServer {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(checker) = &self.admin_checker {
|
||||
let state = AuthState::new(self.user_provider.clone())
|
||||
.with_permission_checker(Some(checker.clone()));
|
||||
router = router.route_layer(middleware::from_fn_with_state(
|
||||
state,
|
||||
authorize::check_admin_auth,
|
||||
));
|
||||
}
|
||||
|
||||
// Add a layer to collect HTTP metrics for axum.
|
||||
router = router.route_layer(middleware::from_fn(http_metrics_layer));
|
||||
|
||||
@@ -2067,6 +2088,38 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_auth_is_independent_of_debug_database_access() {
|
||||
let provider = auth::tests::MockUserProvider {
|
||||
schema: "operations".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
let server = HttpServerBuilder::new(HttpOptions::default())
|
||||
.with_user_provider(Arc::new(provider))
|
||||
.with_admin_checker(auth::DefaultPermissionChecker::arc())
|
||||
.with_extra_router(
|
||||
Router::new().route("/admin/plugin", routing::get(|| async { StatusCode::OK })),
|
||||
)
|
||||
.build();
|
||||
let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
|
||||
for (path, expected) in [
|
||||
("/admin/plugin", StatusCode::OK),
|
||||
("/debug/workload_scheduler", StatusCode::UNAUTHORIZED),
|
||||
("/debug/workload_scheduler?db=operations", StatusCode::OK),
|
||||
] {
|
||||
assert_eq!(
|
||||
client
|
||||
.get(path)
|
||||
.header("Authorization", "Basic Z3JlcHRpbWU6Z3JlcHRpbWU=")
|
||||
.send()
|
||||
.await
|
||||
.status(),
|
||||
expected,
|
||||
"{path}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packed_capability_requires_auth_on_full_and_api_listeners() {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use ::auth::{AuthMethod, UserProviderRef};
|
||||
use ::auth::{
|
||||
AuthMethod, DefaultPermissionChecker, METASRV_ADMIN, PermissionCheckerRef, PermissionReq,
|
||||
PermissionResp, UserProviderRef,
|
||||
};
|
||||
use api::v1::Basic;
|
||||
use axum::Json;
|
||||
use axum::extract::{Request, State};
|
||||
@@ -49,11 +52,23 @@ use crate::influxdb::{is_influxdb_request, is_influxdb_v2_request};
|
||||
#[derive(Clone)]
|
||||
pub struct AuthState {
|
||||
user_provider: Option<UserProviderRef>,
|
||||
permission_checker: PermissionCheckerRef,
|
||||
}
|
||||
|
||||
impl AuthState {
|
||||
pub fn new(user_provider: Option<UserProviderRef>) -> Self {
|
||||
Self { user_provider }
|
||||
Self {
|
||||
user_provider,
|
||||
permission_checker: DefaultPermissionChecker::arc(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses the registered checker for administration requests.
|
||||
pub fn with_permission_checker(mut self, checker: Option<PermissionCheckerRef>) -> Self {
|
||||
if let Some(checker) = checker {
|
||||
self.permission_checker = checker;
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +236,89 @@ pub async fn check_http_auth(
|
||||
}
|
||||
}
|
||||
|
||||
/// Authenticates a cluster administration request independently of database access.
|
||||
/// No provider preserves the unauthenticated deployment mode.
|
||||
pub async fn inner_admin_auth<B>(
|
||||
user_provider: Option<UserProviderRef>,
|
||||
permission_checker: PermissionCheckerRef,
|
||||
mut req: Request<B>,
|
||||
) -> std::result::Result<Request<B>, Response> {
|
||||
let Some(provider) = user_provider else {
|
||||
return Ok(req);
|
||||
};
|
||||
let user = if let Some(token) = extract_bearer_token(&req) {
|
||||
// Admin operations have no database target. Never let a caller-selected
|
||||
// catalog change the identity used for cluster administration.
|
||||
provider
|
||||
.authenticate_bearer_token(token, common_catalog::consts::DEFAULT_CATALOG_NAME)
|
||||
.await
|
||||
} else {
|
||||
let (username, password) = match auth_header(&req) {
|
||||
Ok(AuthScheme::Basic(username, password)) => (username, password),
|
||||
Err(err) => return Err(admin_auth_failure(err)),
|
||||
};
|
||||
provider
|
||||
.authenticate(
|
||||
auth::Identity::UserId(&username, None),
|
||||
auth::Password::PlainText(password),
|
||||
)
|
||||
.await
|
||||
}
|
||||
.map_err(admin_auth_failure)?;
|
||||
|
||||
if matches!(
|
||||
permission_checker
|
||||
.check_permission(user.clone(), PermissionReq::Action(METASRV_ADMIN))
|
||||
.map_err(|err| ErrorResponse::from_error(err).into_response())?,
|
||||
PermissionResp::Reject
|
||||
) {
|
||||
return Err((
|
||||
StatusCode::FORBIDDEN,
|
||||
ErrorResponse::from_error_message(
|
||||
common_error::status_code::StatusCode::PermissionDenied,
|
||||
"Permission denied for metasrv administration".to_string(),
|
||||
),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
let query_ctx = req
|
||||
.extensions()
|
||||
.get::<QueryContext>()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| QueryContextBuilder::default().build());
|
||||
query_ctx.set_current_user(user);
|
||||
req.extensions_mut().insert(query_ctx);
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
fn admin_auth_failure(err: impl ErrorExt) -> Response {
|
||||
let status = err.status_code();
|
||||
warn!("Admin authentication failed: {}", status.as_ref());
|
||||
crate::metrics::METRIC_AUTH_FAILURE
|
||||
.with_label_values(&[status.as_ref()])
|
||||
.inc();
|
||||
ErrorResponse::from_error(err).into_response()
|
||||
}
|
||||
|
||||
/// Applies the metasrv policy to matched admin routes, including plugin routes.
|
||||
pub async fn check_admin_auth(
|
||||
State(auth_state): State<AuthState>,
|
||||
req: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let path = req
|
||||
.extensions()
|
||||
.get::<axum::extract::OriginalUri>()
|
||||
.map_or_else(|| req.uri().path(), |uri| uri.path());
|
||||
if !is_namespace(path, "/admin") {
|
||||
return next.run(req).await;
|
||||
}
|
||||
match inner_admin_auth(auth_state.user_provider, auth_state.permission_checker, req).await {
|
||||
Ok(req) => next.run(req).await,
|
||||
Err(resp) => resp,
|
||||
}
|
||||
}
|
||||
|
||||
/// HEC-shaped auth error (`{"text","code"}`) so Splunk clients can branch on `code`.
|
||||
fn splunk_hec_err(status: StatusCode, code: u32) -> Response {
|
||||
let text = match code {
|
||||
@@ -532,6 +630,138 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
struct AdminTokenProvider {
|
||||
user: auth::UserInfoRef,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl auth::UserProvider for AdminTokenProvider {
|
||||
fn name(&self) -> &str {
|
||||
"admin-token-test"
|
||||
}
|
||||
|
||||
async fn authenticate(
|
||||
&self,
|
||||
_: auth::Identity<'_>,
|
||||
_: auth::Password<'_>,
|
||||
) -> auth::error::Result<auth::UserInfoRef> {
|
||||
unreachable!("Bearer requests must not use password authentication")
|
||||
}
|
||||
|
||||
async fn authorize(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &str,
|
||||
_: &auth::UserInfoRef,
|
||||
) -> auth::error::Result<()> {
|
||||
unreachable!("Cluster administration must not use database authorization")
|
||||
}
|
||||
|
||||
async fn authenticate_bearer_token(
|
||||
&self,
|
||||
token: &str,
|
||||
catalog: &str,
|
||||
) -> auth::error::Result<auth::UserInfoRef> {
|
||||
assert_eq!(catalog, common_catalog::consts::DEFAULT_CATALOG_NAME);
|
||||
if token == "valid" {
|
||||
Ok(self.user.clone())
|
||||
} else if token == "backend-error" {
|
||||
auth::error::InternalStateSnafu {
|
||||
msg: "provider unavailable",
|
||||
}
|
||||
.fail()
|
||||
} else {
|
||||
auth::error::UnsupportedAuthMethodSnafu {
|
||||
method: "invalid test token",
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_admin_bearer_identity_and_privileges() {
|
||||
for writable in [false, true] {
|
||||
let option = if writable {
|
||||
"static_user_provider:cmd:user:rw=secret"
|
||||
} else {
|
||||
"static_user_provider:cmd:user:ro=secret"
|
||||
};
|
||||
let user = auth::user_provider_from_option(option)
|
||||
.unwrap()
|
||||
.authenticate(
|
||||
auth::Identity::UserId("user", None),
|
||||
auth::Password::PlainText("secret".to_string().into()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for header in [http::header::AUTHORIZATION.as_str(), AUTHORIZATION_HEADER] {
|
||||
for token in ["valid", "invalid", "backend-error"] {
|
||||
let req = Request::builder()
|
||||
.uri("/admin/maintenance/enable?db=untrusted")
|
||||
.header(header, format!("Bearer {token}"))
|
||||
.header(GreptimeDbName::name(), "untrusted")
|
||||
.body(())
|
||||
.unwrap();
|
||||
let provider: UserProviderRef =
|
||||
std::sync::Arc::new(AdminTokenProvider { user: user.clone() });
|
||||
let result =
|
||||
inner_admin_auth(Some(provider), DefaultPermissionChecker::arc(), req)
|
||||
.await;
|
||||
if token == "backend-error" {
|
||||
assert_eq!(
|
||||
result.unwrap_err().status(),
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
);
|
||||
} else if token != "valid" {
|
||||
assert_eq!(result.unwrap_err().status(), StatusCode::UNAUTHORIZED);
|
||||
} else if !writable {
|
||||
assert_eq!(result.unwrap_err().status(), StatusCode::FORBIDDEN);
|
||||
} else {
|
||||
let req = result.unwrap();
|
||||
assert_eq!(
|
||||
req.extensions()
|
||||
.get::<QueryContext>()
|
||||
.unwrap()
|
||||
.current_user()
|
||||
.username(),
|
||||
"user"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_admin_auth_failure_metrics() {
|
||||
use common_error::status_code::StatusCode as ErrorCode;
|
||||
|
||||
let provider =
|
||||
auth::user_provider_from_option("static_user_provider:cmd:user=secret").unwrap();
|
||||
for (header, code) in [
|
||||
("Basic dXNlcjpiYWQ=", ErrorCode::UserPasswordMismatch),
|
||||
("Basic YWJj", ErrorCode::InvalidAuthHeader),
|
||||
("Bearer invalid", ErrorCode::UserPasswordMismatch),
|
||||
] {
|
||||
let counter = crate::metrics::METRIC_AUTH_FAILURE.with_label_values(&[code.as_ref()]);
|
||||
let before = counter.get();
|
||||
let request = Request::builder()
|
||||
.header(http::header::AUTHORIZATION, header)
|
||||
.body(())
|
||||
.unwrap();
|
||||
let response = inner_admin_auth(
|
||||
Some(provider.clone()),
|
||||
DefaultPermissionChecker::arc(),
|
||||
request,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
assert!(counter.get() > before, "missing auth failure for {code:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_need_auth() {
|
||||
let req = Request::builder()
|
||||
|
||||
@@ -73,6 +73,11 @@ impl TestClient {
|
||||
axum::serve(listener, svc).await.expect("server error");
|
||||
});
|
||||
|
||||
Self::from_addr(addr)
|
||||
}
|
||||
|
||||
/// Connects to a running HTTP server.
|
||||
pub fn from_addr(addr: SocketAddr) -> Self {
|
||||
let client = reqwest::Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
|
||||
@@ -45,6 +45,7 @@ use common_frontend::slow_query_event::{
|
||||
SLOW_QUERY_TABLE_NAME, SLOW_QUERY_TABLE_QUERY_COLUMN_NAME,
|
||||
};
|
||||
use common_memory_manager::OnExhaustedPolicy;
|
||||
use common_meta::kv_backend::memory::MemoryKvBackend;
|
||||
use common_options::plugin_options::StandaloneFlag;
|
||||
use common_query::prelude::{GREPTIME_TEMPORALITY_DELTA, OTLP_AGGREGATION_TEMPORALITY_LABEL};
|
||||
use datafusion::common::{DFSchema, ToDFSchema};
|
||||
@@ -64,6 +65,9 @@ use futures::TryStreamExt;
|
||||
use log_query::{AggFunc, Context, Limit, LogExpr, LogQuery, TimeFilter};
|
||||
use loki_proto::logproto::{EntryAdapter, LabelPairAdapter, PushRequest, StreamAdapter};
|
||||
use loki_proto::prost_types::Timestamp;
|
||||
use meta_srv::bootstrap::MetasrvInstance;
|
||||
use meta_srv::metasrv::MetasrvOptions;
|
||||
use meta_srv::metasrv::builder::MetasrvBuilder;
|
||||
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
|
||||
use opentelemetry_proto::tonic::collector::metrics::v1::{
|
||||
ExportMetricsServiceRequest, ExportMetricsServiceResponse,
|
||||
@@ -491,6 +495,115 @@ pub async fn test_http_auth_from_standalone_user_provider_config() {
|
||||
guard.remove_all().await;
|
||||
}
|
||||
|
||||
pub async fn test_metasrv_admin_http_auth_from_config() {
|
||||
use servers::http::{ExtraHttpRouterProvider, ExtraHttpRouterProviders};
|
||||
use servers::server::Server;
|
||||
|
||||
struct PluginRoutes;
|
||||
impl ExtraHttpRouterProvider for PluginRoutes {
|
||||
fn router(&self) -> axum::Router {
|
||||
axum::Router::new().nest(
|
||||
"/admin",
|
||||
axum::Router::new()
|
||||
.route("/plugin", axum::routing::get(|| async { StatusCode::OK })),
|
||||
)
|
||||
}
|
||||
}
|
||||
common_telemetry::init_default_ut_logging();
|
||||
|
||||
for configured in [false, true] {
|
||||
let config = tempfile::NamedTempFile::new().unwrap();
|
||||
let contents = if configured {
|
||||
r#"user_provider = "static_user_provider:cmd:default=secret,reader:ro=secret,writer:rw=secret,ingest:wo=secret""#
|
||||
} else {
|
||||
""
|
||||
};
|
||||
std::fs::write(config.path(), contents).unwrap();
|
||||
let mut options =
|
||||
GreptimeOptions::<MetasrvOptions>::load_layered_options(config.path().to_str(), "")
|
||||
.unwrap();
|
||||
options.component.http.addr = "127.0.0.1:0".into();
|
||||
options.component.grpc.bind_addr = "127.0.0.1:0".into();
|
||||
options.component.enable_telemetry = false;
|
||||
let mut plugins = Plugins::new();
|
||||
plugins::setup_metasrv_plugins_pre_build(
|
||||
&mut plugins,
|
||||
&options.plugins,
|
||||
&options.component,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let builder = MetasrvBuilder::new()
|
||||
.options(options.component)
|
||||
.kv_backend(Arc::new(MemoryKvBackend::new()));
|
||||
plugins::setup_metasrv_plugins_post_build(&mut plugins, &options.plugins, &builder)
|
||||
.await
|
||||
.unwrap();
|
||||
let metasrv = builder.plugins(plugins).build().await.unwrap();
|
||||
let manager = metasrv.runtime_switch_manager().clone();
|
||||
let mut instance = MetasrvInstance::new(metasrv).await.unwrap();
|
||||
let mut providers = ExtraHttpRouterProviders::new();
|
||||
providers.add(Arc::new(PluginRoutes));
|
||||
instance.plugins().insert(providers);
|
||||
instance.start().await.unwrap();
|
||||
let server = instance.http_server().unwrap();
|
||||
let client = TestClient::from_addr(server.bind_addr().unwrap());
|
||||
|
||||
for (credentials, authenticated_status) in [
|
||||
(None, StatusCode::UNAUTHORIZED),
|
||||
(Some(("writer", "wrong")), StatusCode::UNAUTHORIZED),
|
||||
(Some(("reader", "secret")), StatusCode::FORBIDDEN),
|
||||
(Some(("default", "secret")), StatusCode::OK),
|
||||
(Some(("writer", "secret")), StatusCode::OK),
|
||||
(Some(("ingest", "secret")), StatusCode::OK),
|
||||
] {
|
||||
let expected = if configured {
|
||||
authenticated_status
|
||||
} else {
|
||||
StatusCode::OK
|
||||
};
|
||||
manager.unset_maintenance_mode().await.unwrap();
|
||||
let mut request = client.post("/admin/maintenance/enable");
|
||||
if let Some((username, password)) = credentials {
|
||||
request = request.header("Authorization", basic_auth(username, password));
|
||||
}
|
||||
let response = request.send().await;
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
expected,
|
||||
"configured={configured}, credentials={credentials:?}"
|
||||
);
|
||||
let enabled = expected == StatusCode::OK;
|
||||
assert_eq!(manager.maintenance_mode().await.unwrap(), enabled);
|
||||
if enabled {
|
||||
assert_eq!(response.json::<Value>().await, json!({"enabled": true}));
|
||||
}
|
||||
|
||||
for path in ["/admin/health", "/admin/plugin"] {
|
||||
let mut request = client.get(path);
|
||||
if let Some((username, password)) = credentials {
|
||||
request = request.header("Authorization", basic_auth(username, password));
|
||||
}
|
||||
assert_eq!(request.send().await.status(), expected);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
client
|
||||
.get("/debug/workload_scheduler")
|
||||
.header("Authorization", basic_auth("reader", "secret"))
|
||||
.send()
|
||||
.await
|
||||
.status(),
|
||||
StatusCode::OK
|
||||
);
|
||||
assert_eq!(
|
||||
client.get("/admin/unknown").send().await.status(),
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
instance.shutdown().await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
pub async fn test_cors() {
|
||||
let (app, mut guard) = setup_test_http_app_with_frontend(StorageType::File, "test_cors").await;
|
||||
|
||||
@@ -76,6 +76,11 @@ async fn test_http_auth_from_standalone_user_provider_config() {
|
||||
http::test_http_auth_from_standalone_user_provider_config().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_metasrv_admin_http_auth_from_config() {
|
||||
http::test_metasrv_admin_http_auth_from_config().await;
|
||||
}
|
||||
|
||||
sql_tests!(File);
|
||||
|
||||
region_migration_tests!(File);
|
||||
|
||||
Reference in New Issue
Block a user