bsv-auth-actix-middleware 0.1.21

BSV BRC-31 authentication middleware for Actix-web
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
//! Configuration types and builder for the BSV auth middleware.
//!
//! Provides `AuthMiddlewareConfig` and its builder for constructing the
//! middleware with a required wallet and optional fields. The config is
//! generic over `W: WalletInterface` for zero-cost static dispatch.

use std::sync::Arc;

use bsv::auth::session_manager::SessionManager;
use bsv::auth::types::RequestedCertificateSet;
use bsv::wallet::interfaces::{Certificate, WalletInterface};
use futures_util::future::BoxFuture;

use crate::error::AuthMiddlewareError;

/// Callback type invoked when certificates are received from a peer.
///
/// Receives `(sender_identity_key, certificates)`. The callback is invoked
/// fire-and-forget: panics are caught and logged but do not affect request flow.
pub type OnCertificatesReceived =
    Box<dyn Fn(String, Vec<Certificate>) -> BoxFuture<'static, ()> + Send + Sync>;

impl<W: WalletInterface> std::fmt::Debug for AuthMiddlewareConfig<W> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthMiddlewareConfig")
            .field("allow_unauthenticated", &self.allow_unauthenticated)
            .field(
                "certificates_to_request",
                &self.certificates_to_request.is_some(),
            )
            .field("session_manager", &self.session_manager.is_some())
            .field(
                "on_certificates_received",
                &self.on_certificates_received.is_some(),
            )
            .finish()
    }
}

/// Configuration for the BSV authentication middleware.
///
/// Generic over `W: WalletInterface` for zero-cost static dispatch.
/// WalletInterface uses `#[async_trait]` and is object-safe, but generics
/// are preferred to avoid dynamic dispatch overhead.
pub struct AuthMiddlewareConfig<W: WalletInterface> {
    /// The wallet implementation used for authentication operations.
    #[allow(dead_code)]
    pub wallet: W,
    /// Whether to allow unauthenticated requests to pass through.
    /// Defaults to `false`.
    pub allow_unauthenticated: bool,
    /// Optional set of certificates to request from peers during authentication.
    pub certificates_to_request: Option<RequestedCertificateSet>,
    /// Optional session manager for tracking authenticated sessions.
    pub session_manager: Option<SessionManager>,
    /// Optional callback invoked when certificates are received from a peer.
    pub on_certificates_received: Option<Arc<OnCertificatesReceived>>,
}

/// Builder for `AuthMiddlewareConfig`.
///
/// The wallet field is required; all other fields are optional with sensible
/// defaults. Call `build()` to produce the final configuration, which returns
/// an error if the wallet has not been set.
pub struct AuthMiddlewareConfigBuilder<W: WalletInterface> {
    wallet: Option<W>,
    allow_unauthenticated: bool,
    certificates_to_request: Option<RequestedCertificateSet>,
    session_manager: Option<SessionManager>,
    on_certificates_received: Option<Arc<OnCertificatesReceived>>,
}

impl<W: WalletInterface> AuthMiddlewareConfigBuilder<W> {
    /// Create a new builder with default values.
    ///
    /// Defaults:
    /// - `wallet`: None (must be set before `build()`)
    /// - `allow_unauthenticated`: false
    /// - `certificates_to_request`: None
    /// - `session_manager`: None
    pub fn new() -> Self {
        Self {
            wallet: None,
            allow_unauthenticated: false,
            certificates_to_request: None,
            session_manager: None,
            on_certificates_received: None,
        }
    }

    /// Set the wallet implementation (required).
    pub fn wallet(mut self, wallet: W) -> Self {
        self.wallet = Some(wallet);
        self
    }

    /// Set whether unauthenticated requests are allowed through.
    pub fn allow_unauthenticated(mut self, value: bool) -> Self {
        self.allow_unauthenticated = value;
        self
    }

    /// Set the certificates to request from peers.
    pub fn certificates_to_request(mut self, certs: RequestedCertificateSet) -> Self {
        self.certificates_to_request = Some(certs);
        self
    }

    /// Set the session manager.
    pub fn session_manager(mut self, manager: SessionManager) -> Self {
        self.session_manager = Some(manager);
        self
    }

    /// Set the callback invoked when certificates are received from a peer.
    pub fn on_certificates_received(mut self, cb: OnCertificatesReceived) -> Self {
        self.on_certificates_received = Some(Arc::new(cb));
        self
    }

    /// Build the configuration.
    ///
    /// Returns `AuthMiddlewareError::Config` if the wallet has not been set.
    pub fn build(self) -> Result<AuthMiddlewareConfig<W>, AuthMiddlewareError> {
        let wallet = self
            .wallet
            .ok_or_else(|| AuthMiddlewareError::Config("wallet is required".to_string()))?;

        let config = AuthMiddlewareConfig {
            wallet,
            allow_unauthenticated: self.allow_unauthenticated,
            certificates_to_request: self.certificates_to_request,
            session_manager: self.session_manager,
            on_certificates_received: self.on_certificates_received,
        };

        tracing::info!(
            allow_unauthenticated = config.allow_unauthenticated,
            "auth middleware configured"
        );

        Ok(config)
    }
}

