libsalus 0.2.0

A key/value store protected by secret shares and encryption
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
// Copyright (c) 2025 salus developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Salus - A secure secret store in Rust

// rustc lints
#![cfg_attr(
    all(feature = "unstable", nightly),
    feature(
        multiple_supertrait_upcastable,
        must_not_suspend,
        non_exhaustive_omitted_patterns_lint,
        strict_provenance_lints,
        unqualified_local_imports,
    )
)]
#![cfg_attr(nightly, allow(single_use_lifetimes))]
#![cfg_attr(
    nightly,
    deny(
        absolute_paths_not_starting_with_crate,
        ambiguous_glob_imports,
        ambiguous_glob_reexports,
        ambiguous_negative_literals,
        ambiguous_wide_pointer_comparisons,
        anonymous_parameters,
        array_into_iter,
        asm_sub_register,
        async_fn_in_trait,
        bad_asm_style,
        bare_trait_objects,
        boxed_slice_into_iter,
        break_with_label_and_loop,
        clashing_extern_declarations,
        closure_returning_async_block,
        coherence_leak_check,
        confusable_idents,
        const_evaluatable_unchecked,
        const_item_mutation,
        dangling_pointers_from_temporaries,
        dead_code,
        dependency_on_unit_never_type_fallback,
        deprecated,
        deprecated_in_future,
        deprecated_safe_2024,
        deprecated_where_clause_location,
        deref_into_dyn_supertrait,
        deref_nullptr,
        double_negations,
        drop_bounds,
        dropping_copy_types,
        dropping_references,
        duplicate_macro_attributes,
        dyn_drop,
        edition_2024_expr_fragment_specifier,
        elided_lifetimes_in_paths,
        ellipsis_inclusive_range_patterns,
        explicit_outlives_requirements,
        exported_private_dependencies,
        ffi_unwind_calls,
        forbidden_lint_groups,
        forgetting_copy_types,
        forgetting_references,
        for_loops_over_fallibles,
        function_item_references,
        hidden_glob_reexports,
        if_let_rescope,
        impl_trait_overcaptures,
        impl_trait_redundant_captures,
        improper_ctypes,
        improper_ctypes_definitions,
        inline_no_sanitize,
        internal_features,
        invalid_from_utf8,
        invalid_macro_export_arguments,
        invalid_nan_comparisons,
        invalid_value,
        irrefutable_let_patterns,
        keyword_idents_2018,
        keyword_idents_2024,
        large_assignments,
        late_bound_lifetime_arguments,
        legacy_derive_helpers,
        let_underscore_drop,
        macro_use_extern_crate,
        map_unit_fn,
        meta_variable_misuse,
        mismatched_lifetime_syntaxes,
        missing_abi,
        missing_copy_implementations,
        missing_debug_implementations,
        missing_docs,
        missing_unsafe_on_extern,
        mixed_script_confusables,
        named_arguments_used_positionally,
        never_type_fallback_flowing_into_unsafe,
        no_mangle_generic_items,
        non_ascii_idents,
        non_camel_case_types,
        non_contiguous_range_endpoints,
        non_fmt_panics,
        non_local_definitions,
        non_shorthand_field_patterns,
        non_snake_case,
        non_upper_case_globals,
        noop_method_call,
        opaque_hidden_inferred_bound,
        out_of_scope_macro_calls,
        overlapping_range_endpoints,
        path_statements,
        private_bounds,
        private_interfaces,
        ptr_to_integer_transmute_in_consts,
        redundant_imports,
        redundant_lifetimes,
        redundant_semicolons,
        refining_impl_trait_internal,
        refining_impl_trait_reachable,
        renamed_and_removed_lints,
        rust_2021_incompatible_closure_captures,
        rust_2021_incompatible_or_patterns,
        rust_2021_prefixes_incompatible_syntax,
        rust_2021_prelude_collisions,
        rust_2024_guarded_string_incompatible_syntax,
        rust_2024_incompatible_pat,
        rust_2024_prelude_collisions,
        self_constructor_from_outer_item,
        semicolon_in_expressions_from_macros,
        single_use_lifetimes,
        special_module_name,
        stable_features,
        static_mut_refs,
        suspicious_double_ref_op,
        tail_expr_drop_order,
        trivial_bounds,
        trivial_casts,
        trivial_numeric_casts,
        type_alias_bounds,
        tyvar_behind_raw_pointer,
        uncommon_codepoints,
        unconditional_recursion,
        uncovered_param_in_projection,
        unexpected_cfgs,
        unfulfilled_lint_expectations,
        ungated_async_fn_track_caller,
        uninhabited_static,
        unit_bindings,
        unknown_lints,
        unknown_or_malformed_diagnostic_attributes,
        unnameable_test_items,
        unnameable_types,
        unpredictable_function_pointer_comparisons,
        unreachable_code,
        unreachable_patterns,
        unreachable_pub,
        unsafe_attr_outside_unsafe,
        unsafe_code,
        unsafe_op_in_unsafe_fn,
        unstable_name_collisions,
        unstable_syntax_pre_expansion,
        unused_allocation,
        unused_assignments,
        unused_associated_type_bounds,
        unused_attributes,
        unused_braces,
        unused_comparisons,
        unused_crate_dependencies,
        unused_doc_comments,
        unused_extern_crates,
        unused_features,
        unused_import_braces,
        unused_imports,
        unused_labels,
        unused_lifetimes,
        unused_macro_rules,
        unused_macros,
        unused_must_use,
        unused_mut,
        unused_parens,
        unused_qualifications,
        unused_results,
        unused_unsafe,
        unused_variables,
        useless_ptr_null_checks,
        uses_power_alignment,
        variant_size_differences,
        while_true,
    )
)]
// If nightly and unstable, allow `incomplete_features` and `unstable_features`
#![cfg_attr(
    all(feature = "unstable", nightly),
    allow(incomplete_features, unstable_features)
)]
// If nightly and not unstable, deny `incomplete_features` and `unstable_features`
#![cfg_attr(
    all(not(feature = "unstable"), nightly),
    deny(incomplete_features, unstable_features)
)]
// The unstable lints
#![cfg_attr(
    all(feature = "unstable", nightly),
    deny(
        fuzzy_provenance_casts,
        lossy_provenance_casts,
        multiple_supertrait_upcastable,
        must_not_suspend,
        non_exhaustive_omitted_patterns,
        unqualified_local_imports,
    )
)]
// clippy lints
#![cfg_attr(nightly, deny(clippy::all, clippy::pedantic))]
// no-panic restriction lints: handle every error, never panic (see CLAUDE.md)
#![cfg_attr(
    nightly,
    deny(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::unreachable,
        clippy::todo,
        clippy::unimplemented,
        clippy::indexing_slicing,
        clippy::arithmetic_side_effects,
        clippy::get_unwrap,
        clippy::unwrap_in_result,
    )
)]
// rustdoc lints
#![cfg_attr(
    nightly,
    deny(
        rustdoc::bare_urls,
        rustdoc::broken_intra_doc_links,
        rustdoc::invalid_codeblock_attributes,
        rustdoc::invalid_html_tags,
        rustdoc::missing_crate_level_docs,
        rustdoc::private_doc_tests,
        rustdoc::private_intra_doc_links,
    )
)]
#![cfg_attr(all(docsrs), feature(doc_cfg))]

