Skip to main content

risingwave_license/
manager.rs

1// Copyright 2024 RisingWave Labs
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::num::NonZeroU64;
16use std::sync::{LazyLock, RwLock};
17
18use jsonwebtoken::{Algorithm, DecodingKey, Validation};
19use risingwave_pb::common::ClusterResource;
20use serde::{Deserialize, Serialize};
21use thiserror::Error;
22use thiserror_ext::AsReport;
23
24use crate::{Feature, LicenseKeyRef};
25
26/// A feature that's specified in the custom tier.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(untagged)]
29pub enum MaybeFeature {
30    /// A known feature that exists in the [`Feature`] enum.
31    Feature(Feature),
32    /// An unknown feature. It could be features introduced in future release. We still allow it to
33    /// be here for compatibility purposes.
34    Unknown(String),
35}
36
37/// License tier.
38///
39/// A tier controls which enterprise [`Feature`]s are available.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum Tier {
43    /// Free tier. No feature is available. This is more like a placeholder.
44    Free,
45
46    /// All features available as of 2.5.
47    #[serde(rename = "paid")]
48    AllAsOf2_5,
49
50    /// All features available currently and in the future.
51    All,
52
53    /// Custom tier, with an allowlist of available features.
54    #[serde(untagged)]
55    CustomAllowList {
56        name: String,
57        /// Keep serializing this field as `features` for compatibility with existing licenses.
58        #[serde(rename = "features")]
59        allowed_features: Vec<MaybeFeature>,
60    },
61
62    /// Custom tier, with a denylist of unavailable features.
63    ///
64    /// Features added in future versions are available by default unless they are explicitly
65    /// included in `excluded_features`.
66    #[serde(untagged)]
67    CustomDenyList {
68        name: String,
69        excluded_features: Vec<MaybeFeature>,
70    },
71}
72
73impl Tier {
74    /// Get all available features based on the license tier.
75    #[auto_enums::auto_enum(Iterator)]
76    pub fn available_features(&self) -> impl Iterator<Item = Feature> {
77        match self {
78            Tier::Free => std::iter::empty(),
79            Tier::AllAsOf2_5 => Feature::all_as_of_2_5().iter().copied(),
80            Tier::All => Feature::all().iter().copied(),
81            Tier::CustomAllowList {
82                allowed_features, ..
83            } => allowed_features.iter().filter_map(|feature| match feature {
84                MaybeFeature::Feature(feature) => Some(*feature),
85                MaybeFeature::Unknown(_) => None,
86            }),
87            Tier::CustomDenyList {
88                excluded_features, ..
89            } => Feature::all()
90                .iter()
91                .copied()
92                .filter(|feature| !excluded_features.contains(&MaybeFeature::Feature(*feature))),
93        }
94    }
95
96    pub fn name(&self) -> &str {
97        match self {
98            Tier::Free => "free",
99            Tier::AllAsOf2_5 => "paid",
100            Tier::All => "all",
101            Tier::CustomAllowList { name, .. } | Tier::CustomDenyList { name, .. } => name,
102        }
103    }
104}
105
106/// Issuer of the license.
107///
108/// The issuer must be `prod.risingwave.com` in production, and can be `test.risingwave.com` in
109/// development. This will be validated when refreshing the license key.
110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
111pub enum Issuer {
112    #[serde(rename = "prod.risingwave.com")]
113    Prod,
114
115    #[serde(rename = "test.risingwave.com")]
116    Test,
117
118    #[serde(untagged)]
119    Unknown(String),
120}
121
122/// The content of a license.
123///
124/// We use JSON Web Token (JWT) to represent the license. This struct is the payload.
125///
126/// Prefer calling [`crate::Feature::check_available`] to check the availability of a feature,
127/// other than directly checking the content of the license.
128// TODO(license): Shall we add a version field?
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "snake_case")]
131pub struct License {
132    /// Subject of the license.
133    ///
134    /// See <https://tools.ietf.org/html/rfc7519#section-4.1.2>.
135    pub sub: String,
136
137    /// Issuer of the license.
138    ///
139    /// See <https://tools.ietf.org/html/rfc7519#section-4.1.1>.
140    pub iss: Issuer,
141
142    /// Tier of the license.
143    pub tier: Tier,
144
145    /// Maximum number of RWU allowed to use.
146    ///
147    /// 1 RWU corresponds to 4 GiB memory and 1 CPU core.
148    /// See <https://docs.risingwave.com/cloud/pricing#risingwave-unit-rwu> for more details.
149    #[serde(alias = "cpu_core_limit")]
150    pub rwu_limit: Option<NonZeroU64>,
151
152    /// Expiration time in seconds since UNIX epoch.
153    ///
154    /// See <https://tools.ietf.org/html/rfc7519#section-4.1.4>.
155    pub exp: u64,
156}
157
158impl License {
159    /// Return the CPU core limit based on the RWU limit in the license.
160    pub fn cpu_core_limit(&self) -> Option<u64> {
161        self.rwu_limit.map(|limit| limit.get())
162    }
163
164    /// Return the memory limit (in bytes) based on the RWU limit in the license.
165    pub fn memory_limit(&self) -> Option<u64> {
166        // 4GB per RWU
167        const MEMORY_PER_RWU: u64 = 4 * 1024 * 1024 * 1024;
168
169        self.rwu_limit.map(
170            |limit| (limit.get() + 1) * MEMORY_PER_RWU - 1, // allow some margin
171        )
172    }
173
174    /// Check whether the given cluster resource exceeds the limit in the license.
175    pub fn check_cluster_resource(&self, resource: ClusterResource) -> Result<(), LicenseError> {
176        let ClusterResource {
177            total_memory_bytes,
178            total_cpu_cores,
179        } = resource;
180
181        if let Some(limit) = self.cpu_core_limit()
182            && total_cpu_cores > limit
183        {
184            return Err(LicenseError::CpuLimitExceeded {
185                limit,
186                actual: total_cpu_cores,
187            });
188        }
189
190        #[cfg(not(madsim))] // skip checking memory limit in simulation tests
191        if let Some(limit) = self.memory_limit()
192            && total_memory_bytes > limit
193        {
194            return Err(LicenseError::MemoryLimitExceeded {
195                limit,
196                actual: total_memory_bytes,
197            });
198        }
199
200        Ok(())
201    }
202}
203
204impl Default for License {
205    /// The default license is a free license that never expires.
206    ///
207    /// Used when `license_key` is unset or invalid.
208    fn default() -> Self {
209        Self {
210            sub: "default".to_owned(),
211            tier: Tier::Free,
212            iss: Issuer::Prod,
213            rwu_limit: None,
214            exp: u64::MAX,
215        }
216    }
217}
218
219/// The error type for invalid license key when verifying as JWT.
220#[derive(Debug, Clone, Error)]
221pub enum LicenseError {
222    #[error("invalid license key")]
223    InvalidKey(#[source] jsonwebtoken::errors::Error),
224
225    #[error(
226        "a valid license key is set, but it is currently not effective because the CPU core in the cluster \
227        ({actual}) exceeds the maximum allowed by the license key ({limit}); \
228        consider removing some nodes or acquiring a new license key with a higher limit"
229    )]
230    CpuLimitExceeded { limit: u64, actual: u64 },
231
232    #[error(
233        "a valid license key is set, but it is currently not effective because the memory in the cluster \
234        ({actual}) exceeds the maximum allowed by the license key ({limit}); \
235        consider removing some nodes or acquiring a new license key with a higher limit",
236        actual = humansize::format_size(*actual, humansize::BINARY),
237        limit = humansize::format_size(*limit, humansize::BINARY),
238    )]
239    MemoryLimitExceeded { limit: u64, actual: u64 },
240}
241
242struct Inner {
243    license: Result<License, LicenseError>,
244    cached_cluster_resource: ClusterResource,
245}
246
247/// The singleton license manager.
248pub struct LicenseManager {
249    inner: RwLock<Inner>,
250}
251
252static PUBLIC_KEY: LazyLock<DecodingKey> = LazyLock::new(|| {
253    DecodingKey::from_rsa_pem(include_bytes!("key.pub"))
254        .expect("invalid public key for license validation")
255});
256
257impl LicenseManager {
258    /// Create a new license manager with the default license.
259    pub(crate) fn new() -> Self {
260        Self {
261            inner: RwLock::new(Inner {
262                license: Ok(License::default()),
263                cached_cluster_resource: ClusterResource {
264                    total_cpu_cores: 0,
265                    total_memory_bytes: 0,
266                },
267            }),
268        }
269    }
270
271    /// Get the singleton instance of the license manager.
272    pub fn get() -> &'static Self {
273        static INSTANCE: LazyLock<LicenseManager> = LazyLock::new(LicenseManager::new);
274        &INSTANCE
275    }
276
277    /// Refresh the license with the given license key.
278    pub fn refresh(&self, license_key: LicenseKeyRef<'_>) {
279        let license_key = license_key.0;
280        let mut inner = self.inner.write().unwrap();
281
282        // Empty license key means unset. Use the default one here.
283        if license_key.is_empty() {
284            inner.license = Ok(License::default());
285            return;
286        }
287
288        // TODO(license): shall we also validate `nbf`(Not Before)?
289        let mut validation = Validation::new(Algorithm::RS512);
290        // Only accept `prod` issuer in production, so that we can use license keys issued by
291        // the `test` issuer in development without leaking them to production.
292        validation.set_issuer(&[
293            "prod.risingwave.com",
294            #[cfg(debug_assertions)]
295            "test.risingwave.com",
296        ]);
297
298        inner.license = match jsonwebtoken::decode(license_key, &PUBLIC_KEY, &validation) {
299            Ok(data) => Ok(data.claims),
300            Err(error) => Err(LicenseError::InvalidKey(error)),
301        };
302
303        match &inner.license {
304            Ok(license) => tracing::info!(?license, "license refreshed"),
305            Err(error) => tracing::warn!(error = %error.as_report(), "invalid license key"),
306        }
307    }
308
309    /// Update the cached cluster resource.
310    pub fn update_cluster_resource(&self, resource: ClusterResource) {
311        let mut inner = self.inner.write().unwrap();
312        inner.cached_cluster_resource = resource;
313    }
314
315    /// Get the current license if it is valid.
316    ///
317    /// Since the license can expire, the returned license should not be cached by the caller.
318    ///
319    /// Prefer calling [`crate::Feature::check_available`] to check the availability of a feature,
320    /// other than directly calling this method and checking the content of the license.
321    pub fn license(&self) -> Result<License, LicenseError> {
322        let inner = self.inner.read().unwrap();
323        let license = inner.license.clone()?;
324
325        // Check the expiration time additionally.
326        if license.exp < jsonwebtoken::get_current_timestamp() {
327            return Err(LicenseError::InvalidKey(
328                jsonwebtoken::errors::ErrorKind::ExpiredSignature.into(),
329            ));
330        }
331
332        // Check the resource limit.
333        license.check_cluster_resource(inner.cached_cluster_resource)?;
334
335        Ok(license)
336    }
337}
338
339// Tests below only work in debug mode.
340#[cfg(debug_assertions)]
341#[cfg(test)]
342mod tests {
343    use expect_test::expect;
344
345    use super::*;
346    use crate::{LicenseKey, PROD_ALL_4_CORE_LICENSE_KEY_CONTENT, TEST_ALL_LICENSE_KEY_CONTENT};
347
348    fn do_test(key: &str, expect: expect_test::Expect) -> LicenseManager {
349        let manager = LicenseManager::new();
350        manager.refresh(LicenseKey(key));
351
352        match manager.license() {
353            Ok(license) => expect.assert_debug_eq(&license),
354            Err(error) => expect.assert_eq(&error.to_report_string()),
355        }
356
357        manager
358    }
359
360    fn manager_with_tier(tier: Tier) -> LicenseManager {
361        let manager = LicenseManager::new();
362        manager.inner.write().unwrap().license = Ok(License {
363            sub: "rw-unit-test".to_owned(),
364            iss: Issuer::Test,
365            tier,
366            rwu_limit: None,
367            exp: 10000627200,
368        });
369        manager
370    }
371
372    #[test]
373    fn test_all_license_key() {
374        do_test(
375            TEST_ALL_LICENSE_KEY_CONTENT,
376            expect![[r#"
377                License {
378                    sub: "rw-test-all",
379                    iss: Test,
380                    tier: All,
381                    rwu_limit: None,
382                    exp: 10000627200,
383                }
384            "#]],
385        );
386    }
387
388    #[test]
389    fn test_prod_all_4_core_license_key() {
390        do_test(
391            PROD_ALL_4_CORE_LICENSE_KEY_CONTENT,
392            expect![[r#"
393                License {
394                    sub: "rw-default-all-4-core",
395                    iss: Prod,
396                    tier: All,
397                    rwu_limit: Some(
398                        4,
399                    ),
400                    exp: 10000627200,
401                }
402            "#]],
403        );
404    }
405
406    #[test]
407    fn test_free_license_key() {
408        const KEY: &str = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.\
409          eyJzdWIiOiJydy10ZXN0IiwidGllciI6ImZyZWUiLCJpc3MiOiJ0ZXN0LnJpc2luZ3dhdmUuY29tIiwiZXhwIjo5OTk5OTk5OTk5fQ.\
410          ALC3Kc9LI6u0S-jeMB1YTxg1k8Azxwvc750ihuSZgjA_e1OJC9moxMvpLrHdLZDzCXHjBYi0XJ_1lowmuO_0iPEuPqN5AFpDV1ywmzJvGmMCMtw3A2wuN7hhem9OsWbwe6lzdwrefZLipyo4GZtIkg5ZdwGuHzm33zsM-X5gl_Ns4P6axHKiorNSR6nTAyA6B32YVET_FAM2YJQrXqpwA61wn1XLfarZqpdIQyJ5cgyiC33BFBlUL3lcRXLMLeYe6TjYGeV4K63qARCjM9yeOlsRbbW5ViWeGtR2Yf18pN8ysPXdbaXm_P_IVhl3jCTDJt9ctPh6pUCbkt36FZqO9A";
411
412        do_test(
413            KEY,
414            expect![[r#"
415                License {
416                    sub: "rw-test",
417                    iss: Test,
418                    tier: Free,
419                    rwu_limit: None,
420                    exp: 9999999999,
421                }
422            "#]],
423        );
424    }
425
426    #[test]
427    fn test_empty_license_key() {
428        // Default license will be used.
429        do_test(
430            "",
431            expect![[r#"
432                License {
433                    sub: "default",
434                    iss: Prod,
435                    tier: Free,
436                    rwu_limit: None,
437                    exp: 18446744073709551615,
438                }
439            "#]],
440        );
441    }
442
443    #[test]
444    fn test_custom_tier_license_key() {
445        const KEY: &str = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.\
446          eyJzdWIiOiJydy11bml0LXRlc3QiLCJpc3MiOiJ0ZXN0LnJpc2luZ3dhdmUuY29tIiwiZXhwIjoxMDAwMDYyNzIwMCwiaWF0IjoxNzUxODY5OTI3LCJ0aWVyIjp7Im5hbWUiOiJzZWNyZXQtb25seSIsImZlYXR1cmVzIjpbIlNlY3JldE1hbmFnZW1lbnQiXX19.\
447          iZKNyAHxz1l24Qh4F9wauuQEtDPLAeOmW2m_ttlew2ENmP_XcGWCx_O8r50NXRDaKv66z-ibteWVL5XOUqaVgJw9EnCyfVuFNoKtFQu18Vt0l52Yw2zNh3iHNQFKwHuCUki5FlOHw-K57a5f414-gzfwAwQkO1bAYoyAFhtoX6QQ2jdbxctFg0NxTQqpjnP-h0k2myZ_IhxA8fKrQIAqBj5Y8tGljuxjTLJpoK7X0ESXNh7bhA8njEf2Hm4QCymI1uo8OYRaR1Siw87r0aZykw9wW15Q8VK58VxIQLS7b7gQOmDToBjJt9yIF3MT6YMfqMX_l3Dtn9bOS_htVd1bjQ";
448
449        let manager = do_test(
450            KEY,
451            expect![[r#"
452                License {
453                    sub: "rw-unit-test",
454                    iss: Test,
455                    tier: CustomAllowList {
456                        name: "secret-only",
457                        allowed_features: [
458                            Feature(
459                                SecretManagement,
460                            ),
461                        ],
462                    },
463                    rwu_limit: None,
464                    exp: 10000627200,
465                }
466            "#]],
467        );
468
469        let tier = manager.license().unwrap().tier;
470        assert_eq!(
471            tier.available_features().collect::<Vec<_>>(),
472            vec![Feature::SecretManagement]
473        );
474        assert!(
475            Feature::SecretManagement
476                .check_available_with(&manager)
477                .is_ok()
478        );
479        assert!(
480            Feature::BigQuerySink
481                .check_available_with(&manager)
482                .is_err()
483        );
484    }
485
486    #[test]
487    fn test_custom_allow_list_json_compatibility() {
488        let tier: Tier = serde_json::from_str(
489            r#"{
490                "name": "secret-only",
491                "features": ["SecretManagement", "FutureFeature"]
492            }"#,
493        )
494        .unwrap();
495
496        assert_eq!(
497            tier,
498            Tier::CustomAllowList {
499                name: "secret-only".to_owned(),
500                allowed_features: vec![
501                    MaybeFeature::Feature(Feature::SecretManagement),
502                    MaybeFeature::Unknown("FutureFeature".to_owned()),
503                ],
504            }
505        );
506        assert_eq!(
507            serde_json::to_value(tier).unwrap(),
508            serde_json::json!({
509                "name": "secret-only",
510                "features": ["SecretManagement", "FutureFeature"],
511            })
512        );
513    }
514
515    #[test]
516    fn test_custom_deny_list() {
517        let tier: Tier = serde_json::from_str(
518            r#"{
519                "name": "all-except-secret",
520                "excluded_features": ["SecretManagement", "FutureFeature"]
521            }"#,
522        )
523        .unwrap();
524
525        assert_eq!(
526            serde_json::to_value(&tier).unwrap(),
527            serde_json::json!({
528                "name": "all-except-secret",
529                "excluded_features": ["SecretManagement", "FutureFeature"],
530            })
531        );
532        assert_eq!(tier.name(), "all-except-secret");
533        assert_eq!(
534            tier.available_features().collect::<Vec<_>>(),
535            Feature::all()
536                .iter()
537                .copied()
538                .filter(|feature| *feature != Feature::SecretManagement)
539                .collect::<Vec<_>>()
540        );
541
542        let manager = manager_with_tier(tier);
543        assert!(
544            Feature::SecretManagement
545                .check_available_with(&manager)
546                .is_err()
547        );
548        assert!(Feature::BigQuerySink.check_available_with(&manager).is_ok());
549    }
550
551    #[test]
552    fn test_empty_custom_deny_list_allows_all_features() {
553        let tier: Tier = serde_json::from_str(
554            r#"{
555                "name": "all-features",
556                "excluded_features": []
557            }"#,
558        )
559        .unwrap();
560
561        assert_eq!(
562            tier.available_features().collect::<Vec<_>>(),
563            Feature::all()
564        );
565    }
566
567    #[test]
568    fn test_legacy_custom_tier_rejects_deny_list() {
569        #[allow(dead_code)]
570        #[derive(Deserialize)]
571        struct LegacyCustomTier {
572            name: String,
573            features: Vec<MaybeFeature>,
574        }
575
576        assert!(
577            serde_json::from_str::<LegacyCustomTier>(
578                r#"{
579                    "name": "all-except-secret",
580                    "excluded_features": ["SecretManagement"]
581                }"#,
582            )
583            .is_err()
584        );
585    }
586
587    #[test]
588    fn test_invalid_license_key() {
589        const KEY: &str = "invalid";
590
591        do_test(KEY, expect!["invalid license key: InvalidToken"]);
592    }
593
594    #[test]
595    fn test_expired_license_key() {
596        // "exp": 0
597        const KEY: &str = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.\
598          eyJzdWIiOiJydy10ZXN0IiwidGllciI6InBhaWQiLCJpc3MiOiJ0ZXN0LnJpc2luZ3dhdmUuY29tIiwiZXhwIjowfQ.\
599          TyYmoT5Gw9-FN7DWDbeg3myW8g_3Xlc90i4M9bGuPf2WLv9zRMJy2r9J7sl1BO7t6F1uGgyrvNxsVRVZ2XF_WAs6uNlluYBnd4Cqvsj6Xny1XJCCo8II3RIea-ZlRjp6tc1saaoe-_eTtqDH8NIIWe73vVtBeBTBU4zAiN2vCtU_Si2XuoTLBKJMIjtn0HjLNhb6-DX2P3SCzp75tMyWzr49qcsBgratyKdu_v2kqBM1qw_dTaRg2ZeNNO6scSOBwu4YHHJTL4nUaZO2yEodI_OKUztIPLYuO2A33Fb5OE57S7LTgSzmxZLf7e23Vrck7Os14AfBQr7p9ncUeyIXhA";
600
601        do_test(KEY, expect!["invalid license key: ExpiredSignature"]);
602    }
603
604    #[test]
605    fn test_invalid_issuer() {
606        // "iss": "bad.risingwave.com"
607        const KEY: &str = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.\
608          eyJzdWIiOiJydy10ZXN0IiwidGllciI6ImZyZWUiLCJpc3MiOiJiYWQucmlzaW5nd2F2ZS5jb20iLCJleHAiOjk5OTk5OTk5OTl9.\
609          SUbDJTri902FbGgIoe5L3LG4edTXoR42BQCIu_KLyW41OK47bMnD2aK7JggyJmWyGtN7b_596hxM9HjU58oQtHePUo_zHi5li5IcRaMi8gqHae7CJGqOGAUo9vYOWCP5OjEuDfozJhpgcHBLzDRnSwYnWhLKtsrzb3UcpOXEqRVK7EDShBNx6kNqfYs2LlFI7ASsgFRLhoRuOTR5LeVDjj6NZfkZGsdMe1VyrODWoGT9kcAF--hBpUd1ZJ5mZ67A0_948VPFBYDbDPcTRnw1-5MvdibO-jKX49rJ0rlPXcAbqKPE_yYUaqUaORUzb3PaPgCT_quO9PWPuAFIgAb_fg";
610
611        do_test(KEY, expect!["invalid license key: InvalidIssuer"]);
612    }
613
614    #[test]
615    fn test_invalid_signature() {
616        const KEY: &str = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.\
617         eyJzdWIiOiJydy10ZXN0IiwidGllciI6ImZyZWUiLCJpc3MiOiJ0ZXN0LnJpc2luZ3dhdmUuY29tIiwiZXhwIjo5OTk5OTk5OTk5fQ.\
618         InvalidSignatureoe5L3LG4edTXoR42BQCIu_KLyW41OK47bMnD2aK7JggyJmWyGtN7b_596hxM9HjU58oQtHePUo_zHi5li5IcRaMi8gqHae7CJGqOGAUo9vYOWCP5OjEuDfozJhpgcHBLzDRnSwYnWhLKtsrzb3UcpOXEqRVK7EDShBNx6kNqfYs2LlFI7ASsgFRLhoRuOTR5LeVDjj6NZfkZGsdMe1VyrODWoGT9kcAF--hBpUd1ZJ5mZ67A0_948VPFBYDbDPcTRnw1-5MvdibO-jKX49rJ0rlPXcAbqKPE_yYUaqUaORUzb3PaPgCT_quO9PWPuAFIgAb_fg";
619
620        do_test(KEY, expect!["invalid license key: InvalidSignature"]);
621    }
622}