refactor: add warnings about jwt token secret not set (#986)

r0.7
Meng Zhang 2023-12-08 19:46:06 +08:00 committed by GitHub
parent 2714b88878
commit 711a389197
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 25 additions and 3 deletions

View File

@ -8,17 +8,20 @@ use juniper::{FieldError, GraphQLObject, IntoFieldError, ScalarValue};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{error, warn};
use uuid::Uuid;
use validator::ValidationErrors;
use super::from_validation_errors;
lazy_static! {
static ref JWT_TOKEN_SECRET: String = jwt_token_secret();
static ref JWT_ENCODING_KEY: jwt::EncodingKey = jwt::EncodingKey::from_secret(
jwt_token_secret().as_bytes()
JWT_TOKEN_SECRET.as_bytes()
);
static ref JWT_DECODING_KEY: jwt::DecodingKey = jwt::DecodingKey::from_secret(
jwt_token_secret().as_bytes()
JWT_TOKEN_SECRET.as_bytes()
);
static ref JWT_DEFAULT_EXP: u64 = 30 * 60; // 30 minutes
}
@ -36,7 +39,26 @@ pub fn validate_jwt(token: &str) -> jwt::errors::Result<Claims> {
}
fn jwt_token_secret() -> String {
std::env::var("TABBY_WEBSERVER_JWT_TOKEN_SECRET").unwrap_or("default_secret".to_string())
let jwt_secret = match std::env::var("TABBY_WEBSERVER_JWT_TOKEN_SECRET") {
Ok(x) => x,
Err(_) => {
eprintln!("
\x1b[93;1mJWT secret is not set\x1b[0m
Tabby server will generate a one-time (non-persisted) JWT secret for the current process.
Please set the \x1b[94mTABBY_WEBSERVER_JWT_TOKEN_SECRET\x1b[0m environment variable for production usage.
"
);
Uuid::new_v4().to_string()
}
};
if uuid::Uuid::parse_str(&jwt_secret).is_err() {
warn!("JWT token secret needs to be in standard uuid format to ensure its security, you might generate one at https://www.uuidgenerator.net");
std::process::exit(1)
}
jwt_secret
}
pub fn generate_refresh_token() -> String {