use std::path::PathBuf;

use anyhow::Result;
use interprocess::local_socket::GenericFilePath;
use interprocess::local_socket::Name;
use interprocess::local_socket::ToFsName;

mod key;
mod message;
mod search;

pub use crate::key::gen_shares;
pub use crate::key::unlock_key;
pub use crate::message::Action;
pub use crate::message::Init;
pub use crate::message::MAX_MESSAGE_SIZE;
pub use crate::message::MAX_UNLOCK_SECONDS;
pub use crate::message::Response;
pub use crate::message::SearchQuery;
pub use crate::message::Share;
pub use crate::message::Shares;
pub use crate::message::Store;
pub use crate::message::UnlockTimeout;
pub use crate::message::agent::AgentAction;
pub use crate::message::agent::AgentResponse;
pub use crate::message::agent::SetInfo;
pub use crate::message::decode;
pub use crate::message::encode;
pub use crate::search::fuzzy_rank;
use interprocess::local_socket::GenericNamespaced;
use interprocess::local_socket::NameType;
use interprocess::local_socket::ToNsName;
pub use ssss::SsssConfig;

/// The base file name used for the daemon IPC socket.
const SOCKET_FILE_NAME: &str = "salus.sock";

/// The base file name used for the `salus-agent` IPC socket.
const AGENT_SOCKET_FILE_NAME: &str = "salus-agent.sock";

/// The environment variable, shared by both the daemon and the client, that
/// overrides the IPC socket location. Resolving it inside this crate keeps the
/// two processes in sync from a single setting.
const SOCKET_ENV: &str = "SALUS_SOCKET";

/// The environment variable, shared by the agent and the client, that overrides
/// the `salus-agent` IPC socket location.
const AGENT_SOCKET_ENV: &str = "SALUS_AGENT_SOCKET";

/// Where the IPC socket lives once resolved.
#[derive(Clone, Debug, Eq, PartialEq)]
enum SocketTarget {
    /// A namespaced socket addressed by a bare name (e.g. the Linux abstract
    /// namespace), used by default where the platform supports it.
    Namespaced(String),
    /// A filesystem socket addressed by path, used for explicit overrides and
    /// as the fallback on platforms without namespaced socket support.
    File(PathBuf),
}

