mako-as4 0.13.0

BDEW MaKo AS4 profile — AS4/ebMS3 transport for German energy market communication
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
//! BDEW MaKo AS4 profile stack and `BdewAs4Profile` entry point.
//!
//! [`bdew_mako_profile_stack`] returns an [`asx_rs`] [`ProfileStack`] pre-configured
//! for BDEW AS4 strict compliance.  [`BdewAs4Profile`] combines the profile stack
//! with a [`PModeRegistry`] for a single, startup-time entry point.

pub use asx_rs::as4::As4PushPolicy;
pub use asx_rs::as4::FragmentScopePolicy;
use asx_rs::core::InteropMode;
use asx_rs::interop::{
    BaseProfile, CanonicalizationPolicy, ProfileStack, ProfileValidationReport,
    ProfileValidationResult, SecurityPolicy, ValidationPolicy,
};

use crate::{
    constants,
    pmode::{BdewAction, PMode, PModeRegistry, bdew_pmode_with_endpoint},
};

// ── Per-partner encryption certificate store ──────────────────────────────────
/// PEM-encoded X.509 certificate for encrypting outbound AS4 messages to a
/// specific trading partner.
///
/// Stored as `Arc<[u8]>` (byte slice) to allow cheap cloning across the
/// `BdewAs4Sender` and the `BdewAs4Profile`.
type EncryptionCertPem = std::sync::Arc<[u8]>;

/// Short identifier for the BDEW MaKo AS4 profile.
pub const PROFILE_NAME: &str = "bdew_mako_as4";

/// Profile version string (mirrors the AS4 Kommunikationshandbuch edition).
pub const PROFILE_VERSION: &str = "2.0.0";

/// Build an [`As4PushPolicy`] preset for BDEW AS4-Profil v1.2 inbound receive.
///
/// Equivalent to [`As4PushPolicy::regulated()`] with the operator's own
/// decryption private key wired in, enabling decryption of inbound encrypted
/// AS4 messages.
///
/// # BDEW AS4-Profil v1.2 §2.2.6.2.2
///
/// BDEW requires every inbound message to be encrypted with the operator's
/// EC (BrainpoolP256r1) public key. Supply the corresponding private key here
/// to decrypt them. The key must be in PEM format (PKCS#8 or SEC1 encoding).
///
/// # Parameters
///
/// - `decryption_key_pem` — `None` for sign-only mode (testing / before certs arrive).
///   `Some(pem_bytes)` for production with inbound decryption enabled.
///
/// # Example
///
/// ```rust
/// use mako_as4::profile::bdew_push_policy;
///
/// // Sign-only (development / no BDEW PKI certs yet)
/// let policy = bdew_push_policy(None);
///
/// // Production with inbound decryption
/// let key_pem: Vec<u8> = std::fs::read("/etc/certs/as4-decrypt.key.pem").unwrap_or_default();
/// let policy = bdew_push_policy(Some(key_pem));
/// ```
pub fn bdew_push_policy(decryption_key_pem: Option<Vec<u8>>) -> As4PushPolicy {
    let mut policy = As4PushPolicy::regulated();
    if let Some(key) = decryption_key_pem {
        policy.inbound_decryption_key_pem = Some(std::sync::Arc::from(key.as_slice()));
        // Enforce that every inbound message is encrypted (BDEW AS4-Profil v1.2 §2.2.6.2.2).
        // Only set when a decryption key is provided; otherwise the policy builder
        // would reject the config (require_encrypted_inbound = true without a key).
        policy.require_encrypted_inbound = true;
    }
    // BDEW AS4-Profil v1.2 uses single-message `UserMessage` only — no fragmentation.
    // `RequireAuthenticatedScope` (the strict default) would reject any multi-fragment
    // message unless `authenticated_sender_scope` is supplied.  Since fragmentation is
    // not used in BDEW MaKo, switch to `UseSoapSenderId` so that
    // `authenticated_sender_scope: None` is always safe to pass.  The SOAP sender ID
    // is already authenticated by the mandatory WS-Security XML-DSig signature.
    policy.fragment_scope_policy = FragmentScopePolicy::UseSoapSenderId;
    policy
}

