withone 0.1.1

Typed Rust client for the One API: the client, webhooks and the action type every withone-<platform> crate builds on.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
use crate::{
    retry::{RetrySchedule, Retryable},
    transport::types::PaginatedVaultConnectionView,
    webhooks::Webhooks
};
use bytes::Bytes;
use handlebars::Handlebars;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
use reqwest::{
    Client as HttpClient, Error as ReqwestError, RequestBuilder,
    header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap, RETRY_AFTER}
};
pub use reqwest::{Method, StatusCode};
use secrecy::{ExposeSecret, SecretBox, SecretString};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Error as JsonError, Map, Value, from_slice, to_value, to_vec};
use std::{
    collections::BTreeMap,
    env::var,
    error::Error as StdError,
    fmt,
    marker::PhantomData,
    sync::{Arc, Once},
    time::Duration
};

use rustls::{ClientConfig, RootCertStore, crypto::ring::default_provider};
use tokio::time::sleep;
use webpki_roots::TLS_SERVER_ROOTS;

/// A connection record from the vault, typed straight from the One API schema.
pub use crate::transport::types::PaginatedVaultConnectionViewRowsItem as Connection;

const SECRET_HEADER: &str = "X-One-Secret";
const BEARER_PREFIX: &str = "Bearer ";
const CONNECTION_KEY_HEADER: &str = "X-One-Connection-Key";
const ACTION_ID_HEADER: &str = "X-One-Action-Id";
const ORGANIZATION_ID_HEADER: &str = "X-One-Organization-Id";
const PROJECT_ID_HEADER: &str = "X-One-Project-Id";
const DEFAULT_BASE_URL: &str = "https://api.picaos.com";
const SECRET_ENV: &str = "ONE_SECRET";
const ACCESS_TOKEN_ENV: &str = "ONE_ACCESS_TOKEN";
const BASE_URL_ENV: &str = "ONE_BASE_URL";
const VAULT_CONNECTIONS_PATH: &str = "/v1/vault/connections";
const CONNECTION_KEY_PARAM: &str = "key";
const PAGE_PARAM: &str = "page";
const LIMIT_PARAM: &str = "limit";
const APPLICATION_JSON: &str = "application/json";
const NON_OBJECT_INPUT: &str = "the input must be a JSON object";

/// Characters to percent-encode in a path-parameter value: everything except
/// the RFC 3986 unreserved set (`ALPHA / DIGIT / - . _ ~`). This keeps a value
/// like `a/b` as a single path segment (`a%2Fb`) instead of letting `/`, `?`,
/// `#`, or spaces re-shape the URL.
pub(crate) const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');

/// The value of an environment variable that was actually configured, treating
/// "set but blank" as unset.
///
/// A leftover `ONE_SECRET=` in a shell profile, a compose file, or a CI matrix
/// is how an environment says *not this one* - but `env::var` reports it as a
/// present value, so it would win the credential precedence over the
/// `ONE_ACCESS_TOKEN` sitting beside it and then fail the build as a missing
/// secret. Nothing here has a meaningful blank value, so every read goes
/// through this.
fn configured(key: &str) -> Option<String> {
    var(key).ok().filter(|value| !value.trim().is_empty())
}

/// Errors returned by SDK calls.
///
/// `#[non_exhaustive]`: new variants may be added in future releases, so
/// downstream `match` statements must include a `_ =>` arm.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The request could not be sent (DNS, TLS, connect).
    #[error("transport error: {0}")]
    Transport(ReqwestError),
    /// The request exceeded its configured timeout.
    #[error("request timed out")]
    Timeout,
    /// The response body could not be read.
    #[error("failed to read response body: {0}")]
    Body(ReqwestError),
    /// The platform returned a non-2xx status; the raw body is preserved.
    #[error("upstream returned status {status}")]
    Status { status: StatusCode, body: Bytes },
    /// A response body could not be deserialized into the requested type.
    #[error("failed to decode response: {0}")]
    Decode(JsonError),
    /// No connection matched the requested key.
    #[error("no connection found for the given key")]
    NotFound,
    /// The client was built without a credential.
    #[error(
        "a credential is required: a secret key (.secret() or ONE_SECRET) or an OAuth access token (.access_token() \
         or ONE_ACCESS_TOKEN)"
    )]
    MissingSecret,
    /// A path template referenced a variable not supplied in the path object.
    #[error("path template error: {0}")]
    PathTemplate(String),
    /// A generated action's input is missing a required field or holds an
    /// invalid value; the source is the builder's or the router's own error.
    #[error("invalid action input: {0}")]
    InvalidInput(#[source] Box<dyn StdError + Send + Sync>)
}

/// A part of an action request that a flat input field is routed into.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Part {
    Path,
    Query,
    Headers,
    Body
}

/// Where one field of a generated action's flat input goes in the request.
#[derive(Debug, Clone, Copy)]
pub struct Route {
    /// The field's name in the serialized input.
    pub field: &'static str,
    /// The request part it belongs to.
    pub part:  Part,
    /// Its key within that part, or `None` when the field is the whole part.
    pub key:   Option<&'static str>
}

