holochain_conductor_api/
admin_interface.rs

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