venice-e2ee-proxy 0.1.0

OpenAI-compatible proxy for Venice.ai E2EE models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Configuration loading and validation.
//!
//! This module provides a typed representation of the proxy configuration,
//! default values, validation, and redacted handling for the Venice API key.

use std::{path::Path, time::Duration};

use axum::http::HeaderName;
use figment::{
    Figment,
    providers::{Env, Format, Toml},
};
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Deserializer, de};
use thiserror::Error;
use tracing_subscriber::EnvFilter;

/// Top-level proxy configuration.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ProxyConfig {
    pub server: ServerConfig,
    pub logging: LoggingConfig,
    pub venice: VeniceConfig,
    pub keys: KeysConfig,
    pub session: SessionConfig,
    pub attestation: AttestationConfig,
    pub e2ee: E2eeConfig,
    pub tools: ToolsConfig,
}

impl ProxyConfig {
    /// Prefix used when loading configuration overrides from environment variables.
    pub const ENV_PREFIX: &'static str = "VENICE_E2EE_PROXY__";

    /// Loads configuration from a TOML file with environment overrides.
    pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        Self::from_figment(
            Figment::new()
                .merge(Toml::file(path.as_ref()))
                .merge(Self::env_provider()),
        )
    }

    /// Parses TOML configuration and validates the result.
    pub fn from_toml_str(contents: &str) -> Result<Self, ConfigError> {
        Self::from_figment(Figment::new().merge(Toml::string(contents)))
    }

    /// Builds the environment provider used to overlay nested config values.
    fn env_provider() -> Env {
        Env::prefixed(Self::ENV_PREFIX).split("__")
    }

    /// Extracts proxy configuration from a Figment provider and validates it before returning.
    fn from_figment(figment: Figment) -> Result<Self, ConfigError> {
        let config: Self = figment.extract()?;
        config.validate()?;
        Ok(config)
    }

    /// Validates a fully materialized configuration.
    pub fn validate(&self) -> Result<(), ConfigError> {
        validate_non_empty("server.host", &self.server.host)?;
        validate_non_empty("logging.level", &self.logging.level)?;
        validate_env_filter("logging.level", &self.logging.level)?;
        validate_http_url("venice.base_url", &self.venice.base_url, false)?;
        validate_duration_non_zero("venice.request_timeout", self.venice.request_timeout)?;

        validate_duration_non_zero("session.idle_ttl", self.session.idle_ttl)?;
        validate_duration_non_zero("session.max_ttl", self.session.max_ttl)?;
        if self.session.idle_ttl > self.session.max_ttl {
            return Err(ConfigError::invalid(
                "session.idle_ttl",
                "must be less than or equal to session.max_ttl",
            ));
        }
        if self.session.max_requests == 0 {
            return Err(ConfigError::invalid(
                "session.max_requests",
                "must be greater than zero",
            ));
        }
        validate_header_name("session.headers.preferred", &self.session.headers.preferred)?;
        validate_header_name(
            "session.headers.open_webui",
            &self.session.headers.open_webui,
        )?;

        validate_http_url("attestation.pccs_url", &self.attestation.pccs_url, true)?;

        validate_non_empty("e2ee.hkdf_info", &self.e2ee.hkdf_info)?;

        if self.tools.tool_call_max_bytes == 0 {
            return Err(ConfigError::invalid(
                "tools.tool_call_max_bytes",
                "must be greater than zero",
            ));
        }
        validate_duration_non_zero(
            "tools.tool_call_marker_timeout",
            self.tools.tool_call_marker_timeout,
        )?;

        Ok(())
    }

    /// Returns the configured Venice API key.
    pub fn venice_api_key(&self) -> Result<&SecretString, ConfigError> {
        if self.venice.api_key.expose_secret().trim().is_empty() {
            return Err(ConfigError::MissingApiKey);
        }
        Ok(&self.venice.api_key)
    }
}

/// HTTP listener configuration for the local proxy server.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
}

impl Default for ServerConfig {
    /// Returns the default listener binding used when server config is omitted.
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_owned(),
            port: 8080,
        }
    }
}

/// Tracing configuration for proxy logs.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct LoggingConfig {
    /// Tracing filter directive. Accepts simple levels like `info` or full
    /// `tracing_subscriber::EnvFilter` directives like
    /// `venice_e2ee_proxy=debug,tower_http=warn`.
    pub level: String,
}

impl Default for LoggingConfig {
    /// Returns the default tracing filter for proxy logs.
    fn default() -> Self {
        Self {
            level: "info".to_owned(),
        }
    }
}