/// How a generated action's flat input maps onto its request.
#[derive(Debug, Clone, Copy)]
pub struct Routing {
    /// Where each field goes.
    pub routes:         &'static [Route],
    /// Object parts the action requires, sent as `{}` when no field sets them.
    pub required_parts: &'static [Part]
}

/// Anything [`ConnectionScope::run`] executes: an [`Operation`], or a
/// generated action's input or builder.
pub trait IntoOperation {
    /// The type the response decodes to.
    type Output;

    /// Builds the operation, failing when the input does not validate.
    fn into_operation(self) -> Result<Operation<Self::Output>, Error>;
}

impl<Out> IntoOperation for Operation<Out> {
    type Output = Out;

    fn into_operation(self) -> Result<Self, Error> {
        Ok(self)
    }
}

impl Retryable for Error {
    fn is_transient(&self) -> bool {
        match self {
            Self::Transport(e) => e.is_timeout() || e.is_connect() || e.is_request(),
            Self::Timeout => true,
            Self::Status { status, .. } => status.is_server_error() || *status == StatusCode::TOO_MANY_REQUESTS,
            Self::Body(_)
            | Self::Decode(_)
            | Self::NotFound
            | Self::MissingSecret
            | Self::PathTemplate(_)
            | Self::InvalidInput(_) => false
        }
    }
}

/// A successful (2xx) response, tagged with the action's default output type
/// `Out` (the io_schema output, or [`Value`] for raw calls). Holds the raw
/// body; [`CallResponse::output`] decodes the default, [`CallResponse::json`]
/// any caller type.
pub struct CallResponse<Out = Value> {
    status:  StatusCode,
    headers: BTreeMap<String, String>,
    body:    Bytes,
    _out:    PhantomData<fn() -> Out>
}

impl<Out> Clone for CallResponse<Out> {
    fn clone(&self) -> Self {
        Self {
            status:  self.status,
            headers: self.headers.clone(),
            body:    self.body.clone(),
            _out:    PhantomData
        }
    }
}

impl<Out> CallResponse<Out> {
    /// The HTTP status of the response.
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// The response headers (rate-limit, request-id, `ETag`, `Link`, …), header
    /// names mapped to their value.
    pub fn headers(&self) -> &BTreeMap<String, String> {
        &self.headers
    }

    /// The raw response body.
    pub fn bytes(&self) -> &Bytes {
        &self.body
    }

    /// The response body as a UTF-8 string (lossy).
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    /// Decodes the body into a caller-supplied type — the override for when the
    /// synced output is wrong.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
        from_slice(&self.body).map_err(Error::Decode)
    }

    /// Re-tags the response with a different output type. The engine attaches
    /// the operation's `Out` here.
    fn retype<U>(self) -> CallResponse<U> {
        CallResponse {
            status:  self.status,
            headers: self.headers,
            body:    self.body,
            _out:    PhantomData
        }
    }
}

impl<Out: DeserializeOwned> CallResponse<Out> {
    /// Decodes the body into the action's default output type.
    pub fn output(&self) -> Result<Out, Error> {
        from_slice(&self.body).map_err(Error::Decode)
    }
}

type SuccessHook = Arc<dyn Fn(&CallResponse) + Send + Sync>;
type ErrorHook = Arc<dyn Fn(&Error) + Send + Sync>;

/// What the client authenticates with.
///
/// Two credentials reach the same API by different headers, and a request
/// carries exactly one. Modelling it as a choice rather than two optional
/// fields means "both set" and "neither set" are states that cannot be built.
///
/// Both arms hold the value in [`SecretBox`], so a credential is redacted in
/// `Debug` and zeroized on drop. It is exposed only in [`Self::apply`], at the
/// moment the header is written.
#[derive(Clone)]
pub enum Credential {
    /// A One secret key, sent as `X-One-Secret`. The long-lived agency
    /// credential.
    Secret(Arc<SecretBox<String>>),
    /// An OAuth access token, sent as `Authorization: Bearer`. What an app
    /// holding an end user's grant uses; the reachable surface is whatever that
    /// grant consented to, not the whole account.
    AccessToken(Arc<SecretBox<String>>)
}

impl fmt::Debug for Credential {
    /// Names which credential is in play and never its value, so a client
    /// dumped into a log or a panic cannot leak the token.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Secret(_) => f.write_str("Credential::Secret(<redacted>)"),
            Self::AccessToken(_) => f.write_str("Credential::AccessToken(<redacted>)")
        }
    }
}

impl Credential {
    /// A One secret key.
    pub fn secret(secret: impl Into<String>) -> Self {
        Self::Secret(Arc::new(SecretBox::new(Box::new(secret.into()))))
    }

    /// An OAuth access token.
    pub fn access_token(token: impl Into<String>) -> Self {
        Self::AccessToken(Arc::new(SecretBox::new(Box::new(token.into()))))
    }

    /// Adds this credential to a request. The one place either header is
    /// written, and the only place the value is exposed.
    fn apply(&self, request: RequestBuilder) -> RequestBuilder {
        match self {
            Self::Secret(secret) => request.header(SECRET_HEADER, secret.expose_secret()),
            Self::AccessToken(token) => {
                request.header(AUTHORIZATION, format!("{BEARER_PREFIX}{}", token.expose_secret()))
            }
        }
    }

