mz_license_keys/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use anyhow::{anyhow, bail};
11use jsonwebtoken::{Algorithm, DecodingKey, TokenData, Validation};
12use serde::{Deserialize, Serialize};
13
14#[cfg(feature = "signing")]
15mod signing;
16#[cfg(feature = "signing")]
17pub use signing::{get_pubkey_pem, make_license_key};
18
19const ISSUER: &str = "Materialize, Inc.";
20// this will be used specifically by cloud to avoid needing to issue separate
21// license keys for each environment when it comes up - just being able to
22// share a single license key that allows all environments and never expires
23// will be much simpler to maintain
24const ANY_ENVIRONMENT_AUD: &str = "00000000-0000-0000-0000-000000000000";
25// list of public keys which are allowed to validate license keys. this is a
26// list to allow for key rotation if necessary.
27const PUBLIC_KEYS: &[&str] = &[include_str!("license_keys/production.pub")];
28// keys which we have issued but need to be revoked before their expiration
29// (due to being accidentally exposed or similar).
30const REVOKED_KEYS: &[&str] = &["eddaf004-dc1e-48cf-9cc1-41d1543d940a"];
31
32#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
33pub enum ExpirationBehavior {
34    Warn,
35    DisableClusterCreation,
36    Disable,
37}
38
39#[derive(Debug, Clone, Copy)]
40pub struct ValidatedLicenseKey {
41    pub max_credit_consumption_rate: f64,
42    pub allow_credit_consumption_override: bool,
43    pub expiration_behavior: ExpirationBehavior,
44    pub expired: bool,
45}
46
47impl ValidatedLicenseKey {
48    pub fn for_tests() -> Self {
49        Self {
50            max_credit_consumption_rate: 999999.0,
51            allow_credit_consumption_override: true,
52            expiration_behavior: ExpirationBehavior::Warn,
53            expired: false,
54        }
55    }
56
57    pub fn max_credit_consumption_rate(&self) -> Option<f64> {
58        if self.expired
59            && matches!(
60                self.expiration_behavior,
61                ExpirationBehavior::DisableClusterCreation | ExpirationBehavior::Disable
62            )
63        {
64            Some(0.0)
65        } else if self.allow_credit_consumption_override {
66            None
67        } else {
68            Some(self.max_credit_consumption_rate)
69        }
70    }
71}
72
73impl Default for ValidatedLicenseKey {
74    fn default() -> Self {
75        // this is used for the emulator if no license key is provided
76        Self {
77            max_credit_consumption_rate: 24.0,
78            allow_credit_consumption_override: false,
79            expiration_behavior: ExpirationBehavior::Disable,
80            expired: false,
81        }
82    }
83}
84
85pub fn validate(license_key: &str, environment_id: &str) -> anyhow::Result<ValidatedLicenseKey> {
86    let mut err = None;
87    for pubkey in PUBLIC_KEYS {
88        match validate_with_pubkey(license_key, pubkey, environment_id) {
89            Ok(key) => {
90                return Ok(key);
91            }
92            Err(e) => {
93                err = Some(e);
94            }
95        }
96    }
97
98    if let Some(err) = err {
99        Err(err)
100    } else {
101        Err(anyhow!("no public key found"))
102    }
103}
104
105fn validate_with_pubkey(
106    license_key: &str,
107    pubkey_pem: &str,
108    environment_id: &str,
109) -> anyhow::Result<ValidatedLicenseKey> {
110    // don't just read the version out of the payload before verifying it,
111    // trusting unsigned data to determine how to verify the signature is a
112    // bad idea. instead, just try validating it as each version
113    // independently, and if the signature is valid, only then check to
114    // ensure that the version matches what we validated.
115
116    // try current version first, so we can prefer that for error messages
117    let res = validate_with_pubkey_v1(license_key, pubkey_pem, environment_id);
118    let err = match res {
119        Ok(key) => return Ok(key),
120        Err(e) => e,
121    };
122
123    let previous_versions: Vec<Box<dyn Fn() -> anyhow::Result<ValidatedLicenseKey>>> = vec![
124        // add to this if/when we add new versions
125        // for example,
126        // Box::new(|| validate_with_pubkey_v1(license_key, pubkey_pem, environment_id)),
127    ];
128    for validator in previous_versions {
129        if let Ok(key) = validator() {
130            return Ok(key);
131        }
132    }
133
134    Err(err)
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
138struct Payload {
139    sub: String,
140    exp: u64,
141    nbf: u64,
142    iss: String,
143    aud: String,
144    iat: u64,
145    jti: String,
146
147    version: u64,
148    max_credit_consumption_rate: f64,
149    #[serde(default, skip_serializing_if = "is_default")]
150    allow_credit_consumption_override: bool,
151    expiration_behavior: ExpirationBehavior,
152}
153
154fn validate_with_pubkey_v1(
155    license_key: &str,
156    pubkey_pem: &str,
157    environment_id: &str,
158) -> anyhow::Result<ValidatedLicenseKey> {
159    let mut validation = Validation::new(Algorithm::PS256);
160    validation.set_required_spec_claims(&["exp", "nbf", "aud", "iss", "sub"]);
161    validation.set_audience(&[environment_id, ANY_ENVIRONMENT_AUD]);
162    validation.set_issuer(&[ISSUER]);
163    validation.validate_exp = true;
164    validation.validate_nbf = true;
165    validation.validate_aud = true;
166
167    let key = DecodingKey::from_rsa_pem(pubkey_pem.as_bytes())?;
168
169    let (jwt, expired): (TokenData<Payload>, _) =
170        jsonwebtoken::decode(license_key, &key, &validation).map_or_else(
171            |e| {
172                if matches!(e.kind(), jsonwebtoken::errors::ErrorKind::ExpiredSignature) {
173                    validation.validate_exp = false;
174                    Ok((jsonwebtoken::decode(license_key, &key, &validation)?, true))
175                } else {
176                    Err::<_, anyhow::Error>(e.into())
177                }
178            },
179            |jwt| Ok((jwt, false)),
180        )?;
181
182    if jwt.header.typ.as_deref() != Some("JWT") {
183        bail!("invalid jwt header type");
184    }
185
186    if jwt.claims.version != 1 {
187        bail!("invalid license key version");
188    }
189
190    if !(jwt.claims.nbf..=jwt.claims.exp).contains(&jwt.claims.iat) {
191        bail!("invalid issuance time");
192    }
193
194    if REVOKED_KEYS.contains(&jwt.claims.jti.as_str()) {
195        bail!("revoked license key");
196    }
197
198    Ok(ValidatedLicenseKey {
199        max_credit_consumption_rate: jwt.claims.max_credit_consumption_rate,
200        allow_credit_consumption_override: jwt.claims.allow_credit_consumption_override,
201        expiration_behavior: jwt.claims.expiration_behavior,
202        expired,
203    })
204}
205
206fn is_default<T: PartialEq + Eq + Default>(val: &T) -> bool {
207    *val == T::default()
208}