Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add license parsing function #11303

Merged
merged 4 commits into from
May 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions src/common/exception/src/exception_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,18 @@ build_exceptions! {
///
/// For example: try to with 3 columns into a table with 4 columns.
TableSchemaMismatch(1303),

// License related errors starts here

/// LicenseKeyParseError is used when license key cannot be pared by the jwt public key
///
/// For example: license key is not valid
LicenseKeyParseError(1401),

/// LicenseKeyInvalid is used when license key verification error occurs
///
/// For example: license key is expired
LicenseKeyInvalid(1402)
}

// Meta service errors [2001, 3000].
Expand Down
2 changes: 2 additions & 0 deletions src/common/license/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ test = false
# Workspace dependencies
common-base = { path = "../base" }
common-exception = { path = "../exception" }
jwt-simple = "0.11.0"
serde = { workspace = true }
1 change: 1 addition & 0 deletions src/common/license/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@
// See the License for the specific language governing permissions and
// limitations under the License.

pub mod license;
pub mod license_manager;
29 changes: 29 additions & 0 deletions src/common/license/src/license.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2021 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use serde::Deserialize;
use serde::Serialize;

pub const LICENSE_PUBLIC_KEY: &str = r#"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGsKCbhXU7j56VKZ7piDlLXGhud0a
pWjW3wxSdeARerxs/BeoWK7FspDtfLaAT8iJe4YEmR0JpkRQ8foWs0ve3w==
-----END PUBLIC KEY-----"#;
ZhiHanZ marked this conversation as resolved.
Show resolved Hide resolved

#[derive(Serialize, Deserialize)]
pub struct LicenseInfo {
#[serde(rename = "type")]
pub r#type: Option<String>,
pub org: Option<String>,
pub tenants: Option<Vec<String>>,
ZhiHanZ marked this conversation as resolved.
Show resolved Hide resolved
}
30 changes: 30 additions & 0 deletions src/common/license/src/license_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,43 @@ use std::sync::Arc;

use common_base::base::GlobalInstance;
use common_exception::Result;
use jwt_simple::claims::JWTClaims;

use crate::license::LicenseInfo;

pub trait LicenseManager {
fn init() -> Result<()>
where Self: Sized;
fn instance() -> Arc<Box<dyn LicenseManager>>
where Self: Sized;
fn is_active(&self) -> bool;

/// Encodes a raw license string as a JWT using the constant public key.
///
/// This function takes a raw license string and a secret key,
/// The function returns a `jwt_simple::Claim` object that represents the
/// decoded contents of the JWT with custom fields `LicenseInfo`
///
/// # Arguments
///
/// * `raw` - The raw license string to be encoded.
///
/// # Returns
///
/// A `jwt_simple::Claim` object representing the decoded contents of the JWT.
///
/// # Errors
///
/// This function may return `LicenseKeyParseError` error if the encoding or decoding of the JWT fails.
///
/// # Examples
///
/// ```
/// let raw_license = "my_license";
/// let claim = make_license(raw_license).unwrap();
/// ```
fn make_license(raw: &str) -> Result<JWTClaims<LicenseInfo>>
where Self: Sized;
}

pub struct LicenseManagerWrapper {
Expand Down
4 changes: 2 additions & 2 deletions src/query/ee/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ test = false

[dependencies]
# Workspace dependencies
async-backtrace = { workspace = true }
common-base = { path = "../../common/base" }
common-config = { path = "../config" }
common-exception = { path = "../../common/exception" }
common-license = { path = "../../common/license" }

async-backtrace = { workspace = true }
jwt-simple = "0.11.0"

[build-dependencies]
common-building = { path = "../../common/building" }
Expand Down
18 changes: 18 additions & 0 deletions src/query/ee/src/license/license_mgr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,16 @@
use std::sync::Arc;

use common_base::base::GlobalInstance;
use common_exception::exception::ErrorCode;
use common_exception::Result;
use common_exception::ToErrorCode;
use common_license::license::LicenseInfo;
use common_license::license::LICENSE_PUBLIC_KEY;
use common_license::license_manager::LicenseManager;
use common_license::license_manager::LicenseManagerWrapper;
use jwt_simple::algorithms::ES256PublicKey;
use jwt_simple::claims::JWTClaims;
use jwt_simple::prelude::ECDSAP256PublicKeyLike;

pub struct RealLicenseManager {}

Expand All @@ -38,4 +45,15 @@ impl LicenseManager for RealLicenseManager {
fn is_active(&self) -> bool {
true
}

fn make_license(raw: &str) -> Result<JWTClaims<LicenseInfo>> {
let public_key = ES256PublicKey::from_pem(LICENSE_PUBLIC_KEY)
.map_err_to_code(ErrorCode::LicenseKeyParseError, || "public key load failed")?;
public_key
.verify_token::<LicenseInfo>(raw, None)
.map_err_to_code(
ErrorCode::LicenseKeyParseError,
|| "jwt claim decode failed",
)
}
}
34 changes: 34 additions & 0 deletions src/query/ee/tests/it/license/license_mgr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2023 Databend Cloud
//
// Licensed under the Elastic License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.elastic.co/licensing/elastic-license
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use common_license::license_manager::LicenseManager;
use enterprise_query::license::license_mgr::RealLicenseManager;

#[test]
fn test_make_license() -> common_exception::Result<()> {
assert_eq!(
RealLicenseManager::make_license("not valid")
.err()
.unwrap()
.code(),
common_exception::ErrorCode::LicenseKeyParseError("").code()
);
let valid_key = "eyJhbGciOiAiRVMyNTYiLCAidHlwIjogIkpXVCJ9.eyJ0eXBlIjogInRyaWFsIiwgIm9yZyI6ICJ0ZXN0IiwgInRlbmFudHMiOiBudWxsLCAiaXNzIjogImRhdGFiZW5kIiwgImlhdCI6IDE2ODE4OTk1NjIsICJuYmYiOiAxNjgxODk5NTYyLCAiZXhwIjogMTY4MzE5NTU2MX0.EfnbkZgNGuCUM0yZ7wg1ARgkiY3g32OHkoWZYoEADNEBPd4Dp8Dhq-W5qzTTSEthiMiiRym0DswGpzYPFSwQww";
let claim = RealLicenseManager::make_license(valid_key).unwrap();
assert_eq!(claim.issuer.unwrap(), "databend");
assert_eq!(claim.custom.org.unwrap(), "test");
assert_eq!(claim.custom.r#type.unwrap(), "trial");
assert!(claim.custom.tenants.is_none());
Ok(())
}
15 changes: 15 additions & 0 deletions src/query/ee/tests/it/license/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2023 Databend Cloud
//
// Licensed under the Elastic License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.elastic.co/licensing/elastic-license
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod license_mgr;
16 changes: 16 additions & 0 deletions src/query/ee/tests/it/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2023 Databend Cloud
//
// Licensed under the Elastic License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.elastic.co/licensing/elastic-license
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(unwrap_infallible)]
mod license;