    /// Whether this carries nothing usable.
    ///
    /// Blank counts, matching [`configured`]: a credential of spaces is a
    /// misconfiguration however it arrives, and the builder exists to catch it
    /// here rather than at the first 401. The two doors must agree - the same
    /// `"  "` cannot be unset when it comes from the environment and a valid
    /// secret when it comes from the builder.
    fn is_empty(&self) -> bool {
        match self {
            Self::Secret(value) | Self::AccessToken(value) => value.expose_secret().trim().is_empty()
        }
    }
}

/// The tenant a request acts within: an organization, optionally narrowed to
/// one of its projects. Empty means the caller's own personal scope.
///
/// **A secret key does not need this and an access token does.** A key is
/// bound to its tenant server-side, so the API reads tenancy off the key and
/// ignores what the request claims. A bearer is not: one token can hold grants
/// on several organizations, so the tenant is decided per request from these
/// headers - and a request that sends neither resolves to the personal tier no
/// matter what the token was granted. That is why an org-owned connection is
/// simply absent from a bearer's results until this is set.
#[derive(Clone, Debug, Default)]
pub struct Tenancy {
    organization: Option<String>,
    project:      Option<String>
}

impl Tenancy {
    /// Adds the tenant headers to a request. The one place either is written.
    fn apply(&self, request: RequestBuilder) -> RequestBuilder {
        let request = match &self.organization {
            Some(id) => request.header(ORGANIZATION_ID_HEADER, id),
            None => request
        };
        match &self.project {
            Some(id) => request.header(PROJECT_ID_HEADER, id),
            None => request
        }
    }
}

/// The One SDK client.
///
/// Holds the credential, base URL, default retry schedule, and global
/// success/error hooks. Cheap to clone; wraps a shared `reqwest` client.
#[derive(Clone)]
pub struct One {
    http:       HttpClient,
    base_url:   String,
    credential: Credential,
    tenancy:    Tenancy,
    retry:      RetrySchedule,
    timeout:    Option<Duration>,
    on_success: Option<SuccessHook>,
    on_error:   Option<ErrorHook>
}

impl One {
    /// Starts a request carrying this client's credential and tenant scope.
    ///
    /// The one door every call goes through, so a new endpoint cannot ship
    /// having attached one and forgotten the other - which for tenancy fails
    /// silently, as a request with no tenant headers is a valid personal-scope
    /// request that simply cannot see the tenant's rows.
    fn request(&self, method: Method, url: &str) -> RequestBuilder {
        self.tenancy
            .apply(self.credential.apply(self.http.request(method, url)))
    }

    /// Creates a client from a One secret key, targeting the default base URL.
    /// Panics if `secret` is empty; use [`OneBuilder::build`] for a fallible
    /// path.
    pub fn new(secret: impl Into<String>) -> Self {
        Self::builder()
            .secret(secret)
            .build()
            .expect("One::new requires a non-empty secret")
    }

    /// Creates a client from the environment: a credential (required) and
    /// `ONE_BASE_URL` (optional, defaults to the production base URL).
    ///
    /// The credential is `ONE_SECRET`, or `ONE_ACCESS_TOKEN` for an OAuth
    /// grant. `ONE_SECRET` wins if both are set, because it is the
    /// longer-standing variable and silently preferring the newer one would
    /// change what an existing environment authenticates as. Set-but-blank does
    /// not count as set - see [`configured`].
    pub fn from_env() -> Result<Self, Error> {
        let credential = configured(SECRET_ENV)
            .map(Credential::secret)
            .or_else(|| configured(ACCESS_TOKEN_ENV).map(Credential::access_token))
            .ok_or(Error::MissingSecret)?;

        let mut builder = Self::builder().credential(credential);
        if let Some(base_url) = configured(BASE_URL_ENV) {
            builder = builder.base_url(base_url);
        }
        builder.build()
    }

    /// Starts building a client with full configuration.
    pub fn builder() -> OneBuilder {
        OneBuilder::default()
    }

