qubip_aurora 0.11.0

A framework to build OpenSSL Providers tailored for the transition to post-quantum cryptography
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
use super::keymgmt_functions::KeyPair;

use super::*;
use bindings::ffi_c_types::*;
use bindings::{
    OSSL_CALLBACK, OSSL_CORE_BIO, OSSL_DECODER_PARAM_PROPERTIES,
    OSSL_KEYMGMT_SELECT_ALL_PARAMETERS, OSSL_KEYMGMT_SELECT_KEYPAIR,
    OSSL_KEYMGMT_SELECT_PRIVATE_KEY, OSSL_KEYMGMT_SELECT_PUBLIC_KEY, OSSL_OBJECT_PARAM_DATA_TYPE,
    OSSL_OBJECT_PARAM_REFERENCE, OSSL_OBJECT_PARAM_TYPE, OSSL_PARAM, OSSL_PASSPHRASE_CALLBACK,
};
use forge::operations::{keymgmt, transcoders};
use forge::ossl_callback::OSSLCallback;
use forge::osslparams::*;
use keymgmt::selection::Selection;
use pem;

use super::OurError as EncoderError;
type OurResult<T> = anyhow::Result<T, EncoderError>;

struct EncoderContext<'a> {
    provctx: &'a ProviderInstance<'a>,
}

impl<'a> EncoderContext<'a> {
    pub(super) fn new(provctx: &'a ProviderInstance<'a>) -> Self {
        Self { provctx }
    }
}

impl<'a> TryFrom<*mut c_void> for &mut EncoderContext<'a> {
    type Error = OurError;

    #[named]
    fn try_from(vptr: *mut c_void) -> Result<Self, Self::Error> {
        trace!(target: log_target!(), "Called for {}",
        "impl TryFrom<*mut c_void> for &mut EncoderContext"
        );
        let ptr = vptr as *mut EncoderContext;
        if ptr.is_null() {
            return Err(anyhow::anyhow!("vptr was null"));
        }
        Ok(unsafe { &mut *ptr })
    }
}

impl<'a> TryFrom<*mut c_void> for &EncoderContext<'a> {
    type Error = OurError;

    #[named]
    fn try_from(vptr: *mut c_void) -> Result<Self, Self::Error> {
        trace!(target: log_target!(), "Called for {}",
        "impl TryFrom<*mut c_void> for &mut EncoderContext"
        );
        let ptr = vptr as *mut EncoderContext;
        if ptr.is_null() {
            return Err(anyhow::anyhow!("vptr was null"));
        }
        Ok(unsafe { &mut *ptr })
    }
}

#[named]
pub(super) unsafe extern "C" fn newctx(vprovctx: *mut c_void) -> *mut c_void {
    const ERROR_RET: *mut c_void = std::ptr::null_mut();
    trace!(target: log_target!(), "{}", "Called!");
    let provctx: &ProviderInstance<'_> = handleResult!(vprovctx.try_into());

    let encoder_ctx = Box::new(EncoderContext::new(provctx));

    Box::into_raw(encoder_ctx).cast()
}

#[named]
pub(super) unsafe extern "C" fn get_params(params: *mut OSSL_PARAM) -> c_int {
    trace!(target: log_target!(), "{}", "Called!");

    let _ = params;
    warn!(target: log_target!(), "Ignoring params");

    todo!();
}

#[named]
pub(super) unsafe extern "C" fn gettable_params(vprovctx: *mut c_void) -> *const OSSL_PARAM {
    const ERROR_RET: *const OSSL_PARAM = std::ptr::null();
    trace!(target: log_target!(), "{}", "Called!");
    let _provctx: &ProviderInstance<'_> = handleResult!(vprovctx.try_into());

    std::ptr::from_ref(&CONST_OSSL_PARAM::END)
}

#[named]
pub(super) unsafe extern "C" fn freectx(vencoderctx: *mut c_void) {
    trace!(target: log_target!(), "{}", "Called!");

    if !vencoderctx.is_null() {
        let encoder_ctx: Box<EncoderContext> = unsafe { Box::from_raw(vencoderctx.cast()) };
        drop(encoder_ctx);
    }
}

