-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_gmail.rs
More file actions
1601 lines (1511 loc) · 64.4 KB
/
Copy pathgoogle_gmail.rs
File metadata and controls
1601 lines (1511 loc) · 64.4 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
//! Google Gmail adapter (`/google/gmail/v1/...`).
//!
//! Authority: spec.md §2.1. Three routes — `send`, `list`, `get` — share the
//! same template as `google_drive::proxy_request`: build a `RequestContext`,
//! evaluate Layer B (policy), mint a PCA_2 successor with the narrowed ops
//! (Layer A), forward to Google, apply the read filter on reads, publish the
//! action event.
//!
//! The novelty over Drive is the **send** path: it parses the RFC 2822 body
//! out of the `{ "raw": "<base64url>" }` payload, extracts recipient domains
//! plus subject + attachment count, and exposes them under `body.*` so the
//! policy engine can implement the gmail-external-send-gate per spec.md §9.
use std::collections::HashMap;
use axum::body::Bytes;
use axum::extract::{Path, Query, State};
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap};
use axum::http::{HeaderName, HeaderValue, Method, Response, StatusCode};
use axum::routing::{get, post};
use axum::{Json, Router};
use base64::engine::general_purpose::{URL_SAFE as B64URL, URL_SAFE_NO_PAD as B64URL_NP};
use base64::{Engine, engine::general_purpose::STANDARD as B64};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use shared_types::provenance::pca::ExecutorBinding;
use tracing::{info, instrument, warn};
use uuid::Uuid;
use super::action_stream::ActionEvent;
use super::error::{AppError, upstream_error_kind};
use super::read_filter;
use super::state::AdapterState;
use crate::pic::{CachedPca, PcaCache, SuccessorOutcome};
use crate::session::SessionCtx;
use policy_engine::{Decision, Outcome, RequestContext, UserCtx};
const MAX_BODY: usize = 10 * 1024 * 1024;
/// Hard cap on the raw RFC2822 payload from agents. Gmail itself caps at
/// 35MB with attachments; we refuse anything past 10MB at the proxy.
const MAX_RAW_MIME: usize = 10 * 1024 * 1024;
/// Upper bound on `multipart/*` containers in an agent-supplied MIME payload.
/// `mailparse::parse_mail` descends into every `multipart/*` subpart with no
/// recursion bound, so a payload nesting containers tens of thousands deep
/// overflows the worker thread's stack *during parsing* (before our own
/// `count_parts` walk). Each level that recurses carries its own
/// `Content-Type: multipart/...` marker, so the marker count is a cheap
/// (single-scan) upper bound on the parser's recursion depth; we reject past
/// this cap before handing the bytes to the recursive parser. The cap is far
/// above any realistic agent-composed message (mixed › alternative › related
/// is depth 3) and fails *closed* — the safe direction for a gating proxy.
/// Mirrors the `MAX_SAMPLES` / `MAX_CHAIN_HOPS` bounds elsewhere.
const MAX_MIME_MULTIPART: usize = 100;
pub fn router(state: AdapterState) -> Router {
Router::new()
.route(
"/google/gmail/v1/users/me/messages/send",
post(send_message),
)
.route("/google/gmail/v1/users/me/messages", get(list_messages))
.route("/google/gmail/v1/users/me/messages/{id}", get(get_message))
.with_state(state)
}
#[derive(Debug, Deserialize)]
struct SendBody {
/// base64url (with or without padding) of the RFC 2822 message.
raw: String,
}
#[derive(Debug, Serialize)]
struct SendUpstreamBody<'a> {
raw: &'a str,
}
#[instrument(skip(state, session, body))]
async fn send_message(
State(state): State<AdapterState>,
SessionCtx(session): SessionCtx,
Json(body): Json<SendBody>,
) -> Result<Response<axum::body::Body>, AppError> {
// Decode raw RFC 2822 and extract recipient + subject + attachment info.
if body.raw.len() > MAX_RAW_MIME * 4 / 3 + 16 {
return Err(AppError::Internal(
"gmail send: raw payload exceeds 10MB cap".into(),
));
}
let raw_bytes = decode_b64url(&body.raw)
.map_err(|e| AppError::Internal(format!("gmail send: bad base64url: {e}")))?;
if raw_bytes.len() > MAX_RAW_MIME {
return Err(AppError::Internal(
"gmail send: decoded payload exceeds 10MB cap".into(),
));
}
let parsed = parse_mime(&raw_bytes)
.map_err(|e| AppError::Internal(format!("gmail send: parse failure: {e}")))?;
let body_ctx = build_send_body_ctx(&parsed, &state.customer_domain, session.p_0.as_str());
proxy_request(
&state,
&session,
GmailRequest {
action: "gmail.messages.send".into(),
upstream_path: "/gmail/v1/users/me/messages/send".into(),
method: Method::POST,
policy_path: HashMap::new(),
query: HashMap::new(),
body_for_policy: body_ctx,
// Re-serialize the raw payload — we never trust round-trip of the
// mailparse output (it normalizes headers). Forward exactly what
// the agent sent.
upstream_body: Some(
serde_json::to_vec(&SendUpstreamBody { raw: &body.raw })
.map_err(|e| AppError::Internal(e.to_string()))?,
),
upstream_content_type: Some("application/json".into()),
},
)
.await
}
#[instrument(skip(state, session, query))]
async fn list_messages(
State(state): State<AdapterState>,
SessionCtx(session): SessionCtx,
Query(query): Query<HashMap<String, String>>,
) -> Result<Response<axum::body::Body>, AppError> {
proxy_request(
&state,
&session,
GmailRequest {
action: "gmail.messages.list".into(),
upstream_path: "/gmail/v1/users/me/messages".into(),
method: Method::GET,
policy_path: HashMap::new(),
query,
body_for_policy: HashMap::new(),
upstream_body: None,
upstream_content_type: None,
},
)
.await
}
#[instrument(skip(state, session, query))]
async fn get_message(
State(state): State<AdapterState>,
SessionCtx(session): SessionCtx,
Path(msg_id): Path<String>,
Query(query): Query<HashMap<String, String>>,
) -> Result<Response<axum::body::Body>, AppError> {
let mut policy_path = HashMap::new();
policy_path.insert("id".to_string(), msg_id.clone());
proxy_request(
&state,
&session,
GmailRequest {
action: "gmail.messages.get".into(),
upstream_path: format!(
"/gmail/v1/users/me/messages/{}",
super::encoded_segment("google", &msg_id)
),
method: Method::GET,
policy_path,
query,
body_for_policy: HashMap::new(),
upstream_body: None,
upstream_content_type: None,
},
)
.await
}
struct GmailRequest {
action: String,
upstream_path: String,
method: Method,
policy_path: HashMap<String, String>,
query: HashMap<String, String>,
/// Body fields the adapter chose to expose to the policy engine
/// (default-deny per spec.md §5.4).
body_for_policy: HashMap<String, Value>,
/// Optional bytes to send upstream verbatim (for `send`).
upstream_body: Option<Vec<u8>>,
upstream_content_type: Option<String>,
}
async fn proxy_request(
state: &AdapterState,
session: &std::sync::Arc<crate::session::SessionContext>,
req: GmailRequest,
) -> Result<Response<axum::body::Body>, AppError> {
let request_id = Uuid::new_v4();
// spec.md §3.2 — `proxilion_adapter_request_duration_seconds`.
let adapter_started = std::time::Instant::now();
let ctx = build_policy_ctx(state, session, &req);
// spec.md §3.2 — `proxilion_policy_evaluations_total` + duration.
let eval_started = std::time::Instant::now();
let eval_result = state.policy.load().evaluate_with_trace(&ctx);
metrics::histogram!("proxilion_policy_evaluation_duration_seconds")
.record(eval_started.elapsed().as_secs_f64());
let (outcome, mut policy_trace) = match eval_result {
Ok(pair) => {
metrics::counter!(
"proxilion_policy_evaluations_total",
"policy_id" => pair.0.matched_policy_id.clone().unwrap_or_else(|| "(none)".into()),
"result" => if pair.0.matched_policy_id.is_some() { "match" } else { "nomatch" },
)
.increment(1);
pair
}
Err(e) => {
metrics::counter!(
"proxilion_policy_evaluations_total",
"policy_id" => "(error)",
"result" => "error",
)
.increment(1);
return Err(e.into());
}
};
// ui-less-surfaces.md §5.7 dev 2 — per-policy escalation deadline.
let escalation_after_minutes = outcome
.matched_policy_id
.as_deref()
.and_then(|id| state.policy.load().escalation_after_minutes_for(id));
let requested_ops: Vec<String> = outcome
.required_ops
.required
.iter()
.map(|a| a.to_canonical())
.collect();
let method_str = req.method.to_string();
// Layer B.
if let Err(e) = enforce_pre_request_decision(&outcome) {
super::policy_trace::emit(&policy_trace, request_id, "google", &req.action);
let (layer_label, detail_str) = match &e {
AppError::PolicyBlocked { .. } => ("policy", format!("{e}")),
AppError::RequireConfirmation(_) => ("policy", "require_confirmation".to_string()),
_ => ("policy", format!("{e}")),
};
if super::persists_blocked_action(&e) {
crate::blocked::persist_and_notify(
&state.auth.db,
&state.notifier,
crate::blocked::BlockedActionRecord {
request_id,
session_id: session.agent_session_id,
p_0: Some(&session.p_0),
vendor: "google",
action: &req.action,
method: &method_str,
path: &req.upstream_path,
layer: layer_label,
policy_id: outcome.matched_policy_id.as_deref(),
detail: Some(&detail_str),
predecessor_pca_id: Some(session.leaf_pca_id),
requested_ops: &requested_ops,
escalation_after_minutes,
request_canonical_json: Some(crate::blocked::canonical_request_json(
&method_str,
&req.upstream_path,
"google",
&req.action,
&req.policy_path,
&req.body_for_policy,
)),
},
)
.await;
}
return Err(e);
}
// Layer A: narrowed PCA_2.
let leaf_ops: Vec<String> = if requested_ops.is_empty() {
session.granted_ops.clone()
} else {
requested_ops.clone()
};
let binding = ExecutorBinding::new()
.with("service", "proxilion-proxy")
.with("action", req.action.as_str())
.with("request_id", request_id.to_string().as_str());
let (pca2_id, audit_violation_detail) = match state
.pic
.request_or_audit_successor(
session.leaf_pca_cbor.clone(),
leaf_ops.clone(),
binding,
outcome.pic_mode,
)
.await
{
Ok(SuccessorOutcome::Issued(pca2)) => {
let pca2_cbor = B64
.decode(&pca2.pca)
.map_err(|e| AppError::Internal(format!("PCA_2 base64: {e}")))?;
let pca2_id = Uuid::new_v4();
let cache = PcaCache::new(state.auth.db.clone());
cache
.insert(&CachedPca {
pca_id: pca2_id,
cbor: pca2_cbor,
p_0: pca2.p_0.clone(),
ops: pca2.ops.clone(),
hop: pca2.hop as i32,
predecessor_id: Some(session.leaf_pca_id),
signature: vec![],
pic_profile: crate::pic::cache::CURRENT_PIC_PROFILE.to_string(),
})
.await
.map_err(|e| AppError::Internal(format!("pca_cache: {e}")))?;
(pca2_id, None)
}
Ok(SuccessorOutcome::AuditFallback { detail }) => {
let missing = crate::pic::violations::parse_missing_atoms(&detail);
crate::pic::violations::persist(
&state.auth.db,
crate::pic::PicViolationRecord {
request_id,
session_id: session.agent_session_id,
p_0: Some(&session.p_0),
vendor: "google",
action: &req.action,
method: &method_str,
path: &req.upstream_path,
policy_id: outcome.matched_policy_id.as_deref(),
predecessor_pca_id: Some(session.leaf_pca_id),
attempted_ops: &leaf_ops,
missing_atoms: &missing,
pic_mode: "audit",
detail: Some(&detail),
},
)
.await;
metrics::counter!(
"proxilion_pic_violations_total",
"mode" => "audit",
"vendor" => "google",
"action" => req.action.clone(),
)
.increment(1);
(session.leaf_pca_id, Some(detail))
}
Err(crate::pic::ExecutorError::Invariant(d)) => {
super::policy_trace::mark_layer_a_failed(&mut policy_trace, d.clone());
super::policy_trace::emit(&policy_trace, request_id, "google", &req.action);
crate::pic::violations::persist(
&state.auth.db,
crate::pic::PicViolationRecord {
request_id,
session_id: session.agent_session_id,
p_0: Some(&session.p_0),
vendor: "google",
action: &req.action,
method: &method_str,
path: &req.upstream_path,
policy_id: outcome.matched_policy_id.as_deref(),
predecessor_pca_id: Some(session.leaf_pca_id),
attempted_ops: &leaf_ops,
missing_atoms: &crate::pic::violations::parse_missing_atoms(&d),
pic_mode: "runtime_gate",
detail: Some(&d),
},
)
.await;
metrics::counter!(
"proxilion_pic_violations_total",
"mode" => "runtime_gate",
"vendor" => "google",
"action" => req.action.clone(),
)
.increment(1);
crate::blocked::persist_and_notify(
&state.auth.db,
&state.notifier,
crate::blocked::BlockedActionRecord {
request_id,
session_id: session.agent_session_id,
p_0: Some(&session.p_0),
vendor: "google",
action: &req.action,
method: &method_str,
path: &req.upstream_path,
layer: "pic_invariant",
policy_id: outcome.matched_policy_id.as_deref(),
detail: Some(&d),
predecessor_pca_id: Some(session.leaf_pca_id),
requested_ops: &leaf_ops,
escalation_after_minutes,
request_canonical_json: Some(crate::blocked::canonical_request_json(
&method_str,
&req.upstream_path,
"google",
&req.action,
&req.policy_path,
&req.body_for_policy,
)),
},
)
.await;
return Err(AppError::PicInvariantViolation(d));
}
Err(crate::pic::ExecutorError::Upstream { status, body }) => {
return Err(AppError::Internal(format!("trust plane {status}: {body}")));
}
Err(other) => return Err(AppError::Internal(other.to_string())),
};
// Upstream call.
let upstream_url = format!("{}{}", state.google_api_base(), req.upstream_path);
let mut builder = state
.upstream
.request(req.method.clone(), &upstream_url)
.header(
AUTHORIZATION,
HeaderValue::try_from(format!("Bearer {}", session.google_access_token))
.map_err(|_| AppError::Internal("bad google bearer".into()))?,
);
if !req.query.is_empty() {
builder = builder.query(&req.query);
}
if let Some(b) = req.upstream_body.as_ref() {
if let Some(ct) = req.upstream_content_type.as_deref() {
builder = builder.header(CONTENT_TYPE, ct);
}
builder = builder.body(b.clone());
}
let upstream_resp = match builder.send().await {
Ok(r) => r,
Err(e) => {
// spec.md §3.2 — `proxilion_adapter_upstream_errors_total{vendor,action,kind}`.
metrics::counter!(
"proxilion_adapter_upstream_errors_total",
"vendor" => "google",
"action" => req.action.clone(),
"kind" => upstream_error_kind(&e),
)
.increment(1);
return Err(e.into());
}
};
let status = upstream_resp.status();
if status.is_server_error() {
metrics::counter!(
"proxilion_adapter_upstream_errors_total",
"vendor" => "google",
"action" => req.action.clone(),
"kind" => "5xx",
)
.increment(1);
}
let content_type = upstream_resp
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_owned());
let body_bytes = super::read_bounded(upstream_resp, MAX_BODY).await?;
// Read filter — only for read paths.
let (final_body, filter_outcome) =
if let (&Method::GET, Some(filter)) = (&req.method, outcome.read_filter.as_ref()) {
let compiled = read_filter::CompiledFilter::compile(filter)
.map_err(|e| AppError::Internal(format!("read-filter regex: {e}")))?;
let (b, o) = read_filter::apply(&body_bytes, &compiled, content_type.as_deref());
// spec.md §3.2 — readfilter scan + quarantined-bytes counters.
let scan_result = if !o.triggered {
"clean"
} else if o.block {
"quarantined"
} else {
"stripped"
};
metrics::counter!(
"proxilion_readfilter_scans_total",
"vendor" => "google",
"action" => req.action.clone(),
"result" => scan_result,
)
.increment(1);
if o.triggered {
let quarantined_bytes = if o.block {
body_bytes.len() as u64
} else {
(body_bytes.len() as u64).saturating_sub(b.len() as u64)
};
metrics::counter!(
"proxilion_readfilter_quarantined_bytes_total",
"vendor" => "google",
)
.increment(quarantined_bytes);
}
if o.block {
super::policy_trace::mark_read_filter(
&mut policy_trace,
true,
outcome.matched_policy_id.clone(),
format!("BlockRequest pattern matched ({} hits)", o.matches),
);
super::policy_trace::emit(&policy_trace, request_id, "google", &req.action);
crate::blocked::persist_and_notify(
&state.auth.db,
&state.notifier,
crate::blocked::BlockedActionRecord {
request_id,
session_id: session.agent_session_id,
p_0: Some(&session.p_0),
vendor: "google",
action: &req.action,
method: &method_str,
path: &req.upstream_path,
layer: "read_filter",
policy_id: outcome.matched_policy_id.as_deref(),
detail: Some("BlockRequest pattern matched"),
predecessor_pca_id: None,
requested_ops: &[],
escalation_after_minutes,
request_canonical_json: Some(crate::blocked::canonical_request_json(
&method_str,
&req.upstream_path,
"google",
&req.action,
&req.policy_path,
&req.body_for_policy,
)),
},
)
.await;
return Err(AppError::ReadFilterBlocked);
}
persist_quarantine_samples(
&state.auth.db,
request_id,
session.agent_session_id,
outcome.matched_policy_id.as_deref(),
&o.samples,
)
.await;
super::policy_trace::mark_read_filter(
&mut policy_trace,
false,
outcome.matched_policy_id.clone(),
format!("{} matches, {} samples", o.matches, o.samples.len()),
);
(b, o)
} else {
(body_bytes, Default::default())
};
// Observe mode (ui-less-surfaces.md §2.5): if the policy would have
// blocked / required_confirmation / rate_limited but is in observe
// mode, the engine returns Decision::Allow + an `observe_would_have`
// label. The action event records the "would have" outcome so the
// operator can promote the policy to enforce later.
let decision_label = match &outcome.decision {
Decision::Allow => outcome.observe_would_have.as_deref().unwrap_or("allow"),
Decision::Block { .. } => "block",
Decision::RequireConfirmation { .. } => "require_confirmation",
Decision::RateLimit { .. } => "rate_limit",
};
if let Some(woulda) = outcome.observe_would_have.as_deref() {
// Strip the `observe_` prefix to keep the metric label bounded.
let reason = woulda.strip_prefix("observe_").unwrap_or(woulda);
metrics::counter!(
"proxilion_observe_would_have_blocked_total",
"policy_id" => outcome
.matched_policy_id
.clone()
.unwrap_or_else(|| "unknown".into()),
"reason" => reason.to_string(),
)
.increment(1);
}
// Per-policy audit-body capture (ui-less-surfaces.md §6.4).
if let Some(mode) = outcome.audit_body {
let req_bytes: &[u8] = req.upstream_body.as_deref().unwrap_or(&[]);
crate::audit_body::persist(&state.auth.db, request_id, mode, req_bytes, &final_body).await;
}
// spec.md §3.2 — `proxilion_adapter_requests_total{vendor,action,decision,mode}`.
metrics::counter!(
"proxilion_adapter_requests_total",
"vendor" => "google",
"action" => req.action.clone(),
"decision" => decision_label.to_string(),
"mode" => if outcome.observe_would_have.is_some() { "observe" } else { "enforce" },
)
.increment(1);
metrics::histogram!(
"proxilion_adapter_request_duration_seconds",
"vendor" => "google",
"action" => req.action.clone(),
)
.record(adapter_started.elapsed().as_secs_f64());
state
.stream
.publish(ActionEvent {
request_id,
agent_session_id: session.agent_session_id,
p_0: session.p_0.clone(),
leaf_pca_id: Some(pca2_id),
vendor: "google".to_string(),
action: req.action.clone(),
method: req.method.to_string(),
path: req.upstream_path.clone(),
status: status.as_u16(),
decision: decision_label.to_string(),
block_reason: None,
read_filter_triggered: filter_outcome.triggered,
quarantined_count: filter_outcome.matches,
at: Utc::now(),
policy_id: outcome.matched_policy_id.clone(),
extra: json!({
"request_path_params": req.policy_path,
"to_domain": ctx.body.get("to_domain"),
"to_domains": ctx.body.get("to_domains"),
"external_recipient": ctx.body.get("external_recipient"),
"recipient_count": ctx.body.get("recipient_count"),
"attachment_count": ctx.body.get("attachment_count"),
"pic_audit_violation": audit_violation_detail,
}),
})
.await;
info!(
request_id = %request_id,
action = %req.action,
status = status.as_u16(),
pca2_id = %pca2_id,
"proxied gmail request"
);
let mut builder = Response::builder().status(status);
let resp_headers = builder.headers_mut().expect("fresh builder has headers");
if let Some(ct) = content_type.as_deref() {
if let Ok(v) = HeaderValue::from_str(ct) {
resp_headers.insert(CONTENT_TYPE, v);
}
}
insert_proxy_headers(resp_headers, request_id, &outcome, pca2_id);
if let Ok(v) = HeaderValue::from_str(&policy_trace.trace_id.to_string()) {
resp_headers.insert(HeaderName::from_static("x-proxilion-trace-id"), v);
}
super::policy_trace::emit(&policy_trace, request_id, "google", &req.action);
builder
.body(axum::body::Body::from(final_body))
.map_err(|e| AppError::Internal(e.to_string()))
}
fn build_policy_ctx(
state: &AdapterState,
session: &crate::session::SessionContext,
req: &GmailRequest,
) -> RequestContext {
RequestContext {
vendor: "google".into(),
action: req.action.clone(),
user: UserCtx {
email: session.p_0.clone(),
groups: vec![],
},
path: req.policy_path.clone(),
body: req.body_for_policy.clone(),
headers: HashMap::new(),
customer_domain: state.customer_domain.clone(),
}
}
fn enforce_pre_request_decision(outcome: &Outcome) -> Result<(), AppError> {
match &outcome.decision {
Decision::Allow => Ok(()),
Decision::Block {
reason,
override_allowed,
} => Err(AppError::PolicyBlocked {
policy_id: outcome.matched_policy_id.clone(),
reason: reason.clone(),
override_allowed: *override_allowed,
}),
Decision::RequireConfirmation { reason } => {
Err(AppError::RequireConfirmation(reason.clone()))
}
Decision::RateLimit { .. } => Err(AppError::RateLimit),
}
}
fn insert_proxy_headers(
headers: &mut HeaderMap,
request_id: Uuid,
outcome: &Outcome,
pca_id: Uuid,
) {
headers.insert(
HeaderName::from_static("x-proxilion-request-id"),
HeaderValue::from_str(&request_id.to_string()).expect("uuid"),
);
headers.insert(
HeaderName::from_static("x-proxilion-pca-id"),
HeaderValue::from_str(&pca_id.to_string()).expect("uuid"),
);
if let Some(pid) = outcome.matched_policy_id.as_deref() {
if let Ok(v) = HeaderValue::from_str(pid) {
headers.insert(HeaderName::from_static("x-proxilion-policy"), v);
}
}
}
async fn persist_quarantine_samples(
db: &sqlx::PgPool,
request_id: Uuid,
session_id: Uuid,
policy_id: Option<&str>,
samples: &[read_filter::QuarantineSample],
) {
for s in samples {
let res = sqlx::query(
"INSERT INTO quarantined_payloads
(request_id, session_id, policy_id, pattern, snippet)
VALUES ($1, $2, $3, $4, $5)",
)
.bind(request_id)
.bind(session_id)
.bind(policy_id)
.bind(&s.pattern)
.bind(&s.snippet)
.execute(db)
.await;
if let Err(e) = res {
warn!(error = %e, "failed to persist quarantine sample");
}
}
}
// ============ body parsing ============
#[derive(Debug, Default)]
struct ParsedSend {
to: Vec<String>,
cc: Vec<String>,
bcc: Vec<String>,
subject: Option<String>,
attachment_count: usize,
body_text_preview: Option<String>,
}
fn decode_b64url(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
// Gmail's `raw` is base64url; padding is optional. Try padded first,
// fall back to no-pad.
B64URL.decode(s).or_else(|_| B64URL_NP.decode(s))
}
/// Cheap single-pass upper bound on `mailparse`'s recursion depth: count the
/// case-insensitive `multipart/` markers in the raw MIME. Every `multipart/*`
/// container the parser recurses into carries one in its `Content-Type`, so
/// `depth ≤ marker_count`. Used to reject pathologically-nested bodies before
/// they can overflow the stack (see `MAX_MIME_MULTIPART`).
fn count_multipart_markers(raw: &[u8]) -> usize {
const NEEDLE: &[u8] = b"multipart/";
let mut count = 0;
let mut i = 0;
while i + NEEDLE.len() <= raw.len() {
if raw[i].eq_ignore_ascii_case(&b'm')
&& raw[i..i + NEEDLE.len()].eq_ignore_ascii_case(NEEDLE)
{
count += 1;
i += NEEDLE.len();
} else {
i += 1;
}
}
count
}
fn parse_mime(raw: &[u8]) -> Result<ParsedSend, mailparse::MailParseError> {
if count_multipart_markers(raw) > MAX_MIME_MULTIPART {
return Err(mailparse::MailParseError::Generic(
"MIME multipart nesting exceeds bound",
));
}
let parsed = mailparse::parse_mail(raw)?;
let mut out = ParsedSend::default();
for header in parsed.get_headers() {
let key = header.get_key();
let value = header.get_value();
match key.to_ascii_lowercase().as_str() {
"to" => out.to.extend(split_addresses(&value)),
"cc" => out.cc.extend(split_addresses(&value)),
"bcc" => out.bcc.extend(split_addresses(&value)),
"subject" => out.subject = Some(value),
_ => {}
}
}
// Count attachments + capture a preview of the first text/plain part.
count_parts(&parsed, &mut out);
Ok(out)
}
fn count_parts(part: &mailparse::ParsedMail<'_>, out: &mut ParsedSend) {
if part.subparts.is_empty() {
let ct = part.ctype.mimetype.to_ascii_lowercase();
let disposition: String = part
.get_headers()
.into_iter()
.find(|h: &&mailparse::MailHeader<'_>| {
h.get_key().eq_ignore_ascii_case("Content-Disposition")
})
.map(|h: &mailparse::MailHeader<'_>| h.get_value().to_ascii_lowercase())
.unwrap_or_default();
if disposition.starts_with("attachment") {
out.attachment_count += 1;
return;
}
if ct.starts_with("text/plain") && out.body_text_preview.is_none() {
if let Ok(body) = part.get_body() {
let preview: String = body.chars().take(512).collect();
out.body_text_preview = Some(preview);
}
}
} else {
for sub in &part.subparts {
count_parts(sub, out);
}
}
}
/// Split a comma-separated address list into bare email addresses.
/// Handles `"Name" <addr@host>` and bare `addr@host` and groups (`undisclosed:;`).
fn split_addresses(value: &str) -> Vec<String> {
// mailparse::addrparse handles RFC 5322 properly.
if let Ok(list) = mailparse::addrparse(value) {
let mut out = Vec::new();
for info in list.iter() {
match info {
mailparse::MailAddr::Single(s) => out.push(s.addr.clone()),
mailparse::MailAddr::Group(g) => {
for m in &g.addrs {
out.push(m.addr.clone());
}
}
}
}
return out;
}
// Fail-closed on a parse error. `addrparse` rejects RFC-5322-malformed
// header values (unbalanced quotes, dangling angle brackets, unterminated
// groups), but Gmail's own parser is more lenient and may still *route*
// such a header. We forward `body.raw` to Gmail verbatim, so if we drop
// the recipients here the §9 `gmail-external-send-gate` — decided on
// `body.external_recipient`, derived from these addresses — sees an empty
// set and fails OPEN (an external send slips through unblocked). Instead,
// fall back to a permissive split that still surfaces any `@`-bearing
// token, stripping address-syntax noise, so domain extraction keeps
// flagging external recipients.
value
.split([',', ' ', '\t', '\r', '\n', ';', '<', '>', '"', '(', ')'])
.map(str::trim)
.filter(|t| t.contains('@'))
.map(str::to_owned)
.collect()
}
fn domain_of(email: &str) -> Option<String> {
email
.rsplit_once('@')
.map(|(_, d)| d.trim().to_ascii_lowercase())
}
fn build_send_body_ctx(
parsed: &ParsedSend,
customer_domain: &str,
from_p0: &str,
) -> HashMap<String, Value> {
let mut recipients: Vec<String> = Vec::new();
recipients.extend(parsed.to.iter().cloned());
recipients.extend(parsed.cc.iter().cloned());
recipients.extend(parsed.bcc.iter().cloned());
let domains: Vec<String> = recipients
.iter()
.filter_map(|r| domain_of(r))
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
let to_domain_first = domains.first().cloned().unwrap_or_default();
let cd = customer_domain.to_ascii_lowercase();
let external_recipient = domains.iter().any(|d| d != &cd);
let mut body = HashMap::new();
body.insert(
"to".into(),
Value::Array(parsed.to.iter().map(|s| Value::String(s.clone())).collect()),
);
body.insert(
"cc".into(),
Value::Array(parsed.cc.iter().map(|s| Value::String(s.clone())).collect()),
);
body.insert(
"bcc".into(),
Value::Array(
parsed
.bcc
.iter()
.map(|s| Value::String(s.clone()))
.collect(),
),
);
// `to_domain` is the FIRST unique recipient domain (alphabetical) — a
// convenience/display value and an input to single-domain ops narrowing.
// SECURITY: do NOT author an external-send gate against `to_domain`. It
// reflects only one recipient, so a send to `[internal, external]` whose
// internal domain sorts first masks the external one and the gate fails
// OPEN. Gate on `external_recipient` (bool over all recipients) or
// `to_domains` (the full sorted set) instead. Multi-domain ops expansion
// uses `to_domains` (§2.2).
body.insert("to_domain".into(), Value::String(to_domain_first));
body.insert(
"to_domains".into(),
Value::Array(domains.into_iter().map(Value::String).collect()),
);
body.insert("external_recipient".into(), Value::Bool(external_recipient));
body.insert(
"recipient_count".into(),
Value::Number((recipients.len() as u64).into()),
);
body.insert(
"attachment_count".into(),
Value::Number((parsed.attachment_count as u64).into()),
);
body.insert(
"subject_present".into(),
Value::Bool(parsed.subject.is_some()),
);
body.insert("from_p0".into(), Value::String(from_p0.to_owned()));
body
}
// Quiet unused-import warnings on rarely-used types.
#[allow(dead_code)]
const _USED: (Option<Bytes>, StatusCode) = (None, StatusCode::OK);
#[cfg(test)]
mod tests {
use super::*;
fn build_raw(to: &str, subject: &str, body: &str) -> String {
let raw =
format!("To: {to}\r\nFrom: alice@acme.com\r\nSubject: {subject}\r\n\r\n{body}\r\n");
B64URL_NP.encode(raw.as_bytes())
}
#[test]
fn decode_handles_padded_and_unpadded() {
let padded = B64URL.encode(b"hello world");
let unpadded = B64URL_NP.encode(b"hello world");
assert_eq!(decode_b64url(&padded).unwrap(), b"hello world");
assert_eq!(decode_b64url(&unpadded).unwrap(), b"hello world");
}
#[test]
fn parse_simple_message() {
let raw = "To: bob@acme.com\r\nFrom: alice@acme.com\r\nSubject: hi\r\n\r\nhello\r\n";
let p = parse_mime(raw.as_bytes()).unwrap();
assert_eq!(p.to, vec!["bob@acme.com".to_string()]);
assert_eq!(p.subject.as_deref(), Some("hi"));
assert_eq!(p.attachment_count, 0);
assert!(p.body_text_preview.as_deref().unwrap().starts_with("hello"));
}
#[test]
fn parse_multiple_recipients_with_display_names() {
let raw = "To: \"Bob\" <bob@acme.com>, eve@evilcorp.example\r\nCc: c@third.example\r\nFrom: alice@acme.com\r\nSubject: x\r\n\r\n.\r\n";
let p = parse_mime(raw.as_bytes()).unwrap();
assert_eq!(p.to.len(), 2);
assert!(p.to.iter().any(|a| a == "bob@acme.com"));
assert!(p.to.iter().any(|a| a == "eve@evilcorp.example"));
assert_eq!(p.cc, vec!["c@third.example".to_string()]);
}
#[test]
fn body_ctx_flags_external_recipient() {
let raw_b64 = build_raw("bob@acme.com, eve@evil.example", "hi", ".");
let raw = decode_b64url(&raw_b64).unwrap();
let p = parse_mime(&raw).unwrap();
let ctx = build_send_body_ctx(&p, "acme.com", "alice@acme.com");
assert_eq!(ctx.get("external_recipient"), Some(&Value::Bool(true)));
assert_eq!(ctx.get("recipient_count").unwrap().as_u64(), Some(2));
let domains = ctx.get("to_domains").unwrap().as_array().unwrap();
let strs: Vec<&str> = domains.iter().filter_map(|v| v.as_str()).collect();
assert!(strs.contains(&"acme.com"));
assert!(strs.contains(&"evil.example"));
}