Skip to main content

servers/http/
authorize.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use ::auth::{
16    AuthMethod, DefaultPermissionChecker, METASRV_ADMIN, PermissionCheckerRef, PermissionReq,
17    PermissionResp, UserProviderRef,
18};
19use api::v1::Basic;
20use axum::Json;
21use axum::extract::{Request, State};
22use axum::http::{self, StatusCode};
23use axum::middleware::Next;
24use axum::response::{IntoResponse, Response};
25use base64::Engine;
26use base64::prelude::BASE64_STANDARD;
27use common_base::secrets::{ExposeSecret, SecretString};
28use common_catalog::consts::DEFAULT_SCHEMA_NAME;
29use common_catalog::parse_catalog_and_schema_from_db_string;
30use common_error::ext::ErrorExt;
31use common_telemetry::warn;
32use common_time::Timezone;
33use common_time::timezone::parse_timezone;
34use headers::Header;
35use serde::Serialize;
36use session::context::{QueryContext, QueryContextBuilder};
37use snafu::{OptionExt, ResultExt, ensure};
38
39use crate::error::{
40    self, InvalidAuthHeaderInvisibleASCIISnafu, InvalidAuthHeaderSnafu, InvalidParameterSnafu,
41    NotFoundAuthHeaderSnafu, NotFoundInfluxAuthSnafu, Result, UnsupportedAuthSchemeSnafu,
42    UrlDecodeSnafu,
43};
44use crate::http::header::{GREPTIME_TIMEZONE_HEADER_NAME, GreptimeDbName};
45use crate::http::result::error_result::ErrorResponse;
46use crate::http::splunk::is_splunk_request;
47use crate::http::{AUTHORIZATION_HEADER, HTTP_API_PREFIX, PUBLIC_API_PREFIX, is_namespace};
48use crate::influxdb::{is_influxdb_request, is_influxdb_v2_request};
49
50/// AuthState is a holder state for [`UserProviderRef`]
51/// during [`check_http_auth`] function in axum's middleware
52#[derive(Clone)]
53pub struct AuthState {
54    user_provider: Option<UserProviderRef>,
55    permission_checker: PermissionCheckerRef,
56}
57
58impl AuthState {
59    pub fn new(user_provider: Option<UserProviderRef>) -> Self {
60        Self {
61            user_provider,
62            permission_checker: DefaultPermissionChecker::arc(),
63        }
64    }
65
66    /// Uses the registered checker for administration requests.
67    pub fn with_permission_checker(mut self, checker: Option<PermissionCheckerRef>) -> Self {
68        if let Some(checker) = checker {
69            self.permission_checker = checker;
70        }
71        self
72    }
73}
74
75/// Public authentication configuration used by browser clients.
76#[derive(Debug, Serialize)]
77pub(crate) struct AuthConfig {
78    auth_required: bool,
79    methods: Vec<AuthMethod>,
80}
81
82/// Returns the configured login methods without requiring authentication.
83pub(crate) async fn auth_config(State(auth_state): State<AuthState>) -> Json<AuthConfig> {
84    let (auth_required, methods) = match auth_state.user_provider {
85        Some(user_provider) => (true, user_provider.auth_methods()),
86        None => (false, Vec::new()),
87    };
88
89    Json(AuthConfig {
90        auth_required,
91        methods,
92    })
93}
94
95pub async fn inner_auth<B>(
96    user_provider: Option<UserProviderRef>,
97    mut req: Request<B>,
98) -> std::result::Result<Request<B>, Response> {
99    // 1. prepare
100    let (catalog, schema) = extract_catalog_and_schema(&req);
101    // TODO(ruihang): move this out of auth module
102    let timezone = extract_timezone(&req);
103    let query_ctx_builder = QueryContextBuilder::default()
104        .current_catalog(catalog.clone())
105        .current_schema(schema.clone())
106        .timezone(timezone);
107
108    let query_ctx = query_ctx_builder.build();
109    let need_auth = need_auth(&req);
110
111    // 2. check if auth is needed
112    let user_provider = if let Some(user_provider) = user_provider.filter(|_| need_auth) {
113        user_provider
114    } else {
115        query_ctx.set_current_user(auth::userinfo_by_name(None));
116        let _ = req.extensions_mut().insert(query_ctx);
117        return Ok(req);
118    };
119
120    // 3. bearer token auth (JWT / OAuth2). When an `Authorization: Bearer
121    //    <token>` header is present, authenticate via
122    //    [`UserProvider::auth_bearer_token`]; otherwise fall through to the
123    //    username/password path (Basic / influxdb / splunk) below.
124    if let Some(token) = extract_bearer_token(&req) {
125        match user_provider
126            .auth_bearer_token(token, &catalog, &schema)
127            .await
128        {
129            Ok(userinfo) => {
130                query_ctx.set_current_user(userinfo);
131                req.extensions_mut().insert(user_provider);
132                let _ = req.extensions_mut().insert(query_ctx);
133                return Ok(req);
134            }
135            Err(e) => {
136                warn!(e; "bearer token authentication failed");
137                crate::metrics::METRIC_AUTH_FAILURE
138                    .with_label_values(&[e.status_code().as_ref()])
139                    .inc();
140                // Splunk HEC clients expect `{"text":"Invalid token","code":4}`
141                // (FORBIDDEN), not the generic 401 `ErrorResponse`.
142                if is_splunk_request(&req) {
143                    return Err(splunk_hec_err(StatusCode::FORBIDDEN, 4));
144                }
145                return Err(err_response(e));
146            }
147        }
148    }
149
150    // 4. get username and pwd
151    let (username, password) = match extract_username_and_password(&req) {
152        Ok((username, password)) => (username, password),
153        Err(e) => {
154            warn!(e; "extract username and password failed");
155            crate::metrics::METRIC_AUTH_FAILURE
156                .with_label_values(&[e.status_code().as_ref()])
157                .inc();
158            if is_splunk_request(&req) {
159                // HEC: missing header -> 2 ("token is required"), else 4 ("invalid token").
160                let (status, code) = match &e {
161                    error::Error::NotFoundAuthHeader { .. } => (StatusCode::UNAUTHORIZED, 2),
162                    _ => (StatusCode::FORBIDDEN, 4),
163                };
164                return Err(splunk_hec_err(status, code));
165            }
166            return Err(err_response(e));
167        }
168    };
169
170    // 5. auth
171    match user_provider
172        .auth(
173            auth::Identity::UserId(&username, None),
174            auth::Password::PlainText(password),
175            &catalog,
176            &schema,
177        )
178        .await
179    {
180        Ok(userinfo) => {
181            query_ctx.set_current_user(userinfo);
182            req.extensions_mut().insert(user_provider);
183            let _ = req.extensions_mut().insert(query_ctx);
184            Ok(req)
185        }
186        Err(e) => {
187            warn!(e; "authenticate failed");
188            crate::metrics::METRIC_AUTH_FAILURE
189                .with_label_values(&[e.status_code().as_ref()])
190                .inc();
191            // HEC: bad credentials -> 4 ("invalid token", 403).
192            if is_splunk_request(&req) {
193                return Err(splunk_hec_err(StatusCode::FORBIDDEN, 4));
194            }
195            Err(err_response(e))
196        }
197    }
198}
199
200pub(crate) async fn select_database(
201    query_ctx: &mut QueryContext,
202    db: Option<&str>,
203    user_provider: Option<&UserProviderRef>,
204) -> auth::error::Result<()> {
205    let Some(db) = db else {
206        return Ok(());
207    };
208    let (catalog, schema) = parse_catalog_and_schema_from_db_string(db);
209    if catalog == query_ctx.current_catalog() && schema == query_ctx.current_schema() {
210        return Ok(());
211    }
212    // Middleware authorized the initial scope; form and query parameters can change it.
213    if let Some(provider) = user_provider
214        && let Err(error) = provider
215            .authorize(&catalog, &schema, &query_ctx.current_user())
216            .await
217    {
218        crate::metrics::METRIC_AUTH_FAILURE
219            .with_label_values(&[error.status_code().as_ref()])
220            .inc();
221        return Err(error);
222    }
223    query_ctx.set_current_catalog(&catalog);
224    query_ctx.set_current_schema(&schema);
225    Ok(())
226}
227
228pub async fn check_http_auth(
229    State(auth_state): State<AuthState>,
230    req: Request,
231    next: Next,
232) -> Response {
233    match inner_auth(auth_state.user_provider, req).await {
234        Ok(req) => next.run(req).await,
235        Err(resp) => resp,
236    }
237}
238
239/// Authenticates a cluster administration request independently of database access.
240/// No provider preserves the unauthenticated deployment mode.
241pub async fn inner_admin_auth<B>(
242    user_provider: Option<UserProviderRef>,
243    permission_checker: PermissionCheckerRef,
244    mut req: Request<B>,
245) -> std::result::Result<Request<B>, Response> {
246    let Some(provider) = user_provider else {
247        return Ok(req);
248    };
249    let user = if let Some(token) = extract_bearer_token(&req) {
250        // Admin operations have no database target. Never let a caller-selected
251        // catalog change the identity used for cluster administration.
252        provider
253            .authenticate_bearer_token(token, common_catalog::consts::DEFAULT_CATALOG_NAME)
254            .await
255    } else {
256        let (username, password) = match auth_header(&req) {
257            Ok(AuthScheme::Basic(username, password)) => (username, password),
258            Err(err) => return Err(admin_auth_failure(err)),
259        };
260        provider
261            .authenticate(
262                auth::Identity::UserId(&username, None),
263                auth::Password::PlainText(password),
264            )
265            .await
266    }
267    .map_err(admin_auth_failure)?;
268
269    if matches!(
270        permission_checker
271            .check_permission(user.clone(), PermissionReq::Action(METASRV_ADMIN))
272            .map_err(|err| ErrorResponse::from_error(err).into_response())?,
273        PermissionResp::Reject
274    ) {
275        return Err((
276            StatusCode::FORBIDDEN,
277            ErrorResponse::from_error_message(
278                common_error::status_code::StatusCode::PermissionDenied,
279                "Permission denied for metasrv administration".to_string(),
280            ),
281        )
282            .into_response());
283    }
284    let query_ctx = req
285        .extensions()
286        .get::<QueryContext>()
287        .cloned()
288        .unwrap_or_else(|| QueryContextBuilder::default().build());
289    query_ctx.set_current_user(user);
290    req.extensions_mut().insert(query_ctx);
291    Ok(req)
292}
293
294fn admin_auth_failure(err: impl ErrorExt) -> Response {
295    let status = err.status_code();
296    warn!("Admin authentication failed: {}", status.as_ref());
297    crate::metrics::METRIC_AUTH_FAILURE
298        .with_label_values(&[status.as_ref()])
299        .inc();
300    ErrorResponse::from_error(err).into_response()
301}
302
303/// Applies the metasrv policy to matched admin routes, including plugin routes.
304pub async fn check_admin_auth(
305    State(auth_state): State<AuthState>,
306    req: Request,
307    next: Next,
308) -> Response {
309    let path = req
310        .extensions()
311        .get::<axum::extract::OriginalUri>()
312        .map_or_else(|| req.uri().path(), |uri| uri.path());
313    if !is_namespace(path, "/admin") {
314        return next.run(req).await;
315    }
316    match inner_admin_auth(auth_state.user_provider, auth_state.permission_checker, req).await {
317        Ok(req) => next.run(req).await,
318        Err(resp) => resp,
319    }
320}
321
322/// HEC-shaped auth error (`{"text","code"}`) so Splunk clients can branch on `code`.
323fn splunk_hec_err(status: StatusCode, code: u32) -> Response {
324    let text = match code {
325        2 => "Token is required",
326        4 => "Invalid token",
327        _ => "Unauthorized",
328    };
329    (
330        status,
331        axum::Json(serde_json::json!({ "text": text, "code": code })),
332    )
333        .into_response()
334}
335
336fn err_response(err: impl ErrorExt) -> Response {
337    (StatusCode::UNAUTHORIZED, ErrorResponse::from_error(err)).into_response()
338}
339
340pub fn extract_catalog_and_schema<B>(request: &Request<B>) -> (String, String) {
341    // parse database from header
342    let dbname = request
343        .headers()
344        .get(GreptimeDbName::name())
345        // eat this invalid ascii error and give user the final IllegalParam error
346        .and_then(|header| header.to_str().ok())
347        .or_else(|| {
348            let query = request.uri().query().unwrap_or_default();
349            if is_influxdb_v2_request(request) {
350                extract_db_from_query(query).or_else(|| extract_bucket_from_query(query))
351            } else {
352                extract_db_from_query(query)
353            }
354        })
355        .unwrap_or(DEFAULT_SCHEMA_NAME);
356
357    parse_catalog_and_schema_from_db_string(dbname)
358}
359
360fn extract_timezone<B>(request: &Request<B>) -> Timezone {
361    // parse timezone from header
362    let timezone = request
363        .headers()
364        .get(&GREPTIME_TIMEZONE_HEADER_NAME)
365        // eat this invalid ascii error and give user the final IllegalParam error
366        .and_then(|header| header.to_str().ok())
367        .unwrap_or("");
368    parse_timezone(Some(timezone))
369}
370
371fn get_influxdb_credentials<B>(request: &Request<B>) -> Result<Option<(Username, Password)>> {
372    // compat with influxdb v2 and v1
373    if let Some(header) = request.headers().get(http::header::AUTHORIZATION) {
374        // try header
375        let (auth_scheme, credential) = header
376            .to_str()
377            .context(InvalidAuthHeaderInvisibleASCIISnafu)?
378            .split_once(' ')
379            .context(InvalidAuthHeaderSnafu)?;
380
381        let (username, password) = match auth_scheme.to_lowercase().as_str() {
382            "token" => {
383                let (u, p) = credential.split_once(':').context(InvalidAuthHeaderSnafu)?;
384                (u.to_string(), p.to_string().into())
385            }
386            "basic" => decode_basic(credential)?,
387            _ => UnsupportedAuthSchemeSnafu { name: auth_scheme }.fail()?,
388        };
389
390        Ok(Some((username, password)))
391    } else {
392        // try u and p in query
393        let Some(query_str) = request.uri().query() else {
394            return Ok(None);
395        };
396
397        let query_str = urlencoding::decode(query_str).context(UrlDecodeSnafu)?;
398
399        match extract_influxdb_user_from_query(&query_str) {
400            (None, None) => Ok(None),
401            (Some(username), Some(password)) => {
402                Ok(Some((username.to_string(), password.to_string().into())))
403            }
404            _ => InvalidParameterSnafu {
405                reason: "influxdb auth: username and password must be provided together"
406                    .to_string(),
407            }
408            .fail(),
409        }
410    }
411}
412
413fn get_splunk_credentials<B>(request: &Request<B>) -> Result<Option<(Username, Password)>> {
414    let Some(header) = request.headers().get(http::header::AUTHORIZATION) else {
415        return Ok(None);
416    };
417    let (auth_scheme, credential) = header
418        .to_str()
419        .context(InvalidAuthHeaderInvisibleASCIISnafu)?
420        .split_once(' ')
421        .context(InvalidAuthHeaderSnafu)?;
422
423    let (username, password) = match auth_scheme.to_lowercase().as_str() {
424        "splunk" => {
425            let (u, p) = credential.split_once(':').context(InvalidAuthHeaderSnafu)?;
426            (u.to_string(), p.to_string().into())
427        }
428        "basic" => decode_basic(credential)?,
429        _ => UnsupportedAuthSchemeSnafu { name: auth_scheme }.fail()?,
430    };
431    Ok(Some((username, password)))
432}
433
434pub fn extract_username_and_password<B>(request: &Request<B>) -> Result<(Username, Password)> {
435    Ok(if is_influxdb_request(request) {
436        // compatible with influxdb auth
437        get_influxdb_credentials(request)?.context(NotFoundInfluxAuthSnafu)?
438    } else if is_splunk_request(request) {
439        get_splunk_credentials(request)?.context(NotFoundAuthHeaderSnafu)?
440    } else {
441        // normal http auth
442        let scheme = auth_header(request)?;
443        match scheme {
444            AuthScheme::Basic(username, password) => (username, password),
445        }
446    })
447}
448
449#[derive(Debug)]
450pub enum AuthScheme {
451    Basic(Username, Password),
452}
453
454type Username = String;
455type Password = SecretString;
456
457impl TryFrom<&str> for AuthScheme {
458    type Error = error::Error;
459
460    fn try_from(value: &str) -> Result<Self> {
461        let (scheme, encoded_credentials) =
462            value.split_once(' ').context(InvalidAuthHeaderSnafu)?;
463
464        ensure!(!encoded_credentials.contains(' '), InvalidAuthHeaderSnafu);
465
466        match scheme.to_lowercase().as_str() {
467            "basic" => decode_basic(encoded_credentials)
468                .map(|(username, password)| AuthScheme::Basic(username, password)),
469            other => UnsupportedAuthSchemeSnafu { name: other }.fail(),
470        }
471    }
472}
473
474impl From<AuthScheme> for api::v1::auth_header::AuthScheme {
475    fn from(value: AuthScheme) -> Self {
476        match value {
477            AuthScheme::Basic(username, password) => {
478                api::v1::auth_header::AuthScheme::Basic(Basic {
479                    username,
480                    password: password.expose_secret().clone(),
481                })
482            }
483        }
484    }
485}
486
487type Credential<'a> = &'a str;
488
489/// Extracts an opaque bearer token from an `Authorization: Bearer <token>`
490/// header (the standard or `x-greptime-auth` header).
491///
492/// Returns `None` for any other scheme (`Basic`, influxdb `Token`, splunk
493/// `Splunk`, …) so the caller can fall through to the username/password path.
494fn extract_bearer_token<B>(req: &Request<B>) -> Option<&str> {
495    let header = req
496        .headers()
497        .get(AUTHORIZATION_HEADER)
498        .or_else(|| req.headers().get(http::header::AUTHORIZATION))?;
499    let value = header.to_str().ok()?;
500    // HTTP authentication schemes are case-insensitive (RFC 9110 §11.1), so
501    // match the scheme with `eq_ignore_ascii_case` — but never lowercase the
502    // *token* itself, which is opaque and case-sensitive. Returns a borrow
503    // into the request's headers, so there is no allocation.
504    let (scheme, token) = value.split_once(' ')?;
505    if !scheme.eq_ignore_ascii_case("bearer") {
506        return None;
507    }
508    let token = token.trim_start();
509    (!token.is_empty()).then_some(token)
510}
511
512fn auth_header<B>(req: &Request<B>) -> Result<AuthScheme> {
513    let auth_header = req
514        .headers()
515        .get(AUTHORIZATION_HEADER)
516        .or_else(|| req.headers().get(http::header::AUTHORIZATION))
517        .context(error::NotFoundAuthHeaderSnafu)?
518        .to_str()
519        .context(InvalidAuthHeaderInvisibleASCIISnafu)?;
520
521    auth_header.try_into()
522}
523
524fn decode_basic(credential: Credential) -> Result<(Username, Password)> {
525    let decoded = BASE64_STANDARD
526        .decode(credential)
527        .context(error::InvalidBase64ValueSnafu)?;
528    let as_utf8 =
529        String::from_utf8(decoded).context(error::InvalidAuthHeaderInvalidUtf8ValueSnafu)?;
530
531    if let Some((user_id, password)) = as_utf8.split_once(':') {
532        return Ok((user_id.to_string(), password.to_string().into()));
533    }
534
535    InvalidAuthHeaderSnafu {}.fail()
536}
537
538fn need_auth<B>(req: &Request<B>) -> bool {
539    let path = req.uri().path();
540
541    for api in PUBLIC_API_PREFIX {
542        if path.starts_with(api) {
543            return false;
544        }
545    }
546
547    path.starts_with(HTTP_API_PREFIX) || is_namespace(path, "/debug")
548}
549
550fn extract_param_from_query<'a>(query: &'a str, param: &'a str) -> Option<&'a str> {
551    let prefix = format!("{}=", param);
552    for pair in query.split('&') {
553        if let Some(param) = pair.strip_prefix(&prefix) {
554            return if param.is_empty() { None } else { Some(param) };
555        }
556    }
557    None
558}
559
560fn extract_db_from_query(query: &str) -> Option<&str> {
561    extract_param_from_query(query, "db")
562}
563
564/// InfluxDB v2 uses "bucket" instead of "db"
565/// https://docs.influxdata.com/influxdb/v1/tools/api/#apiv2write-http-endpoint
566fn extract_bucket_from_query(query: &str) -> Option<&str> {
567    extract_param_from_query(query, "bucket")
568}
569
570fn extract_influxdb_user_from_query(query: &str) -> (Option<&str>, Option<&str>) {
571    let mut username = None;
572    let mut password = None;
573
574    for pair in query.split('&') {
575        if pair.starts_with("u=") && pair.len() > 2 {
576            username = Some(&pair[2..]);
577        } else if pair.starts_with("p=") && pair.len() > 2 {
578            password = Some(&pair[2..]);
579        }
580    }
581    (username, password)
582}
583
584#[cfg(test)]
585pub(crate) mod tests {
586    use std::assert_matches;
587
588    use common_base::secrets::ExposeSecret;
589
590    use super::*;
591
592    pub(crate) struct ScopedUserProvider;
593
594    #[async_trait::async_trait]
595    impl auth::UserProvider for ScopedUserProvider {
596        fn name(&self) -> &str {
597            "scoped-test"
598        }
599
600        async fn authenticate(
601            &self,
602            _: auth::Identity<'_>,
603            _: auth::Password<'_>,
604        ) -> auth::error::Result<auth::UserInfoRef> {
605            Ok(auth::userinfo_by_name(Some("reader".to_string())))
606        }
607
608        async fn authorize(
609            &self,
610            catalog: &str,
611            schema: &str,
612            _: &auth::UserInfoRef,
613        ) -> auth::error::Result<()> {
614            if catalog == "greptime" && matches!(schema, "public" | "%64enied") {
615                Ok(())
616            } else {
617                auth::error::PermissionDeniedSnafu.fail()
618            }
619        }
620
621        async fn auth_bearer_token(
622            &self,
623            _: &str,
624            catalog: &str,
625            schema: &str,
626        ) -> auth::error::Result<auth::UserInfoRef> {
627            let user = auth::userinfo_by_name(Some("reader".to_string()));
628            self.authorize(catalog, schema, &user).await?;
629            Ok(user)
630        }
631    }
632
633    struct AdminTokenProvider {
634        user: auth::UserInfoRef,
635    }
636
637    #[async_trait::async_trait]
638    impl auth::UserProvider for AdminTokenProvider {
639        fn name(&self) -> &str {
640            "admin-token-test"
641        }
642
643        async fn authenticate(
644            &self,
645            _: auth::Identity<'_>,
646            _: auth::Password<'_>,
647        ) -> auth::error::Result<auth::UserInfoRef> {
648            unreachable!("Bearer requests must not use password authentication")
649        }
650
651        async fn authorize(
652            &self,
653            _: &str,
654            _: &str,
655            _: &auth::UserInfoRef,
656        ) -> auth::error::Result<()> {
657            unreachable!("Cluster administration must not use database authorization")
658        }
659
660        async fn authenticate_bearer_token(
661            &self,
662            token: &str,
663            catalog: &str,
664        ) -> auth::error::Result<auth::UserInfoRef> {
665            assert_eq!(catalog, common_catalog::consts::DEFAULT_CATALOG_NAME);
666            if token == "valid" {
667                Ok(self.user.clone())
668            } else if token == "backend-error" {
669                auth::error::InternalStateSnafu {
670                    msg: "provider unavailable",
671                }
672                .fail()
673            } else {
674                auth::error::UnsupportedAuthMethodSnafu {
675                    method: "invalid test token",
676                }
677                .fail()
678            }
679        }
680    }
681
682    #[tokio::test]
683    async fn test_admin_bearer_identity_and_privileges() {
684        for writable in [false, true] {
685            let option = if writable {
686                "static_user_provider:cmd:user:rw=secret"
687            } else {
688                "static_user_provider:cmd:user:ro=secret"
689            };
690            let user = auth::user_provider_from_option(option)
691                .unwrap()
692                .authenticate(
693                    auth::Identity::UserId("user", None),
694                    auth::Password::PlainText("secret".to_string().into()),
695                )
696                .await
697                .unwrap();
698            for header in [http::header::AUTHORIZATION.as_str(), AUTHORIZATION_HEADER] {
699                for token in ["valid", "invalid", "backend-error"] {
700                    let req = Request::builder()
701                        .uri("/admin/maintenance/enable?db=untrusted")
702                        .header(header, format!("Bearer {token}"))
703                        .header(GreptimeDbName::name(), "untrusted")
704                        .body(())
705                        .unwrap();
706                    let provider: UserProviderRef =
707                        std::sync::Arc::new(AdminTokenProvider { user: user.clone() });
708                    let result =
709                        inner_admin_auth(Some(provider), DefaultPermissionChecker::arc(), req)
710                            .await;
711                    if token == "backend-error" {
712                        assert_eq!(
713                            result.unwrap_err().status(),
714                            StatusCode::INTERNAL_SERVER_ERROR
715                        );
716                    } else if token != "valid" {
717                        assert_eq!(result.unwrap_err().status(), StatusCode::UNAUTHORIZED);
718                    } else if !writable {
719                        assert_eq!(result.unwrap_err().status(), StatusCode::FORBIDDEN);
720                    } else {
721                        let req = result.unwrap();
722                        assert_eq!(
723                            req.extensions()
724                                .get::<QueryContext>()
725                                .unwrap()
726                                .current_user()
727                                .username(),
728                            "user"
729                        );
730                    }
731                }
732            }
733        }
734    }
735
736    #[tokio::test]
737    async fn test_admin_auth_failure_metrics() {
738        use common_error::status_code::StatusCode as ErrorCode;
739
740        let provider =
741            auth::user_provider_from_option("static_user_provider:cmd:user=secret").unwrap();
742        for (header, code) in [
743            ("Basic dXNlcjpiYWQ=", ErrorCode::UserPasswordMismatch),
744            ("Basic YWJj", ErrorCode::InvalidAuthHeader),
745            ("Bearer invalid", ErrorCode::UserPasswordMismatch),
746        ] {
747            let counter = crate::metrics::METRIC_AUTH_FAILURE.with_label_values(&[code.as_ref()]);
748            let before = counter.get();
749            let request = Request::builder()
750                .header(http::header::AUTHORIZATION, header)
751                .body(())
752                .unwrap();
753            let response = inner_admin_auth(
754                Some(provider.clone()),
755                DefaultPermissionChecker::arc(),
756                request,
757            )
758            .await
759            .unwrap_err();
760            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
761            assert!(counter.get() > before, "missing auth failure for {code:?}");
762        }
763    }
764
765    #[test]
766    fn test_need_auth() {
767        let req = Request::builder()
768            .uri("http://127.0.0.1/v1/influxdb/ping")
769            .body(())
770            .unwrap();
771
772        assert!(!need_auth(&req));
773
774        let req = Request::builder()
775            .uri("http://127.0.0.1/v1/influxdb/health")
776            .body(())
777            .unwrap();
778
779        assert!(!need_auth(&req));
780
781        let req = Request::builder()
782            .uri("http://127.0.0.1/v1/influxdb/write")
783            .body(())
784            .unwrap();
785
786        assert!(need_auth(&req));
787    }
788
789    #[test]
790    fn test_splunk_auth() {
791        let splunk_uri = "http://127.0.0.1/v1/splunk/services/collector/event";
792        let splunk_req = |auth: Option<&str>| {
793            let mut req = Request::builder().uri(splunk_uri);
794            if let Some(auth) = auth {
795                req = req.header(http::header::AUTHORIZATION, auth);
796            }
797            req.body(()).unwrap()
798        };
799
800        // is_splunk_request matches our mount, not other endpoints.
801        assert!(is_splunk_request(&splunk_req(None)));
802        assert!(!is_splunk_request(
803            &Request::builder()
804                .uri("http://127.0.0.1/v1/influxdb/write")
805                .body(())
806                .unwrap()
807        ));
808        assert!(!is_splunk_request(
809            &Request::builder()
810                .uri("http://127.0.0.1/v1/sql")
811                .body(())
812                .unwrap()
813        ));
814
815        // `Splunk <user:pass>` -> (user, pass).
816        let (username, password) =
817            get_splunk_credentials(&splunk_req(Some("Splunk teamA:secretA")))
818                .unwrap()
819                .unwrap();
820        assert_eq!(username, "teamA");
821        assert_eq!(password.expose_secret(), "secretA");
822
823        // standard Basic is also accepted (parity with influxdb).
824        let basic = basic_auth("u", "p");
825        let (username, password) = get_splunk_credentials(&splunk_req(Some(&basic)))
826            .unwrap()
827            .unwrap();
828        assert_eq!(username, "u");
829        assert_eq!(password.expose_secret(), "p");
830
831        // missing header -> None; token without ':' -> error.
832        assert!(get_splunk_credentials(&splunk_req(None)).unwrap().is_none());
833        assert!(get_splunk_credentials(&splunk_req(Some("Splunk no_colon_token"))).is_err());
834
835        // full dispatch routes a splunk request through the splunk scheme.
836        let (username, password) =
837            extract_username_and_password(&splunk_req(Some("Splunk teamA:secretA"))).unwrap();
838        assert_eq!(username, "teamA");
839        assert_eq!(password.expose_secret(), "secretA");
840    }
841
842    #[test]
843    fn test_decode_basic() {
844        let credential = basic_auth_credentials("username", "password");
845        let (username, pwd) = decode_basic(&credential).unwrap();
846        assert_eq!("username", username);
847        assert_eq!("password", pwd.expose_secret());
848
849        let wrong_credential = credential.replacen('c', "c ", 1);
850        let result = decode_basic(&wrong_credential);
851        assert_matches!(result.err(), Some(error::Error::InvalidBase64Value { .. }));
852    }
853
854    #[test]
855    fn test_try_into_auth_scheme() {
856        let auth_scheme_str = "basic";
857        let re: Result<AuthScheme> = auth_scheme_str.try_into();
858        assert!(re.is_err());
859
860        let auth_scheme_str = basic_auth("test", "test");
861        let scheme: AuthScheme = auth_scheme_str.as_str().try_into().unwrap();
862        assert_matches!(scheme, AuthScheme::Basic(username, pwd) if username == "test" && pwd.expose_secret() == "test");
863
864        let unsupported = "digest";
865        let auth_scheme: Result<AuthScheme> = unsupported.try_into();
866        assert!(auth_scheme.is_err());
867    }
868
869    #[test]
870    fn test_inner_auth_assigns_remote_query_id() {
871        let req =
872            mock_http_request(None, Some("http://127.0.0.1/v1/sql?db=greptime-public")).unwrap();
873        let req = futures::executor::block_on(inner_auth::<()>(None, req)).unwrap();
874        let query_ctx = req
875            .extensions()
876            .get::<session::context::QueryContext>()
877            .unwrap();
878
879        assert!(query_ctx.remote_query_id().is_some());
880    }
881
882    #[test]
883    fn test_auth_header() {
884        let header_value = basic_auth("username", "password");
885        let req = mock_http_request(Some(&header_value), None).unwrap();
886
887        let auth_scheme = auth_header(&req).unwrap();
888        assert_matches!(auth_scheme, AuthScheme::Basic(username, pwd) if username == "username" && pwd.expose_secret() == "password");
889
890        let wrong_auth_header = header_value.replacen('c', "c ", 1);
891        let wrong_req = mock_http_request(Some(&wrong_auth_header), None).unwrap();
892        let res = auth_header(&wrong_req);
893        assert_matches!(res.err(), Some(error::Error::InvalidAuthHeader { .. }));
894
895        let wrong_req = mock_http_request(
896            Some(&format!(
897                "Digest {}",
898                basic_auth_credentials("username", "password")
899            )),
900            None,
901        )
902        .unwrap();
903        let res = auth_header(&wrong_req);
904        assert_matches!(res.err(), Some(error::Error::UnsupportedAuthScheme { .. }));
905    }
906
907    fn basic_auth(username: &str, password: &str) -> String {
908        format!("Basic {}", basic_auth_credentials(username, password))
909    }
910
911    fn basic_auth_credentials(username: &str, password: &str) -> String {
912        BASE64_STANDARD.encode(format!("{username}:{password}"))
913    }
914
915    fn mock_http_request(auth_header: Option<&str>, uri: Option<&str>) -> Result<Request<()>> {
916        let http_api_version = crate::http::HTTP_API_VERSION;
917        let mut req = Request::builder()
918            .uri(uri.unwrap_or(format!("http://localhost/{http_api_version}/sql").as_str()));
919        if let Some(auth_header) = auth_header {
920            req = req.header(http::header::AUTHORIZATION, auth_header);
921        }
922
923        Ok(req.body(()).unwrap())
924    }
925
926    #[test]
927    fn test_db_name_header() {
928        let http_api_version = crate::http::HTTP_API_VERSION;
929        let req = Request::builder()
930            .uri(format!("http://localhost/{http_api_version}/sql").as_str())
931            .header(GreptimeDbName::name(), "greptime-tomcat")
932            .body(())
933            .unwrap();
934
935        let db = extract_catalog_and_schema(&req);
936        assert_eq!(db, ("greptime".to_string(), "tomcat".to_string()));
937    }
938
939    #[test]
940    fn test_extract_db() {
941        assert_matches!(extract_db_from_query(""), None);
942        assert_matches!(extract_db_from_query("&"), None);
943        assert_matches!(extract_db_from_query("db="), None);
944        assert_matches!(extract_bucket_from_query("bucket="), None);
945        assert_matches!(extract_bucket_from_query("db=foo"), None);
946        assert_matches!(extract_db_from_query("db=foo"), Some("foo"));
947        assert_matches!(extract_bucket_from_query("bucket=foo"), Some("foo"));
948        assert_matches!(extract_db_from_query("name=bar"), None);
949        assert_matches!(extract_db_from_query("db=&name=bar"), None);
950        assert_matches!(extract_db_from_query("db=foo&name=bar"), Some("foo"));
951        assert_matches!(extract_bucket_from_query("db=foo&bucket=bar"), Some("bar"));
952        assert_matches!(extract_db_from_query("name=bar&db="), None);
953        assert_matches!(extract_db_from_query("name=bar&db=foo"), Some("foo"));
954        assert_matches!(extract_db_from_query("name=bar&db=&name=bar"), None);
955        assert_matches!(
956            extract_db_from_query("name=bar&db=foo&name=bar"),
957            Some("foo")
958        );
959    }
960
961    #[test]
962    fn test_extract_user() {
963        assert_matches!(extract_influxdb_user_from_query(""), (None, None));
964        assert_matches!(extract_influxdb_user_from_query("u="), (None, None));
965        assert_matches!(
966            extract_influxdb_user_from_query("u=123"),
967            (Some("123"), None)
968        );
969        assert_matches!(
970            extract_influxdb_user_from_query("u=123&p="),
971            (Some("123"), None)
972        );
973        assert_matches!(
974            extract_influxdb_user_from_query("u=123&p=4"),
975            (Some("123"), Some("4"))
976        );
977        assert_matches!(extract_influxdb_user_from_query("p="), (None, None));
978        assert_matches!(extract_influxdb_user_from_query("p=4"), (None, Some("4")));
979        assert_matches!(
980            extract_influxdb_user_from_query("p=4&u="),
981            (None, Some("4"))
982        );
983        assert_matches!(
984            extract_influxdb_user_from_query("p=4&u=123"),
985            (Some("123"), Some("4"))
986        );
987    }
988
989    #[test]
990    fn test_extract_bearer_token() {
991        let bearer = |scheme: &str, val: &str| {
992            mock_http_request(Some(&format!("{scheme} {val}")), None).unwrap()
993        };
994
995        // Standard bearer scheme, on either header.
996        assert_eq!(
997            extract_bearer_token(&bearer("Bearer", "abc.def.ghi")),
998            Some("abc.def.ghi")
999        );
1000        assert_eq!(extract_bearer_token(&bearer("bearer", "tok")), Some("tok"));
1001        // HTTP schemes are case-insensitive (RFC 9110 §11.1); the token
1002        // itself is opaque and must NOT be lowercased.
1003        assert_eq!(
1004            extract_bearer_token(&bearer("BEARER", "ABC.DEF.GHI")),
1005            Some("ABC.DEF.GHI")
1006        );
1007        assert_eq!(extract_bearer_token(&bearer("BeArEr", "tok")), Some("tok"));
1008        let mut req = mock_http_request(Some("Bearer xyz"), None).unwrap();
1009        req.headers_mut().insert(
1010            AUTHORIZATION_HEADER,
1011            "Bearer from-x-greptime".parse().unwrap(),
1012        );
1013        assert_eq!(extract_bearer_token(&req), Some("from-x-greptime"));
1014
1015        // Non-bearer schemes are ignored so the caller falls through to Basic.
1016        assert_eq!(extract_bearer_token(&bearer("Basic", "dXNlcjpwYXNz")), None);
1017        assert_eq!(extract_bearer_token(&bearer("Token", "u:p")), None);
1018        assert_eq!(extract_bearer_token(&bearer("Splunk", "u:p")), None);
1019
1020        // No header, empty token.
1021        assert_eq!(
1022            extract_bearer_token(&mock_http_request(None, None).unwrap()),
1023            None
1024        );
1025        assert_eq!(extract_bearer_token(&bearer("Bearer", "")), None);
1026    }
1027
1028    /// A `UserProvider` that resolves exactly one bearer token to a known user
1029    /// and rejects everything else (including password auth).
1030    struct TokenUserProvider {
1031        token: String,
1032        user: auth::UserInfoRef,
1033    }
1034
1035    #[async_trait::async_trait]
1036    impl auth::UserProvider for TokenUserProvider {
1037        fn name(&self) -> &str {
1038            "token-test"
1039        }
1040
1041        async fn authenticate(
1042            &self,
1043            _: auth::Identity<'_>,
1044            _: auth::Password<'_>,
1045        ) -> auth::error::Result<auth::UserInfoRef> {
1046            unreachable!("password auth should not be reached for a bearer request")
1047        }
1048
1049        async fn authorize(
1050            &self,
1051            _: &str,
1052            _: &str,
1053            _: &auth::UserInfoRef,
1054        ) -> auth::error::Result<()> {
1055            Ok(())
1056        }
1057
1058        async fn auth_bearer_token(
1059            &self,
1060            token: &str,
1061            _: &str,
1062            _: &str,
1063        ) -> auth::error::Result<auth::UserInfoRef> {
1064            if token == self.token {
1065                Ok(self.user.clone())
1066            } else {
1067                auth::error::UnsupportedAuthMethodSnafu {
1068                    method: "bearer token",
1069                }
1070                .fail()
1071            }
1072        }
1073    }
1074
1075    #[tokio::test]
1076    async fn test_bearer_token_dispatches_to_auth_bearer_token() {
1077        let provider = TokenUserProvider {
1078            token: "good-token".to_string(),
1079            user: auth::userinfo_by_name(Some("alice".into())),
1080        };
1081        let req = mock_http_request(Some("Bearer good-token"), None).unwrap();
1082
1083        let req = inner_auth::<()>(
1084            Some(std::sync::Arc::new(provider) as auth::UserProviderRef),
1085            req,
1086        )
1087        .await
1088        .expect("valid bearer token authenticates");
1089
1090        let user = req
1091            .extensions()
1092            .get::<session::context::QueryContext>()
1093            .expect("query context is populated")
1094            .current_user();
1095        assert_eq!(user.username(), "alice");
1096    }
1097
1098    #[tokio::test]
1099    async fn test_bearer_token_failure_rejects() {
1100        let provider = TokenUserProvider {
1101            token: "good-token".to_string(),
1102            user: auth::userinfo_by_name(Some("alice".into())),
1103        };
1104        let req = mock_http_request(Some("Bearer bad-token"), None).unwrap();
1105
1106        let result = inner_auth::<()>(
1107            Some(std::sync::Arc::new(provider) as auth::UserProviderRef),
1108            req,
1109        )
1110        .await;
1111        assert!(result.is_err(), "an invalid bearer token is rejected");
1112    }
1113
1114    #[tokio::test]
1115    async fn test_default_provider_rejects_bearer() {
1116        // A password-only provider uses the default `auth_bearer_token`, which rejects.
1117        let provider =
1118            auth::user_provider_from_option("static_user_provider:cmd:alice=s3cret").unwrap();
1119        let req = mock_http_request(Some("Bearer some-jwt"), None).unwrap();
1120        let result = inner_auth::<()>(Some(provider), req).await;
1121        assert!(
1122            result.is_err(),
1123            "password-only providers reject bearer tokens"
1124        );
1125    }
1126
1127    /// A bearer-token failure on a Splunk HEC request must keep the HEC
1128    /// contract — `{"text":"Invalid token","code":4}` with FORBIDDEN —
1129    /// instead of falling through to the generic 401 `ErrorResponse`.
1130    /// Regression for the bearer/splunk routing gap.
1131    #[tokio::test]
1132    async fn test_bearer_failure_on_splunk_keeps_hec_contract() {
1133        let provider = TokenUserProvider {
1134            token: "good-token".to_string(),
1135            user: auth::userinfo_by_name(Some("alice".into())),
1136        };
1137        let req = mock_http_request(
1138            Some("Bearer bad-token"),
1139            Some("http://127.0.0.1/v1/splunk/services/collector/event"),
1140        )
1141        .unwrap();
1142
1143        let resp = inner_auth::<()>(
1144            Some(std::sync::Arc::new(provider) as auth::UserProviderRef),
1145            req,
1146        )
1147        .await
1148        .expect_err("an invalid bearer token is rejected");
1149
1150        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1151        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
1152            .await
1153            .unwrap();
1154        let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1155        assert_eq!(payload["code"], 4);
1156        assert_eq!(payload["text"], "Invalid token");
1157    }
1158}