    /// Scopes subsequent calls to a connection by its key.
    pub fn connection(&self, key: impl Into<String>) -> ConnectionScope<'_> {
        ConnectionScope {
            one: self,
            key: key.into()
        }
    }

    /// Starts building a webhook listener, verified with `signing_secret`.
    ///
    /// The listener owns a clone of this client: it is mounted into an HTTP
    /// server and outlives any single request, so it cannot borrow.
    pub fn webhooks(&self, signing_secret: SecretString) -> Webhooks {
        Webhooks::new(self.clone(), signing_secret)
    }

    /// Sends an authenticated `PUT` with a JSON body to a One API path and
    /// preserves the response metadata for the webhook bindings.
    pub(crate) async fn put_json_response<B: Serialize, Out>(
        &self,
        path: &str,
        body: &B
    ) -> Result<CallResponse<Out>, Error> {
        let url = format!("{}{path}", self.base_url);
        let payload = to_vec(body).map_err(Error::Decode)?;

        let response = self
            .execute(self.retry, None, &[], || {
                let mut request = self
                    .request(Method::PUT, &url)
                    .header(CONTENT_TYPE, APPLICATION_JSON)
                    .body(payload.clone());
                if let Some(timeout) = self.timeout {
                    request = request.timeout(timeout);
                }
                request
            })
            .await?;

        Ok(response.retype())
    }

    /// The one place a request is sent, retried, and reported.
    ///
    /// Applies `retry` honoring `Retry-After`, treats the transient set plus
    /// `retry_on` as retryable, and fires the client hooks followed by the
    /// per-call ones. Both the action engine and the management calls route
    /// through this, so a transport or retry fix lands once.
    pub(crate) async fn execute<F>(
        &self,
        retry: RetrySchedule,
        on_call: Option<(&Option<SuccessHook>, &Option<ErrorHook>)>,
        retry_on: &[StatusCode],
        build: F
    ) -> Result<CallResponse<Value>, Error>
    where
        F: Fn() -> reqwest::RequestBuilder
    {
        let send = || {
            let request = build();
            async move {
                let response = match request.send().await {
                    Ok(response) => response,
                    Err(error) => {
                        let mapped = if error.is_timeout() {
                            Error::Timeout
                        } else {
                            Error::Transport(error)
                        };
                        return Err((mapped, None));
                    }
                };
                let status = response.status();
                let headers: BTreeMap<String, String> = response
                    .headers()
                    .iter()
                    .filter_map(|(name, value)| {
                        value
                            .to_str()
                            .ok()
                            .map(|value| (name.as_str().to_string(), value.to_string()))
                    })
                    .collect();
                let retry_after = Self::retry_after(response.headers());
                let body = match response.bytes().await {
                    Ok(body) => body,
                    Err(error) => return Err((Error::Body(error), None))
                };
                if status.is_success() {
                    Ok(CallResponse {
                        status,
                        headers,
                        body,
                        _out: PhantomData
                    })
                } else {
                    Err((Error::Status { status, body }, retry_after))
                }
            }
        };

        let attempts = retry.max_attempts.max(1);
        let result: Result<CallResponse<Value>, Error> = 'attempts: {
            for attempt in 1..=attempts {
                match send().await {
                    Ok(response) => break 'attempts Ok(response),
                    Err((error, retry_after)) => {
                        if attempt == attempts || !Self::is_retryable(&error, retry_on) {
                            break 'attempts Err(error);
                        }
                        sleep(retry_after.unwrap_or_else(|| retry.delay(attempt))).await;
                    }
                }
            }
            unreachable!("loop runs at least once and breaks on every path")
        };

        match &result {
            Ok(response) => {
                if let Some(hook) = &self.on_success {
                    hook(response);
                }
                if let Some(hook) = on_call.and_then(|(success, _)| success.as_ref()) {
                    hook(response);
                }
            }
            Err(error) => {
                if let Some(hook) = &self.on_error {
                    hook(error);
                }
                if let Some(hook) = on_call.and_then(|(_, failure)| failure.as_ref()) {
                    hook(error);
                }
            }
        }

        result
    }

    /// Whether a failed attempt should be retried: the general transient set
    /// plus any per-call `retry_on` statuses.
    fn is_retryable(error: &Error, retry_on: &[StatusCode]) -> bool {
        error.is_transient() || matches!(error, Error::Status { status, .. } if retry_on.contains(status))
    }

    /// Parses a `Retry-After` header expressed as a whole number of seconds.
    fn retry_after(headers: &HeaderMap) -> Option<Duration> {
        headers
            .get(RETRY_AFTER)?
            .to_str()
            .ok()?
            .trim()
            .parse::<u64>()
            .ok()
            .map(Duration::from_secs)
    }
}

/// Builder for [`One`].
#[derive(Default)]
pub struct OneBuilder {
    base_url:   Option<String>,
    credential: Option<Credential>,
    tenancy:    Tenancy,
    retry:      Option<RetrySchedule>,
    timeout:    Option<Duration>,
    on_success: Option<SuccessHook>,
    on_error:   Option<ErrorHook>
}

impl OneBuilder {
    /// Sets the secret key (`X-One-Secret`).
    pub fn secret(mut self, secret: impl Into<String>) -> Self {
        self.credential = Some(Credential::secret(secret));
        self
    }

    /// Sets the credential directly, for callers that already have one in
    /// hand. [`Self::secret`] and [`Self::access_token`] are the usual doors.
    pub fn credential(mut self, credential: Credential) -> Self {
        self.credential = Some(credential);
        self
    }

    /// Acts within an organization the caller has access to.
    ///
    /// **Required to reach an organization's connections with an access
    /// token.** A token can hold grants on several organizations, so the API
    /// decides which one a request means from this - and a request that omits
    /// it means the user's personal scope, where an organization-owned
    /// connection simply is not present. A secret key already carries its
    /// tenant, so setting this alongside one changes nothing.
    pub fn organization(mut self, organization_id: impl Into<String>) -> Self {
        self.tenancy.organization = Some(organization_id.into());
        self
    }

