Skip to content

Commit

Permalink
Minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
vladbochok committed Dec 10, 2020
1 parent 75a73f0 commit e81d133
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 63 deletions.
10 changes: 6 additions & 4 deletions core/bin/prover/src/auth_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ use std::time;

#[derive(Debug, Serialize, Deserialize)]
struct PayloadAuthToken {
sub: String, // Subject (whom auth token refers to)
exp: usize, // Expiration time (as UTC timestamp)
/// Subject (whom auth token refers to).
sub: String,
/// Expiration time (as UTC timestamp).
exp: usize,
}

impl PayloadAuthToken {
Expand All @@ -24,9 +26,9 @@ pub struct AuthTokenGenerator {
}

impl AuthTokenGenerator {
pub fn new(secret: &str, period_availability: time::Duration) -> Self {
pub fn new(secret: String, period_availability: time::Duration) -> Self {
Self {
secret: secret.to_string(),
secret,
period_availability,
}
}
Expand Down
50 changes: 14 additions & 36 deletions core/bin/prover/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ impl ApiClient {
.timeout(req_server_timeout)
.build()
.expect("Failed to create request client");
let auth_token_generator = AuthTokenGenerator::new(secret, Self::AUTH_TOKEN_LIFETIME);
let auth_token_generator =
AuthTokenGenerator::new(secret.to_string(), Self::AUTH_TOKEN_LIFETIME);
Self {
register_url: base_url.join("/register").unwrap(),
block_to_prove_url: base_url.join("/block_to_prove").unwrap(),
Expand All @@ -62,6 +63,12 @@ impl ApiClient {
}
}

fn get_encoded_token(&self) -> anyhow::Result<String> {
self.auth_token_generator
.encode()
.map_err(|e| format_err!("failed generate authorization token: {}", e))
}

fn with_retries<T>(
&self,
op: &dyn Fn() -> Result<T, anyhow::Error>,
Expand Down Expand Up @@ -98,17 +105,12 @@ impl ApiClient {
}

pub fn register_prover(&self, block_size: usize) -> anyhow::Result<i32> {
let auth_token_generator = self
.auth_token_generator
.encode()
.map_err(|e| format_err!("failed generate authorization token: {}", e))?;

let op = || -> Result<i32, anyhow::Error> {
info!("Registering prover...");
let res = self
.http_client
.post(self.register_url.as_str())
.bearer_auth(&auth_token_generator)
.bearer_auth(&self.get_encoded_token()?)
.json(&client::ProverReq {
name: self.worker.clone(),
block_size,
Expand All @@ -130,17 +132,12 @@ impl ApiClient {

impl crate::ApiClient for ApiClient {
fn block_to_prove(&self, block_size: usize) -> Result<Option<(i64, i32)>, anyhow::Error> {
let auth_token_generator = self
.auth_token_generator
.encode()
.map_err(|e| format_err!("failed generate authorization token: {}", e))?;

let op = || -> Result<Option<(i64, i32)>, anyhow::Error> {
trace!("sending block_to_prove");
let res = self
.http_client
.get(self.block_to_prove_url.as_str())
.bearer_auth(&auth_token_generator)
.bearer_auth(&self.get_encoded_token()?)
.json(&client::ProverReq {
name: self.worker.clone(),
block_size,
Expand All @@ -163,15 +160,11 @@ impl crate::ApiClient for ApiClient {

fn working_on(&self, job_id: i32) -> Result<(), anyhow::Error> {
trace!("sending working_on {}", job_id);
let auth_token_generator = self
.auth_token_generator
.encode()
.map_err(|e| format_err!("failed generate authorization token: {}", e))?;

let res = self
.http_client
.post(self.working_on_url.as_str())
.bearer_auth(&auth_token_generator)
.bearer_auth(&self.get_encoded_token()?)
.json(&client::WorkingOnReq {
prover_run_id: job_id,
})
Expand All @@ -185,17 +178,12 @@ impl crate::ApiClient for ApiClient {
}

fn prover_data(&self, block: i64) -> Result<ZkSyncCircuit<'_, Engine>, anyhow::Error> {
let auth_token_generator = self
.auth_token_generator
.encode()
.map_err(|e| format_err!("failed generate authorization token: {}", e))?;

let op = || -> Result<ProverData, anyhow::Error> {
trace!("sending prover_data");
let res = self
.http_client
.get(self.prover_data_url.as_str())
.bearer_auth(&auth_token_generator)
.bearer_auth(&self.get_encoded_token()?)
.json(&block)
.send()
.map_err(|e| format_err!("failed to request prover data: {}", e))?;
Expand All @@ -212,18 +200,13 @@ impl crate::ApiClient for ApiClient {
}

fn publish(&self, block: i64, proof: EncodedProofPlonk) -> Result<(), anyhow::Error> {
let auth_token_generator = self
.auth_token_generator
.encode()
.map_err(|e| format_err!("failed generate authorization token: {}", e))?;

let op = move || -> Result<(), anyhow::Error> {
trace!("Trying publish proof {}", block);
let proof = proof.clone();
let res = self
.http_client
.post(self.publish_url.as_str())
.bearer_auth(&auth_token_generator)
.bearer_auth(&self.get_encoded_token()?)
.json(&client::PublishReq {
block: block as u32,
proof,
Expand Down Expand Up @@ -257,14 +240,9 @@ impl crate::ApiClient for ApiClient {
}

fn prover_stopped(&self, prover_run_id: i32) -> Result<(), anyhow::Error> {
let auth_token_generator = self
.auth_token_generator
.encode()
.map_err(|e| format_err!("failed generate authorization token: {}", e))?;

self.http_client
.post(self.stopped_url.as_str())
.bearer_auth(&auth_token_generator)
.bearer_auth(&self.get_encoded_token()?)
.json(&prover_run_id)
.send()
.map_err(|e| format_err!("prover stopped request failed: {}", e))?;
Expand Down
23 changes: 15 additions & 8 deletions core/bin/zksync_api/src/api_server/admin_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ use zksync_utils::panic_notify::ThreadPanicNotify;

#[derive(Debug, Serialize, Deserialize)]
struct PayloadAuthToken {
sub: String, // Subject (whom auth token refers to)
exp: usize, // Expiration time (as UTC timestamp)
/// Subject (whom auth token refers to).
sub: String,
/// Expiration time (as UTC timestamp).
exp: usize,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -67,9 +69,9 @@ impl<'a> AuthTokenValidator<'a> {

/// Validate JsonWebToken
fn validate_auth_token(&self, token: &str) -> Result<(), JwtError> {
let token = decode::<PayloadAuthToken>(token, &self.decoding_key, &Validation::default());
decode::<PayloadAuthToken>(token, &self.decoding_key, &Validation::default())?;

token.map(drop)
Ok(())
}

async fn validator(
Expand All @@ -78,10 +80,11 @@ impl<'a> AuthTokenValidator<'a> {
credentials: BearerAuth,
) -> actix_web::Result<ServiceRequest> {
let config = req.app_data::<Config>().cloned().unwrap_or_default();

self.validate_auth_token(credentials.token())
.map(|_| req)
.map_err(|_| AuthenticationError::from(config).into())
.map_err(|_| AuthenticationError::from(config))?;

Ok(req)
}
}

Expand Down Expand Up @@ -125,7 +128,11 @@ async fn add_token(
async fn run_server(app_state: AppState, bind_to: SocketAddr) {
HttpServer::new(move || {
let auth = HttpAuthentication::bearer(move |req, credentials| async {
let secret_auth = req.app_data::<AppState>().unwrap().secret_auth.clone();
let secret_auth = req
.app_data::<AppState>()
.expect("failed get AppState upon receipt of the authentication token")
.secret_auth
.clone();
AuthTokenValidator::new(&secret_auth)
.validator(req, credentials)
.await
Expand Down
17 changes: 10 additions & 7 deletions core/bin/zksync_witness_generator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ mod witness_generator;

#[derive(Debug, Serialize, Deserialize)]
struct PayloadAuthToken {
sub: String, // Subject (whom auth token refers to)
exp: usize, // Expiration time (as UTC timestamp)
/// Subject (whom auth token refers to).
sub: String,
/// Expiration time (as UTC timestamp).
exp: usize,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -82,9 +84,9 @@ impl<'a> AuthTokenValidator<'a> {

/// Checks whether the secret key and the authorization token match.
fn validate_auth_token(&self, token: &str) -> Result<(), JwtError> {
let token = decode::<PayloadAuthToken>(token, &self.decoding_key, &Validation::default());
decode::<PayloadAuthToken>(token, &self.decoding_key, &Validation::default())?;

token.map(drop)
Ok(())
}

async fn validator(
Expand All @@ -95,8 +97,9 @@ impl<'a> AuthTokenValidator<'a> {
let config = req.app_data::<Config>().cloned().unwrap_or_default();

self.validate_auth_token(credentials.token())
.map(|_| req)
.map_err(|_| AuthenticationError::from(config).into())
.map_err(|_| AuthenticationError::from(config))?;

Ok(req)
}
}

Expand Down Expand Up @@ -357,7 +360,7 @@ pub fn run_prover_server(
let auth = HttpAuthentication::bearer(move |req, credentials| async {
let secret_auth = req
.app_data::<web::Data<AppState>>()
.unwrap()
.expect("failed get AppState upon receipt of the authentication token")
.secret_auth
.clone();
AuthTokenValidator::new(&secret_auth)
Expand Down
23 changes: 20 additions & 3 deletions core/lib/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,23 @@ impl ProverOptions {
/// Parses the configuration options values from the environment variables.
/// Panics if any of options is missing or has inappropriate value.
pub fn from_env() -> Self {
let secret_auth = get_env("PROVER_SECRET_AUTH");
let network = get_env("ETH_NETWORK");

// Checks if an untrusted key is being used for production.
if &secret_auth == "sample" && &network != "localhost" {
log::error!("Prover secret for JWT authorization set to 'sample', this is an incorrect value for production");
}

Self {
secret_auth: get_env("PROVER_SECRET_AUTH"),
prepare_data_interval: Duration::from_millis(parse_env("PROVER_PREPARE_DATA_INTERVAL")),
heartbeat_interval: Duration::from_millis(parse_env("PROVER_HEARTBEAT_INTERVAL")),
cycle_wait: Duration::from_millis(parse_env("PROVER_CYCLE_WAIT")),
gone_timeout: Duration::from_millis(parse_env("PROVER_GONE_TIMEOUT")),
prover_server_address: addr_from_port(parse_env("PROVER_SERVER_PORT")),
witness_generators: parse_env("WITNESS_GENERATORS"),
idle_provers: parse_env("IDLE_PROVERS"),
secret_auth,
}
}
}
Expand All @@ -107,10 +115,18 @@ impl AdminServerOptions {
/// Parses the configuration options values from the environment variables.
/// Panics if any of options is missing or has inappropriate value.
pub fn from_env() -> Self {
let secret_auth = get_env("ADMIN_SERVER_SECRET_AUTH");
let network = get_env("ETH_NETWORK");

// Checks if an untrusted key is being used for production.
if &secret_auth == "sample" && &network != "localhost" {
log::error!("Admin server secret for JWT authorization set to 'sample', this is an incorrect value for production");
}

Self {
admin_http_server_url: parse_env("ADMIN_SERVER_API_URL"),
admin_http_server_address: addr_from_port(parse_env("ADMIN_SERVER_API_PORT")),
secret_auth: get_env("ADMIN_SERVER_SECRET_AUTH"),
secret_auth,
}
}
}
Expand Down Expand Up @@ -214,8 +230,9 @@ impl ApiServerOptions {
pub fn from_env() -> Self {
let forced_exit_minimum_account_age =
Duration::from_secs(parse_env::<u64>("FORCED_EXIT_MINIMUM_ACCOUNT_AGE_SECS"));
let network = get_env("ETH_NETWORK");

if forced_exit_minimum_account_age.as_secs() == 0 {
if forced_exit_minimum_account_age.as_secs() == 0 && &network != "localhost" {
log::error!("Forced exit minimum account age is set to 0, this is an incorrect value for production");
}

Expand Down
8 changes: 5 additions & 3 deletions etc/env/dev.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ PROVER_CYCLE_WAIT=500
PROVER_GONE_TIMEOUT=60000

# Shared secret for authorization to prover server using JSON Web Token
PROVER_SECRET_AUTH=321
# Don't use the `sample` for production
PROVER_SECRET_AUTH=sample

# Download setup files from SETUP_NETWORK_DIR if PROVER_DOWNLOAD_SETUP=1 or use local files if PROVER_DOWNLOAD_SETUP=0
PROVER_DOWNLOAD_SETUP=false
Expand All @@ -87,7 +88,8 @@ DOCKER_DUMMY_PROVER=false
ADMIN_SERVER_API_PORT=8080
ADMIN_SERVER_API_URL=http://127.0.0.1:8080
# Shared secret for authorization to admin server using JSON Web Token
ADMIN_SERVER_SECRET_AUTH=123
# Don't use the `sample` for production
ADMIN_SERVER_SECRET_AUTH=sample

REST_API_PORT=3001
HTTP_RPC_API_PORT=3030
Expand Down Expand Up @@ -126,7 +128,7 @@ REQ_SERVER_TIMEOUT=10

API_REQUESTS_CACHES_SIZE=10000

RUST_LOG="zksync_api=debug,zksync_core=debug,zksync_eth_sender=debug,zksync_witness_generator=debug,zksync_server=debug,zksync_prover=debug,dummy_prover=info,key_generator=info,zksync_data_restore=info,zksync_eth_client=info,zksync_storage=info,zksync_state=info,zksync_types=info,exodus_test=info,loadtest=info,kube=debug,dev_ticker=info,block_sizes_test=info"
RUST_LOG="zksync_api=debug,zksync_core=debug,zksync_eth_sender=debug,zksync_witness_generator=debug,zksync_server=debug,zksync_prover=debug,dummy_prover=info,key_generator=info,zksync_data_restore=info,zksync_eth_client=info,zksync_storage=info,zksync_state=info,zksync_types=info,exodus_test=info,loadtest=info,kube=debug,dev_ticker=info,block_sizes_test=info,zksync_config=debug"

ZKSYNC_ACTION=dont_ask

Expand Down
6 changes: 4 additions & 2 deletions infrastructure/tok_cli/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ pub fn get_matches_from_lines(stream: &str, pattern: &str) -> Result<String> {

#[derive(Debug, Serialize, Deserialize)]
struct PayloadAuthToken {
sub: String, // Subject (whom auth token refers to)
exp: usize, // Expiration time (as UTC timestamp)
/// Subject (whom auth token refers to).
sub: String,
/// Expiration time (as UTC timestamp).
exp: usize,
}

/// Encode JsonWebToken with shared secret - secret,
Expand Down

0 comments on commit e81d133

Please sign in to comment.