fn private_key_bytes_to_DER(keypair_bytes: Vec<u8>) -> Result<Vec<u8>, asn1::WriteError> {
    asn1::write(|w| {
        w.write_element(&asn1::SequenceWriter::new(&|w| {
            // version (when reading this we discard it)
            w.write_element(&asn1::BigInt::new(&[0]))?;
            // algorithm identifier
            // (here we can't just use super::ALGORITHM_ID_DER, because it's already just a byte
            // array and therefore the asn1 module would encode it as an OCTET STRING)
            w.write_element(&asn1::SequenceWriter::new(&|w| {
                w.write_element(&super::OID)?;
                Ok(())
            }))?;
            // key data
            w.write_element(&asn1::OctetStringEncoded::new(keypair_bytes.as_slice()))?;
            Ok(())
        }))
    })
}

pub(crate) struct PrivateKeyInfo2DER();

use openssl_provider_forge::bindings::OSSL_FUNC_BIO_WRITE_EX;
use pkcs8::der::Encode;
use pkcs8::spki::{AlgorithmIdentifier, AlgorithmIdentifierWithOid};
use transcoders::DoesSelection;
use transcoders::Encoder;

impl Encoder for PrivateKeyInfo2DER {
    const PROPERTY_DEFINITION: &'static CStr = concat_cstr!(
        super::PROPERTY_DEFINITION,
        c",output=der,structure=PrivateKeyInfo"
    );

    const DISPATCH_TABLE: &'static [OSSL_DISPATCH] = {
        mod dispatch_table_module {
            use super::*;
            use bindings::{OSSL_FUNC_encoder_does_selection_fn, OSSL_FUNC_ENCODER_DOES_SELECTION};
            use bindings::{OSSL_FUNC_encoder_encode_fn, OSSL_FUNC_ENCODER_ENCODE};
            use bindings::{OSSL_FUNC_encoder_freectx_fn, OSSL_FUNC_ENCODER_FREECTX};
            use bindings::{OSSL_FUNC_encoder_newctx_fn, OSSL_FUNC_ENCODER_NEWCTX};

            // TODO reenable typechecking in dispatch_table_entry macro and make sure these still compile!
            // https://docs.openssl.org/3.2/man7/provider-decoder/
            pub(super) const DER_ENCODER_FUNCTIONS: &[OSSL_DISPATCH] = &[
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_NEWCTX,
                    OSSL_FUNC_encoder_newctx_fn,
                    encoder_functions::newctx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_FREECTX,
                    OSSL_FUNC_encoder_freectx_fn,
                    encoder_functions::freectx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_DOES_SELECTION,
                    OSSL_FUNC_encoder_does_selection_fn,
                    encoder_functions::does_selection_PrivateKeyInfo
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_ENCODE,
                    OSSL_FUNC_encoder_encode_fn,
                    encoder_functions::encodePrivateKeyInfo2DER
                ),
                OSSL_DISPATCH::END,
            ];
        }

        dispatch_table_module::DER_ENCODER_FUNCTIONS
    };
}