    /// Narrows [`Self::organization`] to one of its projects.
    ///
    /// A project is always qualified by its organization, so this is only
    /// meaningful beside one; on its own the request still resolves to the
    /// personal scope.
    pub fn project(mut self, project_id: impl Into<String>) -> Self {
        self.tenancy.project = Some(project_id.into());
        self
    }

    /// Authenticates with an OAuth access token instead of a secret key.
    ///
    /// The reachable surface is whatever the end user consented to for this
    /// app, not the whole account. Calling this after [`Self::secret`] (or the
    /// reverse) replaces the credential rather than adding one: a request
    /// carries exactly one.
    pub fn access_token(mut self, token: impl Into<String>) -> Self {
        self.credential = Some(Credential::access_token(token));
        self
    }

    /// Overrides the base URL (e.g. a self-hosted or local instance).
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Sets the default retry schedule, applied to operations that don't
    /// declare their own.
    pub fn retry(mut self, schedule: RetrySchedule) -> Self {
        self.retry = Some(schedule);
        self
    }

    /// Sets the default per-request timeout, applied to operations that don't
    /// declare their own.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Registers a global hook invoked after every successful call.
    pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
        self.on_success = Some(Arc::new(hook));
        self
    }

    /// Registers a global hook invoked after every failed call.
    pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
        self.on_error = Some(Arc::new(hook));
        self
    }

    /// Builds the client, applying defaults for any unset field.
    ///
    /// Fails fast with [`Error::MissingSecret`] when no credential was
    /// configured, rather than deferring the misconfiguration to a runtime auth
    /// failure. **Either credential satisfies it** - a secret key from
    /// [`Self::secret`] or an OAuth access token from [`Self::access_token`] -
    /// and a configured-but-empty one counts as absent, since an empty header
    /// would fail at the API rather than here.
    pub fn build(self) -> Result<One, Error> {
        let credential = self
            .credential
            .filter(|credential| !credential.is_empty())
            .ok_or(Error::MissingSecret)?;
        Self::ensure_crypto_provider();
        let http = HttpClient::builder()
            .use_preconfigured_tls(Self::tls_config())
            .build()
            .map_err(Error::Transport)?;
        Ok(One {
            http,
            base_url: self
                .base_url
                .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
                .trim_end_matches('/')
                .to_string(),
            credential,
            tenancy: self.tenancy,
            retry: self.retry.unwrap_or_default(),
            timeout: self.timeout,
            on_success: self.on_success,
            on_error: self.on_error
        })
    }

    /// Installs the process-default rustls crypto provider (`ring`) once. The
    /// reqwest client uses rustls without a built-in provider, so one must be
    /// registered before the first TLS handshake; `ring` is chosen over
    /// `aws-lc-rs` because it cross-compiles cleanly to every published target.
    fn ensure_crypto_provider() {
        static ONCE: Once = Once::new();
        ONCE.call_once(|| {
            let _ = default_provider().install_default();
        });
    }

    /// A rustls config that trusts the bundled Mozilla root certificates, so
    /// the client establishes TLS without a system certificate store —
    /// required in minimal container images that ship no CA bundle.
    fn tls_config() -> ClientConfig {
        let roots = RootCertStore {
            roots: TLS_SERVER_ROOTS.to_vec()
        };
        ClientConfig::builder()
            .with_root_certificates(roots)
            .with_no_client_auth()
    }
}

/// A declarative description of an action invocation.
///
/// You describe *what* you want — which action (`system_id`), the request
/// shape, and the retry policy — and the engine ([`ConnectionScope::run`])
/// resolves *how* to execute it. The action's verb and path are part of the
/// description; once discovery lands they are filled from the action itself
/// rather than supplied by hand.
pub struct Operation<Out = Value> {
    system_id:  String,
    method:     Method,
    path:       String,
    query:      Value,
    headers:    BTreeMap<String, String>,
    body:       Bytes,
    retry:      Option<RetrySchedule>,
    retry_on:   Vec<StatusCode>,
    timeout:    Option<Duration>,
    on_success: Option<SuccessHook>,
    on_error:   Option<ErrorHook>,
    _out:       PhantomData<fn() -> Out>
}

impl<Out> Clone for Operation<Out> {
    fn clone(&self) -> Self {
        Self {
            system_id:  self.system_id.clone(),
            method:     self.method.clone(),
            path:       self.path.clone(),
            query:      self.query.clone(),
            headers:    self.headers.clone(),
            body:       self.body.clone(),
            retry:      self.retry,
            retry_on:   self.retry_on.clone(),
            timeout:    self.timeout,
            on_success: self.on_success.clone(),
            on_error:   self.on_error.clone(),
            _out:       PhantomData
        }
    }
}

