derec-library 0.0.1-alpha.8

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Library-level transport endpoint type + validation.
//!
//! This is the canonical [`TransportProtocol`] for library callers.
//! It mirrors [`derec_proto::TransportProtocol`] (the protobuf wire
//! type) but holds the protocol enum as a typed value rather than
//! a raw `i32`, exposes [`TransportProtocol::validate`] as a method,
//! and is `TryFrom<&str>` / `TryFrom<String>` for the common case
//! where the caller just has a URI in hand and wants the protocol
//! discriminant derived from the URI scheme in a single validated
//! step.
//!
//! ## Validation rules
//!
//! [`TransportProtocol::validate`] enforces:
//!
//! 1. **Length cap** — URI ≤ [`MAX_TRANSPORT_URI_LEN`] bytes.
//! 2. **No control characters** — bytes `< 0x20` or `= 0x7F` are
//!    rejected (NUL, embedded newlines, terminal escape codes).
//! 3. **Scheme matches the protocol** — `Protocol::Https` ⇒ the URI
//!    must start with `https://`. When the opt-in `unsafe-http` Cargo
//!    feature is enabled, plaintext `http://` is *also* accepted as a
//!    development convenience and emits a WARN through `tracing`
//!    (when the `logging` feature is enabled) so the insecure scheme
//!    is visible in logs. Other schemes (`ws://`, `file://`, …) are
//!    always rejected.
//! 4. **Non-empty URI** — `EmptyUri` is the explicit error.
//!
//! Unknown `protocol` discriminants are caught at the *conversion*
//! boundary by [`TryFrom<derec_proto::TransportProtocol>`] (or by
//! [`TryFrom<&derec_proto::TransportProtocol>`]), so they never reach
//! the typed [`TransportProtocol`] in the first place.

use derec_proto::Protocol;
#[cfg(any(feature = "serde", target_arch = "wasm32"))]
use serde::{Deserialize, Serialize};

/// Maximum accepted transport URI length, in bytes.
///
/// Matches the de-facto 2048-byte limit most HTTP stacks enforce
/// for request URIs. Pairing payloads embed the URI verbatim, so
/// capping it also bounds the propagated blob size.
pub const MAX_TRANSPORT_URI_LEN: usize = 2048;

/// Library-level transport endpoint.
///
/// Use this type in your `DeRecProtocolBuilder` / `set_own_transport`
/// calls; the library converts to the protobuf wire form internally
/// when it needs to encode messages. Construct it from a URI string
/// with [`TryFrom`] / [`TryInto`] (which parses the URI scheme,
/// derives the protocol discriminant, and validates in one step),
/// or directly with [`TransportProtocol::new`] when you already have
/// a typed [`Protocol`] in hand.
///
/// ## Plaintext `http://` is gated behind `unsafe-http` (development only)
///
/// By default, [`TransportProtocol::validate`] only accepts
/// `https://` URIs for [`Protocol::Https`]. The opt-in `unsafe-http`
/// Cargo feature loosens this so a `http://` URI is also accepted —
/// useful for local development and integration testing where TLS is
/// inconvenient. Whenever a plaintext URI is accepted, the library
/// emits a `tracing::warn!` (under the `logging` feature) so the
/// insecure scheme is surfaced in operator logs.
///
/// The feature flag is intentionally pejorative: enabling it also
/// lets a peer-supplied `reply_to` downgrade the reply path to
/// plaintext, since [`validate`](Self::validate) is the same gate
/// used at the peer-extract boundary. Production builds MUST leave
/// `unsafe-http` off.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
    any(feature = "serde", target_arch = "wasm32"),
    derive(Serialize, Deserialize)
)]
pub struct TransportProtocol {
    pub uri: String,
    /// Serialized as the protobuf enum's `i32` discriminant so the
    /// wire shape stays compatible with [`derec_proto::TransportProtocol`]
    /// — important because every binding's JSON Channel marshaller
    /// round-trips this field via the proto-style `{uri, protocol: 0}`
    /// representation.
    #[cfg_attr(
        any(feature = "serde", target_arch = "wasm32"),
        serde(with = "protocol_as_i32")
    )]
    pub protocol: Protocol,
}

