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
#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/52050279?s=200&v=4")]
//! # waSCC Host
//!
//! The WebAssembly Secure Capabilities Connector (waSCC) host runtime manages actors
//! written in WebAssembly (aka _nanoprocesses_) and capability providers written in
//! WebAssembly (via WASI) or as OS-native plugin libraries. waSCC securely manages
//! communications between actors and the capabilities they need.
//!
//! To start a runtime, simply add actors and capabilities to the host. For more information,
//! take a look at the documentation and tutorials at [wascc.dev](https://wascc.dev).
//!
//! # Example
//! ```
//! use std::collections::HashMap;
//! use wascc_host::{Host, Actor, NativeCapability};
//!
//! fn main() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!    env_logger::init();
//!    let host = Host::new();
//!    host.add_actor(Actor::from_file("./examples/.assets/echo.wasm")?)?;
//!    host.add_actor(Actor::from_file("./examples/.assets/echo2.wasm")?)?;
//!    host.add_native_capability(NativeCapability::from_file(
//!        "./examples/.assets/libwascc_httpsrv.so", None
//!    )?)?;
//!
//!    host.bind_actor(
//!        "MDFD7XZ5KBOPLPHQKHJEMPR54XIW6RAG5D7NNKN22NP7NSEWNTJZP7JN",
//!        "wascc:http_server",
//!        None,
//!        generate_port_config(8085),
//!    )?;
//!
//!    host.bind_actor(
//!        "MB4OLDIC3TCZ4Q4TGGOVAZC43VXFE2JQVRAXQMQFXUCREOOFEKOKZTY2",
//!        "wascc:http_server",
//!        None,
//!        generate_port_config(8084),
//!    )?;
//!
//!    assert_eq!(2, host.actors().len());
//!    if let Some(ref claims) = host.claims_for_actor("MB4OLDIC3TCZ4Q4TGGOVAZC43VXFE2JQVRAXQMQFXUCREOOFEKOKZTY2") {
//!        let md = claims.metadata.as_ref().unwrap();
//!        assert!(md.caps.as_ref().unwrap().contains(&"wascc:http_server".to_string()));   
//!    }
//!    
//!
//! # std::thread::sleep(::std::time::Duration::from_millis(10));
//!    // Need to keep the main thread from terminating immediately
//!    // std::thread::park();
//!
//!    Ok(())
//! }
//!
//! fn generate_port_config(port: u16) -> HashMap<String, String> {
//!    let mut hm = HashMap::new();
//!    hm.insert("PORT".to_string(), port.to_string());
//!
//!    hm
//! }
//!
//! ```
//!

#[macro_use]
extern crate log;

#[macro_use]
extern crate crossbeam;

mod actor;
mod authz;
mod bus;
mod capability;
mod dispatch;
pub mod errors;
mod extras;
mod inthost;
#[cfg(feature = "manifest")]
mod manifest;
pub mod middleware;
mod plugins;
mod spawns;

pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const REVISION: u32 = 2;

pub type Result<T> = std::result::Result<T, errors::Error>;

pub use actor::Actor;
pub use capability::NativeCapability;
pub use inthost::{Invocation, InvocationResponse, WasccEntity};

#[cfg(feature = "manifest")]
pub use manifest::{BindingEntry, HostManifest};

#[cfg(feature = "prometheus_middleware")]
pub use middleware::prometheus;

#[cfg(feature = "lattice")]
use latticeclient::BusEvent;

pub use authz::Authorizer;
pub use middleware::Middleware;
pub use wapc::{prelude::WasiParams, WapcHost};

pub type SubjectClaimsPair = (String, Claims<wascap::jwt::Actor>);

use bus::{get_namespace_prefix, MessageBus};
use crossbeam::Sender;
#[cfg(any(feature = "lattice", feature = "manifest"))]
use inthost::RESTRICTED_LABELS;
use plugins::PluginManager;
use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};
use wascap::jwt::Claims;
use wascap::prelude::KeyPair;
use wascc_codec::{
    capabilities::CapabilityDescriptor,
    core::{CapabilityConfiguration, OP_BIND_ACTOR},
    SYSTEM_ACTOR,
};

type BindingsList = HashMap<BindingTuple, CapabilityConfiguration>;
type BindingTuple = (String, String, String); // (from-actor, to-capid, to-binding-name)