/// Resolve where an IPC socket should live.
///
/// Precedence: an explicit per-side override wins, then the shared environment
/// value, then a platform default (a namespaced name where supported, otherwise
/// a file under the runtime/temp directory). `default_name` is the base socket
/// file name used for both the namespaced name and the file fallback.
fn socket_target(
    override_path: Option<&str>,
    env_socket: Option<&str>,
    default_name: &str,
) -> SocketTarget {
    if let Some(path) = override_path.or(env_socket) {
        SocketTarget::File(PathBuf::from(path))
    } else if GenericNamespaced::is_supported() {
        SocketTarget::Namespaced(default_name.to_string())
    } else {
        let dir = dirs2::runtime_dir().unwrap_or_else(std::env::temp_dir);
        SocketTarget::File(dir.join(default_name))
    }
}

/// Turn a resolved [`SocketTarget`] into an interprocess [`Name`].
fn target_to_name<'a>(target: SocketTarget) -> Result<Name<'a>> {
    let name = match target {
        SocketTarget::Namespaced(name) => name.to_ns_name::<GenericNamespaced>()?,
        SocketTarget::File(path) => path.to_fs_name::<GenericFilePath>()?,
    };
    Ok(name)
}

/// Get the socket name used for daemon interprocess communication.
///
/// `override_path`, when `Some`, is an explicit socket path supplied by the
/// caller (CLI flag or config file) and takes precedence over the shared
/// `SALUS_SOCKET` environment variable and the platform default.
///
/// # Errors
///
/// * An error can be thrown if the socket name cannot be created.
///
pub fn socket_name<'a>(override_path: Option<&str>) -> Result<Name<'a>> {
    let env_socket = std::env::var(SOCKET_ENV).ok();
    target_to_name(socket_target(
        override_path,
        env_socket.as_deref(),
        SOCKET_FILE_NAME,
    ))
}

/// Get the socket name used to talk to the `salus-agent`.
///
/// Mirrors [`socket_name`] but resolves the agent-specific override, the shared
/// `SALUS_AGENT_SOCKET` environment variable, and the agent's platform default,
/// so the agent and client always agree on a single location.
///
/// # Errors
///
/// * An error can be thrown if the socket name cannot be created.
///
pub fn agent_socket_name<'a>(override_path: Option<&str>) -> Result<Name<'a>> {
    let env_socket = std::env::var(AGENT_SOCKET_ENV).ok();
    target_to_name(socket_target(
        override_path,
        env_socket.as_deref(),
        AGENT_SOCKET_FILE_NAME,
    ))
}

#[cfg(test)]
mod test {
    use std::path::PathBuf;

    use anyhow::{Context, Result};

    use super::{
        AGENT_SOCKET_FILE_NAME, SOCKET_FILE_NAME, SocketTarget, agent_socket_name, socket_name,
        socket_target, target_to_name,
    };

    #[test]
    fn override_wins_over_env() {
        let target = socket_target(
            Some("/tmp/override.sock"),
            Some("/tmp/env.sock"),
            SOCKET_FILE_NAME,
        );
        assert_eq!(
            target,
            SocketTarget::File(PathBuf::from("/tmp/override.sock"))
        );
    }

    #[test]
    fn env_used_when_no_override() {
        let target = socket_target(None, Some("/tmp/env.sock"), SOCKET_FILE_NAME);
        assert_eq!(target, SocketTarget::File(PathBuf::from("/tmp/env.sock")));
    }

    #[test]
    fn default_used_when_nothing_configured() -> Result<()> {
        // With neither an override nor the env var set, the default depends on
        // platform support: a bare namespaced name, or a file under the
        // runtime/temp directory. Either way it must end with the base name.
        match socket_target(None, None, SOCKET_FILE_NAME) {
            SocketTarget::Namespaced(name) => assert_eq!(name, SOCKET_FILE_NAME),
            SocketTarget::File(path) => {
                let file_name = path.file_name().context("socket path has no file name")?;
                assert_eq!(file_name, SOCKET_FILE_NAME);
            }
        }
        Ok(())
    }

    #[test]
    fn agent_default_uses_agent_base_name() -> Result<()> {
        // The agent default must resolve to the agent base name, not the
        // daemon's, so the two sockets never collide.
        match socket_target(None, None, AGENT_SOCKET_FILE_NAME) {
            SocketTarget::Namespaced(name) => assert_eq!(name, AGENT_SOCKET_FILE_NAME),
            SocketTarget::File(path) => {
                let file_name = path.file_name().context("socket path has no file name")?;
                assert_eq!(file_name, AGENT_SOCKET_FILE_NAME);
            }
        }
        Ok(())
    }

    #[test]
    fn target_to_name_builds_namespaced_and_file() {
        assert!(target_to_name(SocketTarget::Namespaced(SOCKET_FILE_NAME.to_string())).is_ok());
        assert!(target_to_name(SocketTarget::File(PathBuf::from("/tmp/x.sock"))).is_ok());
    }

    #[test]
    fn socket_name_with_override_resolves() {
        assert!(socket_name(Some("/tmp/override.sock")).is_ok());
        assert!(agent_socket_name(Some("/tmp/agent-override.sock")).is_ok());
    }
}