aranya-daemon-api 6.0.0

IPC API between the Aranya client and daemon
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#![allow(clippy::disallowed_macros)] // tarpc uses unreachable

use core::{error, fmt, hash::Hash, time::Duration};

pub use aranya_crypto::tls::CipherSuiteId;
use aranya_crypto::{
    dangerous::spideroak_crypto::hex::Hex,
    default::DefaultEngine,
    id::IdError,
    subtle::{Choice, ConstantTimeEq},
    zeroize::{Zeroize, ZeroizeOnDrop},
    EncryptionPublicKey, Engine,
};
use aranya_id::custom_id;
pub use aranya_policy_text::{text, InvalidText, Text};
use aranya_util::{error::ReportExt, Addr};
use buggy::Bug;
pub use semver::Version;
use serde::{Deserialize, Serialize};

pub mod afc;
pub mod quic_sync;

#[cfg(feature = "afc")]
pub use self::afc::*;
pub use self::quic_sync::*;

/// CE = Crypto Engine
pub type CE = DefaultEngine;
/// CS = Cipher Suite
pub type CS = <DefaultEngine as Engine>::CS;

/// An error returned by the API.
// TODO: add more error variants as needed for control flow.
#[derive(Serialize, Deserialize, Debug)]
pub enum Error {
    /// The requested resource does not exist.
    DoesNotExist(String),
    /// Any other error.
    Other(String),
}

impl Error {
    pub fn from_msg(err: &str) -> Self {
        Self::Other(err.into())
    }

    pub fn from_err<E: error::Error>(err: E) -> Self {
        Self::Other(ReportExt::report(&err).to_string())
    }
}

impl From<Bug> for Error {
    fn from(err: Bug) -> Self {
        Self::from_err(err)
    }
}

impl From<anyhow::Error> for Error {
    fn from(err: anyhow::Error) -> Self {
        Self::Other(format!("{err:?}"))
    }
}

impl From<InvalidText> for Error {
    fn from(err: InvalidText) -> Self {
        Self::Other(format!("{err:?}"))
    }
}

impl From<semver::Error> for Error {
    fn from(err: semver::Error) -> Self {
        Self::from_err(err)
    }
}

impl From<IdError> for Error {
    fn from(err: IdError) -> Self {
        Self::from_err(err)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DoesNotExist(msg) | Self::Other(msg) => msg.fmt(f),
        }
    }
}

impl error::Error for Error {}

pub type Result<T, E = Error> = core::result::Result<T, E>;

custom_id! {
    /// The Device ID.
    pub struct DeviceId;
}

custom_id! {
    /// The Team ID (a.k.a Graph ID).
    pub struct TeamId;
}

custom_id! {
    /// A label ID.
    pub struct LabelId;
}

custom_id! {
    /// A role ID.
    pub struct RoleId;
}

custom_id! {
    /// An identifier for any object with a unique Aranya ID defined in the policy.
    pub struct ObjectId;
}

/// A numerical rank used for authorization in the rank-based hierarchy.
///
/// Higher-ranked objects can operate on lower-ranked objects.
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Rank(i64);

impl Rank {
    /// Creates a new rank from a raw value.
    pub const fn new(value: i64) -> Self {
        Self(value)
    }

    /// Returns the raw rank value.
    pub const fn value(self) -> i64 {
        self.0
    }
}

impl fmt::Display for Rank {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl From<i64> for Rank {
    fn from(value: i64) -> Self {
        Self::new(value)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct Role {
    /// Uniquely identifies the role.
    pub id: RoleId,
    /// The role's friendly name.
    pub name: Text,
    /// The author of the role.
    pub author_id: DeviceId,
    /// Is this a default role?
    pub default: bool,
}

/// A device's public key bundle.
#[derive(Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct PublicKeyBundle {
    pub identity: Vec<u8>,
    pub signing: Vec<u8>,
    pub encryption: Vec<u8>,
}

impl fmt::Debug for PublicKeyBundle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PublicKeyBundle")
            .field("identity", &Hex::new(&*self.identity))
            .field("signing", &Hex::new(&*self.signing))
            .field("encryption", &Hex::new(&*self.encryption))
            .finish()
    }
}

