apub-actix-web 0.2.0

Utilities for building activitypub servers
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
//! Actix Web integration for Apub
//!
//! Currently, this only includes verifying HTTP Signatures and Digests for authorized fetch and
//! inbox delivery, but it doesn't do any further verification

#![deny(missing_docs)]

use actix_web::{
    error::BlockingError,
    http::Uri,
    web::{self, ServiceConfig},
    FromRequest, HttpRequest, HttpResponse, ResponseError,
};
use apub_core::{
    digest::{Digest, DigestBuilder, DigestFactory},
    ingest::{is_local, Authority, Ingest, IngestFactory},
    repo::{Dereference, Repo, RepoFactory},
    session::SessionFactory,
    signature::{PrivateKeyBuilder, Verify, VerifyBuilder, VerifyFactory},
};
use apub_privatekey::{PrivateKeyRepo, PrivateKeyRepoFactory};
use apub_publickey::{PublicKeyClient, PublicKeyError, PublicKeyRepo, PublicKeyRepoFactory};
use http_signature_normalization_actix::{
    digest::DigestName,
    prelude::{
        Algorithm, DeprecatedAlgorithm, DigestPart, DigestVerify, SignatureVerified,
        SignatureVerify, VerifyDigest, VerifySignature,
    },
};
use std::{future::Future, marker::PhantomData, pin::Pin};
use url::{Host, Url};

/// Server configuration
#[derive(Clone, Debug)]
pub struct Config {
    /// the publicly visible the server is located at
    ///
    /// e.g. `hello.com` or `70.123.123.20`
    pub local_host: Host<String>,

    /// the publicly visible port the server is located at
    ///
    /// e.g. `None` or `Some(8080)`
    pub local_port: Option<u16>,

    /// the public scheme the server is accessible over
    ///
    /// e.g. `http://` or `https://`
    pub scheme: String,

    /// Used to look up the server actor's key
    pub server_actor_id: Url,
}

impl Config {
    fn build_uri(&self, uri: &Uri) -> String {
        if let Some(port) = self.local_port {
            format!("{}{}:{}{}", self.scheme, self.local_host, port, uri)
        } else {
            format!("{}{}{}", self.scheme, self.local_host, uri)
        }
    }

    /// Determine if a given URL is local
    pub fn is_local(&self, url: &Url) -> bool {
        is_local(&self.local_host, self.local_port, url)
    }
}

/// The HTTP Signature config for Actix Web
pub use http_signature_normalization_actix::Config as SignatureConfig;

/// Errors that can happen when verifying signatures
#[derive(Debug, thiserror::Error)]
pub enum VerifyError {
    /// An unsupported signature algorithm was provided
    #[error("Unsupported algorithm: {0}")]
    Algorithm(String),

    /// The given KeyId is malformed
    #[error("Invalid Key ID: {0}")]
    KeyId(String),

    /// The owner of the provided key is doesn't match the fetched owner's ID
    #[error("Actor {0} is not public key's owner")]
    InvalidOwner(Url),

    /// They fetched key's ID is different from the ID we expected
    #[error("Public Key {0} is not the expected key")]
    InvalidKey(Url),

    /// The key was unable to be found
    #[error("No key associated with Key ID")]
    KeyNotFound,

    /// The verification task panicked
    #[error("Key verification panicked")]
    Canceled,
}

type RFactErr<R> = <<R as RepoFactory>::Repo as Repo>::Error;
type PubKeyRepoErr<P> = <<P as PublicKeyRepoFactory>::PublicKeyRepo as PublicKeyRepo>::Error;
type VFactErr<V> = <<V as VerifyFactory>::Verify as Verify>::Error;
type PrivKeyRepoErr<P> = <<P as PrivateKeyRepoFactory>::PrivateKeyRepo as PrivateKeyRepo>::Error;
type PrivKeyError<R> = <<R as RepoFactory>::Crypto as PrivateKeyBuilder>::Error;

