1use crate::Cents;
2use crate::db::billing_subscription::SubscriptionKind;
3use crate::db::{billing_subscription, user};
4use crate::llm::{
5 AGENT_EXTENDED_TRIAL_FEATURE_FLAG, DEFAULT_MAX_MONTHLY_SPEND, FREE_TIER_MONTHLY_SPENDING_LIMIT,
6};
7use crate::{Config, db::billing_preference};
8use anyhow::{Result, anyhow};
9use chrono::{NaiveDateTime, Utc};
10use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation};
11use serde::{Deserialize, Serialize};
12use std::time::Duration;
13use thiserror::Error;
14use util::maybe;
15use uuid::Uuid;
16use zed_llm_client::Plan;
17
18#[derive(Clone, Debug, Default, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct LlmTokenClaims {
21 pub iat: u64,
22 pub exp: u64,
23 pub jti: String,
24 pub user_id: u64,
25 pub system_id: Option<String>,
26 pub metrics_id: Uuid,
27 pub github_user_login: String,
28 pub account_created_at: NaiveDateTime,
29 pub is_staff: bool,
30 pub has_llm_closed_beta_feature_flag: bool,
31 pub bypass_account_age_check: bool,
32 pub has_llm_subscription: bool,
33 #[serde(default)]
34 pub use_llm_request_queue: bool,
35 pub max_monthly_spend_in_cents: u32,
36 pub custom_llm_monthly_allowance_in_cents: Option<u32>,
37 #[serde(default)]
38 pub use_new_billing: bool,
39 pub plan: Plan,
40 #[serde(default)]
41 pub has_extended_trial: bool,
42 #[serde(default)]
43 pub subscription_period: Option<(NaiveDateTime, NaiveDateTime)>,
44 #[serde(default)]
45 pub enable_model_request_overages: bool,
46 #[serde(default)]
47 pub model_request_overages_spend_limit_in_cents: u32,
48 #[serde(default)]
49 pub can_use_web_search_tool: bool,
50}
51
52const LLM_TOKEN_LIFETIME: Duration = Duration::from_secs(60 * 60);
53
54impl LlmTokenClaims {
55 pub fn create(
56 user: &user::Model,
57 is_staff: bool,
58 billing_preferences: Option<billing_preference::Model>,
59 feature_flags: &Vec<String>,
60 has_legacy_llm_subscription: bool,
61 subscription: Option<billing_subscription::Model>,
62 system_id: Option<String>,
63 config: &Config,
64 ) -> Result<String> {
65 let secret = config
66 .llm_api_secret
67 .as_ref()
68 .ok_or_else(|| anyhow!("no LLM API secret"))?;
69
70 let now = Utc::now();
71 let claims = Self {
72 iat: now.timestamp() as u64,
73 exp: (now + LLM_TOKEN_LIFETIME).timestamp() as u64,
74 jti: uuid::Uuid::new_v4().to_string(),
75 user_id: user.id.to_proto(),
76 system_id,
77 metrics_id: user.metrics_id,
78 github_user_login: user.github_login.clone(),
79 account_created_at: user.account_created_at(),
80 is_staff,
81 has_llm_closed_beta_feature_flag: feature_flags
82 .iter()
83 .any(|flag| flag == "llm-closed-beta"),
84 bypass_account_age_check: feature_flags
85 .iter()
86 .any(|flag| flag == "bypass-account-age-check"),
87 can_use_web_search_tool: feature_flags.iter().any(|flag| flag == "assistant2"),
88 has_llm_subscription: has_legacy_llm_subscription,
89 max_monthly_spend_in_cents: billing_preferences
90 .as_ref()
91 .map_or(DEFAULT_MAX_MONTHLY_SPEND.0, |preferences| {
92 preferences.max_monthly_llm_usage_spending_in_cents as u32
93 }),
94 custom_llm_monthly_allowance_in_cents: user
95 .custom_llm_monthly_allowance_in_cents
96 .map(|allowance| allowance as u32),
97 use_new_billing: feature_flags.iter().any(|flag| flag == "new-billing"),
98 use_llm_request_queue: feature_flags.iter().any(|flag| flag == "llm-request-queue"),
99 plan: subscription
100 .as_ref()
101 .and_then(|subscription| subscription.kind)
102 .map_or(Plan::Free, |kind| match kind {
103 SubscriptionKind::ZedFree => Plan::Free,
104 SubscriptionKind::ZedPro => Plan::ZedPro,
105 SubscriptionKind::ZedProTrial => Plan::ZedProTrial,
106 }),
107 has_extended_trial: feature_flags
108 .iter()
109 .any(|flag| flag == AGENT_EXTENDED_TRIAL_FEATURE_FLAG),
110 subscription_period: maybe!({
111 let subscription = subscription?;
112 let period_start_at = subscription.current_period_start_at()?;
113 let period_end_at = subscription.current_period_end_at()?;
114
115 Some((period_start_at.naive_utc(), period_end_at.naive_utc()))
116 }),
117 enable_model_request_overages: billing_preferences
118 .as_ref()
119 .map_or(false, |preferences| {
120 preferences.model_request_overages_enabled
121 }),
122 model_request_overages_spend_limit_in_cents: billing_preferences
123 .as_ref()
124 .map_or(0, |preferences| {
125 preferences.model_request_overages_spend_limit_in_cents as u32
126 }),
127 };
128
129 Ok(jsonwebtoken::encode(
130 &Header::default(),
131 &claims,
132 &EncodingKey::from_secret(secret.as_ref()),
133 )?)
134 }
135
136 pub fn validate(token: &str, config: &Config) -> Result<LlmTokenClaims, ValidateLlmTokenError> {
137 let secret = config
138 .llm_api_secret
139 .as_ref()
140 .ok_or_else(|| anyhow!("no LLM API secret"))?;
141
142 match jsonwebtoken::decode::<Self>(
143 token,
144 &DecodingKey::from_secret(secret.as_ref()),
145 &Validation::default(),
146 ) {
147 Ok(token) => Ok(token.claims),
148 Err(e) => {
149 if e.kind() == &jsonwebtoken::errors::ErrorKind::ExpiredSignature {
150 Err(ValidateLlmTokenError::Expired)
151 } else {
152 Err(ValidateLlmTokenError::JwtError(e))
153 }
154 }
155 }
156 }
157
158 pub fn free_tier_monthly_spending_limit(&self) -> Cents {
159 self.custom_llm_monthly_allowance_in_cents
160 .map(Cents)
161 .unwrap_or(FREE_TIER_MONTHLY_SPENDING_LIMIT)
162 }
163}
164
165#[derive(Error, Debug)]
166pub enum ValidateLlmTokenError {
167 #[error("access token is expired")]
168 Expired,
169 #[error("access token validation error: {0}")]
170 JwtError(#[from] jsonwebtoken::errors::Error),
171 #[error("{0}")]
172 Other(#[from] anyhow::Error),
173}