cat_gateway/settings/
mod.rs

1//! Command line and environment variable settings for the service
2use std::{
3    net::{IpAddr, Ipv4Addr, SocketAddr},
4    str::FromStr,
5    sync::{LazyLock, OnceLock},
6    time::Duration,
7};
8
9use anyhow::anyhow;
10use cardano_chain_follower::{Network, Slot};
11use clap::Args;
12use dotenvy::dotenv;
13use str_env_var::StringEnvVar;
14use tracing::error;
15use url::Url;
16
17use crate::{
18    build_info::{BUILD_INFO, log_build_info},
19    logger::{self, LOG_LEVEL_DEFAULT, LogLevel},
20    service::utilities::net::{get_public_ipv4, get_public_ipv6},
21    utils::blake2b_hash::generate_uuid_string_from_data,
22};
23
24pub(crate) mod admin;
25pub(crate) mod cardano_assets_cache;
26pub(crate) mod cassandra_db;
27pub(crate) mod chain_follower;
28pub(crate) mod event_db;
29pub(crate) mod rbac;
30pub(crate) mod signed_doc;
31mod str_env_var;
32
33/// Default address to start service on, '0.0.0.0:3030'.
34const ADDRESS_DEFAULT: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 3030);
35
36/// Default Github repo owner
37const GITHUB_REPO_OWNER_DEFAULT: &str = "input-output-hk";
38
39/// Default Github repo name
40const GITHUB_REPO_NAME_DEFAULT: &str = "catalyst-voices";
41
42/// Default Github issue template to use
43const GITHUB_ISSUE_TEMPLATE_DEFAULT: &str = "bug_report.yml";
44
45/// Default `CLIENT_ID_KEY` used in development.
46const CLIENT_ID_KEY_DEFAULT: &str = "3db5301e-40f2-47ed-ab11-55b37674631a";
47
48/// Default `API_URL_PREFIX` used in development.
49const API_URL_PREFIX_DEFAULT: &str = "/api";
50
51/// Default `CHECK_CONFIG_TICK` used in development, 5 seconds.
52const CHECK_CONFIG_TICK_DEFAULT: Duration = Duration::from_secs(5);
53
54/// Default number of slots used as overlap when purging Live Index data.
55const PURGE_BACKWARD_SLOT_BUFFER_DEFAULT: u64 = 100;
56
57/// Default `SERVICE_LIVE_TIMEOUT_INTERVAL`, that is used to determine if the service is
58/// live, 30 seconds.
59const SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
60
61/// Default `SERVICE_LIVE_COUNTER_THRESHOLD`, that is used to determine if the service is
62/// live.
63const SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT: u64 = 100;
64
65/// Hash the Public IPv4 and IPv6 address of the machine, and convert to a 128 bit V4
66/// UUID.
67fn calculate_service_uuid() -> String {
68    let ip_addr: Vec<String> = vec![get_public_ipv4().to_string(), get_public_ipv6().to_string()];
69
70    generate_uuid_string_from_data("Catalyst-Gateway-Machine-UID", &ip_addr)
71}
72
73/// Settings for the application.
74///
75/// This struct represents the configuration settings for the application.
76/// It is used to specify the server binding address,
77/// the URL to the `PostgreSQL` event database,
78/// and the logging level.
79#[derive(Args, Clone)]
80#[clap(version = BUILD_INFO)]
81pub(crate) struct ServiceSettings {
82    /// Logging level
83    #[clap(long, default_value = LOG_LEVEL_DEFAULT)]
84    pub(crate) log_level: LogLevel,
85}
86
87/// All the `EnvVars` used by the service.
88struct EnvVars {
89    /// The github repo owner
90    github_repo_owner: StringEnvVar,
91
92    /// The github repo name
93    github_repo_name: StringEnvVar,
94
95    /// The github issue template to use
96    github_issue_template: StringEnvVar,
97
98    /// Server binding address
99    address: SocketAddr,
100
101    /// Server name
102    server_name: Option<StringEnvVar>,
103
104    /// Id of the Service.
105    service_id: StringEnvVar,
106
107    /// The client id key used to anonymize client connections.
108    client_id_key: StringEnvVar,
109
110    /// A List of servers to provide
111    api_host_names: Vec<String>,
112
113    /// The base path the API is served at.
114    api_url_prefix: StringEnvVar,
115
116    /// Flag by enabling `/panic` endpoint if its set
117    /// Enabled is `YES_I_REALLY_WANT_TO_PANIC` env var is set
118    /// and equals to `"panic attack"`
119    is_panic_endpoint_enabled: bool,
120
121    /// The Config of the Persistent Cassandra DB.
122    cassandra_persistent_db: cassandra_db::EnvVars,
123
124    /// The Config of the Volatile Cassandra DB.
125    cassandra_volatile_db: cassandra_db::EnvVars,
126
127    /// The Chain Follower configuration
128    chain_follower: chain_follower::EnvVars,
129
130    /// The event db configuration
131    event_db: event_db::EnvVars,
132
133    /// The Catalyst Signed Documents configuration
134    signed_doc: signed_doc::EnvVars,
135
136    /// RBAC configuration.
137    rbac: rbac::EnvVars,
138
139    /// The Cardano assets caches configuration
140    cardano_assets_cache: cardano_assets_cache::EnvVars,
141
142    /// Internal API Access API Key
143    internal_api_key: Option<StringEnvVar>,
144
145    /// Tick every N seconds until config exists in db
146    #[allow(unused)]
147    check_config_tick: Duration,
148
149    /// Slot buffer used as overlap when purging Live Index data.
150    purge_backward_slot_buffer: u64,
151
152    /// Interval for determining if the service is live.
153    service_live_timeout_interval: Duration,
154
155    /// Threshold for determining if the service is live.
156    service_live_counter_threshold: u64,
157
158    /// Set to Log 404 not found.
159    log_not_found: Option<StringEnvVar>,
160}
161
162// Lazy initialization of all env vars which are not command line parameters.
163// All env vars used by the application should be listed here and all should have a
164// default. The default for all NON Secret values should be suitable for Production, and
165// NOT development. Secrets however should only be used with the default value in
166// development
167
168/// Handle to the mithril sync thread. One for each Network ONLY.
169static ENV_VARS: LazyLock<EnvVars> = LazyLock::new(|| {
170    // Support env vars in a `.env` file,  doesn't need to exist.
171    dotenv().ok();
172
173    let address = StringEnvVar::new("ADDRESS", ADDRESS_DEFAULT.to_string().into());
174    let address = SocketAddr::from_str(address.as_str())
175        .inspect_err(|err| {
176            error!(
177                error = ?err,
178                default_addr = ?ADDRESS_DEFAULT,
179                invalid_addr = ?address,
180                "Invalid binding address. Using default binding address value.",
181            );
182        })
183        .unwrap_or(ADDRESS_DEFAULT);
184
185    let purge_backward_slot_buffer = StringEnvVar::new_as_int(
186        "PURGE_BACKWARD_SLOT_BUFFER",
187        PURGE_BACKWARD_SLOT_BUFFER_DEFAULT,
188        0,
189        u64::MAX,
190    );
191
192    EnvVars {
193        github_repo_owner: StringEnvVar::new("GITHUB_REPO_OWNER", GITHUB_REPO_OWNER_DEFAULT.into()),
194        github_repo_name: StringEnvVar::new("GITHUB_REPO_NAME", GITHUB_REPO_NAME_DEFAULT.into()),
195        github_issue_template: StringEnvVar::new(
196            "GITHUB_ISSUE_TEMPLATE",
197            GITHUB_ISSUE_TEMPLATE_DEFAULT.into(),
198        ),
199        address,
200        server_name: StringEnvVar::new_optional("SERVER_NAME", false),
201        service_id: StringEnvVar::new("SERVICE_ID", calculate_service_uuid().into()),
202        client_id_key: StringEnvVar::new("CLIENT_ID_KEY", CLIENT_ID_KEY_DEFAULT.into()),
203        api_host_names: string_to_api_host_names(
204            &StringEnvVar::new_optional("API_HOST_NAMES", false)
205                .map(|v| v.as_string())
206                .unwrap_or_default(),
207        ),
208        api_url_prefix: StringEnvVar::new("API_URL_PREFIX", API_URL_PREFIX_DEFAULT.into()),
209        is_panic_endpoint_enabled: StringEnvVar::new_optional("YES_I_REALLY_WANT_TO_PANIC", false)
210            .is_some_and(|v| v.as_str() == "panic attack"),
211
212        cassandra_persistent_db: cassandra_db::EnvVars::new(
213            cassandra_db::PERSISTENT_URL_DEFAULT,
214            cassandra_db::PERSISTENT_NAMESPACE_DEFAULT,
215        ),
216        cassandra_volatile_db: cassandra_db::EnvVars::new(
217            cassandra_db::VOLATILE_URL_DEFAULT,
218            cassandra_db::VOLATILE_NAMESPACE_DEFAULT,
219        ),
220        chain_follower: chain_follower::EnvVars::new(),
221        event_db: event_db::EnvVars::new(),
222        signed_doc: signed_doc::EnvVars::new(),
223        rbac: rbac::EnvVars::new(),
224        cardano_assets_cache: cardano_assets_cache::EnvVars::new(),
225        internal_api_key: StringEnvVar::new_optional("INTERNAL_API_KEY", true),
226        check_config_tick: StringEnvVar::new_as_duration(
227            "CHECK_CONFIG_TICK",
228            CHECK_CONFIG_TICK_DEFAULT,
229        ),
230        purge_backward_slot_buffer,
231        service_live_timeout_interval: StringEnvVar::new_as_duration(
232            "SERVICE_LIVE_TIMEOUT_INTERVAL",
233            SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT,
234        ),
235        service_live_counter_threshold: StringEnvVar::new_as_int(
236            "SERVICE_LIVE_COUNTER_THRESHOLD",
237            SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT,
238            0,
239            u64::MAX,
240        ),
241        log_not_found: StringEnvVar::new_optional("LOG_NOT_FOUND", false),
242    }
243});
244
245impl EnvVars {
246    /// Validate env vars in ways we couldn't when they were first loaded.
247    pub(crate) fn validate() -> anyhow::Result<()> {
248        let mut status = Ok(());
249
250        let url = ENV_VARS.event_db.url();
251        if let Err(error) = tokio_postgres::config::Config::from_str(url) {
252            error!(error=%error, url=url, "Invalid Postgres DB URL.");
253            status = Err(anyhow!("Environment Variable Validation Error."));
254        }
255
256        status
257    }
258}
259
260/// All Settings/Options for the Service.
261static SERVICE_SETTINGS: OnceLock<ServiceSettings> = OnceLock::new();
262
263/// Our Global Settings for this running service.
264pub(crate) struct Settings();
265
266impl Settings {
267    /// Initialize the settings data.
268    pub(crate) fn init(settings: ServiceSettings) -> anyhow::Result<()> {
269        let log_level = settings.log_level;
270
271        if SERVICE_SETTINGS.set(settings).is_err() {
272            // We use println here, because logger not yet configured.
273            println!("Failed to initialize service settings. Called multiple times?");
274        }
275
276        // Init the logger.
277        logger::init(log_level);
278
279        log_build_info();
280
281        // Validate any settings we couldn't validate when loaded.
282        EnvVars::validate()
283    }
284
285    /// Get the current Event DB settings for this service.
286    pub(crate) fn event_db_settings() -> &'static event_db::EnvVars {
287        &ENV_VARS.event_db
288    }
289
290    /// Get the Persistent & Volatile Cassandra DB config for this service.
291    pub(crate) fn cassandra_db_cfg() -> (cassandra_db::EnvVars, cassandra_db::EnvVars) {
292        (
293            ENV_VARS.cassandra_persistent_db.clone(),
294            ENV_VARS.cassandra_volatile_db.clone(),
295        )
296    }
297
298    /// Get the configuration of the chain follower.
299    pub(crate) fn follower_cfg() -> chain_follower::EnvVars {
300        ENV_VARS.chain_follower.clone()
301    }
302
303    /// Get the configuration of the Catalyst Signed Documents.
304    pub(crate) fn signed_doc_cfg() -> signed_doc::EnvVars {
305        ENV_VARS.signed_doc.clone()
306    }
307
308    /// Returns the RBAC configuration.
309    pub fn rbac_cfg() -> &'static rbac::EnvVars {
310        &ENV_VARS.rbac
311    }
312
313    /// Get the configuration of the Cardano assets cache.
314    pub(crate) fn cardano_assets_cache() -> cardano_assets_cache::EnvVars {
315        ENV_VARS.cardano_assets_cache.clone()
316    }
317
318    /// Chain Follower network (The Blockchain network we are configured to use).
319    /// Note: Catalyst Gateway can ONLY follow one network at a time.
320    pub(crate) fn cardano_network() -> &'static Network {
321        &ENV_VARS.chain_follower.chain
322    }
323
324    /// The API Url prefix
325    pub(crate) fn api_url_prefix() -> &'static str {
326        ENV_VARS.api_url_prefix.as_str()
327    }
328
329    /// The Key used to anonymize client connections in the logs.
330    pub(crate) fn client_id_key() -> &'static str {
331        ENV_VARS.client_id_key.as_str()
332    }
333
334    /// The Service UUID
335    pub(crate) fn service_id() -> &'static str {
336        ENV_VARS.service_id.as_str()
337    }
338
339    /// Get a list of all host names to serve the API on.
340    ///
341    /// Used by the `OpenAPI` Documentation to point to the correct backend.
342    /// Take a list of [scheme://] + host names from the env var and turns it into
343    /// a lits of strings.
344    ///
345    /// Host names are taken from the `API_HOST_NAMES` environment variable.
346    /// If that is not set, returns an empty list.
347    pub(crate) fn api_host_names() -> &'static [String] {
348        &ENV_VARS.api_host_names
349    }
350
351    /// The socket address we are bound to.
352    pub(crate) fn bound_address() -> SocketAddr {
353        ENV_VARS.address
354    }
355
356    /// Get the server name to be used in the `Server` object of the `OpenAPI` Document.
357    pub(crate) fn server_name() -> Option<&'static str> {
358        ENV_VARS.server_name.as_ref().map(StringEnvVar::as_str)
359    }
360
361    /// Get the flag is the `/panic` should be enabled or not
362    pub(crate) fn is_panic_endpoint_enabled() -> bool {
363        ENV_VARS.is_panic_endpoint_enabled
364    }
365
366    /// Generate a github issue url with a given title
367    ///
368    /// ## Arguments
369    ///
370    /// * `title`: &str - the title to give the issue
371    ///
372    /// ## Returns
373    ///
374    /// * String - the url
375    ///
376    /// ## Example
377    ///
378    /// ```rust,no_run
379    /// # use cat_data_service::settings::generate_github_issue_url;
380    /// assert_eq!(
381    ///     generate_github_issue_url("Hello, World! How are you?"),
382    ///     "https://github.com/input-output-hk/catalyst-voices/issues/new?template=bug_report.yml&title=Hello%2C%20World%21%20How%20are%20you%3F"
383    /// );
384    /// ```
385    pub(crate) fn generate_github_issue_url(title: &str) -> Option<Url> {
386        let path = format!(
387            "https://github.com/{}/{}/issues/new",
388            ENV_VARS.github_repo_owner.as_str(),
389            ENV_VARS.github_repo_name.as_str()
390        );
391
392        match Url::parse_with_params(&path, &[
393            ("template", ENV_VARS.github_issue_template.as_str()),
394            ("title", title),
395        ]) {
396            Ok(url) => Some(url),
397            Err(e) => {
398                error!("Failed to generate github issue url {:?}", e.to_string());
399                None
400            },
401        }
402    }
403
404    /// Check a given key matches the internal API Key
405    pub(crate) fn check_internal_api_key(value: &str) -> bool {
406        if let Some(required_key) = ENV_VARS.internal_api_key.as_ref().map(StringEnvVar::as_str) {
407            value == required_key
408        } else {
409            false
410        }
411    }
412
413    /// Slot buffer used as overlap when purging Live Index data.
414    pub(crate) fn purge_backward_slot_buffer() -> Slot {
415        ENV_VARS.purge_backward_slot_buffer.into()
416    }
417
418    /// Duration in seconds used to determine if the system is live during checks.
419    pub(crate) fn service_live_timeout_interval() -> Duration {
420        ENV_VARS.service_live_timeout_interval
421    }
422
423    /// Value after which the service is considered NOT live.
424    pub(crate) fn service_live_counter_threshold() -> u64 {
425        ENV_VARS.service_live_counter_threshold
426    }
427
428    /// If set log the 404 not found, else do not log.
429    pub(crate) fn log_not_found() -> bool {
430        ENV_VARS.log_not_found.is_some()
431    }
432}
433
434/// Transform a string list of host names into a vec of host names.
435fn string_to_api_host_names(hosts: &str) -> Vec<String> {
436    /// Log an invalid hostname.
437    fn invalid_hostname(hostname: &str) -> String {
438        error!(hostname = hostname, "Invalid host name for API");
439        String::new()
440    }
441
442    let configured_hosts: Vec<String> = hosts
443        .split(',')
444        // filters out at the beginning all empty entries, because they all would be invalid and
445        // filtered out anyway
446        .filter(|s| !s.is_empty())
447        .map(|s| {
448            let url = Url::parse(s.trim());
449            match url {
450                Ok(url) => {
451                    // Get the scheme, and if its empty, use http
452                    let scheme = url.scheme();
453
454                    let port = url.port();
455
456                    // Rebuild the scheme + hostname
457                    match url.host() {
458                        Some(host) => {
459                            let host = host.to_string();
460                            if host.is_empty() {
461                                invalid_hostname(s)
462                            } else {
463                                match port {
464                                    Some(port) => {
465                                        format! {"{scheme}://{host}:{port}"}
466                                        // scheme.to_owned() + "://" + &host + ":" +
467                                        // &port.to_string()
468                                    },
469                                    None => {
470                                        format! {"{scheme}://{host}"}
471                                    },
472                                }
473                            }
474                        },
475                        None => invalid_hostname(s),
476                    }
477                },
478                Err(_) => invalid_hostname(s),
479            }
480        })
481        .filter(|s| !s.is_empty())
482        .collect();
483
484    configured_hosts
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    #[test]
492    fn generate_github_issue_url_test() {
493        let title = "Hello, World! How are you?";
494        assert_eq!(
495            Settings::generate_github_issue_url(title)
496                .expect("Failed to generate url")
497                .as_str(),
498            "https://github.com/input-output-hk/catalyst-voices/issues/new?template=bug_report.yml&title=Hello%2C+World%21+How+are+you%3F"
499        );
500    }
501
502    #[test]
503    fn configured_hosts_default() {
504        let configured_hosts = Settings::api_host_names();
505        assert!(configured_hosts.is_empty());
506    }
507
508    #[test]
509    fn configured_hosts_set_multiple() {
510        let configured_hosts = string_to_api_host_names(
511            "http://api.prod.projectcatalyst.io , https://api.dev.projectcatalyst.io:1234",
512        );
513        assert_eq!(configured_hosts, vec![
514            "http://api.prod.projectcatalyst.io",
515            "https://api.dev.projectcatalyst.io:1234"
516        ]);
517    }
518
519    #[test]
520    fn configured_hosts_set_multiple_one_invalid() {
521        let configured_hosts =
522            string_to_api_host_names("not a hostname , https://api.dev.projectcatalyst.io:1234");
523        assert_eq!(configured_hosts, vec![
524            "https://api.dev.projectcatalyst.io:1234"
525        ]);
526    }
527
528    #[test]
529    fn configured_hosts_set_empty() {
530        let configured_hosts = string_to_api_host_names("");
531        assert!(configured_hosts.is_empty());
532    }
533
534    #[test]
535    fn configured_service_live_timeout_interval_default() {
536        let timeout_secs = Settings::service_live_timeout_interval();
537        assert_eq!(timeout_secs, SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT);
538    }
539
540    #[test]
541    fn configured_service_live_counter_threshold_default() {
542        let threshold = Settings::service_live_counter_threshold();
543        assert_eq!(threshold, SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT);
544    }
545}