impl KeyPair<'_> {
    #[named]
    fn to_PrivateKeyInfoDER(&self, _encoderctx: &EncoderContext) -> OurResult<Vec<u8>> {
        trace!(target: log_target!(), "{}", "Called!");

        debug!(target: log_target!(), "Got keypair: {self:?}");
        if self.private.is_none() {
            error!(target: log_target!(), "Keypair does not contain a private key");
            return Err(anyhow!("Keypair does not contain a private key"));
        }
        if self.public.is_none() {
            error!(target: log_target!(), "Keypair does not contain a public key");
            return Err(anyhow!("Keypair does not contain a public key"));
        }

        // unwrap() is safe here because we've already ensured self.private is not None
        let der_sk_bytes = match self.private.as_ref().unwrap().to_DER() {
            Ok(v) => v,
            Err(e) => {
                error!(target: log_target!(), "privkey.to_DER() failed: {e:?}");
                return Err(OurError::from(e));
            }
        };

        let aid = AlgorithmIdentifier {
            oid: super::OID_PKCS8,
            parameters: None,
        };
        let pki = pkcs8::PrivateKeyInfo::new(aid, &der_sk_bytes);
        assert_eq!(pki.version(), pkcs8::Version::V1);

        pki.to_der().map_err(|e| {
            error!(target: log_target!(), "privkey.to_DER() failed: {e:?}");
            anyhow!("Error: {e:?}")
        })
    }

    #[named]
    fn to_SPKIDER(&self, _encoderctx: &EncoderContext) -> OurResult<Vec<u8>> {
        trace!(target: log_target!(), "{}", "Called!");

        debug!(target: log_target!(), "Got keypair: {self:?}");
        if self.public.is_none() {
            error!(target: log_target!(), "Keypair does not contain a public key");
            return Err(anyhow!("Keypair does not contain a public key"));
        }

        // unwrap() is safe here because we've already ensured self.public is not None
        let der_pk_bytes = match self.public.as_ref().unwrap().to_DER() {
            Ok(v) => v,
            Err(e) => {
                error!(target: log_target!(), "pubkey.to_DER() failed: {e:?}");
                return Err(OurError::from(e));
            }
        };
        let bitstring =
            pkcs8::der::asn1::BitString::from_bytes(der_pk_bytes.as_slice()).map_err(|e| {
                error!(target: log_target!(), "Failed to encode bitstring: {e:?}");
                anyhow!("Error: {e:?}")
            })?;

        let aid = AlgorithmIdentifier {
            oid: super::OID_PKCS8,
            parameters: None,
        };
        let spki = pkcs8::spki::SubjectPublicKeyInfoOwned {
            algorithm: aid,
            subject_public_key: bitstring,
        };

        spki.to_der().map_err(|e| {
            error!(target: log_target!(), "spki.to_der() failed: {e:?}");
            anyhow!("Error: {e:?}")
        })
    }
}

/// Encodes a PrivateKeyInfo to DER
///
/// # Arguments
///
/// ## TODO(🛠️): document arguments
///
/// # Notes
///
/// [`OSSL_FUNC_encoder_encode_fn`][provider-encoder(7ossl)]
/// functions such as this one are tightly integrated
/// with the [`super::keymgmt_functions::load`]
/// implementation exposed
/// for [their algorithm][`super`].
///
/// Eventually the `data_cb` argument calls the
/// `OSSL_FUNC_keymgmt_load_fn`
/// exposed by the [keymgmt][`super::keymgmt_functions`]
/// for [this algorithm][`super`].
/// Hence they must agree on how the reference is being passed around.
///
/// Refer to [provider-decoder(7ossl)],
/// [provider-keymgmt(7ossl)],
/// and [provider-object(7ossl)].
///
/// [provider-keymgmt(7ossl)]: https://docs.openssl.org/master/man7/provider-keymgmt/
/// [provider-object(7ossl)]: https://docs.openssl.org/master/man7/provider-object/
/// [provider-encoder(7ossl)]: https://docs.openssl.org/master/man7/provider-encoder/
///
/// # Examples
///
/// ## TODO(🛠️): add examples
///
#[named]
pub(super) unsafe extern "C" fn encodePrivateKeyInfo2DER(
    vencoderctx: *mut c_void,
    out: *mut OSSL_CORE_BIO,
    obj_raw: *const c_void,
    _obj_abstract: *const OSSL_PARAM,
    selection: c_int,
    _cb: OSSL_PASSPHRASE_CALLBACK,
    _cbarg: *mut c_void,
) -> c_int {
    const SUCCESS: c_int = 1;
    const ERROR_RET: c_int = 0;
    trace!(target: log_target!(), "{}", "Called!");

    debug!(target: log_target!(), "Got selection: {selection:#b}");
    if (selection & (OSSL_KEYMGMT_SELECT_PRIVATE_KEY as c_int)) == 0 {
        error!(target: log_target!(), "Invalid selection: {selection:#?}");
        return ERROR_RET;
    }

    let encoderctx: &EncoderContext = handleResult!(vencoderctx.try_into());

    if obj_raw.is_null() {
        error!(target: log_target!(), "No provider-native object passed to encoder");
        return ERROR_RET;
    }

    let keypair: &KeyPair = handleResult!(obj_raw.try_into());
    let pki_bytes_der = handleResult!(keypair.to_PrivateKeyInfoDER(encoderctx).map_err(|e| {
        error!(target: log_target!(), "Failed to generate PrivateKeyInfo: {e:?}");
        OurError::from(e)
    }));

    match encoderctx.provctx.BIO_write_ex(out, &pki_bytes_der) {
        Ok(_bytes_written) => {}
        Err(e) => {
            error!(target: log_target!(), "Failure using BIO_write_ex() upcall pointer: {e:?}");
            return ERROR_RET;
        }
    };

    SUCCESS
}

