auth/
permission.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 std::fmt::Debug;
16
17use api::v1::greptime_request::Request;
18use sql::statements::statement::Statement;
19
20use crate::error::{PermissionDeniedSnafu, Result};
21use crate::{PermissionCheckerRef, UserInfoRef};
22
23#[derive(Debug, Clone)]
24pub enum PermissionReq<'a> {
25    GrpcRequest(&'a Request),
26    SqlStatement(&'a Statement),
27    PromQuery,
28    LogQuery,
29    Opentsdb,
30    LineProtocol,
31    PromStoreWrite,
32    PromStoreRead,
33    Otlp,
34    LogWrite,
35    BulkInsert,
36}
37
38#[derive(Debug)]
39pub enum PermissionResp {
40    Allow,
41    Reject,
42}
43
44pub trait PermissionChecker: Send + Sync {
45    fn check_permission(
46        &self,
47        user_info: UserInfoRef,
48        req: PermissionReq,
49    ) -> Result<PermissionResp>;
50}
51
52impl PermissionChecker for Option<&PermissionCheckerRef> {
53    fn check_permission(
54        &self,
55        user_info: UserInfoRef,
56        req: PermissionReq,
57    ) -> Result<PermissionResp> {
58        match self {
59            Some(checker) => match checker.check_permission(user_info, req) {
60                Ok(PermissionResp::Reject) => PermissionDeniedSnafu.fail(),
61                Ok(PermissionResp::Allow) => Ok(PermissionResp::Allow),
62                Err(e) => Err(e),
63            },
64            None => Ok(PermissionResp::Allow),
65        }
66    }
67}