holochain_conductor_api/
admin_interface.rs

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