impl Operation<Value> {
    /// Starts a typed action operation from its `system_id`, HTTP method, and
    /// path template. Envelope parts are attached with the `with_*` setters,
    /// which take the typed parts directly — the envelope contract is the typed
    /// fields passed by name, not keys fished out of a serialized blob. Output
    /// defaults to [`Value`]; generated actions re-tag it via
    /// [`Operation::returns`].
    pub fn action(system_id: impl Into<String>, method: Method, path_template: impl Into<String>) -> Self {
        Self {
            system_id: system_id.into(),
            method,
            path: path_template.into(),
            query: Value::Null,
            headers: BTreeMap::new(),
            body: Bytes::new(),
            retry: None,
            retry_on: Vec::new(),
            timeout: None,
            on_success: None,
            on_error: None,
            _out: PhantomData
        }
    }
}

impl<Out> Operation<Out> {
    /// Declares the retry policy for this operation, overriding the client
    /// default. Part of the description — the engine resolves it.
    pub fn retry(mut self, schedule: RetrySchedule) -> Self {
        self.retry = Some(schedule);
        self
    }

    /// Adds HTTP status codes that should be retried for this call, on top of
    /// the always-retried transient set (network errors, 5xx, 429). HTTP-only —
    /// status classification has no meaning outside an API call.
    pub fn retry_on(mut self, statuses: impl IntoIterator<Item = StatusCode>) -> Self {
        self.retry_on = statuses.into_iter().collect();
        self
    }