/// Ingest activitypub objects at a given endpoint
///
/// ```rust,ignore
/// use actix_web::App;
/// use apub_actix_web::{inbox, SignatureConfig};
/// use url::Host;
///
/// // Ingest implements Ingest
/// let ingest = Ingest::new();
///
/// // verifier implements Repo, VerifyFactory, and DigestFactory
/// let verifier = DatabaseVerifier::new();
///
/// let config = Config {
///     local_host: Host::Domain(String::from("example.com")),
///     local_port: None,
///     scheme: String::from("https://"),
/// };
///
/// App::new()
///     .service(
///         web::scope("/shared_inbox")
///             .configure(inbox::<A, (), _, _, MyError>(
///                 config,
///                 ingest,
///                 verifier,
///                 SignatureConfig::default(),
///                 true,
///             ))
///     );
/// ```
pub fn inbox<A, I, V, E>(
    config: Config,
    ingest_factory: I,
    verifier: V,
    signature_config: SignatureConfig,
    require_signature: bool,
) -> impl FnOnce(&mut ServiceConfig)
where
    A: for<'de> serde::de::Deserialize<'de> + 'static,
    I: IngestFactory<A> + PrivateKeyRepoFactory + RepoFactory + SessionFactory + 'static,
    I::PrivateKeyRepo: PrivateKeyRepo<PrivateKey = I::Crypto>,
    <I::Ingest as Ingest<A>>::ActorId: FromRequest + AsRef<Url>,
    <I::Ingest as Ingest<A>>::Error: From<<I::Repo as Repo>::Error>,
    V: RepoFactory
        + SessionFactory
        + PublicKeyRepoFactory
        + PrivateKeyRepoFactory
        + VerifyFactory
        + DigestFactory
        + Clone
        + 'static,
    V::PrivateKeyRepo: PrivateKeyRepo<PrivateKey = V::Crypto>,
    V::Crypto: PrivateKeyBuilder,
    <V as DigestFactory>::Digest: Clone,
    E: ResponseError
        + From<VerifyError>
        + From<VFactErr<V>>
        + From<PublicKeyError<PubKeyRepoErr<V>, RFactErr<V>>>
        + From<PrivKeyRepoErr<V>>
        + From<PrivKeyError<V>>
        + 'static,
{
    move |service_config: &mut ServiceConfig| {
        let signature = VerifySignature::new(
            VerifyMiddleware::<V, E>::new(verifier, config),
            signature_config,
        );

        let digest = VerifyDigest::new(DigestWrapper(V::Digest::build()));

        let (signature, digest) = if require_signature {
            (signature, digest)
        } else {
            (signature.optional(), digest.optional())
        };

        service_config.service(
            web::scope("")
                .app_data(web::Data::new(ingest_factory))
                .wrap(digest)
                .wrap(signature)
                .route("", web::post().to(inbox_handler::<A, I>)),
        );
    }
}

/// Serve activitypub objects from a given endpoint
///
/// ```rust,ignore
/// use actix_web::App;
/// use apub_actix_web::{serve_objects, SignatureConfig};
/// use url::Host;
///
/// // repository implements Repo
/// let repository = DatabaseRepo::new();
///
/// // verifier implements Repo and VerifyFactory
/// let verifier = DatabaseVerifier::new();
///
/// let config = Config {
///     local_host: Host::Domain(String::from("example.com")),
///     local_port: None,
///     scheme: String::from("https://"),
/// };
///
/// App::new()
///     .service(
///         web::scope("/activites")
///             .configure(serve_objects::<ObjectId<A>, _, _, MyError>(
///                 config,
///                 repository,
///                 verifier,
///                 SignatureConfig::default(),
///                 true,
///             ))
///     );
/// ```
pub fn serve_objects<D, R, V, E>(
    config: Config,
    repo: R,
    verifier: V,
    signature_config: SignatureConfig,
    require_signature: bool,
) -> impl FnOnce(&mut ServiceConfig)
where
    D: Dereference + From<Url> + 'static,
    <D as Dereference>::Output: serde::ser::Serialize,
    R: Repo + 'static,
    V: RepoFactory
        + SessionFactory
        + PublicKeyRepoFactory
        + PrivateKeyRepoFactory
        + VerifyFactory
        + Clone
        + 'static,
    V::PrivateKeyRepo: PrivateKeyRepo<PrivateKey = V::Crypto>,
    V::Crypto: PrivateKeyBuilder,
    E: ResponseError
        + From<VerifyError>
        + From<VFactErr<V>>
        + From<PublicKeyError<PubKeyRepoErr<V>, RFactErr<V>>>
        + From<PrivKeyRepoErr<V>>
        + From<PrivKeyError<V>>
        + 'static,
{
    move |service_config: &mut ServiceConfig| {
        let verifier = VerifySignature::new(
            VerifyMiddleware::<V, E>::new(verifier, config.clone()),
            signature_config,
        );

        let verifier = if require_signature {
            verifier
        } else {
            verifier.optional()
        };

        service_config.service(
            web::scope("/{object}")
                .app_data(web::Data::new(repo))
                .app_data(web::Data::new(config))
                .wrap(verifier)
                .route("", web::get().to(serve_object_handler::<D, R>)),
        );
    }
}