impl DoesSelection for PrivateKeyInfo2DER {
    const SELECTION_MASK: Selection = Selection::KEYPAIR;
}

transcoders::make_does_selection_fn!(
    does_selection_PrivateKeyInfo,
    PrivateKeyInfo2DER,
    ProviderInstance
);

pub(crate) struct PrivateKeyInfo2PEM();

impl Encoder for PrivateKeyInfo2PEM {
    const PROPERTY_DEFINITION: &'static CStr = concat_cstr!(
        super::PROPERTY_DEFINITION,
        c",output=pem,structure=PrivateKeyInfo"
    );

    const DISPATCH_TABLE: &'static [OSSL_DISPATCH] = {
        mod dispatch_table_module {
            use super::*;
            use bindings::{OSSL_FUNC_encoder_does_selection_fn, OSSL_FUNC_ENCODER_DOES_SELECTION};
            use bindings::{OSSL_FUNC_encoder_encode_fn, OSSL_FUNC_ENCODER_ENCODE};
            use bindings::{OSSL_FUNC_encoder_freectx_fn, OSSL_FUNC_ENCODER_FREECTX};
            use bindings::{OSSL_FUNC_encoder_newctx_fn, OSSL_FUNC_ENCODER_NEWCTX};

            // TODO reenable typechecking in dispatch_table_entry macro and make sure these still compile!
            // https://docs.openssl.org/3.2/man7/provider-decoder/
            pub(super) const PEM_ENCODER_FUNCTIONS: &[OSSL_DISPATCH] = &[
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_NEWCTX,
                    OSSL_FUNC_encoder_newctx_fn,
                    encoder_functions::newctx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_FREECTX,
                    OSSL_FUNC_encoder_freectx_fn,
                    encoder_functions::freectx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_DOES_SELECTION,
                    OSSL_FUNC_encoder_does_selection_fn,
                    encoder_functions::does_selection_PrivateKeyInfo
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_ENCODE,
                    OSSL_FUNC_encoder_encode_fn,
                    encoder_functions::encodePrivateKeyInfo2PEM
                ),
                OSSL_DISPATCH::END,
            ];
        }

        dispatch_table_module::PEM_ENCODER_FUNCTIONS
    };
}

/// Encodes a PrivateKeyInfo to PEM
///
/// # Arguments
///
/// ## TODO(🛠️): document arguments
///
/// # Notes
///
/// [`OSSL_FUNC_encoder_encode_fn`][provider-encoder(7ossl)]
/// functions such as this one are tightly integrated
/// with the [`super::keymgmt_functions::load`]
/// implementation exposed
/// for [their algorithm][`super`].
///
/// Eventually the `data_cb` argument calls the
/// `OSSL_FUNC_keymgmt_load_fn`
/// exposed by the [keymgmt][`super::keymgmt_functions`]
/// for [this algorithm][`super`].
/// Hence they must agree on how the reference is being passed around.
///
/// Refer to [provider-decoder(7ossl)],
/// [provider-keymgmt(7ossl)],
/// and [provider-object(7ossl)].
///
/// [provider-keymgmt(7ossl)]: https://docs.openssl.org/master/man7/provider-keymgmt/
/// [provider-object(7ossl)]: https://docs.openssl.org/master/man7/provider-object/
/// [provider-encoder(7ossl)]: https://docs.openssl.org/master/man7/provider-encoder/
///
/// # Examples
///
/// ## TODO(🛠️): add examples
///
#[named]
pub(super) unsafe extern "C" fn encodePrivateKeyInfo2PEM(
    vencoderctx: *mut c_void,
    out: *mut OSSL_CORE_BIO,
    obj_raw: *const c_void,
    _obj_abstract: *const OSSL_PARAM,
    selection: c_int,
    _cb: OSSL_PASSPHRASE_CALLBACK,
    _cbarg: *mut c_void,
) -> c_int {
    const SUCCESS: c_int = 1;
    const ERROR_RET: c_int = 0;
    trace!(target: log_target!(), "{}", "Called!");

    debug!(target: log_target!(), "Got selection: {selection:#b}");
    if (selection & (OSSL_KEYMGMT_SELECT_PRIVATE_KEY as c_int)) == 0 {
        error!(target: log_target!(), "Invalid selection: {selection:#?}");
        return ERROR_RET;
    }

    let encoderctx: &EncoderContext = handleResult!(vencoderctx.try_into());

    if obj_raw.is_null() {
        error!(target: log_target!(), "No provider-native object passed to encoder");
        return ERROR_RET;
    }

    let keypair: &KeyPair = handleResult!(obj_raw.try_into());
    let pki_bytes_der = handleResult!(keypair.to_PrivateKeyInfoDER(encoderctx).map_err(|e| {
        error!(target: log_target!(), "Failed to generate PrivateKeyInfo: {e:?}");
        OurError::from(e)
    }));
    let pki_bytes_der = pki_bytes_der.as_slice();

    let pem = pem::Pem::new("PRIVATE KEY", pki_bytes_der);
    let pem_bytes = pem::encode(&pem).into_bytes();

    match encoderctx.provctx.BIO_write_ex(out, &pem_bytes) {
        Ok(_bytes_written) => {}
        Err(e) => {
            error!(target: log_target!(), "Failure using BIO_write_ex() upcall pointer: {e:?}");
            return ERROR_RET;
        }
    };

    SUCCESS
}