/// A routing key is a combination of a capability ID and the binding name used for
/// that capability. Think of it as a unique or primary key for a capid+binding.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone)]
pub(crate) struct RouteKey {
    pub binding_name: String,
    pub capid: String,
}

impl RouteKey {
    pub fn new(binding_name: &str, capid: &str) -> RouteKey {
        RouteKey {
            binding_name: binding_name.to_string(),
            capid: capid.to_string(),
        }
    }
}

/// A builder pattern implementation for creating a custom-configured host runtime
pub struct HostBuilder {
    labels: HashMap<String, String>,
    ns: Option<String>,
    authorizer: Box<dyn Authorizer + 'static>,
}

impl HostBuilder {
    /// Creates a new host builder. This builder will initialize itself with some defaults
    /// obtained from the environment. The labels list will pre-populate with the `hostcore.*`
    /// labels, the namespace will be glaned from the `LATTICE_NAMESPACE` environment variable
    /// (if lattice mode is enabled), and the default authorizer will be set.
    pub fn new() -> HostBuilder {
        HostBuilder {
            labels: inthost::detect_core_host_labels(),
            ns: get_namespace_prefix(),
            authorizer: Box::new(authz::DefaultAuthorizer::new()),
        }
    }

    /// Sets the lattice namespace for this host. A lattice namespace is a unit of multi-tenant
    /// isolation on a network
    #[cfg(feature = "lattice")]
    pub fn with_lattice_namespace(self, ns: &str) -> HostBuilder {
        HostBuilder {
            ns: Some(ns.to_string()),
            ..self
        }
    }

    /// Sets a custom authorizer to be used for authorizing actors, capability providers,
    /// and invocation requests. Note that the authorizer cannot be used to implement _less_
    /// strict measures than the default authorizer, it can only be used to implement
    /// _more_ strict rules
    pub fn with_authorizer(self, authorizer: impl Authorizer + 'static) -> HostBuilder {
        HostBuilder {
            authorizer: Box::new(authorizer),
            ..self
        }
    }

    /// Adds an arbitrary label->value pair of metadata to the host. Cannot override
    /// reserved labels such as those that begin with `hostcore.`
    pub fn with_label(self, key: &str, value: &str) -> HostBuilder {
        let mut hm = self.labels.clone();
        if !hm.contains_key(key) {
            hm.insert(key.to_string(), value.to_string());
        }
        HostBuilder { labels: hm, ..self }
    }

    /// Converts the transient builder instance into a realized host runtime instance
    pub fn build(self) -> Host {
        Host::generate(self.authorizer, self.labels, self.ns.clone())
    }
}

/// Represents an instance of a waSCC host
#[derive(Clone)]
pub struct Host {
    bus: Arc<MessageBus>,
    claims: Arc<RwLock<HashMap<String, Claims<wascap::jwt::Actor>>>>,
    plugins: Arc<RwLock<PluginManager>>,
    bindings: Arc<RwLock<BindingsList>>,
    caps: Arc<RwLock<HashMap<RouteKey, CapabilityDescriptor>>>,
    middlewares: Arc<RwLock<Vec<Box<dyn Middleware>>>>,
    // the key to this field is the subscription subject, and not either a pk or a capid
    terminators: Arc<RwLock<HashMap<String, Sender<bool>>>>,
    #[cfg(feature = "gantry")]
    gantry_client: Arc<RwLock<Option<gantryclient::Client>>>,
    key: KeyPair,
    authorizer: Arc<RwLock<Box<dyn Authorizer>>>,
    labels: Arc<RwLock<HashMap<String, String>>>,
    ns: Option<String>,
}

impl Host {
    /// Creates a new runtime host using all of the default values. Use the host builder
    /// if you want to provide more customization options
    pub fn new() -> Self {
        Self::generate(
            Box::new(authz::DefaultAuthorizer::new()),
            inthost::detect_core_host_labels(),
            get_namespace_prefix(),
        )
    }

