diff --git a/Cargo.lock b/Cargo.lock
index b644c9077ca..8fcec39a0ca 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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]]
diff --git a/config/config.md b/config/config.md
index 713286afc2a..3e5f81c95e2 100644
--- a/config/config.md
+++ b/config/config.md
@@ -458,6 +458,7 @@
| Key | Type | Default | Descriptions |
| --- | -----| ------- | ----------- |
+| `user_provider` | String | Unset | 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. |
| `data_home` | String | `./greptimedb_data` | The working home directory. |
| `store_addrs` | Array | -- | Store server address(es). The format depends on the selected backend.
For etcd: a list of "host:port" endpoints. e.g. ["192.168.1.1:2379", "192.168.1.2:2379"]
For PostgreSQL: a connection string in libpq format or URI. e.g. - "host=localhost port=5432 user=postgres password= dbname=postgres" - "postgresql://user:password@localhost:5432/mydb?connect_timeout=10" The detail see: https://docs.rs/tokio-postgres/latest/tokio_postgres/config/struct.Config.html
For mysql store, the format is a MySQL connection URL. 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. |
diff --git a/config/metasrv.example.toml b/config/metasrv.example.toml
index 3508a0e1e8c..8f0b6ad757d 100644
--- a/config/metasrv.example.toml
+++ b/config/metasrv.example.toml
@@ -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"
diff --git a/src/auth/src/lib.rs b/src/auth/src/lib.rs
index 4bc1a4eb324..0bfe100afb7 100644
--- a/src/auth/src/lib.rs
+++ b/src/auth/src/lib.rs
@@ -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,
diff --git a/src/auth/src/permission.rs b/src/auth/src/permission.rs
index 04d9ab88ff4..699f81a7f5e 100644
--- a/src/auth/src/permission.rs
+++ b/src/auth/src/permission.rs
@@ -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,
diff --git a/src/cmd/src/metasrv.rs b/src/cmd/src/metasrv.rs
index 7df4b92ab00..983a2d27ad1 100644
--- a/src/cmd/src/metasrv.rs
+++ b/src/cmd/src/metasrv.rs
@@ -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,
#[clap(long)]
http_timeout: Option,
+ /// User provider for admin authentication; authenticated users must have permission for admin operations.
+ #[clap(long)]
+ user_provider: Option,
#[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 {
diff --git a/src/meta-srv/AGENTS.md b/src/meta-srv/AGENTS.md
index d9989534d01..e586d6d18c3 100644
--- a/src/meta-srv/AGENTS.md
+++ b/src/meta-srv/AGENTS.md
@@ -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
diff --git a/src/meta-srv/Cargo.toml b/src/meta-srv/Cargo.toml
index fa339d76774..1344430384e 100644
--- a/src/meta-srv/Cargo.toml
+++ b/src/meta-srv/Cargo.toml
@@ -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
diff --git a/src/meta-srv/src/bootstrap.rs b/src/meta-srv/src/bootstrap.rs
index 3be37c1a436..30f15945d56 100644
--- a/src/meta-srv/src/bootstrap.rs
+++ b/src/meta-srv/src/bootstrap.rs
@@ -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::() {
+ let checker = plugins
+ .get::()
+ .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::>(metasrv.clone());
diff --git a/src/meta-srv/src/metasrv.rs b/src/meta-srv/src/metasrv.rs
index 0337793453f..616c58e68bb 100644
--- a/src/meta-srv/src/metasrv.rs
+++ b/src/meta-srv/src/metasrv.rs
@@ -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,
/// 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";
diff --git a/src/meta-srv/src/metasrv/builder.rs b/src/meta-srv/src/metasrv/builder.rs
index 7aac89a4a13..ca161819fa1 100644
--- a/src/meta-srv/src/metasrv/builder.rs
+++ b/src/meta-srv/src/metasrv/builder.rs
@@ -232,6 +232,23 @@ impl MetasrvBuilder {
let options = options.unwrap_or_default();
options.gc.validate()?;
+ if let Some(plugins) = &plugins
+ && plugins.get::().is_some()
+ {
+ ensure!(
+ plugins.get::().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::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;
diff --git a/src/meta-srv/src/service/admin.rs b/src/meta-srv/src/service/admin.rs
index 17aec347364..e8db5d4c7fd 100644
--- a/src/meta-srv/src/service/admin.rs
+++ b/src/meta-srv/src/service/admin.rs
@@ -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) -> Admin {
);
let router = Router::nest("/admin", router);
- Admin::new(router)
+ Admin {
+ router: Arc::new(router),
+ user_provider: metasrv.plugins().get::(),
+ permission_checker: metasrv
+ .plugins()
+ .get::()
+ .unwrap_or_else(DefaultPermissionChecker::arc),
+ }
}
#[async_trait::async_trait]
@@ -114,12 +123,16 @@ where
Self: Send,
{
router: Arc,
+ user_provider: Option,
+ 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> for Admin {
fn call(&mut self, req: http::Request) -> 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) -> AxumRouter {
+ let auth_state = AuthState::new(metasrv.plugins().get::())
+ .with_permission_checker(metasrv.plugins().get::());
+ builtin_admin_router(metasrv)
+ .route_layer(middleware::from_fn_with_state(auth_state, check_admin_auth))
+}
+
+pub(crate) fn builtin_admin_router(metasrv: Arc) -> 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,
+ }
+
+ impl auth::PermissionChecker for RejectAdminChecker {
+ fn check_permission(
+ &self,
+ _: auth::UserInfoRef,
+ req: auth::PermissionReq,
+ ) -> auth::error::Result {
+ 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 {
+ 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::(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::(Arc::new(RejectAdminChecker {
+ error: match checker_mode {
+ 2 => Some(StatusCode::FORBIDDEN),
+ 3 => Some(StatusCode::INTERNAL_SERVER_ERROR),
+ _ => None,
+ },
+ }));
+ } else if configured {
+ plugins.insert::(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()
diff --git a/src/plugins/Cargo.toml b/src/plugins/Cargo.toml
index e26fe653b55..588fb688d89 100644
--- a/src/plugins/Cargo.toml
+++ b/src/plugins/Cargo.toml
@@ -25,3 +25,6 @@ serde.workspace = true
serde_json.workspace = true
snafu.workspace = true
standalone.workspace = true
+
+[dev-dependencies]
+tokio.workspace = true
diff --git a/src/plugins/src/meta_srv.rs b/src/plugins/src/meta_srv.rs
index a6c39aa1122..8cb1d7937fa 100644
--- a/src/plugins/src/meta_srv.rs
+++ b/src/plugins/src/meta_srv.rs
@@ -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::(provider);
+ plugins.insert::(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::().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::()
+ .unwrap()
+ .authenticate(
+ auth::Identity::UserId("operator", None),
+ auth::Password::PlainText("secret".to_string().into()),
+ )
+ .await
+ .unwrap();
+ assert!(matches!(
+ plugins
+ .get::()
+ .unwrap()
+ .check_permission(user, auth::PermissionReq::Action(auth::METASRV_ADMIN))
+ .unwrap(),
+ auth::PermissionResp::Reject
+ ));
+ }
+}
diff --git a/src/servers/AGENTS.md b/src/servers/AGENTS.md
index aaf4374f764..84fb5f417fc 100644
--- a/src/servers/AGENTS.md
+++ b/src/servers/AGENTS.md
@@ -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
diff --git a/src/servers/src/http.rs b/src/servers/src/http.rs
index e6032986a5f..7c6f2878ed4 100644
--- a/src/servers/src/http.rs
+++ b/src/servers/src/http.rs
@@ -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,
shutdown_tx: Mutex