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}
36
37#[derive(Debug)]
38pub enum PermissionResp {
39    Allow,
40    Reject,
41}
42
43pub trait PermissionChecker: Send + Sync {
44    fn check_permission(
45        &self,
46        user_info: UserInfoRef,
47        req: PermissionReq,
48    ) -> Result<PermissionResp>;
49}
50
51impl PermissionChecker for Option<&PermissionCheckerRef> {
52    fn check_permission(
53        &self,
54        user_info: UserInfoRef,
55        req: PermissionReq,
56    ) -> Result<PermissionResp> {
57        match self {
58            Some(checker) => match checker.check_permission(user_info, req) {
59                Ok(PermissionResp::Reject) => PermissionDeniedSnafu.fail(),
60                Ok(PermissionResp::Allow) => Ok(PermissionResp::Allow),
61                Err(e) => Err(e),
62            },
63            None => Ok(PermissionResp::Allow),
64        }
65    }
66}