// Note: any fields added to this type should be public
/// A configuration for adding a team in the daemon.
#[derive(Debug, Serialize, Deserialize)]
pub struct AddTeamConfig {
    pub team_id: TeamId,
    pub quic_sync: Option<AddTeamQuicSyncConfig>,
}

// Note: any fields added to this type should be public
/// A configuration for creating a team in the daemon.
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateTeamConfig {
    pub quic_sync: Option<CreateTeamQuicSyncConfig>,
}

/// A label.
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Label {
    pub id: LabelId,
    pub name: Text,
    pub author_id: DeviceId,
}

/// A PSK IKM.
#[derive(Clone, Serialize, Deserialize)]
pub struct Ikm([u8; SEED_IKM_SIZE]);

impl Ikm {
    /// Provides access to the raw IKM bytes.
    #[inline]
    pub fn raw_ikm_bytes(&self) -> &[u8; SEED_IKM_SIZE] {
        &self.0
    }
}

impl From<[u8; SEED_IKM_SIZE]> for Ikm {
    fn from(value: [u8; SEED_IKM_SIZE]) -> Self {
        Self(value)
    }
}

impl ConstantTimeEq for Ikm {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.0.ct_eq(&other.0)
    }
}

impl ZeroizeOnDrop for Ikm {}
impl Drop for Ikm {
    fn drop(&mut self) {
        self.0.zeroize()
    }
}

impl fmt::Debug for Ikm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Ikm").finish_non_exhaustive()
    }
}

/// A secret.
#[derive(Clone, Serialize, Deserialize)]
pub struct Secret(Box<[u8]>);

impl Secret {
    /// Provides access to the raw secret bytes.
    #[inline]
    pub fn raw_secret_bytes(&self) -> &[u8] {
        &self.0
    }
}

impl<T> From<T> for Secret
where
    T: Into<Box<[u8]>>,
{
    fn from(value: T) -> Self {
        Self(value.into())
    }
}

impl ConstantTimeEq for Secret {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.0.ct_eq(&other.0)
    }
}

impl ZeroizeOnDrop for Secret {}
impl Drop for Secret {
    fn drop(&mut self) {
        self.0.zeroize()
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Secret").finish_non_exhaustive()
    }
}

/// Configuration values for syncing with a peer
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncPeerConfig {
    /// The interval at which syncing occurs. If None, the peer will not be periodically synced.
    pub interval: Option<Duration>,
    /// Determines whether the peer will be scheduled for an immediate sync when added.
    pub sync_now: bool,
    /// Determines if the peer should be synced with when a hello message is received
    /// indicating they have a head that we don't have
    #[cfg(feature = "preview")]
    pub sync_on_hello: bool,
}

/// Valid channel operations for a label assignment.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum ChanOp {
    /// The device can only receive data in channels with this
    /// label.
    RecvOnly,
    /// The device can only send data in channels with this
    /// label.
    SendOnly,
    /// The device can send or receive data in channels with this
    /// label.
    SendRecv,
}

/// Permissions that can be granted to a role.
///
/// # Stability
///
/// New permissions may be added to the end of this enum without breaking
/// backward compatibility. Existing permissions will not be removed or
/// renamed.
///
/// # Deprecation
///
/// Deprecated variants are marked with `#[deprecated]` and will emit
/// compiler warnings when used. They remain in the enum for backward
/// compatibility — see the deprecation note on each variant for the
/// migration path.
// This enum is re-exported as `aranya_client::Permission`. New
// permissions may be added as the policy evolves, so `non_exhaustive`
// ensures downstream match statements continue to compile.
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum Perm {
    // # Team management
    //
    // The role can add a device to the team.
    AddDevice,
    // The role can remove a device from the team.
    RemoveDevice,
    // The role can terminate the team.
    TerminateTeam,

    // # Rank
    //
    // The role can change the rank of objects.
    ChangeRank,

    // # Roles
    //
    // The role can create a role.
    CreateRole,
    // The role can delete a role.
    DeleteRole,
    // The role can assign a role to other devices.
    AssignRole,
    // The role can revoke a role from other devices.
    RevokeRole,
    // The role can change permissions on roles.
    ChangeRolePerms,
    // The role can set up default roles.
    SetupDefaultRole,

    // # Labels
    //
    // The role can create a label.
    CreateLabel,
    // The role can delete a label.
    DeleteLabel,
    // The role can assign a label to a device.
    AssignLabel,
    // The role can revoke a label from a device.
    RevokeLabel,

    // # AFC
    //
    // The role can use AFC.
    CanUseAfc,
    // The role can create a unidirectional AFC channel.
    CreateAfcUniChannel,
}