    /// Sets a per-request timeout for this call, overriding the client default.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Registers a per-call success hook, run in addition to the client's
    /// global `on_success`.
    pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
        self.on_success = Some(Arc::new(hook));
        self
    }

    /// Registers a per-call error hook, run in addition to the client's global
    /// `on_error`.
    pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
        self.on_error = Some(Arc::new(hook));
        self
    }

    /// Re-tags the operation's output type. Generated actions attach the
    /// io_schema's `Output`; callers can override a wrong synced output.
    pub fn returns<Out2>(self) -> Operation<Out2> {
        Operation {
            system_id:  self.system_id,
            method:     self.method,
            path:       self.path,
            query:      self.query,
            headers:    self.headers,
            body:       self.body,
            retry:      self.retry,
            retry_on:   self.retry_on,
            timeout:    self.timeout,
            on_success: self.on_success,
            on_error:   self.on_error,
            _out:       PhantomData
        }
    }

    /// Fills the path template's `{{name}}` placeholders from the typed path
    /// part.
    pub fn with_path<P: Serialize>(mut self, path: &P) -> Result<Self, Error> {
        let value = to_value(path).map_err(Error::Decode)?;
        self.path = Self::resolve_path(&self.path, Some(&value))?;
        Ok(self)
    }

    /// Attaches the typed query part; serde lowers it to query parameters.
    pub fn with_query<Q: Serialize>(mut self, query: &Q) -> Result<Self, Error> {
        self.query = to_value(query).map_err(Error::Decode)?;
        Ok(self)
    }

    /// Attaches the typed headers part as request headers.
    pub fn with_headers<H: Serialize>(mut self, headers: &H) -> Result<Self, Error> {
        let value = to_value(headers).map_err(Error::Decode)?;
        self.headers = Self::string_map(Some(&value));
        Ok(self)
    }

    /// Serializes the typed body part as the request payload. An omitted
    /// optional body (`Option<Body>` left unset) serializes to the literal
    /// `null`; treat that as "no body" and leave the payload empty so the
    /// engine omits it rather than sending `null` bytes upstream.
    pub fn with_body<B: Serialize>(mut self, body: &B) -> Result<Self, Error> {
        let bytes = to_vec(body).map_err(Error::Decode)?;
        if bytes != b"null" {
            self.body = Bytes::from(bytes);
        }
        Ok(self)
    }

    /// Distributes a generated action's flat input into its request parts:
    /// an unkeyed route supplies the whole part, a keyed route then sets one
    /// entry of its part, and a field the input leaves out is skipped. A
    /// required part with nothing set is sent as `{}`, and the path template is
    /// always rendered, so a missing path value fails here instead of going
    /// upstream.
    pub fn with_routed<I: Serialize>(self, input: &I, routing: &Routing) -> Result<Self, Error> {
        let Value::Object(mut fields) = to_value(input).map_err(Error::Decode)? else {
            return Err(Error::InvalidInput(NON_OBJECT_INPUT.into()));
        };
        let mut parts: BTreeMap<Part, Value> = routing
            .required_parts
            .iter()
            .chain([&Part::Path])
            .map(|part| (*part, Value::Object(Map::new())))
            .collect();
        let (whole, keyed): (Vec<&Route>, Vec<&Route>) = routing.routes.iter().partition(|route| route.key.is_none());
        for route in whole {
            if let Some(value) = fields.remove(route.field) {
                parts.insert(route.part, value);
            }
        }
        for route in keyed {
            let (Some(key), Some(value)) = (route.key, fields.remove(route.field)) else {
                continue;
            };
            match parts.entry(route.part).or_insert_with(|| Value::Object(Map::new())) {
                Value::Object(entries) => {
                    entries.insert(key.to_string(), value);
                }
                _ => {
                    let message = format!("`{}` needs `{key}` set on an object", route.field);
                    return Err(Error::InvalidInput(message.into()));
                }
            }
        }
        parts.into_iter().try_fold(self, |operation, (part, value)| match part {
            Part::Path => operation.with_path(&value),
            Part::Query => operation.with_query(&value),
            Part::Headers => operation.with_headers(&value),
            Part::Body => operation.with_body(&value)
        })
    }

    /// Sets the request body to raw bytes, for non-JSON payloads. The typed
    /// `with_body` is preferred for action calls.
    pub fn raw_body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = body.into();
        self
    }

    /// Merges extra fields into the request body, on top of the typed body —
    /// the escape hatch for attributes a stale or incomplete io_schema omits.
    pub fn merge_body(mut self, extra: Value) -> Result<Self, Error> {
        let mut body: Value = if self.body.is_empty() {
            Value::Object(Default::default())
        } else {
            from_slice(&self.body).map_err(Error::Decode)?
        };
        Self::merge(&mut body, extra);
        self.body = Bytes::from(to_vec(&body).map_err(Error::Decode)?);
        Ok(self)
    }

    /// Merges extra parameters on top of the typed query.
    pub fn merge_query(mut self, extra: Value) -> Self {
        Self::merge(&mut self.query, extra);
        self
    }

    /// Merges extra headers on top of the typed headers.
    pub fn merge_headers(mut self, extra: Value) -> Self {
        if let Value::Object(entries) = extra {
            for (key, value) in entries {
                let rendered = value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string());
                self.headers.insert(key, rendered);
            }
        }
        self
    }

    /// Removes a header — e.g. to drop one injected from a busted `const`.
    pub fn remove_header(mut self, name: &str) -> Self {
        self.headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
        self
    }

    /// Removes a query parameter.
    pub fn remove_query(mut self, name: &str) -> Self {
        if let Some(object) = self.query.as_object_mut() {
            object.remove(name);
        }
        self
    }

    /// The action's system id (sent as `X-One-Action-Id`).
    pub fn system_id(&self) -> &str {
        &self.system_id
    }

    /// The resolved HTTP method.
    pub fn method(&self) -> &Method {
        &self.method
    }

    /// The resolved upstream path, with placeholders filled in.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The resolved query parameters.
    pub fn query(&self) -> &Value {
        &self.query
    }

    /// The resolved request headers, including injected `const` headers.
    pub fn headers(&self) -> &BTreeMap<String, String> {
        &self.headers
    }

    /// The serialized request body.
    pub fn body(&self) -> &Bytes {
        &self.body
    }

    /// Shallow-merges the entries of `extra` into `target` when both are
    /// objects, or replaces `target` if it was null.
    fn merge(target: &mut Value, extra: Value) {
        if target.is_null() {
            *target = extra;
        } else if let (Some(base), Value::Object(entries)) = (target.as_object_mut(), extra) {
            for (key, value) in entries {
                base.insert(key, value);
            }
        }
    }

    /// Fills a path template from a `path` object, rendering it with the same
    /// Handlebars engine the platform uses so every template form resolves the
    /// way the server expects: `{{name}}` percent-encodes its value into a
    /// single path segment, `{{{name}}}` emits it raw (unescaped), and dotted
    /// paths (`{{a.b}}`) resolve into the object. Strict mode: a variable the
    /// template references but the path object does not supply is an error —
    /// the client renders the final route, so a missing value cannot be filled
    /// later; fail fast rather than ship `//` or stray braces upstream.
    fn resolve_path(template: &str, path: Option<&Value>) -> Result<String, Error> {
        let mut renderer = Handlebars::new();
        renderer.set_strict_mode(true);
        renderer.register_escape_fn(|raw| utf8_percent_encode(raw, PATH_SEGMENT).to_string());
        let context = path.cloned().unwrap_or(Value::Null);
        renderer
            .render_template(template, &context)
            .map_err(|error| Error::PathTemplate(error.to_string()))
    }

    /// Renders a JSON object into a string map for query params / headers.
    fn string_map(object: Option<&Value>) -> BTreeMap<String, String> {
        let mut map = BTreeMap::new();
        if let Some(Value::Object(entries)) = object {
            for (key, value) in entries {
                let rendered = value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string());
                map.insert(key.clone(), rendered);
            }
        }
        map
    }
}

impl<Out> fmt::Debug for Operation<Out> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Operation")
            .field("system_id", &self.system_id)
            .field("method", &self.method.as_str())
            .field("path", &self.path)
            .field("query", &self.query)
            .field("headers", &self.headers)
            .field("body", &String::from_utf8_lossy(&self.body))
            .finish()
    }
}

/// A connection-scoped handle. The engine ([`ConnectionScope::run`]) executes
/// declarative [`Operation`]s against this connection.
pub struct ConnectionScope<'a> {
    one: &'a One,
    key: String
}