/// Venice upstream API client configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct VeniceConfig {
    pub base_url: String,
    pub api_key: SecretString,
    #[serde(deserialize_with = "deserialize_duration")]
    pub request_timeout: Duration,
}

impl Default for VeniceConfig {
    /// Returns default Venice API endpoint and timeout settings with an empty API key.
    fn default() -> Self {
        Self {
            base_url: "https://api.venice.ai/api/v1".to_owned(),
            api_key: SecretString::default(),
            request_timeout: Duration::from_secs(30),
        }
    }
}

/// Proxy instance key generation configuration.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct KeysConfig {
    pub generate_proxy_instance_key_on_startup: bool,
}

impl Default for KeysConfig {
    /// Returns the default key policy that generates a proxy instance key at startup.
    fn default() -> Self {
        Self {
            generate_proxy_instance_key_on_startup: true,
        }
    }
}

/// Session lifetime, reuse, and identifier-resolution configuration.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct SessionConfig {
    #[serde(deserialize_with = "deserialize_duration")]
    pub idle_ttl: Duration,
    #[serde(deserialize_with = "deserialize_duration")]
    pub max_ttl: Duration,
    pub max_requests: u64,
    pub fallback_scope: SessionFallbackScope,
    pub headers: SessionHeadersConfig,
}

impl Default for SessionConfig {
    /// Returns the default session TTLs, request budget, fallback behavior, and headers.
    fn default() -> Self {
        Self {
            idle_ttl: Duration::from_secs(600),
            max_ttl: Duration::from_secs(1_800),
            max_requests: 100,
            fallback_scope: SessionFallbackScope::Request,
            headers: SessionHeadersConfig::default(),
        }
    }
}

/// Header names used to resolve stable agent session identifiers.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct SessionHeadersConfig {
    pub preferred: String,
    pub open_webui: String,
}

impl Default for SessionHeadersConfig {
    /// Returns the default preferred and Open WebUI compatibility session headers.
    fn default() -> Self {
        Self {
            preferred: "X-Venice-Proxy-Session-Id".to_owned(),
            open_webui: "X-OpenWebUI-Chat-Id".to_owned(),
        }
    }
}

/// Fallback strategy used when a request does not include a session identifier.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SessionFallbackScope {
    Agent,
    #[default]
    Request,
    Disabled,
}

/// Attestation verification policy for Venice model-key evidence.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct AttestationConfig {
    pub mode: AttestationMode,
    pub require_tdx: bool,
    pub require_nvidia: NvidiaRequirement,
    pub allow_debug: bool,
    pub pccs_url: String,
}

impl Default for AttestationConfig {
    /// Returns the default attestation policy used when attestation requirements are not configured.
    fn default() -> Self {
        Self {
            mode: AttestationMode::Independent,
            require_tdx: false,
            require_nvidia: NvidiaRequirement::Never,
            allow_debug: false,
            pccs_url: String::new(),
        }
    }
}

/// Attestation strategy exposed in proxy metadata and config.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AttestationMode {
    #[default]
    Independent,
}

impl AttestationMode {
    /// Returns the lowercase metadata/header value for this attestation mode.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Independent => "independent",
        }
    }
}

/// Policy for how NVIDIA attestation payloads are required or ignored.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NvidiaRequirement {
    Required,
    WhenPresent,
    #[default]
    Never,
}

/// E2EE codec configuration for request encryption and response decryption.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct E2eeConfig {
    pub hkdf_info: String,
    pub require_encrypted_response_content: bool,
}

impl Default for E2eeConfig {
    /// Returns the default HKDF context and encrypted-response policy.
    fn default() -> Self {
        Self {
            hkdf_info: "ecdsa_encryption".to_owned(),
            require_encrypted_response_content: true,
        }
    }
}

/// Tool-call emulation configuration for OpenAI-style function calls.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct ToolsConfig {
    pub enabled: bool,
    pub mode: ToolMode,
    pub max_retries: u32,
    pub tool_call_max_bytes: usize,
    #[serde(deserialize_with = "deserialize_duration")]
    pub tool_call_marker_timeout: Duration,
    pub validate_json_schema: bool,
}

impl Default for ToolsConfig {
    /// Returns the default tool-emulation limits and retry policy.
    fn default() -> Self {
        Self {
            enabled: true,
            mode: ToolMode::Emulated,
            max_retries: 2,
            tool_call_max_bytes: 65_536,
            tool_call_marker_timeout: Duration::from_secs(30),
            validate_json_schema: true,
        }
    }
}

/// Tool handling mode used by the proxy.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolMode {
    #[default]
    Emulated,
    None,
}

impl ToolMode {
    /// Returns the lowercase metadata/header value for this tool mode.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Emulated => "emulated",
            Self::None => "none",
        }
    }
}