#[cfg(any(feature = "serde", target_arch = "wasm32"))]
mod protocol_as_i32 {
    use super::Protocol;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(p: &Protocol, ser: S) -> Result<S::Ok, S::Error> {
        i32::from(*p).serialize(ser)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Protocol, D::Error> {
        let raw = i32::deserialize(de)?;
        Protocol::try_from(raw)
            .map_err(|_| serde::de::Error::custom(format!("unknown Protocol discriminant {raw}")))
    }
}

impl TransportProtocol {
    /// Construct a [`TransportProtocol`] directly from its components.
    pub fn new(uri: impl Into<String>, protocol: Protocol) -> Self {
        Self {
            uri: uri.into(),
            protocol,
        }
    }

    /// Validate the endpoint's structural soundness + scheme/protocol
    /// consistency. See the module docs for the rules.
    pub fn validate(&self) -> Result<(), TransportValidationError> {
        if self.uri.is_empty() {
            return Err(TransportValidationError::EmptyUri);
        }
        if self.uri.len() > MAX_TRANSPORT_URI_LEN {
            return Err(TransportValidationError::UriTooLong {
                got: self.uri.len(),
                limit: MAX_TRANSPORT_URI_LEN,
            });
        }
        if self.uri.bytes().any(|b| b < 0x20 || b == 0x7F) {
            return Err(TransportValidationError::ControlCharacters);
        }
        match self.protocol {
            Protocol::Https => {
                if self.uri.starts_with("https://") {
                    // canonical, secure scheme — nothing to flag
                } else if cfg!(feature = "unsafe-http")
                    && self.uri.starts_with("http://")
                {
                    // Plaintext is accepted only when the opt-in
                    // `unsafe-http` Cargo feature is set; flag it
                    // loudly so an operator running with logs
                    // enabled notices the insecure scheme.
                    #[cfg(all(feature = "unsafe-http", feature = "logging"))]
                    tracing::warn!(
                        uri = %self.uri,
                        "accepting plaintext http:// transport URI — \
                         confidentiality and authenticity are NOT provided \
                         by the transport layer; use https:// in production",
                    );
                } else {
                    return Err(TransportValidationError::SchemeMismatch {
                        expected: "https://",
                        protocol: self.protocol,
                    });
                }
            }
        }
        Ok(())
    }
}

impl TryFrom<&str> for TransportProtocol {
    type Error = TransportValidationError;

    /// Build a validated [`TransportProtocol`] from a URI literal,
    /// deriving the [`Protocol`] discriminant from the URI scheme:
    ///
    /// - `https://…` → [`Protocol::Https`]
    /// - `http://…`  → [`Protocol::Https`] (development-only; emits
    ///   a `tracing::warn!` under the `logging` feature — see the
    ///   struct-level docs)
    /// - any other scheme → [`TransportValidationError::SchemeMismatch`]
    ///
    /// Also runs the full [`validate`](Self::validate) chain (length
    /// cap, control-character check, non-empty URI), so a successful
    /// result is a fully-checked endpoint ready to embed in a
    /// pairing payload.
    fn try_from(uri: &str) -> Result<Self, Self::Error> {
        let tp = Self {
            uri: uri.to_owned(),
            protocol: Protocol::Https,
        };
        tp.validate()?;
        Ok(tp)
    }
}

impl TryFrom<String> for TransportProtocol {
    type Error = TransportValidationError;