impl DoesSelection for PrivateKeyInfo2PEM {
    const SELECTION_MASK: Selection = Selection::KEYPAIR;
}

// We can use the same does_selection function as PrivateKeyInfo2DER, so there's no need to call
// the make_does_selection_fn macro again.

// generate the plain text encoder
use crate::adapters::common::transcoders::make_privkey_text_encoder;
make_privkey_text_encoder!(
    PrivateKeyInfo2Text,
    concat_cstr!(
        super::PROPERTY_DEFINITION,
        c",output=text,structure=PrivateKeyInfo"
    )
);

pub(crate) struct SubjectPublicKeyInfo2DER();
impl Encoder for SubjectPublicKeyInfo2DER {
    const PROPERTY_DEFINITION: &'static CStr = concat_cstr!(
        super::PROPERTY_DEFINITION,
        c",output=der,structure=SubjectPublicKeyInfo"
    );

    const DISPATCH_TABLE: &'static [OSSL_DISPATCH] = {
        mod dispatch_table_module {
            use super::*;
            use bindings::{OSSL_FUNC_encoder_does_selection_fn, OSSL_FUNC_ENCODER_DOES_SELECTION};
            use bindings::{OSSL_FUNC_encoder_encode_fn, OSSL_FUNC_ENCODER_ENCODE};
            use bindings::{OSSL_FUNC_encoder_freectx_fn, OSSL_FUNC_ENCODER_FREECTX};
            use bindings::{OSSL_FUNC_encoder_newctx_fn, OSSL_FUNC_ENCODER_NEWCTX};

            // TODO reenable typechecking in dispatch_table_entry macro and make sure these still compile!
            // https://docs.openssl.org/3.2/man7/provider-decoder/
            pub(super) const DER_ENCODER_FUNCTIONS: &[OSSL_DISPATCH] = &[
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_NEWCTX,
                    OSSL_FUNC_encoder_newctx_fn,
                    encoder_functions::newctx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_FREECTX,
                    OSSL_FUNC_encoder_freectx_fn,
                    encoder_functions::freectx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_DOES_SELECTION,
                    OSSL_FUNC_encoder_does_selection_fn,
                    encoder_functions::does_selection_SPKI
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_ENCODE,
                    OSSL_FUNC_encoder_encode_fn,
                    encoder_functions::encodeSPKI2DER
                ),
                OSSL_DISPATCH::END,
            ];
        }

        dispatch_table_module::DER_ENCODER_FUNCTIONS
    };
}

