-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathraw_client.rs
More file actions
1222 lines (1133 loc) · 37.7 KB
/
Copy pathraw_client.rs
File metadata and controls
1222 lines (1133 loc) · 37.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
//! Raw/generic Datadog HTTP client support: request routing for endpoints not
//! covered by the typed SDK (the `pup api` passthrough and several hand-written
//! commands), plus the OAuth-exclusion fallback table shared with the typed path.
use crate::config::Config;
use crate::useragent;
/// HTTP error with the status code preserved for programmatic matching.
#[derive(Debug)]
pub struct HttpError {
pub status: u16,
pub method: String,
pub url: String,
pub body: String,
}
impl std::fmt::Display for HttpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} {} failed (HTTP {}): {}",
self.method, self.url, self.status, self.body
)
}
}
impl std::error::Error for HttpError {}
// ---------------------------------------------------------------------------
// Auth type detection
// ---------------------------------------------------------------------------
// Parse a reqwest response body as JSON without serde_json's default 128-level
// recursion cap. Some Datadog endpoints (e.g. /profiling/api/v1/aggregate)
// return deeply-nested flame-graph trees that exceed it. serde_stacker grows
// the thread stack on demand so disabling the limit can't blow it.
async fn parse_response_json(resp: reqwest::Response) -> anyhow::Result<serde_json::Value> {
use serde::Deserialize;
let bytes = resp.bytes().await?;
// Some endpoints return a success status (e.g. 200) with an empty body, such
// as GET /api/v2/on-call/pages/{id} which responds with content-length: 0.
// Treat an empty or whitespace-only body as JSON null rather than failing
// with "EOF while parsing value at line 1 column 0".
if bytes.iter().all(u8::is_ascii_whitespace) {
return Ok(serde_json::Value::Null);
}
let mut de = serde_json::Deserializer::from_slice(&bytes);
de.disable_recursion_limit();
let de = serde_stacker::Deserializer::new(&mut de);
Ok(serde_json::Value::deserialize(de)?)
}
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthType {
None,
OAuth,
ApiKeys,
}
impl std::fmt::Display for AuthType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AuthType::None => write!(f, "None"),
AuthType::OAuth => write!(f, "OAuth2 Bearer Token"),
AuthType::ApiKeys => write!(f, "API Keys (DD_API_KEY + DD_APP_KEY)"),
}
}
}
#[allow(dead_code)]
pub fn get_auth_type(cfg: &Config) -> AuthType {
if cfg.has_bearer_token() {
AuthType::OAuth
} else if cfg.has_api_keys() {
AuthType::ApiKeys
} else {
AuthType::None
}
}
// ---------------------------------------------------------------------------
// OAuth-excluded endpoint validation
// ---------------------------------------------------------------------------
struct EndpointRequirement {
path: &'static str,
method: &'static str,
}
/// Returns true if the endpoint doesn't support OAuth and requires API key fallback.
#[allow(dead_code)]
pub fn requires_api_key_fallback(method: &str, path: &str) -> bool {
find_endpoint_requirement(method, path).is_some()
}
/// Returns true if the endpoint accepts an API key without an application key.
pub(crate) fn requires_api_key_only(method: &str, path: &str) -> bool {
method == "POST" && path == "/api/v1/events"
}
fn find_endpoint_requirement(method: &str, path: &str) -> Option<&'static EndpointRequirement> {
OAUTH_EXCLUDED_ENDPOINTS.iter().find(|req| {
if req.method != method {
return false;
}
// Trailing "/" means prefix match (for ID-parameterized paths)
if req.path.ends_with('/') {
path.starts_with(&req.path[..req.path.len() - 1])
} else {
req.path == path
}
})
}
// ---------------------------------------------------------------------------
// Static tables
// ---------------------------------------------------------------------------
/// Endpoints that don't support OAuth.
/// Trailing "/" means prefix match for ID-parameterized paths.
static OAUTH_EXCLUDED_ENDPOINTS: &[EndpointRequirement] = &[
// API/App Keys (8)
EndpointRequirement {
path: "/api/v2/api_keys",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/api_keys/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/api_keys",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/api_keys/",
method: "DELETE",
},
EndpointRequirement {
path: "/api/v2/application_keys",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/application_keys/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/application_keys/",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/application_keys/",
method: "PATCH",
},
// DDSQL editor tools (3)
EndpointRequirement {
path: "/api/unstable/ddsql-editor/tools/ddsql-docs",
method: "GET",
},
EndpointRequirement {
path: "/api/unstable/ddsql-editor/tools/table-names",
method: "GET",
},
EndpointRequirement {
path: "/api/unstable/ddsql-editor/tools/table-data",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/application_keys/",
method: "DELETE",
},
// Fleet Automation (15)
EndpointRequirement {
path: "/api/v2/fleet/agents",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/fleet/agents/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/fleet/agents/versions",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/fleet/deployments",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/fleet/deployments/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/fleet/deployments/configure",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/fleet/deployments/upgrade",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/fleet/deployments/",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/fleet/deployments/",
method: "DELETE",
},
EndpointRequirement {
path: "/api/v2/fleet/schedules",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/fleet/schedules/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/fleet/schedules",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/fleet/schedules/",
method: "PATCH",
},
EndpointRequirement {
path: "/api/v2/fleet/schedules/",
method: "DELETE",
},
EndpointRequirement {
path: "/api/v2/fleet/schedules/",
method: "POST",
},
// Observability Pipelines (6) — API key only, no OAuth support
EndpointRequirement {
path: "/api/v2/obs-pipelines/pipelines",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/obs-pipelines/pipelines",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/obs-pipelines/pipelines/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/obs-pipelines/pipelines/",
method: "PUT",
},
EndpointRequirement {
path: "/api/v2/obs-pipelines/pipelines/",
method: "DELETE",
},
EndpointRequirement {
path: "/api/v2/obs-pipelines/pipelines/validate",
method: "POST",
},
// Cost / Billing (11) — API key only, no OAuth support
EndpointRequirement {
path: "/api/v2/usage/projected_cost",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/usage/cost_by_org",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost_by_tag/monthly_cost_attribution",
method: "GET",
},
// Cloud Cost Management config (12)
EndpointRequirement {
path: "/api/v2/cost/aws_cur_config",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost/aws_cur_config",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/cost/aws_cur_config/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost/aws_cur_config/",
method: "DELETE",
},
EndpointRequirement {
path: "/api/v2/cost/azure_uc_config",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost/azure_uc_config",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/cost/azure_uc_config/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost/azure_uc_config/",
method: "DELETE",
},
EndpointRequirement {
path: "/api/v2/cost/gcp_uc_config",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost/gcp_uc_config",
method: "POST",
},
EndpointRequirement {
path: "/api/v2/cost/gcp_uc_config/",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost/gcp_uc_config/",
method: "DELETE",
},
EndpointRequirement {
path: "/api/v2/cost/oci_config",
method: "GET",
},
EndpointRequirement {
path: "/api/v2/cost/anomalies",
method: "GET",
},
// Profiling (4)
// No OAuth scope is declared for Continuous Profiler endpoints; force API-key auth.
EndpointRequirement {
path: "/profiling/api/v1/",
method: "POST",
},
EndpointRequirement {
path: "/profiling/api/v1/",
method: "GET",
},
EndpointRequirement {
path: "/api/unstable/profiles/",
method: "POST",
},
EndpointRequirement {
path: "/api/ui/profiling/",
method: "GET",
},
// Events intake (1)
// Posting an event uses the V1 intake endpoint, which authenticates with the
// API key and does not accept OAuth2 bearer tokens. Listing/getting events
// (GET) is fine over OAuth, so only POST is excluded.
EndpointRequirement {
path: "/api/v1/events",
method: "POST",
},
// Logs saved views write endpoints accept full API users, not OAuth tokens.
// List/get support OAuth, so only create/delete are excluded here.
EndpointRequirement {
path: "/api/v1/logs/views",
method: "POST",
},
EndpointRequirement {
path: "/api/v1/logs/views/",
method: "DELETE",
},
];
// ---------------------------------------------------------------------------
// Raw HTTP helpers
// ---------------------------------------------------------------------------
/// Raw HTTP response returned by [`raw_request`].
#[derive(Debug)]
pub struct HttpResponse {
/// The `Content-Type` header value from the response, or an empty string if absent.
pub content_type: String,
/// The raw response body bytes.
pub bytes: Vec<u8>,
}
/// Makes an authenticated request with any HTTP method via reqwest.
///
/// - `query` — key/value pairs appended as URL query parameters (reqwest handles percent-encoding).
/// Pass `&[]` when no query parameters are needed.
/// - `body` — raw bytes to send; `content_type` sets the `Content-Type` header when present.
/// - `accept` — value for the `Accept` header (e.g. `"application/json"`, `"*/*"`).
/// - `extra_headers` — additional headers applied after auth and before the body.
/// - Returns an [`HttpResponse`] with the raw bytes and response `Content-Type`.
/// Callers are responsible for decoding the bytes.
#[allow(clippy::too_many_arguments)]
pub async fn raw_request(
cfg: &Config,
method: &str,
path: &str,
query: &[(&str, &str)],
body: Option<Vec<u8>>,
content_type: Option<&str>,
accept: &str,
extra_headers: &[(&str, &str)],
) -> anyhow::Result<HttpResponse> {
let url = format!("{}{}", cfg.api_base_url(), path);
let client = reqwest::Client::new();
let method_name = method.to_uppercase();
let method = reqwest::Method::from_bytes(method_name.as_bytes())
.map_err(|_| anyhow::anyhow!("unsupported HTTP method: {method_name}"))?;
let mut req = client.request(method, &url);
if !query.is_empty() {
req = req.query(query);
}
req = apply_auth(req, cfg, &method_name, path)?;
req = req
.header("Accept", accept)
.header("User-Agent", useragent::get());
for (k, v) in extra_headers {
req = req.header(*k, *v);
}
if let Some(b) = body {
if let Some(ct) = content_type {
req = req.header("Content-Type", ct);
}
req = req.body(b);
}
let resp = req.send().await?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
return Err(HttpError {
status: status.as_u16(),
method: method_name,
url,
body: text,
}
.into());
}
let resp_ct = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
if resp.status() == reqwest::StatusCode::NO_CONTENT {
return Ok(HttpResponse {
content_type: resp_ct,
bytes: vec![],
});
}
let bytes = resp.bytes().await?.to_vec();
Ok(HttpResponse {
content_type: resp_ct,
bytes,
})
}
/// Makes an authenticated GET request directly via reqwest.
/// Used for endpoints not covered by the typed DD API client.
/// Pass an empty slice for `query` when no query parameters are needed.
pub async fn raw_get(
cfg: &Config,
path: &str,
query: &[(&str, &str)],
) -> anyhow::Result<serde_json::Value> {
let url = format!("{}{}", cfg.api_base_url(), path);
let client = reqwest::Client::new();
let mut req = client.get(&url);
req = apply_auth(req, cfg, "GET", path)?;
if !query.is_empty() {
req = req.query(query);
}
let resp = req
.header("Accept", "application/json")
.header("User-Agent", useragent::get())
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(HttpError {
status: status.as_u16(),
method: "GET".into(),
url,
body,
}
.into());
}
parse_response_json(resp).await
}
/// Makes an authenticated PATCH request directly via reqwest.
/// Used for endpoints not covered by the typed DD API client.
#[allow(dead_code)]
pub async fn raw_patch(
cfg: &Config,
path: &str,
body: serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
let url = format!("{}{}", cfg.api_base_url(), path);
let client = reqwest::Client::new();
let mut req = client.patch(&url);
req = apply_auth(req, cfg, "PATCH", path)?;
let resp = req
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("User-Agent", useragent::get())
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(HttpError {
status: status.as_u16(),
method: "PATCH".into(),
url,
body,
}
.into());
}
parse_response_json(resp).await
}
/// Makes an authenticated POST request directly via reqwest.
/// Used for endpoints not covered by the typed DD API client.
pub async fn raw_post(
cfg: &Config,
path: &str,
body: serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
let url = format!("{}{}", cfg.api_base_url(), path);
raw_post_impl(cfg, path, &url, body, useragent::get()).await
}
/// Like `raw_post`, but with a custom User-Agent string for audit log differentiation.
pub async fn raw_post_with_ua(
cfg: &Config,
path: &str,
body: serde_json::Value,
ua: String,
) -> anyhow::Result<serde_json::Value> {
let url = format!("{}{}", cfg.api_base_url(), path);
raw_post_impl(cfg, path, &url, body, ua).await
}
async fn raw_post_impl(
cfg: &Config,
path: &str,
url: &str,
body: serde_json::Value,
ua: String,
) -> anyhow::Result<serde_json::Value> {
let client = reqwest::Client::new();
let mut req = client.post(url);
req = apply_auth(req, cfg, "POST", path)?;
let resp = req
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("User-Agent", ua)
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(HttpError {
status: status.as_u16(),
method: "POST".into(),
url: url.to_string(),
body,
}
.into());
}
parse_response_json(resp).await
}
/// Apply Datadog authentication headers to a request builder.
///
/// Chooses between OAuth bearer and API-key auth based on `cfg` and the
/// per-endpoint requirements in [`requires_api_key_fallback`]. OAuth-excluded
/// endpoints require both API and application keys except for the V1 event
/// intake endpoint, which requires only the API key. Exposed so the generic
/// `pup api` passthrough reuses the same auth routing as the typed clients.
pub fn apply_auth(
mut req: reqwest::RequestBuilder,
cfg: &Config,
method: &str,
path: &str,
) -> anyhow::Result<reqwest::RequestBuilder> {
// Events post is also in the broader OAuth-excluded table, so handle its
// API-key-only requirement before the fallback branch that adds both keys.
if requires_api_key_only(method, path) {
if let Some(api_key) = &cfg.api_key {
return Ok(req.header("DD-API-KEY", api_key.as_str()));
}
anyhow::bail!(
"{method} {path} requires DD_API_KEY; OAuth2 bearer tokens are not supported"
);
}
if requires_api_key_fallback(method, path) {
if let (Some(api_key), Some(app_key)) = (&cfg.api_key, &cfg.app_key) {
req = req
.header("DD-API-KEY", api_key.as_str())
.header("DD-APPLICATION-KEY", app_key.as_str());
return Ok(req);
}
anyhow::bail!(
"{method} {path} requires DD_API_KEY and DD_APP_KEY; OAuth2 bearer tokens are not supported"
);
}
if let Some(token) = &cfg.access_token {
req = req.header("Authorization", format!("Bearer {token}"));
return Ok(req);
}
if let (Some(api_key), Some(app_key)) = (&cfg.api_key, &cfg.app_key) {
req = req
.header("DD-API-KEY", api_key.as_str())
.header("DD-APPLICATION-KEY", app_key.as_str());
return Ok(req);
}
anyhow::bail!("no authentication configured")
}
/// POST a JSON:API document. Wraps `attributes` in `{data:{type,attributes}}`
/// and sends with `Content-Type: application/vnd.api+json`. Use for routes
/// whose decoder is configured for JSON:API.
pub async fn raw_post_jsonapi(
cfg: &Config,
path: &str,
resource_type: &str,
attributes: serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
let url = format!("{}{}", cfg.api_base_url(), path);
let envelope = serde_json::json!({
"data": { "type": resource_type, "attributes": attributes },
});
let client = reqwest::Client::new();
let mut req = client.post(&url);
req = apply_auth(req, cfg, "POST", path)?;
let resp = req
.header("Content-Type", "application/vnd.api+json")
.header("Accept", "application/vnd.api+json")
.header("User-Agent", useragent::get())
.json(&envelope)
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("POST {url} failed (HTTP {status}): {body}");
}
parse_response_json(resp).await
}
pub async fn raw_put(
cfg: &Config,
path: &str,
body: serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
let url = format!("{}{}", cfg.api_base_url(), path);
let client = reqwest::Client::new();
let req = client.put(&url);
let req = apply_auth(req, cfg, "PUT", path)?;
let resp = req
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("User-Agent", useragent::get())
.json(&body)
.send()
.await?;
if resp.status() == reqwest::StatusCode::NO_CONTENT {
return Ok(serde_json::Value::Null);
}
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("PUT {url} failed (HTTP {status}): {body}");
}
parse_response_json(resp).await
}
/// Like `raw_post`, but returns the parsed JSON body even on non-2xx responses.
/// Callers are responsible for inspecting the body for errors.
pub async fn raw_post_lenient(
cfg: &Config,
path: &str,
body: serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
let url = format!("{}{}", cfg.api_base_url(), path);
let client = reqwest::Client::new();
let mut req = client.post(&url);
if let Some(token) = &cfg.access_token {
req = req.header("Authorization", format!("Bearer {token}"));
} else if let (Some(api_key), Some(app_key)) = (&cfg.api_key, &cfg.app_key) {
req = req
.header("DD-API-KEY", api_key.as_str())
.header("DD-APPLICATION-KEY", app_key.as_str());
} else {
anyhow::bail!("no authentication configured");
}
let resp = req
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("User-Agent", useragent::get())
.json(&body)
.send()
.await?;
parse_response_json(resp).await
}
/// Makes an authenticated DELETE request directly via reqwest.
/// Used for endpoints not covered by the typed DD API client.
pub async fn raw_delete(cfg: &Config, path: &str) -> anyhow::Result<()> {
let url = format!("{}{}", cfg.api_base_url(), path);
let client = reqwest::Client::new();
let mut req = client.delete(&url);
req = apply_auth(req, cfg, "DELETE", path)?;
let resp = req
.header("Accept", "application/json")
.header("User-Agent", useragent::get())
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(HttpError {
status: status.as_u16(),
method: "DELETE".into(),
url,
body,
}
.into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use crate::test_support::*;
fn test_cfg() -> Config {
Config {
api_key: Some("test".into()),
app_key: Some("test".into()),
access_token: None,
site: "datadoghq.com".into(),
site_explicit: false,
org: None,
output_format: crate::config::OutputFormat::Json,
auto_approve: false,
agent_mode: false,
read_only: false,
jq: None,
}
}
#[test]
fn test_auth_type_api_keys() {
let cfg = test_cfg();
assert_eq!(get_auth_type(&cfg), AuthType::ApiKeys);
}
#[test]
fn test_auth_type_bearer() {
let mut cfg = test_cfg();
cfg.access_token = Some("token".into());
assert_eq!(get_auth_type(&cfg), AuthType::OAuth);
}
#[test]
fn test_auth_type_none() {
let mut cfg = test_cfg();
cfg.api_key = None;
cfg.app_key = None;
assert_eq!(get_auth_type(&cfg), AuthType::None);
}
#[test]
fn test_auth_type_display() {
assert_eq!(AuthType::OAuth.to_string(), "OAuth2 Bearer Token");
assert_eq!(
AuthType::ApiKeys.to_string(),
"API Keys (DD_API_KEY + DD_APP_KEY)"
);
assert_eq!(AuthType::None.to_string(), "None");
}
#[test]
fn test_no_fallback_for_logs() {
assert!(!requires_api_key_fallback("POST", "/api/v2/logs/events"));
assert!(!requires_api_key_fallback(
"POST",
"/api/v2/logs/events/search"
));
}
#[test]
fn test_no_fallback_for_rum() {
assert!(!requires_api_key_fallback(
"GET",
"/api/v2/rum/applications"
));
assert!(!requires_api_key_fallback(
"GET",
"/api/v2/rum/applications/abc-123"
));
}
#[test]
fn test_no_fallback_for_events_search() {
assert!(!requires_api_key_fallback("POST", "/api/v2/events/search"));
}
#[test]
fn test_fallback_for_events_post() {
// Posting an event (V1 intake) requires only the API key; reading events
// does not require API-key fallback.
assert!(requires_api_key_fallback("POST", "/api/v1/events"));
assert!(requires_api_key_only("POST", "/api/v1/events"));
assert!(!requires_api_key_fallback("GET", "/api/v1/events"));
assert!(!requires_api_key_only("GET", "/api/v1/events"));
assert!(!requires_api_key_only("POST", "/api/v1/events/12345"));
}
#[test]
fn test_fallback_for_logs_saved_views_writes() {
assert!(!requires_api_key_fallback("GET", "/api/v1/logs/views"));
assert!(!requires_api_key_fallback("GET", "/api/v1/logs/views/123"));
assert!(requires_api_key_fallback("POST", "/api/v1/logs/views"));
assert!(requires_api_key_fallback(
"DELETE",
"/api/v1/logs/views/123"
));
}
#[test]
fn test_no_fallback_for_standard_endpoints() {
assert!(!requires_api_key_fallback("GET", "/api/v1/monitor"));
assert!(!requires_api_key_fallback("GET", "/api/v1/dashboard"));
assert!(!requires_api_key_fallback("GET", "/api/v2/incidents"));
}
#[test]
fn test_prefix_matching_with_id() {
// Trailing "/" in the pattern should match paths with IDs
assert!(requires_api_key_fallback(
"DELETE",
"/api/v2/api_keys/key-123"
));
assert!(requires_api_key_fallback(
"GET",
"/api/v2/fleet/agents/agent-123"
));
}
#[test]
fn test_method_must_match() {
// RUM events/search is POST-excluded, but GET should not match
assert!(!requires_api_key_fallback(
"GET",
"/api/v2/rum/events/search"
));
}
#[test]
fn test_oauth_excluded_count() {
assert_eq!(OAUTH_EXCLUDED_ENDPOINTS.len(), 57);
}
#[test]
fn test_no_fallback_for_notebooks() {
assert!(!requires_api_key_fallback("GET", "/api/v1/notebooks"));
assert!(!requires_api_key_fallback("GET", "/api/v1/notebooks/12345"));
assert!(!requires_api_key_fallback("POST", "/api/v1/notebooks"));
}
#[test]
fn test_requires_api_key_fallback_fleet() {
assert!(requires_api_key_fallback("GET", "/api/v2/fleet/agents"));
assert!(requires_api_key_fallback(
"GET",
"/api/v2/fleet/agents/agent-123"
));
}
#[test]
fn test_requires_api_key_fallback_api_keys() {
assert!(requires_api_key_fallback("GET", "/api/v2/api_keys"));
assert!(requires_api_key_fallback("POST", "/api/v2/api_keys"));
assert!(requires_api_key_fallback(
"DELETE",
"/api/v2/api_keys/key-123"
));
}
#[test]
fn test_requires_api_key_fallback_ddsql_editor_tools() {
assert!(requires_api_key_fallback(
"GET",
"/api/unstable/ddsql-editor/tools/ddsql-docs"
));
assert!(requires_api_key_fallback(
"GET",
"/api/unstable/ddsql-editor/tools/table-names"
));
assert!(requires_api_key_fallback(
"POST",
"/api/unstable/ddsql-editor/tools/table-data"
));
}
#[test]
fn test_no_fallback_for_error_tracking() {
assert!(!requires_api_key_fallback(
"POST",
"/api/v2/error_tracking/issues/search"
));
}
// Verify raw_request reaches the auth check (and fails there) for both the
// empty-query and non-empty-query paths. This ensures the `if !query.is_empty()`
// branch compiles and runs without panic.
#[test]
fn test_raw_request_no_auth_empty_query() {
let rt = tokio::runtime::Runtime::new().unwrap();
let mut cfg = test_cfg();
cfg.api_key = None;
cfg.app_key = None;
let err = rt
.block_on(raw_request(
&cfg,
"GET",
"/api/v2/monitors",
&[],
None,
None,
"application/json",
&[],
))
.unwrap_err();
assert!(
err.to_string().contains("no authentication configured"),
"expected auth error, got: {err}"
);
}
#[test]
fn test_raw_request_no_auth_with_query() {
let rt = tokio::runtime::Runtime::new().unwrap();
let mut cfg = test_cfg();
cfg.api_key = None;
cfg.app_key = None;
let err = rt
.block_on(raw_request(
&cfg,
"GET",
"/api/v2/monitors",
&[("page", "1"), ("page_size", "10")],
None,
None,
"application/json",
&[],
))
.unwrap_err();
assert!(
err.to_string().contains("no authentication configured"),
"expected auth error, got: {err}"
);
}
#[tokio::test]
async fn test_raw_events_post_sends_only_api_key() {
let _lock = lock_env().await;
let mut server = mockito::Server::new_async().await;
let cfg = test_config(&server.url());
let mock = server
.mock("POST", "/api/v1/events")