/// Creates a [`ProfileStack`] pre-configured for BDEW MaKo AS4 compliance.
///
/// The base profile enforces:
///
/// | Policy | Value | Source |
/// |---|---|---|
/// | Interop mode | `Strict` | BDEW requires full AS4 conformance |
/// | Canonicalization | Exclusive C14N, no comments | BDEW KH §5.5 |
/// | Signing required | `true` | BDEW KH §5.5 (mandatory) |
/// | Encryption required | `false` | BDEW KH §5.6 (optional) |
/// | Payload limits enforced | `true` | defense-in-depth |
/// | AS2 MIC required | `false` | not an AS4 concept |
///
/// Add partner-specific overrides via `ProfileStack::partner_overrides` if needed.
///
/// # Panics
///
/// Never panics — the returned profile always satisfies its own invariants.
///
/// # Example
///
/// ```rust
/// use mako_as4::profile::bdew_mako_profile_stack;
///
/// let stack = bdew_mako_profile_stack();
/// stack.validate().expect("BDEW MaKo base profile must pass all invariants");
/// ```
pub fn bdew_mako_profile_stack() -> ProfileStack {
    ProfileStack {
        base: BaseProfile {
            name: PROFILE_NAME.to_string(),
            version: PROFILE_VERSION.to_string(),
            mode: InteropMode::Strict,
            // Exclusive C14N without comments — BDEW AS4 Kommunikationshandbuch §5.5
            canonicalization: CanonicalizationPolicy::default(),
            security: SecurityPolicy {
                require_signature: true,
                // Mandatory per BDEW AS4-Profil v1.2 §2.2.6.2.2.
                // asx-rs v0.6 implements ECDH-ES + ConcatKDF + AES-128-KW with
                // BrainpoolP256r1 (BSI TR-03116-3 §9.2) automatically when the
                // recipient certificate has an EC public key.
                require_encryption: true,
            },
            validation: ValidationPolicy {
                reject_ambiguous_headers: true,
                enforce_payload_limits: true,
                // AS4 does not use AS2 MIC (AS2-specific concept)
                require_as2_mic: false,
            },
        },
        extensions: Vec::new(),
        overrides: Vec::new(),
        partner_overrides: Vec::new(),
    }
}

/// BDEW MaKo AS4 profile — combines a [`ProfileStack`] with a [`PModeRegistry`].
///
/// `BdewAs4Profile` is the main startup entry point.  Build it once, register
/// all bilateral P-Modes, call [`validate`](Self::validate) to fail-fast on
/// misconfiguration, then share the profile (e.g., via `Arc`) across send/receive paths.
///
/// # Example
///
/// ```rust
/// use mako_as4::profile::BdewAs4Profile;
/// use mako_as4::pmode::{bdew_pmode, BdewAction};
///
/// let mut profile = BdewAs4Profile::new();
/// profile
///     .register_pmode(bdew_pmode("pm-utilmd-a", "9900000000001", BdewAction::Utilmd))
///     .register_pmode(bdew_pmode("pm-aperak-a", "9900000000001", BdewAction::Aperak));
///
/// profile.validate().expect("profile must satisfy all security invariants");
/// assert_eq!(profile.registry().len(), 2);
/// ```
#[derive(Debug)]
pub struct BdewAs4Profile {
    stack: ProfileStack,
    registry: PModeRegistry,
    /// Per-partner encryption certificates: `partner_mp_id → PEM cert bytes`.
    ///
    /// Used by the outbound send path to populate `As4SendCredentials::recipient_cert_pem`.
    /// BDEW AS4-Profil v1.2 §2.2.6.2.2 requires each message to be encrypted with the
    /// **recipient's** encryption certificate.
    encryption_certs: std::collections::HashMap<String, EncryptionCertPem>,
}

impl Default for BdewAs4Profile {
    fn default() -> Self {
        Self::new()
    }
}

impl BdewAs4Profile {
    /// Creates a new profile with the BDEW MaKo base stack and an empty P-Mode registry.
    pub fn new() -> Self {
        Self {
            stack: bdew_mako_profile_stack(),
            registry: PModeRegistry::new(),
            encryption_certs: std::collections::HashMap::new(),
        }
    }

    /// Returns the BDEW MaKo [`ProfileStack`].
    pub fn profile_stack(&self) -> &ProfileStack {
        &self.stack
    }

    /// Returns the P-Mode registry.
    pub fn registry(&self) -> &PModeRegistry {
        &self.registry
    }