// TODO(jdygert): tarpc does not cfg return types properly.
#[cfg(not(feature = "afc"))]
use afc_stub::{AfcReceiveChannelInfo, AfcSendChannelInfo, AfcShmInfo};
#[cfg(not(feature = "afc"))]
mod afc_stub {
    #[derive(Debug, serde::Serialize, serde::Deserialize)]
    pub enum Never {}
    pub type AfcShmInfo = Never;
    pub type AfcSendChannelInfo = Never;
    pub type AfcReceiveChannelInfo = Never;
}

#[tarpc::service]
pub trait DaemonApi {
    //
    // Misc
    //

    /// Returns the daemon's version.
    async fn version() -> Result<Version>;
    /// Gets local address the Aranya sync server is bound to.
    async fn aranya_local_addr() -> Result<Addr>;

    /// Gets the public key bundle for this device
    async fn get_public_key_bundle() -> Result<PublicKeyBundle>;
    /// Gets the public device id.
    async fn get_device_id() -> Result<DeviceId>;
    /// Returns the trace ID received in the current RPC context.
    ///
    /// Intended for test/debug validation of client<->daemon trace propagation.
    #[cfg(feature = "test-utils")]
    async fn test_trace_id() -> Result<String>;

    //
    // Syncing
    //

    /// Adds the peer for automatic periodic syncing.
    async fn add_sync_peer(addr: Addr, team: TeamId, config: SyncPeerConfig) -> Result<()>;
    /// Sync with peer immediately.
    async fn sync_now(addr: Addr, team: TeamId, cfg: Option<SyncPeerConfig>) -> Result<()>;

    /// Subscribe to hello notifications from a sync peer.
    #[cfg(feature = "preview")]
    async fn sync_hello_subscribe(
        peer: Addr,
        team: TeamId,
        graph_change_debounce: Duration,
        duration: Duration,
        schedule_delay: Duration,
    ) -> Result<()>;

    /// Unsubscribe from hello notifications from a sync peer.
    #[cfg(feature = "preview")]
    async fn sync_hello_unsubscribe(peer: Addr, team: TeamId) -> Result<()>;

    /// Removes the peer from automatic syncing.
    async fn remove_sync_peer(addr: Addr, team: TeamId) -> Result<()>;
    /// add a team to the local device store that was created by someone else. Not an aranya action/command.
    async fn add_team(cfg: AddTeamConfig) -> Result<()>;

    /// Remove a team from local device storage.
    async fn remove_team(team: TeamId) -> Result<()>;

    /// Create a new graph/team with the current device as the owner.
    async fn create_team(cfg: CreateTeamConfig) -> Result<TeamId>;
    /// Close the team.
    async fn close_team(team: TeamId) -> Result<()>;

    /// Encrypts the team's syncing PSK(s) for the peer.
    async fn encrypt_psk_seed_for_peer(
        team: TeamId,
        peer_enc_pk: EncryptionPublicKey<CS>,
    ) -> Result<WrappedSeed>;

    //
    // Device onboarding
    //

    /// Adds a device to the team with an optional initial role and
    /// explicit rank.
    async fn add_device_to_team(
        team: TeamId,
        keys: PublicKeyBundle,
        initial_role: Option<RoleId>,
        rank: Rank,
    ) -> Result<()>;
    /// Remove device from the team.
    async fn remove_device_from_team(team: TeamId, device: DeviceId) -> Result<()>;
    /// Returns all the devices on the team.
    async fn devices_on_team(team: TeamId) -> Result<Box<[DeviceId]>>;
    /// Returns the device's public key bundle.
    async fn device_public_key_bundle(team: TeamId, device: DeviceId) -> Result<PublicKeyBundle>;

    //
    // Role creation
    //