    /// Same as [`TryFrom<&str>`](Self#impl-TryFrom<%26str>-for-TransportProtocol),
    /// but takes ownership of the URI string instead of cloning it.
    fn try_from(uri: String) -> Result<Self, Self::Error> {
        let tp = Self {
            uri,
            protocol: Protocol::Https,
        };
        tp.validate()?;
        Ok(tp)
    }
}

impl From<TransportProtocol> for derec_proto::TransportProtocol {
    /// Infallible conversion to the protobuf wire type. Used by the
    /// library when it needs to serialize an endpoint into a
    /// `ContactMessage` / `PairRequest` / etc.
    fn from(tp: TransportProtocol) -> Self {
        Self {
            uri: tp.uri,
            protocol: tp.protocol.into(),
        }
    }
}

impl From<&TransportProtocol> for derec_proto::TransportProtocol {
    fn from(tp: &TransportProtocol) -> Self {
        Self {
            uri: tp.uri.clone(),
            protocol: tp.protocol.into(),
        }
    }
}

impl TryFrom<derec_proto::TransportProtocol> for TransportProtocol {
    type Error = TransportValidationError;

    /// Fallible conversion **from** the protobuf wire type.
    ///
    /// Runs the full validation chain — first parses the `protocol`
    /// field as a defined [`Protocol`] variant (fails on unknown
    /// `i32` discriminants), then [`validate`](Self::validate)s the
    /// URI rules. Callers handling untrusted input (wire decode,
    /// FFI/WASM boundary) can therefore use a single `?` to assert
    /// the value is well-formed without a follow-up
    /// `.validate()` call.
    fn try_from(p: derec_proto::TransportProtocol) -> Result<Self, Self::Error> {
        let protocol = Protocol::try_from(p.protocol)
            .map_err(|_| TransportValidationError::UnknownProtocol(p.protocol))?;
        let tp = Self {
            uri: p.uri,
            protocol,
        };
        tp.validate()?;
        Ok(tp)
    }
}

impl TryFrom<&derec_proto::TransportProtocol> for TransportProtocol {
    type Error = TransportValidationError;

    /// Borrowed counterpart of
    /// [`TryFrom<derec_proto::TransportProtocol>`](Self#impl-TryFrom<TransportProtocol>-for-TransportProtocol).
    /// Same validation chain, but clones the URI string instead of
    /// taking ownership.
    fn try_from(p: &derec_proto::TransportProtocol) -> Result<Self, Self::Error> {
        let protocol = Protocol::try_from(p.protocol)
            .map_err(|_| TransportValidationError::UnknownProtocol(p.protocol))?;
        let tp = Self {
            uri: p.uri.clone(),
            protocol,
        };
        tp.validate()?;
        Ok(tp)
    }
}

/// Extension trait that gives the prost wire type
/// [`derec_proto::TransportProtocol`] the same `validate()` shape as the
/// library wrapper [`TransportProtocol`]. Defined here because the wire
/// type lives in another crate — the orphan rule blocks adding an
/// inherent method.
///
/// Brought into scope at every boundary where a remotely-controlled or
/// application-supplied [`derec_proto::TransportProtocol`] surfaces:
/// peer-extracted `reply_to` / `transport_protocol` fields inside
/// `extract` primitives, the orchestrator's `on_request` handlers, and
/// the FFI seam helpers. Centralising the gate in one impl keeps the
/// rejection semantics uniform across SDKs through
/// [`crate::Error::Transport`].
pub trait TransportProtocolExt {
    /// Validate the endpoint's structural soundness + scheme/protocol
    /// consistency. Same rules as [`TransportProtocol::validate`]:
    /// non-empty URI ≤ [`MAX_TRANSPORT_URI_LEN`] bytes, no control
    /// characters, known `protocol` discriminant, and the URI scheme
    /// matches the declared protocol.
    fn validate(&self) -> Result<(), TransportValidationError>;
}

impl TransportProtocolExt for derec_proto::TransportProtocol {
    fn validate(&self) -> Result<(), TransportValidationError> {
        TransportProtocol::try_from(self).map(|_| ())
    }
}

/// Conversion trait for the `with_own_transport` builder setter.
///
/// Lets callers pass either an already-typed [`TransportProtocol`] or
/// a URI string (`&str` / `String`) without having to construct the
/// typed value themselves. Implementations either yield an
/// already-valid endpoint or report a
/// [`TransportValidationError`]; the
/// [`DeRecProtocolBuilder`](crate::protocol::DeRecProtocolBuilder)
/// stashes the result and surfaces failures from `.build()` so the
/// setter chain stays infallible.
pub trait IntoOwnTransport {
    fn into_own_transport(self) -> Result<TransportProtocol, TransportValidationError>;
}

impl IntoOwnTransport for TransportProtocol {
    /// Re-runs [`validate`](TransportProtocol::validate) so a builder
    /// receiving a hand-crafted [`TransportProtocol::new`] with an
    /// invalid URI still fails at `.build()` time.
    fn into_own_transport(self) -> Result<TransportProtocol, TransportValidationError> {
        self.validate()?;
        Ok(self)
    }
}

impl IntoOwnTransport for &str {
    fn into_own_transport(self) -> Result<TransportProtocol, TransportValidationError> {
        TransportProtocol::try_from(self)
    }
}

impl IntoOwnTransport for String {
    fn into_own_transport(self) -> Result<TransportProtocol, TransportValidationError> {
        TransportProtocol::try_from(self)
    }
}

/// Structured error returned by [`TransportProtocol::validate`] and
/// by [`TryFrom`] conversions from the protobuf wire type. Surfaced
/// via [`crate::Error::Transport`] and from there into the FFI's
/// `DeRecError` and the WASM `{code, message}` shape.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TransportValidationError {
    #[error("transport uri is empty")]
    EmptyUri,