    /// Register a [`PMode`] for a bilateral trading-partner channel.
    ///
    /// Returns `&mut self` for chaining.
    pub fn register_pmode(&mut self, pmode: PMode) -> &mut Self {
        self.registry.register(pmode);
        self
    }

    /// Register P-Modes for all standard BDEW EDIFACT message types with one call.
    ///
    /// For each [`BdewAction::all_standard()`] variant, creates a P-Mode with:
    /// - `endpoint_url = Some(endpoint_url)` (HTTPS validated at send time)
    /// - `security.sign = true`, `security.encrypt = false` (BDEW defaults)
    /// - `mep = OneWayPush`
    ///
    /// This is the recommended way to register a trading partner at startup
    /// when you know their single AS4 inbox URL and use BDEW default security
    /// settings (signing required, encryption optional).
    ///
    /// For per-action encryption overrides, register individual P-Modes via
    /// [`bdew_pmode_with_endpoint`] and [`register_pmode`](Self::register_pmode) instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// use mako_as4::profile::BdewAs4Profile;
    /// use mako_as4::pmode::BdewAction;
    ///
    /// let mut profile = BdewAs4Profile::new();
    /// profile.register_partner_all_actions(
    ///     "9900000000001",
    ///     "https://partner.example/as4/inbox",
    /// );
    /// // One P-Mode per standard BDEW action variant
    /// assert_eq!(profile.registry().len(), BdewAction::all_standard().len());
    /// ```
    pub fn register_partner_all_actions(
        &mut self,
        partner_mp_id: impl Into<String>,
        endpoint_url: impl Into<String>,
    ) -> &mut Self {
        let mp_id: String = partner_mp_id.into();
        let url: String = endpoint_url.into();
        for action in BdewAction::all_standard() {
            let action_short = action
                .as_uri()
                .strip_prefix(constants::SERVICE)
                .and_then(|s| s.strip_prefix(':'))
                .unwrap_or("unknown")
                .to_ascii_lowercase();
            let id = format!("pm-{mp_id}-{action_short}");
            self.registry
                .register(bdew_pmode_with_endpoint(id, &mp_id, action, &url));
        }
        self
    }

    /// Register the encryption certificate for a trading partner.
    ///
    /// `cert_pem` is the partner's X.509 certificate (PEM-encoded) used to encrypt
    /// outbound AS4 messages. Per BDEW AS4-Profil v1.2 §2.2.6.2.2 the recipient's
    /// encryption certificate is required for every outbound message when
    /// `security.encrypt = true`.
    ///
    /// The certificate is stored keyed by `partner_mp_id` (13-digit GLN).
    /// It is returned by [`get_partner_encryption_cert`](Self::get_partner_encryption_cert)
    /// for injection into `As4SendCredentials::recipient_cert_pem` at send time.
    ///
    /// # Note
    ///
    /// BDEW uses **separate** signing and encryption keypairs. The encryption certificate
    /// corresponds to the partner's EC keypair (BrainpoolP256r1). Do not use the signing
    /// certificate here.
    pub fn register_partner_encryption_cert(
        &mut self,
        partner_mp_id: impl Into<String>,
        cert_pem: impl Into<Vec<u8>>,
    ) -> &mut Self {
        self.encryption_certs
            .insert(partner_mp_id.into(), cert_pem.into().into());
        self
    }

    /// Return the encryption certificate PEM for a trading partner, if registered.
    ///
    /// Used by the outbound send path to populate `As4SendCredentials::recipient_cert_pem`.
    /// Returns `None` when no encryption certificate has been registered for this partner.
    pub fn get_partner_encryption_cert(&self, partner_mp_id: &str) -> Option<&[u8]> {
        self.encryption_certs
            .get(partner_mp_id)
            .map(|arc| arc.as_ref())
    }

    /// Returns `true` if at least one partner has an encryption certificate registered.
    pub fn has_any_encryption_certs(&self) -> bool {
        !self.encryption_certs.is_empty()
    }