async fn inbox_handler<A, I>(
    ingest_factory: web::Data<I>,
    authority: Option<SignatureVerified>,
    activity: web::Json<A>,
    actor_id: <I::Ingest as Ingest<A>>::ActorId,
) -> HttpResponse
where
    A: for<'de> serde::de::Deserialize<'de> + 'static,
    I: IngestFactory<A> + PrivateKeyRepoFactory + RepoFactory + SessionFactory,
    I::PrivateKeyRepo: PrivateKeyRepo<PrivateKey = I::Crypto>,
    <I::Ingest as Ingest<A>>::ActorId: FromRequest + AsRef<Url>,
    <I::Ingest as Ingest<A>>::Error: From<<I::Repo as Repo>::Error>,
{
    let url = actor_id.as_ref();

    let private_key_repo = ingest_factory.build_private_key_repo();
    let private_key = match private_key_repo.fetch(url).await {
        Ok(private_key) => private_key,
        Err(_) => return HttpResponse::BadRequest().finish(),
    };

    let activity = activity.into_inner();
    let remote_repo = ingest_factory.build_repo(private_key);
    let mut session = ingest_factory.build_session();
    let ingest = ingest_factory.build_ingest();

    if let Some(auth) = authority {
        if let Ok(url) = auth.key_id().parse() {
            if ingest
                .ingest(
                    Authority::Actor(url),
                    actor_id,
                    &activity,
                    &remote_repo,
                    &mut session,
                )
                .await
                .is_ok()
            {
                return HttpResponse::Accepted().finish();
            }
        }
    } else if ingest
        .ingest(
            Authority::None,
            actor_id,
            &activity,
            &remote_repo,
            &mut session,
        )
        .await
        .is_ok()
    {
        return HttpResponse::Accepted().finish();
    }

    HttpResponse::BadRequest().finish()
}

