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