    /// Resolve the first P-Mode for `partner_mp_id` matching this BDEW [`BdewAction`].
    ///
    /// Uses [`PModeRegistry::resolve_by_action`] against the BDEW action URI.
    /// Unlike [`resolve_pmode`](Self::resolve_pmode), the BDEW service URI
    /// ([`constants::SERVICE`]) does not need to match — only the partner GLN
    /// and action URI are compared.  In BDEW deployments this is the correct
    /// strategy since there is only one service URI.
    ///
    /// Returns `None` when no P-Mode is registered for `(partner_mp_id, action)`.
    pub fn resolve_pmode_by_action(
        &self,
        partner_mp_id: &str,
        action: &BdewAction,
    ) -> Option<&PMode> {
        self.registry
            .resolve_by_action(partner_mp_id, &action.as_uri())
    }

    /// All registered P-Modes.
    ///
    /// Useful for startup-validation logging (e.g. warn when a P-Mode has
    /// `endpoint_url = None`) and auditing the registry state.
    pub fn all_pmodes(&self) -> &[PMode] {
        self.registry.all()
    }

    /// Resolve the HTTPS endpoint URL for the first P-Mode matching `partner_mp_id`,
    /// `service`, and `action`.
    ///
    /// Returns `Some(&str)` when a matching P-Mode is registered **and** its
    /// [`PMode::endpoint_url`] field is populated.  Returns `None` when no P-Mode
    /// matches or when the matched P-Mode has `endpoint_url = None`.
    ///
    /// Use this as an alternative to a separate `PartnerDirectory` when endpoint
    /// URLs are baked into P-Mode registrations via [`bdew_pmode_with_endpoint`].
    ///
    /// [`bdew_pmode_with_endpoint`]: crate::pmode::bdew_pmode_with_endpoint
    pub fn resolve_endpoint(
        &self,
        partner_mp_id: &str,
        service: &str,
        action: &str,
    ) -> Option<&str> {
        self.registry
            .resolve(partner_mp_id, service, action)
            .and_then(|pm| pm.endpoint_url.as_deref())
    }

    /// Resolve a P-Mode by partner GLN, service URI, and action URI.
    ///
    /// Returns `None` when no matching P-Mode is registered.
    pub fn resolve_pmode(
        &self,
        partner_mp_id: &str,
        service: &str,
        action: &str,
    ) -> Option<&PMode> {
        self.registry.resolve(partner_mp_id, service, action)
    }

