1#[cfg(all(feature = "native-tls", feature = "rustls-tls"))]
12compile_error!("features `native-tls` and `rustls-tls` cannot be enabled together");
13
14#[cfg(not(any(feature = "native-tls", feature = "rustls-tls")))]
15compile_error!("enable either the `native-tls` or `rustls-tls` feature");
16
17mod auth;
18#[cfg(test)]
19mod tests;
20
21pub mod error;
22pub mod rest;
23pub mod types;
24pub mod ws;
25
26pub use error::{Error, Result};
27pub use types::{OrderType, Side};
28
29use std::time::Duration;
30
31pub const DEFAULT_REST_URL: &str = "https://api.bitvavo.com/v2";
33pub const DEFAULT_WS_URL: &str = "wss://ws.bitvavo.com/v2/";
35pub const DEFAULT_ACCESS_WINDOW_MS: u64 = 10_000;
37
38#[derive(Clone)]
42pub struct ClientConfig {
43 pub api_key: Option<String>,
44 pub api_secret: Option<String>,
45 pub rest_url: String,
46 pub ws_url: String,
47 pub access_window_ms: u64,
49 pub timeout: Duration,
51 pub allow_insecure_transport: bool,
55}
56
57impl std::fmt::Debug for ClientConfig {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 f.debug_struct("ClientConfig")
60 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
61 .field(
62 "api_secret",
63 &self.api_secret.as_ref().map(|_| "<redacted>"),
64 )
65 .field("rest_url", &self.rest_url)
66 .field("ws_url", &self.ws_url)
67 .field("access_window_ms", &self.access_window_ms)
68 .field("timeout", &self.timeout)
69 .field("allow_insecure_transport", &self.allow_insecure_transport)
70 .finish()
71 }
72}
73
74impl Default for ClientConfig {
75 fn default() -> Self {
76 Self {
77 api_key: None,
78 api_secret: None,
79 rest_url: DEFAULT_REST_URL.to_string(),
80 ws_url: DEFAULT_WS_URL.to_string(),
81 access_window_ms: DEFAULT_ACCESS_WINDOW_MS,
82 timeout: Duration::from_secs(30),
83 allow_insecure_transport: false,
84 }
85 }
86}
87
88impl ClientConfig {
89 pub fn new() -> Self {
91 Self::default()
92 }
93
94 pub fn with_credentials(api_key: impl Into<String>, api_secret: impl Into<String>) -> Self {
96 Self {
97 api_key: Some(api_key.into()),
98 api_secret: Some(api_secret.into()),
99 ..Self::default()
100 }
101 }
102
103 pub fn from_env() -> Self {
107 let api_key = std::env::var("BITVAVO_API_KEY")
108 .ok()
109 .filter(|v| !v.is_empty());
110 let api_secret = std::env::var("BITVAVO_API_SECRET")
111 .ok()
112 .filter(|v| !v.is_empty());
113 Self {
114 api_key,
115 api_secret,
116 ..Self::default()
117 }
118 }
119
120 pub fn rest_url(mut self, url: impl Into<String>) -> Self {
122 self.rest_url = url.into();
123 self
124 }
125
126 pub fn ws_url(mut self, url: impl Into<String>) -> Self {
128 self.ws_url = url.into();
129 self
130 }
131
132 pub fn access_window_ms(mut self, window: u64) -> Self {
134 self.access_window_ms = window;
135 self
136 }
137
138 pub fn timeout(mut self, timeout: Duration) -> Self {
140 self.timeout = timeout;
141 self
142 }
143
144 pub fn danger_allow_insecure_transport(mut self, allow: bool) -> Self {
148 self.allow_insecure_transport = allow;
149 self
150 }
151
152 pub fn has_credentials(&self) -> bool {
154 self.api_key.is_some() && self.api_secret.is_some()
155 }
156
157 pub(crate) fn credentials(&self) -> Result<(&str, &str)> {
158 match (self.api_key.as_deref(), self.api_secret.as_deref()) {
159 (Some(key), Some(secret)) => Ok((key, secret)),
160 _ => Err(Error::MissingCredentials),
161 }
162 }
163}
164
165pub(crate) fn validate_transport_url(
166 url: &str,
167 transport: &'static str,
168 secure_scheme: &'static str,
169 insecure_scheme: &'static str,
170 allow_insecure: bool,
171) -> Result<()> {
172 let parsed = reqwest::Url::parse(url).map_err(|_| Error::InvalidUrl { transport })?;
173 let scheme = parsed.scheme();
174
175 if scheme == secure_scheme || allow_insecure && scheme == insecure_scheme {
176 return Ok(());
177 }
178
179 Err(Error::InsecureTransport {
180 transport,
181 required_scheme: secure_scheme,
182 })
183}
184
185#[cfg(test)]
186mod transport_tests {
187 use super::*;
188
189 #[test]
190 fn accepts_secure_transport_urls() {
191 assert!(
192 validate_transport_url("https://example.com", "REST", "https", "http", false).is_ok()
193 );
194 assert!(
195 validate_transport_url("wss://example.com", "WebSocket", "wss", "ws", false).is_ok()
196 );
197 }
198
199 #[test]
200 fn rejects_unencrypted_transport_urls() {
201 assert!(matches!(
202 validate_transport_url("http://example.com", "REST", "https", "http", false),
203 Err(Error::InsecureTransport { .. })
204 ));
205 assert!(matches!(
206 validate_transport_url("ws://example.com", "WebSocket", "wss", "ws", false),
207 Err(Error::InsecureTransport { .. })
208 ));
209 }
210
211 #[test]
212 fn permits_explicit_insecure_transport() {
213 assert!(validate_transport_url("http://127.0.0.1", "REST", "https", "http", true).is_ok());
214 assert!(validate_transport_url("ws://127.0.0.1", "WebSocket", "wss", "ws", true).is_ok());
215 }
216
217 #[test]
218 fn rejects_invalid_and_unsupported_urls() {
219 assert!(matches!(
220 validate_transport_url("not a URL", "REST", "https", "http", false),
221 Err(Error::InvalidUrl { .. })
222 ));
223 assert!(matches!(
224 validate_transport_url("ftp://example.com", "REST", "https", "http", true),
225 Err(Error::InsecureTransport { .. })
226 ));
227 }
228
229 #[test]
230 fn rest_client_rejects_unencrypted_url() {
231 let config = ClientConfig::new().rest_url("http://example.com");
232 assert!(matches!(
233 rest::RestClient::new(config),
234 Err(Error::InsecureTransport { .. })
235 ));
236 }
237
238 #[tokio::test]
239 async fn websocket_client_rejects_unencrypted_url() {
240 let config = ClientConfig::new().ws_url("ws://example.com");
241 assert!(matches!(
242 ws::WsClient::connect(config).await,
243 Err(Error::InsecureTransport { .. })
244 ));
245 }
246}