    pub(crate) fn generate(
        authz: Box<dyn Authorizer + 'static>,
        labels: HashMap<String, String>,
        ns: Option<String>,
    ) -> Self {
        let key = KeyPair::new_server();
        let claims = Arc::new(RwLock::new(HashMap::new()));
        let caps = Arc::new(RwLock::new(HashMap::new()));
        let bindings = Arc::new(RwLock::new(HashMap::new()));
        let labels = Arc::new(RwLock::new(labels));
        let terminators = Arc::new(RwLock::new(HashMap::new()));

        #[cfg(feature = "lattice")]
        let bus = Arc::new(bus::new(
            key.public_key(),
            claims.clone(),
            caps.clone(),
            bindings.clone(),
            labels.clone(),
            terminators.clone(),
            ns.clone(),
        ));

        #[cfg(not(feature = "lattice"))]
        let bus = Arc::new(bus::new());

        #[cfg(feature = "lattice")]
        let _ = bus.publish_event(BusEvent::HostStarted(key.public_key()));

        #[cfg(feature = "gantry")]
        let host = Host {
            terminators: terminators.clone(),
            bus: bus.clone(),
            claims,
            plugins: Arc::new(RwLock::new(PluginManager::default())),
            bindings,
            caps,
            middlewares: Arc::new(RwLock::new(vec![])),
            gantry_client: Arc::new(RwLock::new(None)),
            key: key,
            authorizer: Arc::new(RwLock::new(authz)),
            labels,
            ns,
        };
        #[cfg(not(feature = "gantry"))]
        let host = Host {
            terminators: terminators.clone(),
            bus: bus.clone(),
            claims,
            plugins: Arc::new(RwLock::new(PluginManager::default())),
            bindings,
            middlewares: Arc::new(RwLock::new(vec![])),
            caps,
            key: key,
            authorizer: Arc::new(RwLock::new(authz)),
            labels,
            ns,
        };
        info!("Host ID is {} (v{})", host.key.public_key(), VERSION,);

        host.ensure_extras().unwrap();
        host
    }

    /// Sets an arbitrary label on the host. Discoverable via lattice query
    #[cfg(feature = "lattice")]
    pub fn set_label(&self, label: &str, value: &str) {
        if !RESTRICTED_LABELS.contains(&label) {
            self.labels
                .write()
                .unwrap()
                .insert(label.to_string(), value.to_string());
        }
    }

    /// Adds an actor to the host
    pub fn add_actor(&self, actor: Actor) -> Result<()> {
        if self
            .claims
            .read()
            .unwrap()
            .contains_key(&actor.public_key())
        {
            return Err(errors::new(errors::ErrorKind::MiscHost(
                format!("Actor {} is already in this host. Cannot host multiple instances of the same actor in the same host", actor.public_key())
            )));
        }
        authz::enforce_validation(&actor.token.jwt)?; // returns an `Err` if validation fails
        if !self.check_auth(&actor.token) {
            // invoke the auth hook, if there is one
            return Err(errors::new(errors::ErrorKind::Authorization(
                "Authorization hook denied access to module".into(),
            )));
        }

        authz::register_claims(
            self.claims.clone(),
            &actor.token.claims.subject,
            actor.token.claims.clone(),
        );

        let wg = crossbeam_utils::sync::WaitGroup::new();
        // Spin up a new thread that listens to "wasmbus.Mxxxx" calls on the message bus
        spawns::spawn_actor(
            wg.clone(),
            actor.token.claims.clone(),
            actor.bytes.clone(),
            None,
            true,
            None,
            self.bus.clone(),
            self.middlewares.clone(),
            self.caps.clone(),
            self.bindings.clone(),
            self.claims.clone(),
            self.terminators.clone(),
            self.key.clone(),
            self.authorizer.clone(),
        )?;
        wg.wait();
        if actor.capabilities().contains(&extras::CAPABILITY_ID.into()) {
            // force a binding so that there's a private actor subject on the bus for the
            // actor to communicate with the extras provider
            self.bind_actor(
                &actor.public_key(),
                extras::CAPABILITY_ID,
                None,
                HashMap::new(),
            )?;
        }

        Ok(())
    }