    /// Validate the profile stack.
    ///
    /// Returns an error if any critical security invariant is violated (e.g.,
    /// both `require_signature` and `require_encryption` are `false`).
    ///
    /// Call this at startup before serving traffic to catch misconfiguration early.
    pub fn validate(&self) -> ProfileValidationResult<ProfileValidationReport> {
        self.stack.validate()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constants;
    use crate::pmode::{BdewAction, bdew_pmode};

    #[test]
    fn profile_stack_validates_without_errors() {
        let stack = bdew_mako_profile_stack();
        let report = stack
            .validate()
            .expect("BDEW base profile must pass validation");
        assert!(
            report.lints.is_empty(),
            "no redundant-override lints expected"
        );
    }

    #[test]
    fn profile_stack_name_and_version() {
        let stack = bdew_mako_profile_stack();
        assert_eq!(stack.base.name, PROFILE_NAME);
        assert_eq!(stack.base.version, PROFILE_VERSION);
    }

    #[test]
    fn profile_stack_security_policy() {
        let stack = bdew_mako_profile_stack();
        assert!(
            stack.base.security.require_signature,
            "signing must be required"
        );
        assert!(
            stack.base.security.require_encryption,
            "encryption must be required — BDEW AS4-Profil v1.2 §2.2.6.2.2"
        );
    }

    #[test]
    fn profile_stack_mode_is_strict() {
        let stack = bdew_mako_profile_stack();
        assert_eq!(stack.base.mode, InteropMode::Strict);
    }

    #[test]
    fn profile_stack_no_as2_mic() {
        let stack = bdew_mako_profile_stack();
        assert!(
            !stack.base.validation.require_as2_mic,
            "AS2 MIC must not be required in an AS4 profile"
        );
    }

    #[test]
    fn bdew_as4_profile_register_and_resolve() {
        let mut profile = BdewAs4Profile::new();
        profile
            .register_pmode(bdew_pmode("pm-u", "9900000000001", BdewAction::Utilmd))
            .register_pmode(bdew_pmode("pm-a", "9900000000001", BdewAction::Aperak));

        assert_eq!(profile.registry().len(), 2);

        let pm = profile.resolve_pmode(
            "9900000000001",
            constants::SERVICE,
            &BdewAction::Utilmd.as_uri(),
        );
        assert!(pm.is_some());
        assert_eq!(pm.unwrap().id, "pm-u");

        assert!(
            profile
                .resolve_pmode(
                    "9999999999999",
                    constants::SERVICE,
                    &BdewAction::Utilmd.as_uri()
                )
                .is_none()
        );
    }

    #[test]
    fn bdew_as4_profile_validates() {
        let mut profile = BdewAs4Profile::new();
        profile.register_pmode(bdew_pmode("pm-u", "9900000000001", BdewAction::Utilmd));
        profile
            .validate()
            .expect("profile with registered P-Mode must validate");
    }

    #[test]
    fn bdew_as4_profile_default_equals_new() {
        let a = BdewAs4Profile::new();
        let b = BdewAs4Profile::default();
        assert_eq!(a.registry().len(), b.registry().len());
        assert_eq!(a.profile_stack().base.name, b.profile_stack().base.name);
    }

    #[test]
    fn resolve_endpoint_returns_url_when_baked_in() {
        use crate::pmode::bdew_pmode_with_endpoint;
        let mut profile = BdewAs4Profile::new();
        profile.register_pmode(bdew_pmode_with_endpoint(
            "pm-u",
            "9900000000001",
            BdewAction::Utilmd,
            "https://partner.example/as4",
        ));
        let url = profile.resolve_endpoint(
            "9900000000001",
            constants::SERVICE,
            &BdewAction::Utilmd.as_uri(),
        );
        assert_eq!(url, Some("https://partner.example/as4"));
    }

    #[test]
    fn resolve_endpoint_returns_none_when_not_set() {
        let mut profile = BdewAs4Profile::new();
        profile.register_pmode(bdew_pmode("pm-u", "9900000000001", BdewAction::Utilmd));
        assert!(
            profile
                .resolve_endpoint(
                    "9900000000001",
                    constants::SERVICE,
                    &BdewAction::Utilmd.as_uri()
                )
                .is_none()
        );
    }

    #[test]
    fn register_partner_all_actions_creates_one_pmode_per_standard_action() {
        use crate::pmode::BdewAction;
        let mut profile = BdewAs4Profile::new();
        profile.register_partner_all_actions("9900000000001", "https://partner.example/as4/inbox");
        assert_eq!(profile.registry().len(), BdewAction::all_standard().len());
        // Every P-Mode must carry the endpoint
        for pm in profile.all_pmodes() {
            assert_eq!(
                pm.endpoint_url.as_deref(),
                Some("https://partner.example/as4/inbox"),
            );
        }
    }

    #[test]
    fn register_partner_all_actions_chaining() {
        let mut profile = BdewAs4Profile::new();
        profile
            .register_partner_all_actions("9900000000001", "https://a.example/as4")
            .register_partner_all_actions("9900000000002", "https://b.example/as4");
        use crate::pmode::BdewAction;
        assert_eq!(
            profile.registry().len(),
            2 * BdewAction::all_standard().len()
        );
    }

    #[test]
    fn resolve_pmode_by_action_finds_registered_pmode() {
        use crate::pmode::BdewAction;
        let mut profile = BdewAs4Profile::new();
        profile.register_partner_all_actions("9900000000001", "https://partner.example/as4/inbox");
        let pm = profile.resolve_pmode_by_action("9900000000001", &BdewAction::Utilmd);
        assert!(pm.is_some());
        assert_eq!(pm.unwrap().partner_id, "9900000000001");
        assert_eq!(pm.unwrap().action, BdewAction::Utilmd.as_uri());
    }

    #[test]
    fn resolve_pmode_by_action_returns_none_for_unknown_partner() {
        use crate::pmode::BdewAction;
        let mut profile = BdewAs4Profile::new();
        profile.register_partner_all_actions("9900000000001", "https://partner.example/as4");
        assert!(
            profile
                .resolve_pmode_by_action("9999999999999", &BdewAction::Utilmd)
                .is_none()
        );
    }

    #[test]
    fn all_pmodes_reflects_registered_pmode_count() {
        use crate::pmode::BdewAction;
        let mut profile = BdewAs4Profile::new();
        assert!(profile.all_pmodes().is_empty());
        profile.register_partner_all_actions("9900000000001", "https://a.example/as4");
        assert_eq!(profile.all_pmodes().len(), BdewAction::all_standard().len());
    }
}