mz_license_keys/
lib.rs
1use 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.";
20const ANY_ENVIRONMENT_AUD: &str = "00000000-0000-0000-0000-000000000000";
25const PUBLIC_KEYS: &[&str] = &[include_str!("license_keys/production.pub")];
28const 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 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 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 ];
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}