/// Errors returned while loading or validating proxy configuration.
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("failed to load config: {0}")]
    Figment(#[source] Box<figment::Error>),
    #[error("Venice API key is not configured")]
    MissingApiKey,
    #[error("invalid config value for {field}: {message}")]
    InvalidValue {
        field: &'static str,
        message: String,
    },
}

impl From<figment::Error> for ConfigError {
    /// Converts Figment extraction failures into configuration errors.
    fn from(error: figment::Error) -> Self {
        Self::Figment(Box::new(error))
    }
}

impl ConfigError {
    /// Creates an invalid-value error for a named configuration field.
    fn invalid(field: &'static str, message: impl Into<String>) -> Self {
        Self::InvalidValue {
            field,
            message: message.into(),
        }
    }
}

/// Validates that a string configuration field contains non-whitespace text.
fn validate_non_empty(field: &'static str, value: &str) -> Result<(), ConfigError> {
    if value.trim().is_empty() {
        return Err(ConfigError::invalid(field, "must not be empty"));
    }
    Ok(())
}

/// Validates that a string configuration field is an HTTP(S) URL, optionally allowing empty values.
fn validate_http_url(
    field: &'static str,
    value: &str,
    allow_empty: bool,
) -> Result<(), ConfigError> {
    let value = value.trim();
    if value.is_empty() {
        if allow_empty {
            return Ok(());
        }
        return Err(ConfigError::invalid(field, "must not be empty"));
    }

    if !(value.starts_with("https://") || value.starts_with("http://")) {
        return Err(ConfigError::invalid(
            field,
            "must start with http:// or https://",
        ));
    }

    Ok(())
}

/// Validates that a string configuration field can be used as an HTTP header name.
fn validate_header_name(field: &'static str, value: &str) -> Result<(), ConfigError> {
    validate_non_empty(field, value)?;
    HeaderName::from_bytes(value.as_bytes())
        .map_err(|_| ConfigError::invalid(field, "must be a valid HTTP header name"))?;
    Ok(())
}

/// Validates that a duration configuration field is greater than zero.
fn validate_duration_non_zero(field: &'static str, value: Duration) -> Result<(), ConfigError> {
    if value == Duration::ZERO {
        return Err(ConfigError::invalid(field, "must be greater than zero"));
    }
    Ok(())
}

/// Deserializes human-readable duration strings into [`Duration`] values.
fn deserialize_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    let value = String::deserialize(deserializer)?;
    humantime::parse_duration(&value).map_err(de::Error::custom)
}