    /// Adds an actor to the host by looking it up in a Gantry repository, downloading
    /// the signed module bytes, and adding them to the host
    #[cfg(feature = "gantry")]
    pub fn add_actor_from_gantry(&self, actor: &str) -> Result<()> {
        {
            let lock = self.gantry_client.read().unwrap();
            if lock.as_ref().is_none() {
                return Err(errors::new(errors::ErrorKind::MiscHost(
                    "No gantry client configured".to_string(),
                )));
            }
        }
        use crossbeam_channel::unbounded;
        let (s, r) = unbounded();
        let bytevec = Arc::new(RwLock::new(Vec::new()));
        let b = bytevec.clone();
        let _ack = self
            .gantry_client
            .read()
            .unwrap()
            .as_ref()
            .unwrap()
            .download_actor(actor, move |chunk| {
                bytevec
                    .write()
                    .unwrap()
                    .extend_from_slice(&chunk.chunk_bytes);
                if chunk.sequence_no == chunk.total_chunks {
                    s.send(true).unwrap();
                }
                Ok(())
            });
        let _ = r.recv().unwrap();
        let vec = b.read().unwrap();
        self.add_actor(Actor::from_bytes(vec.clone())?)
    }

    /// Adds a portable capability provider (e.g. a WASI actor) to the waSCC host
    pub fn add_capability(
        &self,
        actor: Actor,
        binding: Option<&str>,
        wasi: WasiParams,
    ) -> Result<()> {
        let binding = binding.unwrap_or("default");

        let wg = crossbeam_utils::sync::WaitGroup::new();
        // Spins up a new thread subscribed to the "wasmbus.{capid}.{binding}" subject
        spawns::spawn_actor(
            wg.clone(),
            actor.token.claims,
            actor.bytes.clone(),
            Some(wasi),
            false,
            Some(binding.to_string()),
            self.bus.clone(),
            self.middlewares.clone(),
            self.caps.clone(),
            self.bindings.clone(),
            self.claims.clone(),
            self.terminators.clone(),
            self.key.clone(),
            self.authorizer.clone(),
        )?;
        wg.wait();
        Ok(())
    }

    /// Removes an actor from the host. Notifies the actor's processing thread to terminate,
    /// which will in turn attempt to unbind that actor from all previously bound capability providers
    pub fn remove_actor(&self, pk: &str) -> Result<()> {
        self.terminators.read().unwrap()
            [&bus::actor_subject(self.ns.as_ref().map(String::as_str), pk)]
            .send(true)
            .unwrap();
        Ok(())
    }

    /// Replaces one running actor with another live actor with no message loss. Note that
    /// the time it takes to perform this replacement can cause pending messages from capability
    /// providers (e.g. messages from subscriptions or HTTP requests) to build up in a backlog,
    /// so make sure the new actor can handle this stream of these delayed messages
    pub fn replace_actor(&self, new_actor: Actor) -> Result<()> {
        crate::inthost::replace_actor(&self.key, self.bus.clone(), new_actor)
    }

    /// Adds a middleware item to the middleware processing pipeline
    pub fn add_middleware(&self, mid: impl Middleware) {
        self.middlewares.write().unwrap().push(Box::new(mid));
    }

    /// Adds a native capability provider plugin to the waSCC runtime. Note that because these capabilities are native,
    /// cross-platform support is not always guaranteed.
    pub fn add_native_capability(&self, capability: NativeCapability) -> Result<()> {
        let capid = capability.id();
        if self
            .caps
            .read()
            .unwrap()
            .contains_key(&RouteKey::new(&capability.binding_name, &capability.id()))
        {
            return Err(errors::new(errors::ErrorKind::CapabilityProvider(format!(
                "Capability provider {} cannot be bound to the same name ({}) twice, loading failed.", capid, capability.binding_name
            ))));
        }
        self.caps.write().unwrap().insert(
            RouteKey::new(&capability.binding_name, &capability.descriptor.id),
            capability.descriptor().clone(),
        );
        let wg = crossbeam_utils::sync::WaitGroup::new();
        spawns::spawn_native_capability(
            capability,
            self.bus.clone(),
            self.middlewares.clone(),
            self.bindings.clone(),
            self.terminators.clone(),
            self.plugins.clone(),
            wg.clone(),
            Arc::new(self.key.clone()),
        )?;
        wg.wait();
        Ok(())
    }