/// Encodes a SubjectPublicKeyInfo to DER
///
/// # Arguments
///
/// ## TODO(🛠️): document arguments
///
/// # Notes
///
/// [`OSSL_FUNC_encoder_encode_fn`][provider-encoder(7ossl)]
/// functions such as this one are tightly integrated
/// with the [`super::keymgmt_functions::load`]
/// implementation exposed
/// for [their algorithm][`super`].
///
/// Eventually the `data_cb` argument calls the
/// `OSSL_FUNC_keymgmt_load_fn`
/// exposed by the [keymgmt][`super::keymgmt_functions`]
/// for [this algorithm][`super`].
/// Hence they must agree on how the reference is being passed around.
///
/// Refer to [provider-decoder(7ossl)],
/// [provider-keymgmt(7ossl)],
/// and [provider-object(7ossl)].
///
/// [provider-keymgmt(7ossl)]: https://docs.openssl.org/master/man7/provider-keymgmt/
/// [provider-object(7ossl)]: https://docs.openssl.org/master/man7/provider-object/
/// [provider-encoder(7ossl)]: https://docs.openssl.org/master/man7/provider-encoder/
///
/// # Examples
///
/// ## TODO(🛠️): add examples
///
#[named]
pub(super) unsafe extern "C" fn encodeSPKI2DER(
    vencoderctx: *mut c_void,
    out: *mut OSSL_CORE_BIO,
    obj_raw: *const c_void,
    _obj_abstract: *const OSSL_PARAM,
    selection: c_int,
    _cb: OSSL_PASSPHRASE_CALLBACK,
    _cbarg: *mut c_void,
) -> c_int {
    const SUCCESS: c_int = 1;
    const ERROR_RET: c_int = 0;
    trace!(target: log_target!(), "{}", "Called!");

    debug!(target: log_target!(), "Got selection: {selection:#b}");
    if (selection & (OSSL_KEYMGMT_SELECT_PUBLIC_KEY as c_int)) == 0 {
        error!(target: log_target!(), "Invalid selection: {selection:#?}");
        return ERROR_RET;
    }

    let encoderctx: &EncoderContext = handleResult!(vencoderctx.try_into());

    if obj_raw.is_null() {
        error!(target: log_target!(), "No provider-native object passed to encoder");
        return ERROR_RET;
    }

    let keypair: &KeyPair = handleResult!(obj_raw.try_into());
    let spki_bytes_der = handleResult!(keypair.to_SPKIDER(encoderctx).map_err(|e| {
        error!(target: log_target!(), "Failed to encode SubjectPublicKeyInfo: {e:?}");
        OurError::from(e)
    }));
    match encoderctx.provctx.BIO_write_ex(out, &spki_bytes_der) {
        Ok(_bytes_written) => {}
        Err(e) => {
            error!(target: log_target!(), "Failure using BIO_write_ex() upcall pointer: {e:?}");
            return ERROR_RET;
        }
    };

    SUCCESS
}

impl DoesSelection for SubjectPublicKeyInfo2DER {
    const SELECTION_MASK: Selection = Selection::PUBLIC_KEY;
}

transcoders::make_does_selection_fn!(
    does_selection_SPKI,
    SubjectPublicKeyInfo2DER,
    ProviderInstance
);

pub(crate) struct SubjectPublicKeyInfo2PEM();
impl Encoder for SubjectPublicKeyInfo2PEM {
    const PROPERTY_DEFINITION: &'static CStr = concat_cstr!(
        super::PROPERTY_DEFINITION,
        c",output=pem,structure=SubjectPublicKeyInfo"
    );

    const DISPATCH_TABLE: &'static [OSSL_DISPATCH] = {
        mod dispatch_table_module {
            use super::*;
            use bindings::{OSSL_FUNC_encoder_does_selection_fn, OSSL_FUNC_ENCODER_DOES_SELECTION};
            use bindings::{OSSL_FUNC_encoder_encode_fn, OSSL_FUNC_ENCODER_ENCODE};
            use bindings::{OSSL_FUNC_encoder_freectx_fn, OSSL_FUNC_ENCODER_FREECTX};
            use bindings::{OSSL_FUNC_encoder_newctx_fn, OSSL_FUNC_ENCODER_NEWCTX};

            // TODO reenable typechecking in dispatch_table_entry macro and make sure these still compile!
            // https://docs.openssl.org/3.2/man7/provider-decoder/
            pub(super) const PEM_ENCODER_FUNCTIONS: &[OSSL_DISPATCH] = &[
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_NEWCTX,
                    OSSL_FUNC_encoder_newctx_fn,
                    encoder_functions::newctx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_FREECTX,
                    OSSL_FUNC_encoder_freectx_fn,
                    encoder_functions::freectx
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_DOES_SELECTION,
                    OSSL_FUNC_encoder_does_selection_fn,
                    encoder_functions::does_selection_SPKI
                ),
                dispatch_table_entry!(
                    OSSL_FUNC_ENCODER_ENCODE,
                    OSSL_FUNC_encoder_encode_fn,
                    encoder_functions::encodeSPKI2PEM
                ),
                OSSL_DISPATCH::END,
            ];
        }

        dispatch_table_module::PEM_ENCODER_FUNCTIONS
    };
}