/// Validates that a string configuration field is accepted by `tracing_subscriber::EnvFilter`.
fn validate_env_filter(field: &'static str, value: &str) -> Result<(), ConfigError> {
    let value = value.trim();
    if value.is_empty() {
        return Ok(());
    }

    EnvFilter::try_new(value).map_err(|source| {
        ConfigError::invalid(
            field,
            format!("must be a valid tracing env filter: {source}"),
        )
    })?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_default_config_values(config: &ProxyConfig) {
        assert_eq!(config.server.host, "0.0.0.0");
        assert_eq!(config.server.port, 8080);
        assert_eq!(config.logging.level, "info");
        assert_eq!(config.venice.base_url, "https://api.venice.ai/api/v1");
        assert_eq!(config.venice.api_key.expose_secret(), "");
        assert_eq!(config.venice.request_timeout, Duration::from_secs(30));
        assert!(config.keys.generate_proxy_instance_key_on_startup);
        assert_eq!(config.session.idle_ttl, Duration::from_secs(600));
        assert_eq!(config.session.max_ttl, Duration::from_secs(1_800));
        assert_eq!(config.session.max_requests, 100);
        assert_eq!(config.session.fallback_scope, SessionFallbackScope::Request);
        assert_eq!(
            config.session.headers.preferred,
            "X-Venice-Proxy-Session-Id"
        );
        assert_eq!(config.session.headers.open_webui, "X-OpenWebUI-Chat-Id");
        assert_eq!(config.attestation.mode, AttestationMode::Independent);
        assert!(!config.attestation.require_tdx);
        assert_eq!(config.attestation.require_nvidia, NvidiaRequirement::Never);
        assert!(!config.attestation.allow_debug);
        assert_eq!(config.attestation.pccs_url, "");
        assert_eq!(config.e2ee.hkdf_info, "ecdsa_encryption");
        assert!(config.e2ee.require_encrypted_response_content);
        assert!(config.tools.enabled);
        assert_eq!(config.tools.mode, ToolMode::Emulated);
        assert_eq!(config.tools.max_retries, 2);
        assert_eq!(config.tools.tool_call_max_bytes, 65_536);
        assert_eq!(
            config.tools.tool_call_marker_timeout,
            Duration::from_secs(30)
        );
        assert!(config.tools.validate_json_schema);

        config.validate().expect("default config is valid");
    }

    #[test]
    fn default_config_matches_expected_values() {
        let config = ProxyConfig::default();

        assert_default_config_values(&config);
    }

    #[test]
    fn checked_in_default_config_matches_code_defaults() {
        let config = ProxyConfig::from_toml_str(include_str!("../config/default.toml"))
            .expect("checked-in default config should load");

        assert_default_config_values(&config);
    }

    #[test]
    fn toml_config_applies_defaults_for_missing_sections() {
        let config = ProxyConfig::from_toml_str(
            r#"
            [server]
            host = "0.0.0.0"
            port = 8080

            [tools]
            enabled = false
            mode = "none"
            "#,
        )
        .expect("partial config should load with defaults");

        assert_eq!(config.server.host, "0.0.0.0");
        assert_eq!(config.server.port, 8080);
        assert_eq!(config.logging.level, "info");
        assert_eq!(config.venice.api_key.expose_secret(), "");
        assert_eq!(config.venice.request_timeout, Duration::from_secs(30));
        assert!(!config.tools.enabled);
        assert_eq!(config.tools.mode, ToolMode::None);
        assert_eq!(config.tools.tool_call_max_bytes, 65_536);
    }

    #[test]
    fn validation_rejects_invalid_values() {
        let err = ProxyConfig::from_toml_str(
            r#"
            [venice]
            base_url = "not-valid-url"
            "#,
        )
        .expect_err("invalid base URL should be rejected");

        assert!(matches!(
            err,
            ConfigError::InvalidValue {
                field: "venice.base_url",
                ..
            }
        ));

        let err = ProxyConfig::from_toml_str(
            r#"
            [venice]
            request_timeout = "0s"
            "#,
        )
        .expect_err("zero Venice timeout should be rejected");

        assert!(matches!(
            err,
            ConfigError::InvalidValue {
                field: "venice.request_timeout",
                ..
            }
        ));
    }

    #[test]
    fn logging_config_accepts_level_or_env_filter_and_rejects_invalid_filters() {
        let config = ProxyConfig::from_toml_str(
            r#"
            [logging]
            level = "debug"
            "#,
        )
        .expect("logging level config should load");
        assert_eq!(config.logging.level, "debug");

        let config = ProxyConfig::from_toml_str(
            r#"
            [logging]
            level = "venice_e2ee_proxy=debug,tower_http=warn"
            "#,
        )
        .expect("logging env filter config should load");
        assert_eq!(
            config.logging.level,
            "venice_e2ee_proxy=debug,tower_http=warn"
        );

        for level in ["", "   "] {
            let err = ProxyConfig::from_toml_str(&format!(
                r#"
                [logging]
                level = {level:?}
                "#
            ))
            .expect_err("empty logging level should be rejected");
            assert!(matches!(
                err,
                ConfigError::InvalidValue {
                    field: "logging.level",
                    ..
                }
            ));
        }

        let err = ProxyConfig::from_toml_str(
            r#"
            [logging]
            level = "venice_e2ee_proxy=[debug"
            "#,
        )
        .expect_err("invalid tracing env filter should be rejected");
        assert!(matches!(
            err,
            ConfigError::InvalidValue {
                field: "logging.level",
                ..
            }
        ));
    }

    #[test]
    fn removed_tool_marker_options_are_rejected_as_unknown_fields() {
        let err = ProxyConfig::from_toml_str("[tools]\nmarker_start = \"<tool_call>\"\n")
            .expect_err("removed tools.marker_start option should be rejected");
        assert!(matches!(err, ConfigError::Figment(_)));
    }

    #[test]
    fn missing_api_key_is_reported() {
        let config = ProxyConfig::default();
        let err = config
            .venice_api_key()
            .expect_err("missing API key should be reported");

        assert!(matches!(err, ConfigError::MissingApiKey));
        assert_eq!(err.to_string(), "Venice API key is not configured");
    }

    #[test]
    fn api_key_debug_output_is_redacted() {
        let config = ProxyConfig::from_toml_str(
            r#"
            [venice]
            api_key = "super-secret-test-key"
            "#,
        )
        .expect("config should load");
        let key = config.venice_api_key().expect("test key should load");

        assert_eq!(key.expose_secret(), "super-secret-test-key");
        assert!(!format!("{key:?}").contains("super-secret-test-key"));
        assert!(!format!("{config:?}").contains("super-secret-test-key"));
    }
}