    /// Removes a native capability provider plugin from the waSCC runtime
    pub fn remove_native_capability(
        &self,
        capability_id: &str,
        binding_name: Option<String>,
    ) -> Result<()> {
        let b = binding_name.unwrap_or("default".to_string());
        let subject =
            bus::provider_subject(self.ns.as_ref().map(String::as_str), capability_id, &b);
        if let Some(terminator) = self.terminators.read().unwrap().get(&subject) {
            terminator.send(true).unwrap();
            Ok(())
        } else {
            Err(errors::new(errors::ErrorKind::MiscHost(
                "No such capability".into(),
            )))
        }
    }

    /// Binds an actor to a capability provider with a given configuration. If the binding name
    /// is `None` then the default binding name will be used. An actor can only have one default
    /// binding per capability provider.
    pub fn bind_actor(
        &self,
        actor: &str,
        capid: &str,
        binding_name: Option<String>,
        config: HashMap<String, String>,
    ) -> Result<()> {
        let claims = self.claims.read().unwrap().get(actor).cloned();
        if claims.is_none() {
            return Err(errors::new(errors::ErrorKind::MiscHost(
                "Attempted to bind non-existent actor".to_string(),
            )));
        }
        let c = claims.unwrap().clone();
        let binding = binding_name.unwrap_or("default".to_string());
        if !authz::can_invoke(&c, capid, OP_BIND_ACTOR) {
            return Err(errors::new(errors::ErrorKind::Authorization(format!(
                "Unauthorized binding: actor {} is not authorized to use capability {}.",
                actor, capid
            ))));
        } else {
            if !self.authorizer.read().unwrap().can_invoke(
                &c,
                &WasccEntity::Capability {
                    capid: capid.to_string(),
                    binding: binding.to_string(),
                },
                OP_BIND_ACTOR,
            ) {
                return Err(errors::new(errors::ErrorKind::Authorization(format!(
                    "Unauthorized binding: actor {} is not authorized to use capability {}.",
                    actor, capid
                ))));
            }
        }

        info!(
            "Attempting to bind actor {} to {},{}",
            actor, &binding, capid
        );

        let tgt_subject = if (actor == capid || actor == SYSTEM_ACTOR) && capid.starts_with("M") {
            // manually injected actor configuration
            bus::actor_subject(self.ns.as_ref().map(String::as_str), actor)
        } else {
            bus::provider_subject(self.ns.as_ref().map(String::as_str), capid, &binding)
        };
        trace!("Binding subject: {}", tgt_subject);
        let inv = inthost::gen_config_invocation(
            &self.key,
            actor,
            capid,
            c.clone(),
            binding.clone(),
            config.clone(),
        );
        match self.bus.invoke(&tgt_subject, inv) {
            Ok(inv_r) => {
                if let Some(e) = inv_r.error {
                    Err(errors::new(errors::ErrorKind::CapabilityProvider(format!(
                        "Failed to configure {},{} - {}",
                        binding, capid, e
                    ))))
                } else {
                    self.record_binding(
                        actor,
                        capid,
                        &binding,
                        &CapabilityConfiguration {
                            module: actor.to_string(),
                            values: config,
                        },
                    )?;
                    #[cfg(feature = "lattice")]
                    let _ = self.bus.publish_event(BusEvent::ActorBindingCreated {
                        actor: actor.to_string(),
                        capid: capid.to_string(),
                        instance_name: binding.to_string(),
                        host: self.id(),
                    });
                    Ok(())
                }
            }
            Err(e) => Err(errors::new(errors::ErrorKind::CapabilityProvider(format!(
                "Failed to configure {},{} - {}",
                binding, capid, e
            )))),
        }
    }

    /// Configure the Gantry client connection information to be used when actors
    /// are loaded remotely via `Actor::from_gantry`
    #[cfg(feature = "gantry")]
    pub fn configure_gantry(&self, nats_urls: Vec<String>, jwt: &str, seed: &str) -> Result<()> {
        *self.gantry_client.write().unwrap() =
            Some(gantryclient::Client::new(nats_urls, jwt, seed));
        Ok(())
    }