async fn serve_object_handler<D, R>(
    req: HttpRequest,
    repo: web::Data<R>,
    config: web::Data<Config>,
) -> HttpResponse
where
    D: Dereference + From<Url> + 'static,
    <D as Dereference>::Output: serde::ser::Serialize,
    R: Repo + 'static,
{
    let url: Url = match config.build_uri(req.uri()).parse() {
        Ok(url) => url,
        Err(_) => return HttpResponse::BadRequest().finish(),
    };

    let res = repo.fetch(D::from(url), ()).await;

    match res {
        Ok(Some(object)) => HttpResponse::Ok()
            .content_type("application/activity+json")
            .json(object),
        Ok(None) => HttpResponse::NotFound().finish(),
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

#[derive(Clone)]
struct DigestWrapper<D>(D);

impl<D> DigestName for DigestWrapper<D>
where
    D: Digest,
{
    const NAME: &'static str = D::NAME;
}

impl<D> DigestVerify for DigestWrapper<D>
where
    D: Digest + Clone,
{
    fn update(&mut self, part: &[u8]) {
        self.0.update(part);
    }

    fn verify(&mut self, digests: &[DigestPart]) -> bool {
        if let Some(part) = digests.iter().find(|part| part.algorithm == D::NAME) {
            return self.0.clone().verify(&part.digest);
        }

        false
    }
}

struct VerifyMiddleware<V, E> {
    verifier: V,
    config: Config,
    _error: PhantomData<fn() -> E>,
}

impl<V, E> Clone for VerifyMiddleware<V, E>
where
    V: Clone,
{
    fn clone(&self) -> Self {
        Self {
            verifier: self.verifier.clone(),
            config: self.config.clone(),
            _error: PhantomData,
        }
    }
}

impl<V, E> VerifyMiddleware<V, E>
where
    V: VerifyFactory,
{
    fn new(verifier: V, config: Config) -> Self {
        Self {
            verifier,
            config,
            _error: PhantomData,
        }
    }
}

async fn verify<V, E>(
    verifier: &V,
    config: Config,
    algorithm: Option<Algorithm>,
    key_id: String,
    signature: String,
    signing_string: String,
) -> Result<bool, E>
where
    V: RepoFactory + SessionFactory + VerifyFactory + PublicKeyRepoFactory + PrivateKeyRepoFactory,
    V::PrivateKeyRepo: PrivateKeyRepo<PrivateKey = V::Crypto>,
    V::Crypto: PrivateKeyBuilder,
    <<V as VerifyFactory>::Verify as Verify>::Error: 'static,
    E: ResponseError
        + From<VerifyError>
        + From<VFactErr<V>>
        + From<PublicKeyError<PubKeyRepoErr<V>, RFactErr<V>>>
        + From<PrivKeyRepoErr<V>>
        + From<PrivKeyError<V>>
        + 'static,
{
    match algorithm {
        None | Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => {}
        Some(other) => return Err(VerifyError::Algorithm(other.to_string()).into()),
    };

    let key_id = key_id.parse().map_err(|_| VerifyError::KeyId(key_id))?;

    let private_key_repo = verifier.build_private_key_repo();

    let crypto = private_key_repo.fetch(&config.server_actor_id).await?;

    let session = verifier.build_session();
    let http_repo = verifier.build_repo(crypto);
    let public_key_repo = verifier.public_key_repo();

    let public_key_client = PublicKeyClient::new(
        public_key_repo,
        http_repo,
        config.local_host,
        config.local_port,
    );

    let public_key = public_key_client
        .find(&key_id, session)
        .await
        .map_err(E::from)?
        .ok_or(VerifyError::KeyNotFound)?;

    let verified = web::block(move || {
        let verified =
            <<V as VerifyFactory>::Verify as VerifyBuilder>::build(&public_key.public_key_pem)?
                .verify(&signing_string, &signature)?;

        Ok(verified) as Result<bool, VFactErr<V>>
    })
    .await
    .map_err(VerifyError::from)??;

    Ok(verified)
}

impl<V, E> SignatureVerify for VerifyMiddleware<V, E>
where
    V: RepoFactory
        + SessionFactory
        + PublicKeyRepoFactory
        + PrivateKeyRepoFactory
        + VerifyFactory
        + Clone
        + 'static,
    V::PrivateKeyRepo: PrivateKeyRepo<PrivateKey = V::Crypto>,
    V::Crypto: PrivateKeyBuilder,
    E: ResponseError
        + From<VerifyError>
        + From<VFactErr<V>>
        + From<PublicKeyError<PubKeyRepoErr<V>, RFactErr<V>>>
        + From<PrivKeyRepoErr<V>>
        + From<PrivKeyError<V>>
        + 'static,
{
    type Error = E;
    type Future = Pin<Box<dyn Future<Output = Result<bool, Self::Error>>>>;

    fn signature_verify(
        &mut self,
        algorithm: Option<Algorithm>,
        key_id: String,
        signature: String,
        signing_string: String,
    ) -> Self::Future {
        let verifier = self.verifier.clone();
        let config = self.config.clone();

        Box::pin(async move {
            verify::<V, E>(
                &verifier,
                config,
                algorithm,
                key_id,
                signature,
                signing_string,
            )
            .await
        })
    }
}

impl From<BlockingError> for VerifyError {
    fn from(_: BlockingError) -> Self {
        VerifyError::Canceled
    }
}