    #[error("transport uri length {got} exceeds cap {limit} bytes — refusing to propagate")]
    UriTooLong { got: usize, limit: usize },

    #[error("transport uri contains control characters (bytes < 0x20 or = 0x7F are not allowed)")]
    ControlCharacters,

    #[error("unknown TransportProtocol.protocol discriminant: {0}")]
    UnknownProtocol(i32),

    #[error(
        "transport uri must start with `{expected}` for protocol {protocol:?} \
         — rejecting plaintext / mismatched scheme"
    )]
    SchemeMismatch {
        expected: &'static str,
        protocol: Protocol,
    },
}

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

    #[test]
    fn try_from_str_derives_https_and_validates() {
        let tp = TransportProtocol::try_from("https://owner.example.com").unwrap();
        assert_eq!(tp.uri, "https://owner.example.com");
        assert_eq!(tp.protocol, Protocol::Https);
    }

    #[test]
    fn try_from_string_takes_ownership_and_validates() {
        let uri = String::from("https://owner.example.com");
        let tp = TransportProtocol::try_from(uri).unwrap();
        assert_eq!(tp.protocol, Protocol::Https);
    }

    #[cfg(feature = "unsafe-http")]
    #[test]
    fn try_from_str_accepts_plaintext_http_when_unsafe_http_enabled() {
        // With the opt-in `unsafe-http` feature on, `http://` is
        // accepted; the library emits a `tracing::warn!` (under the
        // `logging` feature) so the insecure scheme is visible in logs.
        let tp = TransportProtocol::try_from("http://owner.example.com").unwrap();
        assert_eq!(tp.protocol, Protocol::Https);
    }

    #[cfg(not(feature = "unsafe-http"))]
    #[test]
    fn try_from_str_rejects_plaintext_http_by_default() {
        // Without the `unsafe-http` feature, `http://` is treated the
        // same as any other unsupported scheme.
        assert!(matches!(
            TransportProtocol::try_from("http://owner.example.com"),
            Err(TransportValidationError::SchemeMismatch {
                expected: "https://",
                protocol: Protocol::Https,
            })
        ));
    }

    #[test]
    fn try_from_str_rejects_unsupported_scheme() {
        assert!(matches!(
            TransportProtocol::try_from("ws://owner.example.com"),
            Err(TransportValidationError::SchemeMismatch {
                expected: "https://",
                protocol: Protocol::Https,
            })
        ));
    }

    #[test]
    fn validate_rejects_unsupported_scheme() {
        let tp = TransportProtocol::new("ws://owner.example.com", Protocol::Https);
        assert!(matches!(
            tp.validate(),
            Err(TransportValidationError::SchemeMismatch {
                expected: "https://",
                protocol: Protocol::Https,
            })
        ));
    }

    #[test]
    fn validate_rejects_control_characters() {
        let tp = TransportProtocol::new("https://owner.example.com\n", Protocol::Https);
        assert!(matches!(
            tp.validate(),
            Err(TransportValidationError::ControlCharacters)
        ));
    }

    #[test]
    fn validate_rejects_oversize_uri() {
        let oversize = format!("https://{}", "a".repeat(MAX_TRANSPORT_URI_LEN));
        assert!(matches!(
            TransportProtocol::try_from(oversize),
            Err(TransportValidationError::UriTooLong { .. })
        ));
    }

    #[test]
    fn try_from_proto_rejects_unknown_enum() {
        let proto = derec_proto::TransportProtocol {
            uri: "https://x".to_owned(),
            protocol: 9999,
        };
        let res: Result<TransportProtocol, _> = (&proto).try_into();
        assert!(matches!(
            res,
            Err(TransportValidationError::UnknownProtocol(9999))
        ));
    }

    #[test]
    fn try_from_proto_also_runs_uri_validation() {
        // Known protocol enum, but the URI scheme doesn't match.
        // `TryFrom` should reject without needing a follow-up
        // `.validate()` call.
        let proto = derec_proto::TransportProtocol {
            uri: "ws://owner.example.com".to_owned(),
            protocol: 0, // Https
        };
        let res: Result<TransportProtocol, _> = (&proto).try_into();
        assert!(matches!(
            res,
            Err(TransportValidationError::SchemeMismatch {
                expected: "https://",
                ..
            })
        ));
    }

    #[test]
    fn roundtrip_to_proto_and_back() {
        let original = TransportProtocol::new("https://owner.example.com", Protocol::Https);
        let proto: derec_proto::TransportProtocol = original.clone().into();
        let back: TransportProtocol = proto.try_into().unwrap();
        assert_eq!(original, back);
    }

    #[test]
    fn into_own_transport_accepts_str_string_and_typed() {
        let from_str = IntoOwnTransport::into_own_transport("https://owner.example.com").unwrap();
        assert_eq!(from_str.uri, "https://owner.example.com");

        let from_string =
            IntoOwnTransport::into_own_transport(String::from("https://owner.example.com"))
                .unwrap();
        assert_eq!(from_string.uri, "https://owner.example.com");

        let typed = TransportProtocol::new("https://owner.example.com", Protocol::Https);
        let from_typed = IntoOwnTransport::into_own_transport(typed.clone()).unwrap();
        assert_eq!(from_typed, typed);
    }

    #[test]
    fn into_own_transport_revalidates_typed_value() {
        // A caller can hand-build a `TransportProtocol::new(...)` that
        // skips validation. `IntoOwnTransport` runs it through
        // `validate` so the setter still catches the bad URI.
        let malformed = TransportProtocol::new("ws://owner.example.com", Protocol::Https);
        assert!(matches!(
            IntoOwnTransport::into_own_transport(malformed),
            Err(TransportValidationError::SchemeMismatch { .. })
        ));
    }

    #[test]
    fn into_own_transport_rejects_unsupported_str_scheme() {
        assert!(matches!(
            IntoOwnTransport::into_own_transport("ws://owner.example.com"),
            Err(TransportValidationError::SchemeMismatch { .. })
        ));
    }
}