impl ConnectionScope<'_> {
    /// The engine: resolves and executes a declarative [`Operation`] against
    /// this connection. Signs the request with the secret + connection-key +
    /// action-id headers, applies the operation's retry/timeout policy (or the
    /// client defaults), retries transient HTTP failures (network, 5xx, 429,
    /// and any `retry_on` statuses) honoring `Retry-After`, and fires the
    /// client + per-call success/error hooks.
    pub async fn run<O: IntoOperation>(&self, operation: O) -> Result<CallResponse<O::Output>, Error> {
        let Operation {
            system_id,
            method,
            path,
            query,
            headers,
            body,
            retry,
            retry_on,
            timeout,
            on_success,
            on_error,
            ..
        } = operation.into_operation().inspect_err(|error| {
            if let Some(hook) = &self.one.on_error {
                hook(error);
            }
        })?;
        let retry = retry.unwrap_or(self.one.retry);
        let timeout = timeout.or(self.one.timeout);
        let url = format!("{}/v1/passthrough/{}", self.one.base_url, path.trim_start_matches('/'));

        let response = self
            .one
            .execute(retry, Some((&on_success, &on_error)), &retry_on, || {
                let mut request = self
                    .one
                    .request(method.clone(), &url)
                    .header(CONNECTION_KEY_HEADER, &self.key)
                    .header(ACTION_ID_HEADER, &system_id);
                if let Some(timeout) = timeout {
                    request = request.timeout(timeout);
                }
                if !body.is_empty() {
                    request = request.body(body.clone());
                }
                if query.as_object().is_some_and(|object| !object.is_empty()) {
                    request = request.query(&query);
                }
                for (name, value) in &headers {
                    request = request.header(name.as_str(), value.as_str());
                }
                request
            })
            .await;

        response.map(|response| response.retype())
    }

    /// Fetches this connection's record from the vault by key, including its
    /// metadata. Returns [`Error::NotFound`] if no connection matches.
    ///
    /// **The lookup happens within the client's tenant scope, not across every
    /// tenant.** A secret key carries its tenant server-side, so this is
    /// scope-agnostic for one. A bearer is not: the vault resolves the tenant
    /// from the request's headers, so a client built without
    /// [`OneBuilder::organization`] looks in the user's personal connections
    /// and an organization-owned connection reads as absent.
    pub async fn get(&self) -> Result<Connection, Error> {
        let url = format!("{}{VAULT_CONNECTIONS_PATH}", self.one.base_url);
        let response = self
            .one
            .request(Method::GET, &url)
            .query(&[
                (CONNECTION_KEY_PARAM, self.key.as_str()),
                (PAGE_PARAM, "1"),
                (LIMIT_PARAM, "1")
            ])
            .send()
            .await
            .map_err(|error| {
                if error.is_timeout() {
                    Error::Timeout
                } else {
                    Error::Transport(error)
                }
            })?;
        let status = response.status();
        let body = response.bytes().await.map_err(Error::Body)?;
        if !status.is_success() {
            return Err(Error::Status { status, body });
        }
        let page: PaginatedVaultConnectionView = from_slice(&body).map_err(Error::Decode)?;
        page.rows.into_iter().next().ok_or(Error::NotFound)
    }
}

#[cfg(test)]
mod tests {
    use std::env::{remove_var, set_var};

    use super::{ACCESS_TOKEN_ENV, Credential, One, SECRET_ENV};

    /// Reads the credential `from_env` picks for one pair of variable values,
    /// leaving the environment as it found it.
    ///
    /// **One test drives every case, and the restore is not an assertion's
    /// job.** The environment is process-global: two tests setting these
    /// concurrently decide each other's outcome under a plain `cargo test`, and
    /// a cleanup written after the `assert!` never runs on the failing path
    /// that most needs it - leaking the variables into every test that follows.
    fn credential_from(secret: Option<&str>, access_token: Option<&str>) -> Option<Credential> {
        unsafe {
            match secret {
                Some(value) => set_var(SECRET_ENV, value),
                None => remove_var(SECRET_ENV)
            }
            match access_token {
                Some(value) => set_var(ACCESS_TOKEN_ENV, value),
                None => remove_var(ACCESS_TOKEN_ENV)
            }
        }

        let credential = One::from_env().ok().map(|one| one.credential);

        unsafe {
            remove_var(SECRET_ENV);
            remove_var(ACCESS_TOKEN_ENV);
        }

        credential
    }

    /// `ONE_SECRET=` left behind in a profile or a compose file is how an
    /// environment says *not this one*. It used to shadow the access token
    /// beside it and then fail as a missing secret, which reads as "you have
    /// configured nothing" to someone who has configured the newer variable.
    #[test]
    fn test_client_from_env_resolves_the_credential_by_precedence() {
        assert!(
            matches!(credential_from(Some(""), Some("at_from_env")), Some(Credential::AccessToken(_))),
            "a blank legacy secret must not shadow the access token beside it"
        );
        assert!(
            matches!(credential_from(Some("   "), Some("at_from_env")), Some(Credential::AccessToken(_))),
            "nor must a whitespace-only one"
        );
        assert!(
            matches!(credential_from(Some("sk_from_env"), Some("at_from_env")), Some(Credential::Secret(_))),
            "with both set, the longer-standing variable wins"
        );
        assert!(
            matches!(credential_from(Some("sk_from_env"), None), Some(Credential::Secret(_))),
            "and it stands alone"
        );
        assert!(credential_from(None, None).is_none(), "neither configured is a missing secret, not a client");
    }
}