    /// Configures the team with default roles from policy.
    ///
    /// It returns the default roles that were created.
    async fn setup_default_roles(team: TeamId) -> Result<Box<[Role]>>;
    /// Creates a new role with the given rank.
    async fn create_role(team: TeamId, role_name: Text, rank: Rank) -> Result<Role>;
    /// Deletes a role.
    async fn delete_role(team: TeamId, role_id: RoleId) -> Result<()>;
    /// Returns the current team roles.
    async fn team_roles(team: TeamId) -> Result<Box<[Role]>>;

    //
    // Role management
    //

    /// Adds a permission to a role.
    async fn add_perm_to_role(team: TeamId, role: RoleId, perm: Perm) -> Result<()>;
    /// Removes a permission from a role.
    async fn remove_perm_from_role(team: TeamId, role: RoleId, perm: Perm) -> Result<()>;
    /// Queries all permissions assigned to a role.
    async fn query_role_perms(team: TeamId, role: RoleId) -> Result<Vec<Perm>>;
    /// Changes the rank of an object (device or label).
    ///
    /// Note: Role ranks cannot be changed after creation. This maintains the
    /// invariant that `role_rank > device_rank` for all devices assigned to
    /// the role. To effectively change a role's rank, create a new role with
    /// matching permissions at the desired rank, assign the new role to the
    /// devices that had the old role, then delete the old role.
    async fn change_rank(
        team: TeamId,
        object_id: ObjectId,
        old_rank: Rank,
        new_rank: Rank,
    ) -> Result<()>;
    /// Queries the rank of an object.
    async fn query_rank(team: TeamId, object_id: ObjectId) -> Result<Rank>;

    /// Queries the generation counter for a device.
    #[cfg(feature = "test-utils")]
    #[cfg_attr(docsrs, doc(cfg(feature = "test-utils")))]
    async fn query_device_generation(team: TeamId, device_id: DeviceId) -> Result<Option<i64>>;

    //
    // Role assignment
    //

    /// Assign a role to a device.
    async fn assign_role(team: TeamId, device: DeviceId, role: RoleId) -> Result<()>;
    /// Revoke a role from a device.
    async fn revoke_role(team: TeamId, device: DeviceId, role: RoleId) -> Result<()>;
    /// Changes the assigned role of a device.
    async fn change_role(
        team: TeamId,
        device: DeviceId,
        old_role: RoleId,
        new_role: RoleId,
    ) -> Result<()>;
    /// Returns the role assigned to the device.
    async fn device_role(team: TeamId, device: DeviceId) -> Result<Option<Role>>;

    //
    // Label creation
    //

    /// Creates a label with an explicit rank.
    async fn create_label(team: TeamId, name: Text, rank: Rank) -> Result<LabelId>;
    /// Delete a label.
    async fn delete_label(team: TeamId, label_id: LabelId) -> Result<()>;
    /// Returns a specific label.
    async fn label(team: TeamId, label: LabelId) -> Result<Label>;
    /// Returns all labels on the team.
    async fn labels(team: TeamId) -> Result<Vec<Label>>;

    //
    // Label assignments
    //

    /// Assigns a label to a device.
    async fn assign_label_to_device(
        team: TeamId,
        device: DeviceId,
        label: LabelId,
        op: ChanOp,
    ) -> Result<()>;
    /// Revokes a label from a device.
    async fn revoke_label_from_device(team: TeamId, device: DeviceId, label: LabelId)
        -> Result<()>;
    /// Returns all labels assigned to the device.
    async fn labels_assigned_to_device(team: TeamId, device: DeviceId) -> Result<Box<[Label]>>;

    /// Gets AFC shared-memory configuration info.
    #[cfg(feature = "afc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "afc")))]
    async fn afc_shm_info() -> Result<AfcShmInfo>;
    /// Create a send-only AFC channel.
    #[cfg(feature = "afc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "afc")))]
    async fn create_afc_channel(
        team: TeamId,
        peer_id: DeviceId,
        label_id: LabelId,
    ) -> Result<AfcSendChannelInfo>;
    /// Delete a AFC channel.
    #[cfg(feature = "afc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "afc")))]
    async fn delete_afc_channel(chan: AfcLocalChannelId) -> Result<()>;
    /// Accept a receive-only AFC channel by processing a peer's ctrl message.
    #[cfg(feature = "afc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "afc")))]
    async fn accept_afc_channel(team: TeamId, ctrl: AfcCtrl) -> Result<AfcReceiveChannelInfo>;
}