    /// Invoke an operation handler on an actor directly. The caller is responsible for
    /// knowing ahead of time if the given actor supports the specified operation.
    pub fn call_actor(&self, actor: &str, operation: &str, msg: &[u8]) -> Result<Vec<u8>> {
        if !self.claims.read().unwrap().contains_key(actor) {
            return Err(errors::new(errors::ErrorKind::MiscHost(
                "No such actor".into(),
            )));
        }
        let inv = Invocation::new(
            &self.key,
            WasccEntity::Actor(SYSTEM_ACTOR.to_string()),
            WasccEntity::Actor(actor.to_string()),
            operation,
            msg.to_vec(),
        );
        let tgt_subject = bus::actor_subject(self.ns.as_ref().map(String::as_str), actor);
        match self.bus.invoke(&tgt_subject, inv) {
            Ok(resp) => Ok(resp.msg),
            Err(e) => Err(e),
        }
    }

    /// Returns the full set of JWT claims for a given actor, if that actor is running in the host
    pub fn claims_for_actor(&self, pk: &str) -> Option<Claims<wascap::jwt::Actor>> {
        self.claims.read().unwrap().get(pk).cloned()
    }

    /// Applies a manifest JSON or YAML file to set up a host's actors, capability providers,
    /// and actor bindings
    #[cfg(feature = "manifest")]
    pub fn apply_manifest(&self, manifest: HostManifest) -> Result<()> {
        {
            let mut labels = self.labels.write().unwrap();
            for (label, label_value) in manifest.labels {
                if !RESTRICTED_LABELS.contains(&label.as_ref()) {
                    labels.insert(label.to_string(), label_value.to_string());
                }
            }
        }
        for actor in manifest.actors {
            #[cfg(feature = "gantry")]
            self.add_actor_gantry_first(&actor)?;

            #[cfg(not(feature = "gantry"))]
            self.add_actor(Actor::from_file(&actor)?)?;
        }
        for cap in manifest.capabilities {
            // for now, supports only file paths
            self.add_native_capability(NativeCapability::from_file(cap.path, cap.binding_name)?)?;
        }
        for config in manifest.bindings {
            self.bind_actor(
                &config.actor,
                &config.capability,
                config.binding,
                config.values.unwrap_or(HashMap::new()),
            )?;
        }
        Ok(())
    }

    #[cfg(feature = "gantry")]
    fn add_actor_gantry_first(&self, actor: &str) -> Result<()> {
        if actor.len() == 56 && actor.starts_with('M') {
            // This is an actor's public subject
            self.add_actor_from_gantry(actor)
        } else {
            self.add_actor(Actor::from_file(&actor)?)
        }
    }

    /// Returns the list of actors registered in the host
    pub fn actors(&self) -> Vec<SubjectClaimsPair> {
        authz::get_all_claims(self.claims.clone())
    }

    /// Returns the list of capability providers registered in the host. The key is a tuple of (binding, capability ID)
    pub fn capabilities(&self) -> HashMap<(String, String), CapabilityDescriptor> {
        let lock = self.caps.read().unwrap();
        let mut res = HashMap::new();
        for (rk, descriptor) in lock.iter() {
            res.insert(
                (rk.binding_name.to_string(), rk.capid.to_string()),
                descriptor.clone(),
            );
        }
        res
    }

    /// Returns the list of actors in the host that contain all of the tags in the
    /// supplied parameter
    pub fn actors_by_tag(&self, tags: &[&str]) -> Vec<String> {
        let mut actors = vec![];

        for (actor, claims) in self.claims.read().unwrap().iter() {
            if let Some(actor_tags) = claims.metadata.as_ref().and_then(|m| m.tags.as_ref()) {
                if tags.iter().all(|&t| actor_tags.contains(&t.to_string())) {
                    actors.push(actor.to_string())
                }
            }
        }

        actors
    }

    /// Attempts to perform a graceful shutdown of the host by removing all actors in
    /// the host and then removing all capability providers. This function is not guaranteed to
    /// block and wait for the shutdown to finish
    pub fn shutdown(&self) -> Result<()> {
        let actors = self.actors();
        for (pk, _claims) in actors {
            self.remove_actor(&pk)?;
        }
        let caps = self.capabilities();
        for (binding_name, capid) in caps.keys() {
            self.remove_native_capability(&capid, Some(binding_name.to_string()))?;
        }
        self.bus.disconnect();
        Ok(())
    }

    /// Returns the public key of the host
    pub fn id(&self) -> String {
        self.key.public_key()
    }
}