holochain_conductor_api/
admin_interface.rs

1use crate::peer_meta::AgentMetaInfo;
2use crate::{AppInfo, FullStateDump, RevokeAgentKeyPayload, StorageInfo};
3use holo_hash::*;
4use holochain_types::prelude::*;
5use holochain_types::websocket::AllowedOrigins;
6use holochain_zome_types::cell::CellId;
7use kitsune2_api::Url;
8use std::collections::{BTreeMap, HashMap};
9
10/// Represents the available conductor functions to call over an admin interface.
11///
12/// Enum variants follow a general convention of `verb_noun` as opposed to
13/// the `noun_verb` of responses.
14///
15/// # Errors
16///
17/// Returns an [`AdminResponse::Error`] with a reason why the request failed.
18// Expects a serialized object with any contents of the enum on a key `data`
19// and the enum variant on a key `type`, e.g.
20// `{ type: 'enable_app', data: { installed_app_id: 'test_app' } }`
21#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes)]
22#[serde(tag = "type", content = "value", rename_all = "snake_case")]
23pub enum AdminRequest {
24    /// Set up and register one or more new admin interfaces
25    /// as specified by a list of configurations.
26    ///
27    /// # Returns
28    ///
29    /// [`AdminResponse::AdminInterfacesAdded`]
30    AddAdminInterfaces(Vec<crate::config::AdminInterfaceConfig>),
31
32    /// Register a DNA for later app installation.
33    ///
34    /// Stores the given DNA into the Holochain DNA database and returns the hash of it.
35    ///
36    /// # Returns
37    ///
38    /// [`AdminResponse::DnaRegistered`]
39    RegisterDna(Box<RegisterDnaPayload>),
40
41    /// Get the definition of a DNA.
42    ///
43    /// # Returns
44    ///
45    /// [`AdminResponse::DnaDefinitionReturned`]
46    GetDnaDefinition(Box<DnaHash>),
47
48    /// Update coordinator zomes for an already installed DNA.
49    ///
50    /// Replaces any installed coordinator zomes with the same zome name.
51    /// If the zome name doesn't exist then the coordinator zome is appended
52    /// to the current list of coordinator zomes.
53    ///
54    /// # Returns
55    ///
56    /// [`AdminResponse::CoordinatorsUpdated`]
57    UpdateCoordinators(Box<UpdateCoordinatorsPayload>),
58
59    /// Install an app using an [`AppBundle`].
60    ///
61    /// Triggers genesis to be run on all Cells and to be stored.
62    /// An app is intended for use by
63    /// one and only one Agent and for that reason it takes an `AgentPubKey` and
64    /// installs all the DNAs with that `AgentPubKey`, forming new cells.
65    /// See [`InstallAppPayload`] for full details on the configuration.
66    ///
67    /// Note that the new app will not be enabled automatically after installation
68    /// and can be enabled by calling [`EnableApp`].
69    ///
70    /// # Returns
71    ///
72    /// [`AdminResponse::AppInstalled`]
73    ///
74    /// [`EnableApp`]: AdminRequest::EnableApp
75    InstallApp(Box<InstallAppPayload>),
76
77    /// Uninstalls the app specified by argument `installed_app_id` from the conductor.
78    ///
79    /// The app will be removed from the list of installed apps, and any cells
80    /// which were referenced only by this app will be disabled and removed, clearing up
81    /// any persisted data.
82    /// Cells which are still referenced by other installed apps will not be removed.
83    ///
84    /// # Returns
85    ///
86    /// [`AdminResponse::AppUninstalled`]
87    UninstallApp {
88        /// The app ID to uninstall
89        installed_app_id: InstalledAppId,
90
91        /// If anything would prevent this app from being uninstalled, such as the existence
92        /// of protected dependency to one of its cells, this flag will force the uninstallation.
93        /// This will generally lead to bad outcomes, and should not be used unless you're
94        /// aware of the consequences.
95        #[serde(default)]
96        force: bool,
97    },
98
99    /// List the hashes of all installed DNAs.
100    ///
101    /// # Returns
102    ///
103    /// [`AdminResponse::DnasListed`]
104    ListDnas,
105
106    /// Generate a new [`AgentPubKey`].
107    ///
108    /// # Returns
109    ///
110    /// [`AdminResponse::AgentPubKeyGenerated`]
111    GenerateAgentPubKey,
112
113    /// Revoke an agent key for an app.
114    ///
115    /// When an agent key is revoked, it becomes invalid and can no longer be used to author
116    /// actions for that app. The key is revoked in the Deepkey service if installed and deleted on
117    /// the source chains of all cells of the app, making them read-only. Cloning a cell of this app will fail.
118    ///
119    /// If the key could not be deleted from all cells, this call can be re-attempted to delete the key from the remaining cells.
120    ///
121    /// # Returns
122    ///
123    /// [`AdminResponse::AgentKeyRevoked`]
124    RevokeAgentKey(Box<RevokeAgentKeyPayload>),
125
126    /// List the IDs of all live cells currently running in the conductor.
127    ///
128    /// # Returns
129    ///
130    /// [`AdminResponse::CellIdsListed`]
131    ListCellIds,
132
133    /// List the apps and their information that are installed in the conductor.
134    ///
135    /// Results are sorted by the `installed_at` timestamp of the app, in descending order.
136    ///
137    /// If `status_filter` is `Some(_)`, it will return only the apps with the specified status.
138    ///
139    /// # Returns
140    ///
141    /// [`AdminResponse::AppsListed`]
142    ListApps {
143        /// An optional status to filter the list of apps by
144        status_filter: Option<AppStatusFilter>,
145    },
146
147    /// Changes the specified app from a disabled to an enabled state in the conductor.
148    ///
149    /// It is likely to want to call this after calling [`AdminRequest::InstallApp`], since a freshly
150    /// installed app is not enabled automatically. Once the app is enabled,
151    /// zomes can be immediately called and it will also be loaded and enabled automatically on any reboot of the conductor.
152    ///
153    /// # Returns
154    ///
155    /// [`AdminResponse::AppEnabled`]
156    EnableApp {
157        /// The app ID to enable
158        installed_app_id: InstalledAppId,
159    },
160
161    /// Changes the specified app from an enabled to a disabled state in the conductor.
162    ///
163    /// When an app is disabled, zome calls can no longer be made, and the app will not be
164    /// loaded on a reboot of the conductor.
165    ///
166    /// # Returns
167    ///
168    /// [`AdminResponse::AppDisabled`]
169    DisableApp {
170        /// The app ID to disable
171        installed_app_id: InstalledAppId,
172    },
173
174    /// Open up a new websocket for processing [`AppRequest`]s. Any active app will be
175    /// callable via the attached app interface.
176    ///
177    /// **NB:** App interfaces are persisted when shutting down the conductor and are
178    /// restored when restarting the conductor. Unused app interfaces are _not_ cleaned
179    /// up. It is therefore recommended to reuse existing interfaces. They can be queried
180    /// with the call [`AdminRequest::ListAppInterfaces`].
181    ///
182    /// # Returns
183    ///
184    /// [`AdminResponse::AppInterfaceAttached`]
185    ///
186    /// # Arguments
187    ///
188    /// Optionally a `port` parameter can be passed to this request. If it is `None`,
189    /// a free port is chosen by the conductor.
190    ///
191    /// An `allowed_origins` parameter to control which origins are allowed to connect
192    /// to the app interface.
193    ///
194    /// [`AppRequest`]: super::AppRequest
195    AttachAppInterface {
196        /// Optional port number
197        port: Option<u16>,
198
199        /// Allowed origins for this app interface.
200        ///
201        /// This should be one of:
202        /// - A comma separated list of origins - `http://localhost:3000,http://localhost:3001`,
203        /// - A single origin - `http://localhost:3000`,
204        /// - Any origin - `*`
205        ///
206        /// Connections from any origin which is not permitted by this config will be rejected.
207        allowed_origins: AllowedOrigins,
208
209        /// Optionally bind this app interface to a specific installed app.
210        ///
211        /// If this is `None` then the interface can be used to establish a connection for any app.
212        ///
213        /// If this is `Some` then the interface will only accept connections for the specified app.
214        /// Those connections will only be able to make calls to and receive signals from that app.
215        installed_app_id: Option<InstalledAppId>,
216    },
217
218    /// List all the app interfaces currently attached with [`AttachAppInterface`].
219    ///
220    /// # Returns
221    ///
222    /// [`AdminResponse::AppInterfacesListed`], a list of websocket ports that can
223    /// process [`AppRequest`]s.
224    ///
225    /// [`AttachAppInterface`]: AdminRequest::AttachAppInterface
226    /// [`AppRequest`]: super::AppRequest
227    ListAppInterfaces,
228
229    /// Dump the state of the cell specified by argument `cell_id`,
230    /// including its chain, as a string containing JSON.
231    ///
232    /// # Returns
233    ///
234    /// [`AdminResponse::StateDumped`]
235    DumpState {
236        /// The cell ID for which to dump state
237        cell_id: Box<CellId>,
238    },
239
240    /// Dump the state of the conductor, including the in-memory representation
241    /// and the persisted ConductorState, as JSON.
242    ///
243    /// # Returns
244    ///
245    /// [`AdminResponse::ConductorStateDumped`]
246    DumpConductorState,
247
248    /// Dump the full state of the Cell specified by argument `cell_id`,
249    /// including its chain and DHT shard, as a string containing JSON.
250    ///
251    /// **Warning**: this API call is subject to change, and will not be available to hApps.
252    /// This is meant to be used by introspection tooling.
253    ///
254    /// Note that the response to this call can be very big, as it's requesting for
255    /// the full database of the cell.
256    ///
257    /// Also note that while DHT ops about private entries will be returned (like `StoreRecord`),
258    /// the entry in itself will be missing, as it's not actually stored publicly in the DHT shard.
259    ///
260    /// # Returns
261    ///
262    /// [`AdminResponse::FullStateDumped`]
263    DumpFullState {
264        /// The cell ID for which to dump the state
265        cell_id: Box<CellId>,
266        /// The last seen DhtOp RowId, returned in the full dump state.
267        /// Only DhtOps with RowId greater than the cursor will be returned.
268        dht_ops_cursor: Option<u64>,
269    },
270
271    /// Dump the network metrics tracked by kitsune.
272    ///
273    /// # Returns
274    ///
275    /// [`AdminResponse::NetworkMetricsDumped`]
276    DumpNetworkMetrics {
277        /// If set, limits the metrics dumped to a single DNA hash space.
278        #[serde(default)]
279        dna_hash: Option<DnaHash>,
280
281        /// Whether to include a DHT summary.
282        ///
283        /// You need a dump from multiple nodes in order to make a comparison, so this is not
284        /// requested by default.
285        #[serde(default)]
286        include_dht_summary: bool,
287    },
288
289    /// Dump network statistics from the Kitsune2 networking transport module.
290    ///
291    /// # Returns
292    ///
293    /// [`AdminResponse::NetworkStatsDumped`]
294    DumpNetworkStats,
295
296    /// Add a list of agents to this conductor's peer store.
297    ///
298    /// This is a way of shortcutting peer discovery and is useful for testing.
299    ///
300    /// It is also helpful if you know other
301    /// agents on the network and they can send you
302    /// their agent info.
303    ///
304    /// # Returns
305    ///
306    /// [`AdminResponse::AgentInfoAdded`]
307    AddAgentInfo {
308        /// list of signed agent info to add to peer store
309        agent_infos: Vec<String>,
310    },
311
312    /// Request the [`kitsune2_api::AgentInfoSigned`] stored in this conductor's
313    /// peer store.
314    ///
315    /// You can:
316    /// - Get all agent info by leaving `dna_hashes` to `None`.
317    /// - Get agent info for specific dna hashes by setting the `dna_hashes` argument.
318    ///
319    /// This is how you can send your agent info to another agent.
320    /// It is also useful for testing across networks.
321    ///
322    /// # Returns
323    ///
324    /// [`AdminResponse::AgentInfo`]
325    AgentInfo {
326        /// Optionally choose the agent info of a specific cell.
327        cell_id: Option<CellId>,
328    },
329
330    /// Request the contents of the peer meta store(s) related to
331    /// the given dna hashes for the agent at the given Url.
332    ///
333    /// If `dna_hashes` is set to `None` it returns the contents
334    /// for all dnas that the agent is part of.
335    ///
336    /// # Returns
337    ///
338    /// [`AdminResponse::AgentMetaInfo`]
339    AgentMetaInfo {
340        url: Url,
341        dna_hashes: Option<Vec<DnaHash>>,
342    },
343
344    /// "Graft" [`Record`]s onto the source chain of the specified [`CellId`].
345    ///
346    /// The records must form a valid chain segment (ascending sequence numbers,
347    /// and valid `prev_action` references). If the first record contains a `prev_action`
348    /// which matches the existing records, then the new records will be "grafted" onto
349    /// the existing chain at that point, and any other records following that point which do
350    /// not match the new records will be removed.
351    ///
352    /// If this operation is called when there are no forks, the final state will also have
353    /// no forks.
354    ///
355    /// **BEWARE** that this may result in the deletion of data! Any existing records which form
356    /// a fork with respect to the new records will be deleted.
357    ///
358    /// All records must be authored and signed by the same agent.
359    /// The [`DnaFile`] (but not necessarily the cell) must already be installed
360    /// on this conductor.
361    ///
362    /// Care is needed when using this command as it can result in
363    /// an invalid chain.
364    /// Additionally, if conflicting source chain records are
365    /// inserted on different nodes, then the chain will be forked.
366    ///
367    /// If an invalid or forked chain is inserted
368    /// and then pushed to the DHT, it can't be undone.
369    ///
370    /// Note that the cell does not need to exist to run this command.
371    /// It is possible to insert records into a source chain before
372    /// the cell is created. This can be used to restore from backup.
373    ///
374    /// If the cell is installed, it is best to call [`AdminRequest::DisableApp`]
375    /// before running this command, as otherwise the chain head may move.
376    /// If `truncate` is true, the chain head is not checked and any new
377    /// records will be lost.
378    ///
379    /// # Returns
380    ///
381    /// [`AdminResponse::RecordsGrafted`]
382    GraftRecords {
383        /// The cell that the records are being inserted into.
384        cell_id: CellId,
385        /// If this is `true`, then the records will be validated before insertion.
386        /// This is much slower but is useful for verifying the chain is valid.
387        ///
388        /// If this is `false`, then records will be inserted as is.
389        /// This could lead to an invalid chain.
390        validate: bool,
391        /// The records to be inserted into the source chain.
392        records: Vec<Record>,
393    },
394
395    /// Request capability grant for making zome calls.
396    ///
397    /// # Returns
398    ///
399    /// [`AdminResponse::ZomeCallCapabilityGranted`]
400    GrantZomeCallCapability(Box<GrantZomeCallCapabilityPayload>),
401
402    /// Request capability grant info for all cells in the app.
403    ///
404    /// # Returns
405    ///
406    /// [`AdminResponse::CapabilityGrantsInfo`]
407    ListCapabilityGrants {
408        installed_app_id: String,
409        include_revoked: bool,
410    },
411
412    /// Delete a clone cell that was previously disabled.
413    ///
414    /// # Returns
415    ///
416    /// [`AdminResponse::CloneCellDeleted`]
417    DeleteCloneCell(Box<DeleteCloneCellPayload>),
418
419    /// Info about storage used by apps
420    ///
421    /// # Returns
422    ///
423    /// [`AdminResponse::StorageInfo`]
424    StorageInfo,
425
426    /// Connecting to an app over an app websocket requires an authentication token. This endpoint
427    /// is used to issue those tokens for use by app clients.
428    ///
429    /// # Returns
430    ///
431    /// [`AdminResponse::AppAuthenticationTokenIssued`]
432    IssueAppAuthenticationToken(IssueAppAuthenticationTokenPayload),
433
434    /// Revoke an issued app authentication token.
435    ///
436    /// # Returns
437    ///
438    /// [`AdminResponse::AppAuthenticationTokenRevoked`]
439    RevokeAppAuthenticationToken(AppAuthenticationToken),
440
441    /// Find installed cells which use a DNA that's forward-compatible with the given DNA hash.
442    /// Namely, this finds cells with DNAs whose manifest lists the given DNA hash in its `lineage` field.
443    #[cfg(feature = "unstable-migration")]
444    GetCompatibleCells(DnaHash),
445}
446
447/// Represents the possible responses to an [`AdminRequest`]
448/// and follows a general convention of `noun_verb` as opposed to
449/// the `verb_noun` of `AdminRequest`.
450///
451/// Will serialize as an object with any contents of the enum on a key `data`
452/// and the enum variant on a key `type`, e.g.
453/// `{ type: 'app_interface_attached', data: { port: 4000 } }`
454#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes)]
455#[cfg_attr(test, derive(Clone))]
456#[serde(tag = "type", content = "value", rename_all = "snake_case")]
457pub enum AdminResponse {
458    /// Can occur in response to any [`AdminRequest`].
459    ///
460    /// There has been an error during the handling of the request.
461    Error(ExternalApiWireError),
462
463    /// The successful response to an [`AdminRequest::RegisterDna`]
464    DnaRegistered(DnaHash),
465
466    /// The successful response to an [`AdminRequest::GetDnaDefinition`]
467    DnaDefinitionReturned(DnaDef),
468
469    /// The successful response to an [`AdminRequest::UpdateCoordinators`]
470    CoordinatorsUpdated,
471
472    /// The successful response to an [`AdminRequest::InstallApp`].
473    ///
474    /// The resulting [`AppInfo`] contains the app ID,
475    /// the [`RoleName`]s and, most usefully, [`CellInfo`](crate::CellInfo)s
476    /// of the newly installed DNAs.
477    AppInstalled(AppInfo),
478
479    /// The successful response to an [`AdminRequest::UninstallApp`].
480    ///
481    /// It means the app was uninstalled successfully.
482    AppUninstalled,
483
484    /// The successful response to an [`AdminRequest::AddAdminInterfaces`].
485    ///
486    /// It means the `AdminInterface`s have successfully been added.
487    AdminInterfacesAdded,
488
489    /// The successful response to an [`AdminRequest::GenerateAgentPubKey`].
490    ///
491    /// Contains a new [`AgentPubKey`] generated by the keystore.
492    AgentPubKeyGenerated(AgentPubKey),
493
494    /// The successful response to an [`AdminRequest::RevokeAgentKey`].
495    ///
496    /// Contains a list of errors of the cells where deletion was unsuccessful.
497    ///
498    /// If the key could not be deleted from all cells, the call
499    /// [`AdminRequest::RevokeAgentKey`] can be re-attempted to delete the key from the remaining cells.
500    AgentKeyRevoked(Vec<(CellId, String)>),
501
502    /// The successful response to an [`AdminRequest::ListDnas`].
503    ///
504    /// Contains a list of the hashes of all installed DNAs.
505    DnasListed(Vec<DnaHash>),
506
507    /// The successful response to an [`AdminRequest::ListCellIds`].
508    ///
509    /// Contains a list of all the cell IDs in the conductor.
510    CellIdsListed(Vec<CellId>),
511
512    /// The successful response to an [`AdminRequest::ListApps`].
513    ///
514    /// Contains a list of the `InstalledAppInfo` of the installed apps in the conductor.
515    AppsListed(Vec<AppInfo>),
516
517    /// The successful response to an [`AdminRequest::AttachAppInterface`].
518    ///
519    /// Contains the port number of the attached app interface.
520    AppInterfaceAttached {
521        /// Networking port of the new `AppInterfaceApi`
522        port: u16,
523    },
524
525    /// The list of attached app interfaces.
526    AppInterfacesListed(Vec<AppInterfaceInfo>),
527
528    /// The successful response to an [`AdminRequest::EnableApp`].
529    ///
530    /// It means the app was enabled successfully. If it was possible to
531    /// put the app in a running state, it will be running, otherwise it will
532    /// be paused.
533    ///
534    /// Contains the app info and list of errors for cells that could not be enabled.
535    AppEnabled {
536        app: AppInfo,
537        errors: Vec<(CellId, String)>,
538    },
539
540    /// The successful response to an [`AdminRequest::DisableApp`].
541    ///
542    /// It means the app was disabled successfully.
543    AppDisabled,
544
545    /// The successful response to an [`AdminRequest::DumpState`].
546    ///
547    /// The result contains a string of serialized JSON data which can be deserialized to access the
548    /// full state dump and inspect the source chain.
549    StateDumped(String),
550
551    /// The successful response to an [`AdminRequest::DumpFullState`].
552    ///
553    /// The result contains a string of serialized JSON data which can be deserialized to access the
554    /// full state dump and inspect the source chain.
555    ///
556    /// Note that this result can be very big, as it's requesting the full database of the cell.
557    FullStateDumped(FullStateDump),
558
559    /// The successful response to an [`AdminRequest::DumpConductorState`].
560    ///
561    /// Simply a JSON serialized snapshot of `Conductor` and `ConductorState` from the `holochain` crate.
562    ConductorStateDumped(String),
563
564    /// The successful result of a call to [`AdminRequest::DumpNetworkMetrics`].
565    NetworkMetricsDumped(HashMap<DnaHash, Kitsune2NetworkMetrics>),
566
567    /// The successful result of a call to [`AdminRequest::DumpNetworkStats`].
568    NetworkStatsDumped(kitsune2_api::TransportStats),
569
570    /// The successful response to an [`AdminRequest::AddAgentInfo`].
571    ///
572    /// This means the agent info was successfully added to the peer store.
573    AgentInfoAdded,
574
575    /// The successful response to an [`AdminRequest::AgentInfo`].
576    ///
577    /// This is all the agent info that was found for the request.
578    AgentInfo(Vec<String>),
579
580    /// The successful response to an [`AdminRequest::AgentMetaInfo`].
581    ///
582    /// A JSON formatted string.
583    AgentMetaInfo(BTreeMap<DnaHash, BTreeMap<String, AgentMetaInfo>>),
584
585    /// The successful response to an [`AdminRequest::GraftRecords`].
586    RecordsGrafted,
587
588    /// The successful response to an [`AdminRequest::GrantZomeCallCapability`].
589    ZomeCallCapabilityGranted,
590
591    /// The successful response to an [`AdminRequest::ListCapabilityGrants`].
592    CapabilityGrantsInfo(AppCapGrantInfo),
593
594    /// The successful response to an [`AdminRequest::DeleteCloneCell`].
595    CloneCellDeleted,
596
597    /// The successful response to an [`AdminRequest::StorageInfo`].
598    StorageInfo(StorageInfo),
599
600    /// The successful response to an [`AdminRequest::IssueAppAuthenticationToken`].
601    AppAuthenticationTokenIssued(AppAuthenticationTokenIssued),
602
603    /// The successful response to an [`AdminRequest::RevokeAppAuthenticationToken`].
604    AppAuthenticationTokenRevoked,
605
606    /// The successful response to an [`AdminRequest::GetCompatibleCells`].
607    #[cfg(feature = "unstable-migration")]
608    CompatibleCells(CompatibleCells),
609}
610
611#[cfg(feature = "unstable-migration")]
612pub type CompatibleCells =
613    std::collections::BTreeSet<(InstalledAppId, std::collections::BTreeSet<CellId>)>;
614
615/// Error type that goes over the websocket wire.
616/// This intends to be application developer facing
617/// so it should be readable and relevant
618#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes, Clone)]
619#[serde(tag = "type", content = "value", rename_all = "snake_case")]
620pub enum ExternalApiWireError {
621    // TODO: B-01506 Constrain these errors so they are relevant to
622    // application developers and what they would need
623    // to react to using code (i.e. not just print)
624    /// Any internal error
625    InternalError(String),
626    /// The input to the API failed to deseralize.
627    Deserialization(String),
628    /// The DNA path provided was invalid.
629    DnaReadError(String),
630    /// There was an error in the ribosome.
631    RibosomeError(String),
632    /// Error activating app.
633    ActivateApp(String),
634    /// The zome call failed authentication.
635    ///
636    /// [How to sign zome calls.](crate::AppRequest::CallZome)
637    ZomeCallAuthenticationFailed(String),
638    /// The zome call is unauthorized.
639    ZomeCallUnauthorized(String),
640    /// A countersigning session has failed.
641    CountersigningSessionError(String),
642}
643
644impl ExternalApiWireError {
645    /// Convert the error from the display.
646    pub fn internal<T: std::fmt::Display>(e: T) -> Self {
647        // Display format is used because
648        // this version intended for users.
649        ExternalApiWireError::InternalError(e.to_string())
650    }
651}
652
653#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes, Clone)]
654#[serde(rename_all = "snake_case")]
655/// Filter for [`AdminRequest::ListApps`].
656///
657/// App Status is a combination of two pieces of independent state:
658/// - Enabled/Disabled, which is a designation set by the user via the conductor interface.
659/// - Running/Stopped, which is a fact about the reality of the app in the course of its operation.
660pub enum AppStatusFilter {
661    /// Filter on apps which are Enabled, which can include both Running and Paused apps.
662    Enabled,
663    /// Filter only on apps which are Disabled.
664    Disabled,
665    /// Filter on apps which are currently Running (meaning they are also Enabled).
666    Running,
667    /// Filter on apps which are Stopped, i.e. not Running.
668    /// This includes apps in the Disabled status, as well as the Paused status.
669    Stopped,
670    /// Filter only on Paused apps.
671    Paused,
672}
673
674/// Informational response for listing app interfaces.
675#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes, Clone)]
676pub struct AppInterfaceInfo {
677    /// The port that the app interface is listening on.
678    pub port: u16,
679
680    /// The allowed origins for this app interface.
681    pub allowed_origins: AllowedOrigins,
682
683    /// The optional association with a specific installed app.
684    pub installed_app_id: Option<InstalledAppId>,
685}
686
687/// Request payload for [AdminRequest::IssueAppAuthenticationToken].
688#[derive(Debug, serde::Serialize, serde::Deserialize)]
689pub struct IssueAppAuthenticationTokenPayload {
690    /// The app ID to issue a connection token for.
691    pub installed_app_id: InstalledAppId,
692
693    /// The number of seconds that the token should be valid for. After this number of seconds, the
694    /// token will no longer be accepted by the conductor.
695    ///
696    /// This is 30s by default which is reasonably high but with [IssueAppAuthenticationTokenPayload::single_use]
697    /// set to `true`, the token will be invalidated after the first use anyway.
698    ///
699    /// Set this to 0 to create a token that does not expire.
700    #[serde(default = "default_expiry_seconds")]
701    pub expiry_seconds: u64,
702
703    /// Whether the token should be single-use. This is `true` by default and will cause the token
704    /// to be invalidated after the first use, irrespective of connection success.
705    ///
706    /// Set this to `false` to allow the token to be used multiple times.
707    #[serde(default = "default_single_use")]
708    pub single_use: bool,
709}
710
711fn default_expiry_seconds() -> u64 {
712    30
713}
714
715fn default_single_use() -> bool {
716    true
717}
718
719impl IssueAppAuthenticationTokenPayload {
720    /// Create a new payload for issuing a connection token for the specified app.
721    ///
722    /// The token will be valid for 30 seconds and for a single use.
723    pub fn for_installed_app_id(installed_app_id: InstalledAppId) -> Self {
724        installed_app_id.into()
725    }
726
727    /// Set the expiry time for the token.
728    pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self {
729        self.expiry_seconds = expiry_seconds;
730        self
731    }
732
733    /// Set whether the token should be single-use.
734    pub fn single_use(mut self, single_use: bool) -> Self {
735        self.single_use = single_use;
736        self
737    }
738}
739
740impl From<InstalledAppId> for IssueAppAuthenticationTokenPayload {
741    fn from(installed_app_id: InstalledAppId) -> Self {
742        // Defaults here should match the serde defaults in the struct definition
743        Self {
744            installed_app_id,
745            expiry_seconds: 30,
746            single_use: true,
747        }
748    }
749}
750
751/// A token issued by the conductor that can be used to authenticate a connection to an app interface.
752pub type AppAuthenticationToken = Vec<u8>;
753
754/// Response payload for [AdminResponse::AppAuthenticationTokenIssued].
755#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
756pub struct AppAuthenticationTokenIssued {
757    /// A token issued by the conductor that can be used to authenticate a connection to an app interface.
758    /// This is expected to be passed from the caller of the admin interface to the client that will
759    /// use the app interface. It should be treated as secret and kept from other parties.
760    pub token: AppAuthenticationToken,
761
762    /// The timestamp after which Holochain will consider the token invalid. This should be
763    /// considered informational only and the client should not rely on the token being accepted
764    /// following a client-side check that the token has not yet expired.
765    ///
766    /// If the token was created with [IssueAppAuthenticationTokenPayload::expiry_seconds] set to `0`
767    /// then this field will be `None`.
768    // TODO Kitsune type used in the conductor interface
769    pub expires_at: Option<Timestamp>,
770}
771
772#[cfg(test)]
773mod tests {
774    use serde::Deserialize;
775
776    use crate::{AdminRequest, AdminResponse, ExternalApiWireError};
777
778    #[test]
779    fn admin_request_serialization() {
780        use rmp_serde::Deserializer;
781
782        // make sure requests are serialized as expected
783        let request = AdminRequest::DisableApp {
784            installed_app_id: "some_id".to_string(),
785        };
786        let serialized_request = holochain_serialized_bytes::encode(&request).unwrap();
787        assert_eq!(
788            serialized_request,
789            vec![
790                130, 164, 116, 121, 112, 101, 171, 100, 105, 115, 97, 98, 108, 101, 95, 97, 112,
791                112, 165, 118, 97, 108, 117, 101, 129, 176, 105, 110, 115, 116, 97, 108, 108, 101,
792                100, 95, 97, 112, 112, 95, 105, 100, 167, 115, 111, 109, 101, 95, 105, 100
793            ]
794        );
795
796        let json_expected = r#"{"type":"disable_app","value":{"installed_app_id":"some_id"}}"#;
797        let mut deserializer = Deserializer::new(&*serialized_request);
798        let json_value: serde_json::Value = Deserialize::deserialize(&mut deserializer).unwrap();
799        let json_actual = serde_json::to_string(&json_value).unwrap();
800
801        assert_eq!(json_actual, json_expected);
802
803        // make sure responses are serialized as expected
804        let response = AdminResponse::Error(ExternalApiWireError::RibosomeError(
805            "error_text".to_string(),
806        ));
807        let serialized_response = holochain_serialized_bytes::encode(&response).unwrap();
808        assert_eq!(
809            serialized_response,
810            vec![
811                130, 164, 116, 121, 112, 101, 165, 101, 114, 114, 111, 114, 165, 118, 97, 108, 117,
812                101, 130, 164, 116, 121, 112, 101, 174, 114, 105, 98, 111, 115, 111, 109, 101, 95,
813                101, 114, 114, 111, 114, 165, 118, 97, 108, 117, 101, 170, 101, 114, 114, 111, 114,
814                95, 116, 101, 120, 116
815            ]
816        );
817
818        let json_expected =
819            r#"{"type":"error","value":{"type":"ribosome_error","value":"error_text"}}"#;
820        let mut deserializer = Deserializer::new(&*serialized_response);
821        let json_value: serde_json::Value = Deserialize::deserialize(&mut deserializer).unwrap();
822        let json_actual = serde_json::to_string(&json_value).unwrap();
823
824        assert_eq!(json_actual, json_expected);
825    }
826}