impl<W: WalletInterface> Default for AuthMiddlewareConfigBuilder<W> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use bsv::wallet::error::WalletError;
    use bsv::wallet::interfaces::*;

    /// Minimal mock wallet that satisfies `WalletInterface` trait bounds.
    /// All methods return `unimplemented!()` since we only test config building.
    struct MockWallet;

    #[async_trait]
    impl WalletInterface for MockWallet {
        async fn create_action(
            &self,
            _args: CreateActionArgs,
            _originator: Option<&str>,
        ) -> Result<CreateActionResult, WalletError> {
            unimplemented!()
        }

        async fn sign_action(
            &self,
            _args: SignActionArgs,
            _originator: Option<&str>,
        ) -> Result<SignActionResult, WalletError> {
            unimplemented!()
        }

        async fn abort_action(
            &self,
            _args: AbortActionArgs,
            _originator: Option<&str>,
        ) -> Result<AbortActionResult, WalletError> {
            unimplemented!()
        }

        async fn list_actions(
            &self,
            _args: ListActionsArgs,
            _originator: Option<&str>,
        ) -> Result<ListActionsResult, WalletError> {
            unimplemented!()
        }

        async fn internalize_action(
            &self,
            _args: InternalizeActionArgs,
            _originator: Option<&str>,
        ) -> Result<InternalizeActionResult, WalletError> {
            unimplemented!()
        }

        async fn list_outputs(
            &self,
            _args: ListOutputsArgs,
            _originator: Option<&str>,
        ) -> Result<ListOutputsResult, WalletError> {
            unimplemented!()
        }

        async fn relinquish_output(
            &self,
            _args: RelinquishOutputArgs,
            _originator: Option<&str>,
        ) -> Result<RelinquishOutputResult, WalletError> {
            unimplemented!()
        }

        async fn get_public_key(
            &self,
            _args: GetPublicKeyArgs,
            _originator: Option<&str>,
        ) -> Result<GetPublicKeyResult, WalletError> {
            unimplemented!()
        }

        async fn reveal_counterparty_key_linkage(
            &self,
            _args: RevealCounterpartyKeyLinkageArgs,
            _originator: Option<&str>,
        ) -> Result<RevealCounterpartyKeyLinkageResult, WalletError> {
            unimplemented!()
        }

        async fn reveal_specific_key_linkage(
            &self,
            _args: RevealSpecificKeyLinkageArgs,
            _originator: Option<&str>,
        ) -> Result<RevealSpecificKeyLinkageResult, WalletError> {
            unimplemented!()
        }

        async fn encrypt(
            &self,
            _args: EncryptArgs,
            _originator: Option<&str>,
        ) -> Result<EncryptResult, WalletError> {
            unimplemented!()
        }

        async fn decrypt(
            &self,
            _args: DecryptArgs,
            _originator: Option<&str>,
        ) -> Result<DecryptResult, WalletError> {
            unimplemented!()
        }

        async fn create_hmac(
            &self,
            _args: CreateHmacArgs,
            _originator: Option<&str>,
        ) -> Result<CreateHmacResult, WalletError> {
            unimplemented!()
        }

        async fn verify_hmac(
            &self,
            _args: VerifyHmacArgs,
            _originator: Option<&str>,
        ) -> Result<VerifyHmacResult, WalletError> {
            unimplemented!()
        }

        async fn create_signature(
            &self,
            _args: CreateSignatureArgs,
            _originator: Option<&str>,
        ) -> Result<CreateSignatureResult, WalletError> {
            unimplemented!()
        }

        async fn verify_signature(
            &self,
            _args: VerifySignatureArgs,
            _originator: Option<&str>,
        ) -> Result<VerifySignatureResult, WalletError> {
            unimplemented!()
        }

        async fn acquire_certificate(
            &self,
            _args: AcquireCertificateArgs,
            _originator: Option<&str>,
        ) -> Result<Certificate, WalletError> {
            unimplemented!()
        }

        async fn list_certificates(
            &self,
            _args: ListCertificatesArgs,
            _originator: Option<&str>,
        ) -> Result<ListCertificatesResult, WalletError> {
            unimplemented!()
        }

        async fn prove_certificate(
            &self,
            _args: ProveCertificateArgs,
            _originator: Option<&str>,
        ) -> Result<ProveCertificateResult, WalletError> {
            unimplemented!()
        }

        async fn relinquish_certificate(
            &self,
            _args: RelinquishCertificateArgs,
            _originator: Option<&str>,
        ) -> Result<RelinquishCertificateResult, WalletError> {
            unimplemented!()
        }

        async fn discover_by_identity_key(
            &self,
            _args: DiscoverByIdentityKeyArgs,
            _originator: Option<&str>,
        ) -> Result<DiscoverCertificatesResult, WalletError> {
            unimplemented!()
        }

        async fn discover_by_attributes(
            &self,
            _args: DiscoverByAttributesArgs,
            _originator: Option<&str>,
        ) -> Result<DiscoverCertificatesResult, WalletError> {
            unimplemented!()
        }

        async fn is_authenticated(
            &self,
            _originator: Option<&str>,
        ) -> Result<AuthenticatedResult, WalletError> {
            unimplemented!()
        }

        async fn wait_for_authentication(
            &self,
            _originator: Option<&str>,
        ) -> Result<AuthenticatedResult, WalletError> {
            unimplemented!()
        }

        async fn get_height(
            &self,
            _originator: Option<&str>,
        ) -> Result<GetHeightResult, WalletError> {
            unimplemented!()
        }

        async fn get_header_for_height(
            &self,
            _args: GetHeaderArgs,
            _originator: Option<&str>,
        ) -> Result<GetHeaderResult, WalletError> {
            unimplemented!()
        }

        async fn get_network(
            &self,
            _originator: Option<&str>,
        ) -> Result<GetNetworkResult, WalletError> {
            unimplemented!()
        }

        async fn get_version(
            &self,
            _originator: Option<&str>,
        ) -> Result<GetVersionResult, WalletError> {
            unimplemented!()
        }
    }

    #[test]
    fn test_builder_with_wallet_succeeds() {
        let config = AuthMiddlewareConfigBuilder::new()
            .wallet(MockWallet)
            .build();
        assert!(config.is_ok());
    }

    #[test]
    fn test_builder_without_wallet_returns_error() {
        let result = AuthMiddlewareConfigBuilder::<MockWallet>::new().build();
        assert!(result.is_err());
        let err = result.unwrap_err();
        match &err {
            AuthMiddlewareError::Config(msg) => {
                assert_eq!(msg, "wallet is required");
            }
            _ => panic!("expected Config error, got: {:?}", err),
        }
    }

    #[test]
    fn test_allow_unauthenticated_defaults_to_false() {
        let config = AuthMiddlewareConfigBuilder::new()
            .wallet(MockWallet)
            .build()
            .unwrap();
        assert!(!config.allow_unauthenticated);
    }

    #[test]
    fn test_allow_unauthenticated_can_be_set_to_true() {
        let config = AuthMiddlewareConfigBuilder::new()
            .wallet(MockWallet)
            .allow_unauthenticated(true)
            .build()
            .unwrap();
        assert!(config.allow_unauthenticated);
    }

    #[test]
    fn test_certificates_to_request_can_be_set() {
        let mut certs = RequestedCertificateSet::default();
        certs.types.insert("certifier1".to_string(), vec!["field1".to_string()]);

        let config = AuthMiddlewareConfigBuilder::new()
            .wallet(MockWallet)
            .certificates_to_request(certs)
            .build()
            .unwrap();
        assert!(config.certificates_to_request.is_some());
        let certs = config.certificates_to_request.unwrap();
        assert!(certs.types.contains_key("certifier1"));
    }

    #[test]
    fn test_session_manager_can_be_set() {
        let manager = SessionManager::new();
        let config = AuthMiddlewareConfigBuilder::new()
            .wallet(MockWallet)
            .session_manager(manager)
            .build()
            .unwrap();
        assert!(config.session_manager.is_some());
    }

    #[test]
    fn test_tracing_compiles() {
        // This test validates that tracing::info! compiles in this module (CONF-02).
        // If tracing is misconfigured, this test fails at compile time.
        tracing::info!("config test tracing integration check");
    }

    #[test]
    fn test_on_certificates_received_can_be_set() {
        let cb: OnCertificatesReceived = Box::new(|_identity_key, _certs| Box::pin(async {}));
        let config = AuthMiddlewareConfigBuilder::new()
            .wallet(MockWallet)
            .on_certificates_received(cb)
            .build()
            .unwrap();
        assert!(config.on_certificates_received.is_some());
    }

    #[test]
    fn test_on_certificates_received_defaults_to_none() {
        let config = AuthMiddlewareConfigBuilder::new()
            .wallet(MockWallet)
            .build()
            .unwrap();
        assert!(config.on_certificates_received.is_none());
    }

    #[test]
    fn test_default_builder() {
        // Validate that Default trait impl works
        let builder = AuthMiddlewareConfigBuilder::<MockWallet>::default();
        let result = builder.build();
        assert!(result.is_err()); // no wallet set
    }
}