-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathproxy.rs
More file actions
1729 lines (1571 loc) · 67.7 KB
/
Copy pathproxy.rs
File metadata and controls
1729 lines (1571 loc) · 67.7 KB
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// API proxy routes — forward Gemini requests to upstream APIs.
// Keys stay server-side; desktop client authenticates via Firebase token only.
//
// Issue #5861: Remove client-side API key exposure risk.
// Issue #6098 L2: Tiered rate limiting with Pro→Flash degradation.
// Issue #6624: Model allowlist, body size limit, request body validation.
use axum::{
body::Bytes,
extract::{DefaultBodyLimit, Path, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::post,
Router,
};
use crate::auth::AuthUser;
use crate::AppState;
use super::rate_limit::{self, RateDecision};
// Allowed Gemini API actions (suffix after model name)
const GEMINI_ALLOWED_ACTIONS: &[&str] = &[
"generateContent",
"streamGenerateContent",
"embedContent",
"batchEmbedContents",
];
// Allowed Gemini models — driven by model_qos (issue #6834).
// Desktop app uses: gemini-2.5-flash or gemini-2.5-pro (tier-dependent), gemini-embedding-001.
// Provider routing: stable models → Vertex AI, embeddings/preview → AI Studio.
// Rate limiting may degrade requests above soft limit.
/// Maximum request body size for Gemini proxy routes (5 MB).
/// Normal app payloads are 300-600 KB (base64 JPEG + prompt); 5 MB gives ~8x headroom.
const GEMINI_MAX_BODY_SIZE: usize = 5 * 1024 * 1024;
/// Maximum allowed max_output_tokens in generation_config.
/// App uses 8192 (GeminiClient.swift:553,922,1026).
const MAX_OUTPUT_TOKENS_CAP: u64 = 8192;
/// Default thinking budget injected when client omits thinkingConfig.
/// Gemini 2.5 Flash thinking output costs $3.50/M vs $0.60/M regular (5.8x).
/// 1024 tokens caps reasoning for old clients; current Swift client sends budget=0
/// explicitly on all production paths.
const DEFAULT_THINKING_BUDGET: u64 = 1024;
/// Proxy-specific error type — allows JSON 429 responses alongside bare status codes.
enum ProxyError {
Status(StatusCode),
RateLimited,
}
impl IntoResponse for ProxyError {
fn into_response(self) -> Response {
match self {
ProxyError::Status(status) => status.into_response(),
ProxyError::RateLimited => {
// Message must contain "resource exhausted" or "429" for Swift GeminiClient
// to treat it as a transient error and apply retry backoff.
let body = rate_limit::rate_limit_error_json(
"Resource exhausted: rate limit exceeded. Please try again later.",
);
Response::builder()
.status(StatusCode::TOO_MANY_REQUESTS)
.header("content-type", "application/json")
.header("retry-after", "60")
.body(axum::body::Body::from(body))
.unwrap()
}
}
}
}
/// POST /v1/proxy/gemini/*path
/// Proxies requests to Gemini (AI Studio or Vertex AI depending on config).
/// Keys stay server-side; desktop client authenticates via Firebase token only.
/// Rate-limited per user: Tier 1 (allow), Tier 2 (degrade Pro→Flash), Tier 3 (reject 429).
async fn gemini_proxy(
State(state): State<AppState>,
user: AuthUser,
Path(path): Path<String>,
body: Bytes,
) -> Result<Response, ProxyError> {
// Rewrite preview models to stable equivalents (old app compat)
let path = crate::llm::model_qos::rewrite_preview_model(&path);
// Validate the action is in our allowlist
let action = extract_gemini_action(&path);
if !is_gemini_action_allowed(action) {
tracing::warn!("gemini_proxy: blocked action '{}' in path '{}'", action, path);
return Err(ProxyError::Status(StatusCode::FORBIDDEN));
}
// Validate the model is in our allowlist (issue #6624)
let model = extract_gemini_model(&path);
if !is_gemini_model_allowed(model) {
tracing::warn!("gemini_proxy: blocked model '{}' in path '{}'", model, path);
return Err(ProxyError::Status(StatusCode::FORBIDDEN));
}
// Sanitize request body: cap max_output_tokens, reject candidate_count > 1,
// strip safety_settings and cached_content (issue #6624)
let sanitized_body = sanitize_gemini_body(&body, action).map_err(|e| {
tracing::warn!("gemini_proxy: body validation failed: {}", e);
ProxyError::Status(StatusCode::BAD_REQUEST)
})?;
// Rate limit check
let decision = state.gemini_rate_limiter.check_and_record(&user.uid, state.redis.as_ref()).await;
if decision == RateDecision::Reject {
tracing::warn!("gemini_proxy: rate limit rejected uid={}", user.uid);
return Err(ProxyError::RateLimited);
}
// Apply model degradation if needed
let effective_path = rate_limit::maybe_rewrite_model_path(&path, &decision, action);
if effective_path != path {
tracing::info!(
"gemini_proxy: degraded uid={} {} -> {}",
user.uid,
path,
effective_path
);
}
// Resolve provider route: single dispatch point for all provider-specific behavior.
// Returns provider, action override, and body transforms needed.
use crate::llm::model_qos::{resolve_route, BodyTransform, Provider, ResponseTransform};
let route = resolve_route(model, action);
// Apply request body transform if needed (e.g., embedContent → predict format)
let request_body = match route.request_transform {
BodyTransform::EmbedToPredict => transform_embed_request_to_vertex(&sanitized_body)
.map_err(|e| {
tracing::warn!("gemini_proxy: embed body transform failed: {}", e);
ProxyError::Status(StatusCode::BAD_REQUEST)
})?,
BodyTransform::None => sanitized_body.clone(),
};
// Apply Vertex action override (e.g., :embedContent → :predict)
let vertex_path = if let Some(override_action) = route.vertex_action {
effective_path.replace(&format!(":{}", action), &format!(":{}", override_action))
} else {
effective_path.to_string()
};
// Build and send request: Vertex AI (Bearer token) or AI Studio (API key).
// Falls back to AI Studio if Vertex token fetch fails.
let mut used_vertex = false;
let upstream = if route.provider == Provider::VertexAi {
if let Some(ref vertex) = state.vertex_auth {
let url = vertex.build_url_from_path(&vertex_path).ok_or_else(|| {
tracing::error!("gemini_proxy: failed to parse path for Vertex AI: {}", vertex_path);
ProxyError::Status(StatusCode::BAD_REQUEST)
})?;
match vertex.token().await {
Ok(token) => {
used_vertex = true;
reqwest::Client::new()
.post(&url)
.header("content-type", "application/json")
.header("authorization", format!("Bearer {}", token))
.body(request_body)
.send()
.await
}
Err(e) => {
if let Some(gemini_key) = state.config.gemini_api_key.as_ref() {
tracing::warn!("gemini_proxy: Vertex AI token failed, falling back to API key: {}", e);
let url = build_gemini_url(&effective_path, gemini_key);
reqwest::Client::new()
.post(&url)
.header("content-type", "application/json")
.body(sanitized_body.clone())
.send()
.await
} else {
tracing::error!("gemini_proxy: Vertex AI token error and no fallback: {}", e);
return Err(ProxyError::Status(StatusCode::SERVICE_UNAVAILABLE));
}
}
}
} else {
// Vertex AI requested but not configured → AI Studio
let gemini_key = state.config.gemini_api_key.as_ref()
.ok_or(ProxyError::Status(StatusCode::SERVICE_UNAVAILABLE))?;
let url = build_gemini_url(&effective_path, gemini_key);
reqwest::Client::new()
.post(&url)
.header("content-type", "application/json")
.body(sanitized_body.clone())
.send()
.await
}
} else {
// AI Studio route
let gemini_key = state.config.gemini_api_key.as_ref()
.ok_or(ProxyError::Status(StatusCode::SERVICE_UNAVAILABLE))?;
let url = build_gemini_url(&effective_path, gemini_key);
reqwest::Client::new()
.post(&url)
.header("content-type", "application/json")
.body(sanitized_body.clone())
.send()
.await
};
let upstream = upstream.map_err(|e| {
tracing::error!("gemini_proxy: upstream request failed: {}", e);
ProxyError::Status(StatusCode::BAD_GATEWAY)
})?;
let status =
StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
let bytes = upstream.bytes().await.map_err(|e| {
tracing::error!("gemini_proxy: failed to read upstream body: {}", e);
ProxyError::Status(StatusCode::BAD_GATEWAY)
})?;
// Apply response transform if needed (e.g., Vertex predict → AI Studio embed format)
if used_vertex && status.is_success() && route.response_transform != ResponseTransform::None {
let transformed = match route.response_transform {
ResponseTransform::PredictToEmbed => transform_vertex_embed_response(&bytes),
ResponseTransform::None => unreachable!(),
};
match transformed {
Ok(body) => return Ok((status, body).into_response()),
Err(e) => {
tracing::warn!("gemini_proxy: response transform failed: {}", e);
// Fall through to return raw response
}
}
}
Ok((status, bytes).into_response())
}
/// POST /v1/proxy/gemini-stream/*path
/// Same as gemini_proxy but streams the response using SSE (for streamGenerateContent).
/// Rate-limited per user with same tiers as gemini_proxy.
async fn gemini_stream_proxy(
State(state): State<AppState>,
user: AuthUser,
Path(path): Path<String>,
axum::extract::Query(query): axum::extract::Query<std::collections::HashMap<String, String>>,
body: Bytes,
) -> Result<Response, ProxyError> {
// Rewrite preview models to stable equivalents (old app compat)
let path = crate::llm::model_qos::rewrite_preview_model(&path);
// Validate the action
let action = extract_gemini_action(&path);
if !is_gemini_action_allowed(action) {
tracing::warn!("gemini_stream_proxy: blocked action '{}'", action);
return Err(ProxyError::Status(StatusCode::FORBIDDEN));
}
// Validate the model is in our allowlist (issue #6624)
let model = extract_gemini_model(&path);
if !is_gemini_model_allowed(model) {
tracing::warn!("gemini_stream_proxy: blocked model '{}' in path '{}'", model, path);
return Err(ProxyError::Status(StatusCode::FORBIDDEN));
}
// Sanitize request body (issue #6624)
let sanitized_body = sanitize_gemini_body(&body, action).map_err(|e| {
tracing::warn!("gemini_stream_proxy: body validation failed: {}", e);
ProxyError::Status(StatusCode::BAD_REQUEST)
})?;
// Rate limit check
let decision = state.gemini_rate_limiter.check_and_record(&user.uid, state.redis.as_ref()).await;
if decision == RateDecision::Reject {
tracing::warn!("gemini_stream_proxy: rate limit rejected uid={}", user.uid);
return Err(ProxyError::RateLimited);
}
// Apply model degradation if needed
let effective_path = rate_limit::maybe_rewrite_model_path(&path, &decision, action);
if effective_path != path {
tracing::info!(
"gemini_stream_proxy: degraded uid={} {} -> {}",
user.uid,
path,
effective_path
);
}
// Resolve provider route (same dispatch as non-streaming proxy)
use crate::llm::model_qos::{resolve_route, Provider};
let route = resolve_route(model, action);
// Build and send request: Vertex AI or AI Studio
let upstream = if route.provider == Provider::VertexAi {
if let Some(ref vertex) = state.vertex_auth {
let mut url = vertex.build_url_from_path(&effective_path).ok_or_else(|| {
tracing::error!("gemini_stream_proxy: failed to parse path for Vertex AI: {}", effective_path);
ProxyError::Status(StatusCode::BAD_REQUEST)
})?;
// Append extra query params (e.g., alt=sse) for streaming
for (k, v) in &query {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(&urlencoding::encode(k));
url.push('=');
url.push_str(&urlencoding::encode(v));
}
match vertex.token().await {
Ok(token) => {
reqwest::Client::new()
.post(&url)
.header("content-type", "application/json")
.header("authorization", format!("Bearer {}", token))
.body(sanitized_body)
.send()
.await
}
Err(e) => {
if let Some(gemini_key) = state.config.gemini_api_key.as_ref() {
tracing::warn!("gemini_stream_proxy: Vertex AI token failed, falling back to API key: {}", e);
let upstream_url = build_gemini_stream_url(&effective_path, gemini_key, &query);
reqwest::Client::new()
.post(&upstream_url)
.header("content-type", "application/json")
.body(sanitized_body)
.send()
.await
} else {
tracing::error!("gemini_stream_proxy: Vertex AI token error and no fallback: {}", e);
return Err(ProxyError::Status(StatusCode::SERVICE_UNAVAILABLE));
}
}
}
} else {
// Vertex AI requested but not configured → AI Studio
let gemini_key = state.config.gemini_api_key.as_ref()
.ok_or(ProxyError::Status(StatusCode::SERVICE_UNAVAILABLE))?;
let upstream_url = build_gemini_stream_url(&effective_path, gemini_key, &query);
reqwest::Client::new()
.post(&upstream_url)
.header("content-type", "application/json")
.body(sanitized_body)
.send()
.await
}
} else {
// AI Studio route
let gemini_key = state.config.gemini_api_key.as_ref()
.ok_or(ProxyError::Status(StatusCode::SERVICE_UNAVAILABLE))?;
let upstream_url = build_gemini_stream_url(&effective_path, gemini_key, &query);
reqwest::Client::new()
.post(&upstream_url)
.header("content-type", "application/json")
.body(sanitized_body)
.send()
.await
};
let upstream = upstream.map_err(|e| {
tracing::error!("gemini_stream_proxy: upstream request failed: {}", e);
ProxyError::Status(StatusCode::BAD_GATEWAY)
})?;
let status =
StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
// Stream the response body through
let stream = upstream.bytes_stream();
let body = axum::body::Body::from_stream(stream);
Ok(Response::builder()
.status(status)
.header("content-type", "text/event-stream")
.body(body)
.unwrap())
}
/// Extract the action from a Gemini API path (e.g., "models/gemini-3-flash:generateContent" → "generateContent")
fn extract_gemini_action(path: &str) -> &str {
path.rsplit(':').next().unwrap_or("")
}
/// Extract the model from a Gemini API path (e.g., "models/gemini-2.5-flash:generateContent" → "gemini-2.5-flash")
fn extract_gemini_model(path: &str) -> &str {
path.strip_prefix("models/")
.and_then(|rest| rest.split(':').next())
.unwrap_or("")
}
/// Check if a Gemini action is in the allowlist
fn is_gemini_action_allowed(action: &str) -> bool {
GEMINI_ALLOWED_ACTIONS.contains(&action)
}
/// Check if a Gemini model is in the allowlist (issue #6624, #6834)
fn is_gemini_model_allowed(model: &str) -> bool {
crate::llm::model_qos::gemini_proxy_allowed().contains(&model)
}
/// Sanitize a Gemini request body (issue #6624).
///
/// For generateContent/streamGenerateContent:
/// - Cap generation_config.max_output_tokens to MAX_OUTPUT_TOKENS_CAP
/// - Reject candidate_count > 1
/// - Strip safety_settings and cached_content
/// - Inject default thinkingConfig if absent (cost control for Gemini 2.5)
/// - Preserve all other fields (contents, system_instruction, tools, etc.)
///
/// For embedContent/batchEmbedContents:
/// - Skip generation-specific validation (different schema)
/// - Strip safety_settings and cached_content only
fn sanitize_gemini_body(body: &[u8], action: &str) -> Result<Vec<u8>, String> {
let mut json: serde_json::Value = serde_json::from_slice(body)
.map_err(|e| format!("invalid JSON: {}", e))?;
let obj = json.as_object_mut()
.ok_or_else(|| "request body must be a JSON object".to_string())?;
// Strip dangerous fields from all request types
obj.remove("safety_settings");
obj.remove("safetySettings");
obj.remove("cached_content");
obj.remove("cachedContent");
// Sanitize role fields in contents array:
// 1. Inject missing "role" → default to "user" (Vertex AI requires it)
// 2. Move "role":"system" contents → systemInstruction (Vertex AI rejects "system" role)
//
// Vertex AI only accepts "user" or "model" in contents[].role.
// AI Studio silently handles missing roles and "system", but Vertex does not.
if let Some(contents) = obj.get_mut("contents").and_then(|v| v.as_array_mut()) {
// First pass: inject missing roles
for content in contents.iter_mut() {
if let Some(content_obj) = content.as_object_mut() {
if !content_obj.contains_key("role") {
content_obj.insert("role".to_string(), serde_json::Value::String("user".to_string()));
}
}
}
// Second pass: extract "system" role contents → systemInstruction
let mut system_parts: Vec<serde_json::Value> = Vec::new();
contents.retain(|content| {
if let Some(role) = content.get("role").and_then(|r| r.as_str()) {
if role == "system" {
if let Some(parts) = content.get("parts") {
if let Some(arr) = parts.as_array() {
system_parts.extend(arr.iter().cloned());
}
}
return false; // remove from contents
}
}
true
});
if !system_parts.is_empty() {
// Merge into existing systemInstruction or create new one
let si_key = if obj.contains_key("system_instruction") {
"system_instruction"
} else {
"systemInstruction"
};
if let Some(existing) = obj.get_mut(si_key).and_then(|v| v.as_object_mut()) {
if let Some(existing_parts) = existing.get_mut("parts").and_then(|v| v.as_array_mut()) {
existing_parts.extend(system_parts);
}
} else {
obj.insert(
"systemInstruction".to_string(),
serde_json::json!({"parts": system_parts}),
);
}
}
}
// Generation-specific validation (not for embed actions)
let is_embed = action == "embedContent" || action == "batchEmbedContents";
if !is_embed {
// Helper: parse a JSON value as u64 from a number (int or integral float),
// or a string. ProtoJSON allows integer fields as quoted strings and
// protobuf parsers accept integral floats (e.g. 8.0) for int32/int64.
let parse_as_u64 = |v: &serde_json::Value| -> Option<u64> {
v.as_u64()
.or_else(|| {
// Handle integral floats like 8.0, 999999.0
v.as_f64().and_then(|f| {
if f >= 0.0 && f <= (u64::MAX as f64) && f == (f as u64 as f64) {
Some(f as u64)
} else {
None
}
})
})
.or_else(|| v.as_str().and_then(|s| s.parse::<u64>().ok()))
};
// Reject top-level candidate_count > 1
if let Some(cc) = obj.get("candidate_count").or_else(|| obj.get("candidateCount")) {
if let Some(n) = parse_as_u64(cc) {
if n > 1 {
return Err(format!("candidate_count must be 1 or absent, got {}", n));
}
}
}
// Validate inside generation_config / generationConfig.
// Check BOTH casings to prevent dual-key bypass where an attacker
// sends an empty generation_config + a real generationConfig.
let mut found_generation_config = false;
for gc_key in &["generation_config", "generationConfig"] {
if let Some(gc) = obj.get_mut(*gc_key).and_then(|v| v.as_object_mut()) {
found_generation_config = true;
// Reject candidate_count > 1
for cc_key in &["candidate_count", "candidateCount"] {
if let Some(v) = gc.get(*cc_key) {
if let Some(n) = parse_as_u64(v) {
if n > 1 {
return Err(format!("candidate_count must be 1 or absent, got {}", n));
}
}
}
}
// Cap max_output_tokens (handles numeric, integral float, and string-encoded values)
for mot_key in &["max_output_tokens", "maxOutputTokens"] {
if let Some(mot) = gc.get_mut(*mot_key) {
if let Some(n) = parse_as_u64(mot) {
if n > MAX_OUTPUT_TOKENS_CAP {
*mot = serde_json::Value::Number(MAX_OUTPUT_TOKENS_CAP.into());
}
}
}
}
// Defense-in-depth: inject default thinking budget if client omits it.
// Gemini 2.5 Flash defaults to unlimited thinking which is 5.8x more
// expensive than regular output tokens. Cap at 1024 when absent.
let has_thinking = gc.contains_key("thinking_config")
|| gc.contains_key("thinkingConfig");
if !has_thinking {
gc.insert(
"thinkingConfig".to_string(),
serde_json::json!({"thinkingBudget": DEFAULT_THINKING_BUDGET}),
);
}
}
}
// If no generation_config exists at all (legacy clients), create one
// with the default thinking budget to prevent unlimited thinking spend.
if !found_generation_config {
obj.insert(
"generationConfig".to_string(),
serde_json::json!({"thinkingConfig": {"thinkingBudget": DEFAULT_THINKING_BUDGET}}),
);
}
}
serde_json::to_vec(&json).map_err(|e| format!("failed to re-serialize: {}", e))
}
/// Transform an AI Studio embedContent request body to Vertex AI predict format.
///
/// AI Studio: `{"content": {"parts": [{"text": "TEXT"}]}, "taskType": "X", "title": "T"}`
/// Vertex AI: `{"instances": [{"content": "TEXT", "taskType": "X", "title": "T"}]}`
fn transform_embed_request_to_vertex(body: &[u8]) -> Result<Vec<u8>, String> {
let json: serde_json::Value =
serde_json::from_slice(body).map_err(|e| format!("invalid JSON: {}", e))?;
let obj = json
.as_object()
.ok_or_else(|| "request body must be a JSON object".to_string())?;
// Extract text from content.parts[0].text
let text = obj
.get("content")
.and_then(|c| c.get("parts"))
.and_then(|p| p.as_array())
.and_then(|a| a.first())
.and_then(|p| p.get("text"))
.and_then(|t| t.as_str())
.ok_or_else(|| "missing content.parts[0].text in embed request".to_string())?;
let mut instance = serde_json::Map::new();
instance.insert(
"content".to_string(),
serde_json::Value::String(text.to_string()),
);
// Forward optional fields
if let Some(task_type) = obj.get("taskType") {
instance.insert("task_type".to_string(), task_type.clone());
}
if let Some(title) = obj.get("title") {
instance.insert("title".to_string(), title.clone());
}
let vertex_body = serde_json::json!({ "instances": [instance] });
serde_json::to_vec(&vertex_body).map_err(|e| format!("failed to serialize: {}", e))
}
/// Transform a Vertex AI predict response back to AI Studio embedContent format.
///
/// Vertex AI: `{"predictions": [{"embeddings": {"values": [...], "statistics": {...}}}]}`
/// AI Studio: `{"embedding": {"values": [...]}}`
fn transform_vertex_embed_response(body: &[u8]) -> Result<Vec<u8>, String> {
let json: serde_json::Value =
serde_json::from_slice(body).map_err(|e| format!("invalid JSON: {}", e))?;
let values = json
.get("predictions")
.and_then(|p| p.as_array())
.and_then(|a| a.first())
.and_then(|pred| pred.get("embeddings"))
.and_then(|emb| emb.get("values"))
.ok_or_else(|| "missing predictions[0].embeddings.values in Vertex response".to_string())?;
let ai_studio_response = serde_json::json!({
"embedding": { "values": values }
});
serde_json::to_vec(&ai_studio_response).map_err(|e| format!("failed to serialize: {}", e))
}
/// Build upstream Gemini URL for non-streaming requests
fn build_gemini_url(path: &str, api_key: &str) -> String {
format!(
"https://generativelanguage.googleapis.com/v1beta/{}?key={}",
path, api_key
)
}
/// Build upstream Gemini URL for streaming requests with extra query params
fn build_gemini_stream_url(
path: &str,
api_key: &str,
query: &std::collections::HashMap<String, String>,
) -> String {
let mut url = format!(
"https://generativelanguage.googleapis.com/v1beta/{}?key={}",
path, api_key
);
for (k, v) in query {
url.push('&');
url.push_str(&urlencoding::encode(k));
url.push('=');
url.push_str(&urlencoding::encode(v));
}
url
}
pub fn proxy_routes() -> Router<AppState> {
Router::new()
// Gemini HTTP proxy (non-streaming)
.route("/v1/proxy/gemini/*path", post(gemini_proxy))
// Gemini streaming proxy (SSE)
.route("/v1/proxy/gemini-stream/*path", post(gemini_stream_proxy))
// Issue #6624: 5 MB body size limit for proxy routes only (not global).
// Normal app payloads are 300-600 KB; 5 MB gives ~8x headroom.
.layer(DefaultBodyLimit::max(GEMINI_MAX_BODY_SIZE))
}
#[cfg(test)]
mod tests {
use super::*;
// --- Gemini action extraction ---
#[test]
fn extract_action_generate_content() {
assert_eq!(
extract_gemini_action("models/gemini-3-flash:generateContent"),
"generateContent"
);
}
#[test]
fn extract_action_stream() {
assert_eq!(
extract_gemini_action("models/gemini-3-flash:streamGenerateContent"),
"streamGenerateContent"
);
}
#[test]
fn extract_action_embed() {
assert_eq!(
extract_gemini_action("models/gemini-embedding-001:embedContent"),
"embedContent"
);
}
#[test]
fn extract_action_batch_embed() {
assert_eq!(
extract_gemini_action("models/gemini-embedding-001:batchEmbedContents"),
"batchEmbedContents"
);
}
#[test]
fn extract_action_empty_path() {
assert_eq!(extract_gemini_action(""), "");
}
#[test]
fn extract_action_no_colon() {
assert_eq!(extract_gemini_action("models/gemini"), "models/gemini");
}
// --- Gemini action allowlist ---
#[test]
fn allowlist_permits_valid_actions() {
assert!(is_gemini_action_allowed("generateContent"));
assert!(is_gemini_action_allowed("streamGenerateContent"));
assert!(is_gemini_action_allowed("embedContent"));
assert!(is_gemini_action_allowed("batchEmbedContents"));
}
#[test]
fn allowlist_blocks_prefix_bypass() {
assert!(!is_gemini_action_allowed("generateContentX"));
assert!(!is_gemini_action_allowed("embedContentFoo"));
}
#[test]
fn allowlist_blocks_unknown_actions() {
assert!(!is_gemini_action_allowed("deleteModel"));
assert!(!is_gemini_action_allowed("foo"));
assert!(!is_gemini_action_allowed(""));
}
// --- Gemini model extraction ---
#[test]
fn extract_model_flash() {
assert_eq!(
extract_gemini_model("models/gemini-2.5-flash:generateContent"),
"gemini-2.5-flash"
);
}
#[test]
fn extract_model_pro() {
assert_eq!(
extract_gemini_model("models/gemini-2.5-pro:streamGenerateContent"),
"gemini-2.5-pro"
);
}
#[test]
fn extract_model_embedding() {
assert_eq!(
extract_gemini_model("models/gemini-embedding-001:embedContent"),
"gemini-embedding-001"
);
}
#[test]
fn extract_model_no_prefix() {
assert_eq!(extract_gemini_model("gemini-pro:generateContent"), "");
}
#[test]
fn extract_model_empty() {
assert_eq!(extract_gemini_model(""), "");
}
// --- Gemini model allowlist ---
#[test]
fn model_allowlist_permits_valid_models() {
assert!(is_gemini_model_allowed("gemini-2.5-flash"));
assert!(is_gemini_model_allowed("gemini-2.5-pro"));
assert!(is_gemini_model_allowed("gemini-3-flash-preview"), "kept for old app compat");
assert!(is_gemini_model_allowed("gemini-embedding-001"));
}
#[test]
fn model_allowlist_blocks_unknown() {
assert!(!is_gemini_model_allowed("gemini-pro-latest"), "legacy pro not in allowlist");
assert!(!is_gemini_model_allowed("gemini-1.5-pro"));
assert!(!is_gemini_model_allowed("gemini-ultra"));
assert!(!is_gemini_model_allowed(""));
}
#[test]
fn model_allowlist_blocks_prefix_bypass() {
assert!(!is_gemini_model_allowed("gemini-2.5-flash-exp"));
assert!(!is_gemini_model_allowed("gemini-2.5-pro-latest"));
}
// --- Body sanitization ---
#[test]
fn sanitize_caps_max_output_tokens() {
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generation_config": {"max_output_tokens": 99999}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
).unwrap();
let parsed: serde_json::Value = serde_json::from_slice(&result).unwrap();
assert_eq!(
parsed["generation_config"]["max_output_tokens"],
serde_json::json!(MAX_OUTPUT_TOKENS_CAP)
);
}
#[test]
fn sanitize_preserves_valid_max_output_tokens() {
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generation_config": {"max_output_tokens": 4096}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
).unwrap();
let parsed: serde_json::Value = serde_json::from_slice(&result).unwrap();
assert_eq!(parsed["generation_config"]["max_output_tokens"], 4096);
}
#[test]
fn sanitize_caps_camel_case_max_output_tokens() {
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generationConfig": {"maxOutputTokens": 50000}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
).unwrap();
let parsed: serde_json::Value = serde_json::from_slice(&result).unwrap();
assert_eq!(
parsed["generationConfig"]["maxOutputTokens"],
serde_json::json!(MAX_OUTPUT_TOKENS_CAP)
);
}
#[test]
fn sanitize_rejects_candidate_count_gt_1() {
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"candidate_count": 8
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_err());
assert!(result.unwrap_err().contains("candidate_count"));
}
#[test]
fn sanitize_allows_candidate_count_1() {
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"candidate_count": 1
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_ok());
}
#[test]
fn sanitize_rejects_nested_candidate_count_gt_1() {
// candidateCount inside generationConfig (real Gemini API shape)
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generationConfig": {"candidateCount": 4, "maxOutputTokens": 1024}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_err());
assert!(result.unwrap_err().contains("candidate_count"));
}
#[test]
fn sanitize_rejects_nested_snake_case_candidate_count() {
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generation_config": {"candidate_count": 3}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_err());
}
#[test]
fn sanitize_allows_nested_candidate_count_1() {
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generationConfig": {"candidateCount": 1, "maxOutputTokens": 4096}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_ok());
}
#[test]
fn sanitize_rejects_dual_key_bypass() {
// Attacker sends empty generation_config + real generationConfig to bypass validation
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generation_config": {},
"generationConfig": {"candidateCount": 8, "maxOutputTokens": 999999}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_err());
assert!(result.unwrap_err().contains("candidate_count"));
}
#[test]
fn sanitize_caps_dual_key_max_tokens() {
// Both casings present — max_output_tokens should be capped in both
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generation_config": {"max_output_tokens": 100},
"generationConfig": {"maxOutputTokens": 999999}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
).unwrap();
let parsed: serde_json::Value = serde_json::from_slice(&result).unwrap();
assert_eq!(parsed["generation_config"]["max_output_tokens"], 100);
assert_eq!(
parsed["generationConfig"]["maxOutputTokens"],
serde_json::json!(MAX_OUTPUT_TOKENS_CAP)
);
}
#[test]
fn sanitize_rejects_string_encoded_candidate_count() {
// ProtoJSON allows integer fields as quoted strings — must still be caught
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generationConfig": {"candidateCount": "8"}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_err());
assert!(result.unwrap_err().contains("candidate_count"));
}
#[test]
fn sanitize_caps_string_encoded_max_output_tokens() {
// String-encoded maxOutputTokens must still be capped
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"generationConfig": {"maxOutputTokens": "999999"}
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
).unwrap();
let parsed: serde_json::Value = serde_json::from_slice(&result).unwrap();
assert_eq!(
parsed["generationConfig"]["maxOutputTokens"],
serde_json::json!(MAX_OUTPUT_TOKENS_CAP)
);
}
#[test]
fn sanitize_rejects_string_encoded_top_level_candidate_count() {
// Top-level candidate_count as string must also be caught
let body = serde_json::json!({
"contents": [{"parts": [{"text": "hello"}]}],
"candidateCount": "5"
});
let result = sanitize_gemini_body(
serde_json::to_vec(&body).unwrap().as_slice(),
"generateContent",
);
assert!(result.is_err());
assert!(result.unwrap_err().contains("candidate_count"));
}
#[test]
fn sanitize_rejects_float_encoded_candidate_count() {
// Protobuf parsers accept integral floats (8.0) for int32 fields