/// Encodes a SubjectPublicKeyInfo to PEM
///
/// # Arguments
///
/// ## TODO(🛠️): document arguments
///
/// # Notes
///
/// [`OSSL_FUNC_encoder_encode_fn`][provider-encoder(7ossl)]
/// functions such as this one are tightly integrated
/// with the [`super::keymgmt_functions::load`]
/// implementation exposed
/// for [their algorithm][`super`].
///
/// Eventually the `data_cb` argument calls the
/// `OSSL_FUNC_keymgmt_load_fn`
/// exposed by the [keymgmt][`super::keymgmt_functions`]
/// for [this algorithm][`super`].
/// Hence they must agree on how the reference is being passed around.
///
/// Refer to [provider-decoder(7ossl)],
/// [provider-keymgmt(7ossl)],
/// and [provider-object(7ossl)].
///
/// [provider-keymgmt(7ossl)]: https://docs.openssl.org/master/man7/provider-keymgmt/
/// [provider-object(7ossl)]: https://docs.openssl.org/master/man7/provider-object/
/// [provider-encoder(7ossl)]: https://docs.openssl.org/master/man7/provider-encoder/
///
/// # Examples
///
/// ## TODO(🛠️): add examples
///
#[named]
pub(super) unsafe extern "C" fn encodeSPKI2PEM(
    vencoderctx: *mut c_void,
    out: *mut OSSL_CORE_BIO,
    obj_raw: *const c_void,
    _obj_abstract: *const OSSL_PARAM,
    selection: c_int,
    _cb: OSSL_PASSPHRASE_CALLBACK,
    _cbarg: *mut c_void,
) -> c_int {
    const SUCCESS: c_int = 1;
    const ERROR_RET: c_int = 0;
    trace!(target: log_target!(), "{}", "Called!");

    debug!(target: log_target!(), "Got selection: {selection:#b}");
    if (selection & (OSSL_KEYMGMT_SELECT_PUBLIC_KEY as c_int)) == 0 {
        error!(target: log_target!(), "Invalid selection: {selection:#?}");
        return ERROR_RET;
    }

    let encoderctx: &EncoderContext = handleResult!(vencoderctx.try_into());

    if obj_raw.is_null() {
        error!(target: log_target!(), "No provider-native object passed to encoder");
        return ERROR_RET;
    }

    let keypair: &KeyPair = handleResult!(obj_raw.try_into());
    let spki_bytes_der = handleResult!(keypair.to_SPKIDER(encoderctx).map_err(|e| {
        error!(target: log_target!(), "Failed to encode SubjectPublicKeyInfo: {e:?}");
        OurError::from(e)
    }));
    let pem = pem::Pem::new("PUBLIC KEY", spki_bytes_der.as_slice());
    let pem_bytes = pem::encode(&pem).into_bytes();
    let pem_bytes = pem_bytes.as_slice();

    match encoderctx.provctx.BIO_write_ex(out, &pem_bytes) {
        Ok(_bytes_written) => {}
        Err(e) => {
            error!(target: log_target!(), "Failure using BIO_write_ex() upcall pointer: {e:?}");
            return ERROR_RET;
        }
    };

    SUCCESS
}

impl DoesSelection for SubjectPublicKeyInfo2PEM {
    const SELECTION_MASK: Selection = Selection::PUBLIC_KEY;
}

// We can use the same does_selection function as SubjectPublicKeyInfo2DER, so there's no need to
// call the make_does_selection_fn macro again.

// generate the plain text encoder
use crate::adapters::common::transcoders::make_pubkey_text_encoder;
make_pubkey_text_encoder!(
    PubKeyStructureless2Text,
    concat_cstr!(super::PROPERTY_DEFINITION, c",output=text")
);