git.delta.rocks / jrsonnet / refs/commits / 5a5b360a3403

difftreelog

feat unify shared and host secret handling

xwkwvyrvYaroslav Bolyukin2026-01-22parent: #20a41a3.patch.diff
in: trunk

8 files changed

modifiedcmds/fleet/src/cmds/secrets/mod.rsdiffbeforeafterboth
8use chrono::{DateTime, Utc};8use chrono::{DateTime, Utc};
9use clap::Parser;9use clap::Parser;
10use fleet_base::{10use fleet_base::{
11 fleetdata::{11 fleetdata::{FleetSecretData, FleetSecretDistribution, FleetSecretPart, encrypt_secret_data},
12 FleetHostSecret, FleetSecretData, FleetSecretPart, FleetSharedSecret, encrypt_secret_data,
13 },
14 host::Config,12 host::Config,
15 opts::FleetOpts,13 opts::FleetOpts,
16 secret::{Expectations, RegenerationReason, SharedSecretDefinition, secret_needs_regeneration},14 secret::{Expectations, RegenerationReason, SharedSecretDefinition, secret_needs_regeneration},
28 AddManager,26 AddManager,
29 /// Force load host keys for all defined hosts27 /// Force load host keys for all defined hosts
30 ForceKeys,28 ForceKeys,
31 /// Add secret, data should be provided in stdin29 /// Read secret from remote host, requires sudo on one of the owning hosts
32 AddShared {30 Read {
33 /// Secret name31 /// Secret name to read
34 name: String,32 name: String,
35 /// Secret owners
36 #[clap(long, short)]
37 machines: Vec<String>,
38 /// Override secret if already present
39 #[clap(long)]
40 force: bool,
41 /// Secret public part
42 #[clap(long)]
43 public: Option<String>,
44 /// Load public part from specified file
45 #[clap(long)]
46 public_file: Option<PathBuf>,
4733
48 /// Create a notification on secret expiration34 /// Distribution with what machine to read
49 #[clap(long)]
50 expires_at: Option<DateTime<Utc>>,
51
52 /// Secret with this name already exists, override its value while keeping the same owners.
53 #[clap(long)]
54 re_add: bool,
55
56 /// How to name public secret part
57 #[clap(long, short = 'p', default_value = "public")]35 /// If not shared between multiple - defaults to single owner
58 public_part: String,
59 /// How to name private secret part
60 #[clap(short = 's', long, default_value = "secret")]
61 part: String,
62 },
63 /// Add secret, data should be provided in stdin
64 Add {
65 /// Secret name
66 name: String,
67 /// Secret owner
68 #[clap(short = 'm', long)]36 #[clap(short = 'm', long)]
69 machine: String,37 machine: Option<String>,
70 /// Replace secret if already present
71 #[clap(long)]
72 replace: bool,
73 /// Add new parts to existing secret
74 #[clap(long)]
75 merge: bool,
76 /// Secret public part
77 #[clap(long)]
78 public: Option<String>,
79 /// Load public part from specified file
80 #[clap(long)]
81 public_file: Option<PathBuf>,
8238
83 /// How to name public secret part
84 #[clap(short = 'p', long, default_value = "public")]
85 public_part: String,
86 /// How to name private secret part
87 #[clap(short = 's', long, default_value = "secret")]
88 part: String,
89 },
90 /// Read secret from remote host, requires sudo on said host
91 Read {
92 name: String,
93 #[clap(short = 'm', long)]
94 machine: String,
95
96 /// Which private secret part to read39 /// Which private secret part to read
97 #[clap(short = 'p', long, default_value = "secret")]40 #[clap(short = 'p', long, default_value = "secret")]
98 part: String,41 part: String,
99 },42
100 /// Read secret from remote host, requires sudo on said host
101 ReadShared {
102 name: String,
103 /// Which private secret part to read
104 #[clap(short = 'p', long, default_value = "secret")]
105 part: String,
106 /// Which host should we use to decrypt, in case if reencryption is required, without43 /// Which host should we use to decrypt, in case if reencryption is required, without
107 /// regeneration44 /// regeneration
108 #[clap(long)]45 #[clap(long)]
109 prefer_identities: Vec<String>,46 prefer_identities: Vec<String>,
110 },47 },
111 UpdateShared {
112 name: String,
113
114 #[clap(short = 'm', long)]
115 machine: Option<Vec<String>>,
116
117 #[clap(long)]
118 add_machine: Vec<String>,
119 #[clap(long)]
120 remove_machine: Vec<String>,
121
122 /// Which host should we use to decrypt
123 #[clap(long)]
124 prefer_identities: Vec<String>,
125 },
126 Regenerate {48 Regenerate {
127 /// Which host should we use to decrypt, in case if reencryption is required, without49 /// Which host should we use to decrypt, in case if reencryption is required, without
128 /// regeneration50 /// regeneration
152async fn maybe_regenerate_shared_secret(74async fn maybe_regenerate_shared_secret(
153 secret_name: &str,75 secret_name: &str,
154 config: &Config,76 config: &Config,
155 mut secret: FleetSharedSecret,77 mut secret: FleetSecretDistribution,
156 definition: SharedSecretDefinition,78 definition: SharedSecretDefinition,
157 prefer_identities: &[String],79 prefer_identities: &[String],
158 expectations: &Expectations,80 expectations: &Expectations,
159) -> Result<FleetSharedSecret> {81) -> Result<FleetSecretDistribution> {
160 let reason = secret_needs_regeneration(&secret.secret, &secret.owners, expectations);82 let reason = secret_needs_regeneration(&secret.secret, &secret.owners, expectations);
161 let value = definition.definition_value();83 let value = definition.definition_value();
16284
397 display_name: &str,319 display_name: &str,
398 secret: SharedSecretDefinition,320 secret: SharedSecretDefinition,
399 expectations: &Expectations,321 expectations: &Expectations,
400) -> Result<FleetSharedSecret> {322) -> Result<FleetSecretDistribution> {
401 // let owners: Vec<String> = nix_go_json!(secret.expectedOwners);323 // let owners: Vec<String> = nix_go_json!(secret.expectedOwners);
402 Ok(FleetSharedSecret {324 Ok(FleetSecretDistribution {
403 managed: Some(true),325 managed: Some(true),
404 secret: generate(326 secret: generate(
405 config,327 config,
504 config.key(&host.name).await?;426 config.key(&host.name).await?;
505 }427 }
506 }428 }
507 Secret::AddShared {429 Secret::Read {
508 machines,
509 name,430 name,
510 force,431 machine,
511 public,
512 public_part: public_name,
513 public_file,
514 expires_at,
515 re_add,
516 part: part_name,432 part: part_name,
433 mut prefer_identities,
517 } => {434 } => {
518 let mut machines: BTreeSet<String> = machines.into_iter().collect();435 let Some(secret) = config.shared_secret(&name) else {
519 // TODO: Forbid updating secrets with set expectedOwners (= not user-managed).
520
521 if let Some(old_shared) = config.shared_secret(&name)? {
522 if !force && !re_add {
523 bail!("secret already defined");
524 };
525 if old_shared.managed.unwrap_or(false) {
526 bail!("secret is marked as managed, should not be updated manually");
527 };
528 if re_add {
529 // Fixme: use clap to limit this usage
530 ensure!(!force, "--force and --readd are not compatible");
531 ensure!(
532 machines.is_empty(),
533 "you can't use machines argument for --readd"
534 );
535 machines = old_shared.owners;
536 }
537 } else if re_add {
538 bail!("secret doesn't exists");436 bail!("secret doesn't exists");
539 };437 };
540438
541 let recipients = config439 let dist = if secret.len() == 1 {
542 .recipients(machines.iter().cloned().collect())
543 .await?;
544
545 let mut parts = BTreeMap::new();
546
547 let mut input = vec![];
548 io::stdin().read_to_end(&mut input)?;
549
550 if !input.is_empty() {
551 let encrypted = encrypt_secret_data(recipients.iter(), input)440 &secret[0]
552 .ok_or_else(|| anyhow!("no recipients provided"))?;441 } else if let Some(machine) = machine {
553 parts.insert(part_name, FleetSecretPart { raw: encrypted });
554 }
555
556 if let Some(public) = parse_public(public, public_file).await? {
557 parts.insert(public_name, FleetSecretPart { raw: public });442 let dist = secret.get(&machine);
558 }443 let Some(dist) = dist else {
559
560 config.replace_shared(
561 name,
562 FleetSharedSecret {
563 managed: Some(false),
564 owners: machines,
565 secret: FleetSecretData {
566 created_at: Utc::now(),444 bail!("machine {machine} has no distribution of secret {name}");
567 expires_at,
568 parts,
569 generation_data: serde_json::Value::Null,
570 },
571 },
572 );
573 }
574 Secret::Add {
575 machine,
576 name,
577 replace,
578 merge,
579 public,
580 public_part: public_name,
581 public_file,
582 part: part_name,
583 } => {
584 if config.has_secret(&machine, &name) && !replace && !merge {
585 bail!(
586 "secret already defined.\nUse --replace to override, or --merge to add new parts to existing secret"
587 );
588 }445 };
589
590 let mut out = if merge && !replace {446 prefer_identities.push(machine);
591 config
592 .host_secret(&machine, &name)
593 .context("failed to read existing secret for --merge")?447 dist
594 } else {448 } else {
595 FleetHostSecret {449 bail!(
596 managed: Some(false),
597 secret: FleetSecretData {450 "secret {name} has shares, but no --machine specified for specifing which do you need"
598 created_at: Utc::now(),
599 expires_at: None,
600 parts: BTreeMap::new(),
601 generation_data: serde_json::Value::Null,
602 },451 )
603 }
604 };452 };
605 if out.managed.unwrap_or(false) {
606 bail!("secret is managed by fleet and should not be updated manually");
607 }
608 out.managed = Some(false);
609453
610 if let Some(secret) = parse_secret().await? {454 let Some(part) = dist.secret.parts.get(&part_name) else {
611 let recipient = config.recipient(&machine).await?;
612 let encrypted =
613 encrypt_secret_data([&recipient], secret).expect("recipient provided");
614 if out
615 .secret
616 .parts
617 .insert(part_name.clone(), FleetSecretPart { raw: encrypted })
618 .is_some() && !replace
619 {
620 bail!(
621 "part {part_name:?} is already defined, use --replace if you wish to replace it"
622 );
623 }
624 }
625
626 if let Some(public) = parse_public(public, public_file).await? {
627 if out
628 .secret
629 .parts
630 .insert(public_name.clone(), FleetSecretPart { raw: public })
631 .is_some() && !replace
632 {
633 bail!(
634 "part {public_name:?} is already defined, use --replace if you wish to replace it"
635 );
636 }
637 };
638
639 config.insert_secret(&machine, name, out);
640 }
641 #[allow(clippy::await_holding_refcell_ref)]
642 Secret::Read {
643 name,
644 machine,
645 part: part_name,
646 } => {
647 let secret = config.host_secret(&machine, &name)?;
648 let Some(secret) = secret.secret.parts.get(&part_name) else {
649 bail!("no part {part_name} in secret {name}");455 bail!("no part {part_name} in secret {name}");
650 };456 };
651 let data = if secret.raw.encrypted {
652 let host = config.host(&machine).await?;
653 host.decrypt(secret.raw.clone()).await?
654 } else {
655 secret.raw.data.clone()
656 };
657
658 stdout().write_all(&data)?;
659 }
660 Secret::ReadShared {
661 name,
662 part: part_name,
663 prefer_identities,
664 } => {
665 let Some(secret) = config.shared_secret(&name)? else {
666 bail!("secret doesn't exists");
667 };
668 let Some(part) = secret.secret.parts.get(&part_name) else {
669 bail!("no part {part_name} in secret {name}");
670 };
671 let data = if part.raw.encrypted {457 let data = if part.raw.encrypted {
672 let identity_holder = if !prefer_identities.is_empty() {458 let identity_holder = if !prefer_identities.is_empty() {
673 prefer_identities459 prefer_identities
674 .iter()460 .iter()
675 .find(|i| secret.owners.iter().any(|s| s == *i))461 .find(|i| dist.owners.iter().any(|s| s == *i))
676 } else {462 } else {
677 secret.owners.first()463 dist.owners.first()
678 };464 };
679 let Some(identity_holder) = identity_holder else {465 let Some(identity_holder) = identity_holder else {
680 bail!("no available holder found");466 bail!("no available holder found");
686 };472 };
687 stdout().write_all(&data)?;473 stdout().write_all(&data)?;
688 }474 }
689 Secret::UpdateShared {
690 name,
691 machine,
692 add_machine,
693 remove_machine,
694 prefer_identities,
695 } => {
696 // TODO: Forbid updating secrets with set expectedOwners (= not user-managed).
697
698 let Some(secret) = config.shared_secret(&name)? else {
699 bail!("secret doesn't exists");
700 };
701 if secret.secret.parts.values().all(|v| !v.raw.encrypted) {
702 bail!("no secret");
703 }
704
705 let initial_machines = secret.owners.clone();
706 let target_machines = parse_machines(
707 initial_machines.clone(),
708 machine,
709 add_machine,
710 remove_machine,
711 )?;
712
713 if target_machines.is_empty() {
714 info!("no machines left for secret, removing it");
715 config.remove_shared(&name);
716 return Ok(());
717 }
718
719 let definition = config.shared_secret_definition(&name)?;
720 let expectations = definition
721 .expectations()
722 .with_context(|| format!("expectations for shared {name:?}"))?;
723
724 let updated = maybe_regenerate_shared_secret(
725 &name,
726 config,
727 secret,
728 definition,
729 &prefer_identities,
730 &expectations,
731 )
732 .await?;
733 config.replace_shared(name, updated);
734 }
735 Secret::Regenerate {475 Secret::Regenerate {
736 prefer_identities,476 prefer_identities,
737 skip_hosts,477 skip_hosts,
738 } => {478 } => {
739 info!("checking for secrets to regenerate");479 /*
740 let expected_shared_set = config480 info!("checking for secrets to regenerate");
741 .list_configured_shared()481 let expected_shared_set = config
742 .await?482 .list_configured_shared()
743 .into_iter()483 .await?
744 .collect::<HashSet<_>>();484 .into_iter()
745 let stored_shared_set = config.list_shared().into_iter().collect::<HashSet<_>>();485 .collect::<HashSet<_>>();
746 {486 let stored_shared_set = config.list_secrets().into_iter().collect::<HashSet<_>>();
747 // Generate missing shared
748 let _span = info_span!("shared").entered();
749 for missing in expected_shared_set.difference(&stored_shared_set) {
750 let definition = config.shared_secret_definition(missing)?;
751 if !definition.is_managed()? {
752 info!("skipping unmanaged secret: {missing}");
753 continue;
754 }
755 let expectations = definition
756 .expectations()
757 .with_context(|| format!("expectations for shared {missing:?}"))?;
758 info!("generating secret: {missing}");
759 let shared = generate_shared(config, missing, definition, &expectations)
760 .in_current_span()
761 .await?;
762 config.replace_shared(missing.to_string(), shared)
763 }
764 }
765 if !skip_hosts {
766 for host in config.list_hosts().await? {
767 if opts.should_skip(&host).await? {
768 continue;
769 }
770
771 let _span = info_span!("host", host = host.name).entered();
772 let expected_set = host
773 .list_defined_secrets()?
774 .into_iter()
775 .collect::<HashSet<_>>();
776 let stored_set = config
777 .list_secrets(&host.name)
778 .into_iter()
779 .collect::<HashSet<_>>();
780 for missing_secret in expected_set.difference(&stored_set) {
781 let secret = host.secret_definition(missing_secret)?;
782 if secret.is_shared()? {
783 continue;
784 }
785 info!("generating missing secret: {missing_secret}");
786 let expectations = secret.expectations().with_context(|| {
787 format!("expectations for {missing_secret:?} of {:?}", host.name)
788 })?;
789 let generated = match generate(
790 config,
791 missing_secret,
792 secret.definition_value()?,
793 &expectations,
794 )
795 .in_current_span()
796 .await
797 {
798 Ok(v) => v,
799 Err(e) => {
800 error!("{e:?}");
801 continue;
802 }
803 };
804 config.insert_secret(
805 &host.name,
806 missing_secret.to_string(),
807 FleetHostSecret {
808 managed: Some(true),
809 secret: generated,
810 },
811 )
812 }
813 for known_secret in stored_set.intersection(&expected_set) {
814 let secret = host.secret_definition(known_secret)?;
815 if secret.is_shared()? {
816 continue;
817 }
818 info!("updating secret: {known_secret}");
819 let data = config.host_secret(&host.name, known_secret)?;
820 let expectations = secret.expectations()?;
821 if let Some(regen_reason) = data.needs_regeneration(&expectations) {
822 info!("needs regeneration: {regen_reason}");
823 let generated = match generate(
824 config,
825 known_secret,
826 secret.definition_value()?,
827 &expectations,
828 )
829 .in_current_span()
830 .await
831 {487 {
832 Ok(v) => v,488 // Generate missing shared
489 let _span = info_span!("shared").entered();
490 for missing in expected_shared_set.difference(&stored_shared_set) {
491 let definition = config.shared_secret_definition(missing)?;
833 Err(e) => {492 if !definition.is_managed()? {
493 info!("skipping unmanaged secret: {missing}");
834 error!("{e:?}");494 continue;
495 }
496 let expectations = definition
497 .expectations()
498 .with_context(|| format!("expectations for shared {missing:?}"))?;
835 continue;499 info!("generating secret: {missing}");
500 let shared = generate_shared(config, missing, definition, &expectations)
501 .in_current_span()
502 .await?;
503 config.replace_shared(missing.to_string(), shared)
836 }504 }
837 };505 }
838 config.insert_secret(506 if !skip_hosts {
839 &host.name,
840 known_secret.to_string(),
841 FleetHostSecret {
842 managed: Some(true),507 for host in config.list_hosts().await? {
843 secret: generated,
844 },
845 )
846 }
847 }
848 for removed_secret in stored_set.difference(&expected_set) {
849 let definition = host.secret_definition(removed_secret)?;508 if opts.should_skip(&host).await? {
850 if definition.is_shared()? {
851 continue;509 continue;
852 }
853 info!("removing secret: {removed_secret}");
854 config.remove_secret(&host.name, removed_secret);510 }
855 }
856 }
857 }
858 for known_secret in stored_shared_set.intersection(&expected_shared_set) {
859 info!("updating shared secret: {known_secret}");
860 let data = config.shared_secret(known_secret)?.expect("exists");
861511
862 let definition = config.shared_secret_definition(known_secret)?;512 let _span = info_span!("host", host = host.name).entered();
863 let expectations = definition.expectations()?;513 let expected_set = host
864 config.replace_shared(514 .list_defined_secrets()?
865 known_secret.to_owned(),515 .into_iter()
866 maybe_regenerate_shared_secret(516 .collect::<HashSet<_>>();
867 known_secret,517 let stored_set = config
868 config,518 .list_secrets_for_owner(&host.name)
869 data,519 .into_iter()
870 definition,520 .collect::<HashSet<_>>();
871 &prefer_identities,521 for missing_secret in expected_set.difference(&stored_set) {
872 &expectations,522 let secret = host.secret_definition(missing_secret)?;
873 )523 if secret.is_shared()? {
874 .await?,524 continue;
875 );525 }
876 }526 info!("generating missing secret: {missing_secret}");
877 for removed_secret in stored_shared_set.difference(&expected_shared_set) {527 let expectations = secret.expectations().with_context(|| {
878 info!("removing shared secret: {removed_secret}");528 format!("expectations for {missing_secret:?} of {:?}", host.name)
879 config.remove_shared(removed_secret);529 })?;
880 }530 let generated = match generate(
531 config,
532 missing_secret,
533 secret.definition_value()?,
534 &expectations,
535 )
536 .in_current_span()
537 .await
538 {
539 Ok(v) => v,
540 Err(e) => {
541 error!("{e:?}");
542 continue;
543 }
544 };
545 config.insert_secret(host.name, missing_secret.to_string(), generated)
546 }
547 for known_secret in stored_set.intersection(&expected_set) {
548 let secret = host.secret_definition(known_secret)?;
549 if secret.is_shared()? {
550 continue;
551 }
552 info!("updating secret: {known_secret}");
553 let data = config.host_secret(&host.name, known_secret)?;
554 let expectations = secret.expectations()?;
555 if let Some(regen_reason) = data.needs_regeneration(&expectations) {
556 info!("needs regeneration: {regen_reason}");
557 let generated = match generate(
558 config,
559 known_secret,
560 secret.definition_value()?,
561 &expectations,
562 )
563 .in_current_span()
564 .await
565 {
566 Ok(v) => v,
567 Err(e) => {
568 error!("{e:?}");
569 continue;
570 }
571 };
572 config.insert_secret(
573 &host.name,
574 known_secret.to_string(),
575 FleetLegacyHostSecret {
576 managed: Some(true),
577 secret: generated,
578 },
579 )
580 }
581 }
582 for removed_secret in stored_set.difference(&expected_set) {
583 let definition = host.secret_definition(removed_secret)?;
584 if definition.is_shared()? {
585 continue;
586 }
587 info!("removing secret: {removed_secret}");
588 config.remove_secret(&host.name, removed_secret);
589 }
590 }
591 }
592 for known_secret in stored_shared_set.intersection(&expected_shared_set) {
593 info!("updating shared secret: {known_secret}");
594 let data = config.shared_secret(known_secret)?.expect("exists");
595
596 let definition = config.shared_secret_definition(known_secret)?;
597 let expectations = definition.expectations()?;
598 config.replace_shared(
599 known_secret.to_owned(),
600 maybe_regenerate_shared_secret(
601 known_secret,
602 config,
603 data,
604 definition,
605 &prefer_identities,
606 &expectations,
607 )
608 .await?,
609 );
610 }
611 for removed_secret in stored_shared_set.difference(&expected_shared_set) {
612 info!("removing shared secret: {removed_secret}");
613 config.remove_shared(removed_secret);
614 }
615 */
616 todo!()
881 }617 }
882 Secret::List {} => {618 Secret::List {} => {
883 let _span = info_span!("loading secrets").entered();619 let _span = info_span!("loading secrets").entered();
892 let mut table = vec![];628 let mut table = vec![];
893 for name in configured.iter().cloned() {629 for name in configured.iter().cloned() {
894 let config = config.clone();630 let config = config.clone();
895 let data = config.shared_secret(&name)?.expect("exists");631 let data = config.shared_secret(&name).expect("exists");
896 let definition = config.shared_secret_definition(&name)?;632 let definition = config.shared_secret_definition(&name)?;
897 let expectations = definition.expectations()?;633 let expectations = definition.expectations()?;
898 let owners = data634 let owners = data
899 .owners635 .owners()
900 .iter()
901 .map(|o| {636 .map(|o| {
902 if expectations.owners.contains(o) {637 if expectations.owners.contains(o) {
903 o.green().to_string()638 o.green().to_string()
919 part,654 part,
920 add,655 add,
921 } => {656 } => {
922 let secret = config.host_secret(&machine, &name)?;657 let secret = config
658 .host_secret(&machine, &name)
659 .context("secret not found")?;
923 if let Some(data) = secret.secret.parts.get(&part) {660 if let Some(data) = secret.secret.parts.get(&part) {
924 let host = config.host(&machine).await?;661 let host = config.host(&machine).await?;
925 let secret = host.decrypt(data.raw.clone()).await?;662 let secret = host.decrypt(data.raw.clone()).await?;
modifiedcrates/fleet-base/src/fleetdata.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/fleetdata.rs
+++ b/crates/fleet-base/src/fleetdata.rs
@@ -1,6 +1,10 @@
 use std::{
-	collections::{BTreeMap, BTreeSet},
+	collections::{
+		BTreeMap, BTreeSet,
+		btree_map::{self, Entry},
+	},
 	io::{self, Cursor},
+	ops::Deref,
 };
 
 use age::Recipient;
@@ -10,10 +14,12 @@
 	distr::{Alphanumeric, SampleString as _},
 	rng,
 };
-use serde::{Deserialize, Serialize, de::Error};
+use serde::{
+	Deserialize, Serialize,
+	de::{self, Error},
+};
 use serde_json::Value;
-
-use crate::secret::{Expectations, RegenerationReason, secret_needs_regeneration};
+use tracing::info;
 
 #[derive(Serialize, Deserialize, Default)]
 #[serde(rename_all = "camelCase")]
@@ -72,17 +78,29 @@
 
 	#[serde(default)]
 	pub hosts: BTreeMap<String, HostData>,
+
+	#[serde(default, alias = "shared_secrets")]
+	pub secrets: FleetSecrets,
+
+	// extra_name => anything
 	#[serde(default)]
 	#[serde(skip_serializing_if = "BTreeMap::is_empty")]
-	pub shared_secrets: BTreeMap<String, FleetSharedSecret>,
-	#[serde(default)]
-	#[serde(skip_serializing_if = "BTreeMap::is_empty")]
-	pub host_secrets: BTreeMap<String, BTreeMap<String, FleetHostSecret>>,
+	pub extra: BTreeMap<String, Value>,
 
-	// extra_name => anything
 	#[serde(default)]
 	#[serde(skip_serializing_if = "BTreeMap::is_empty")]
-	pub extra: BTreeMap<String, Value>,
+	host_secrets: BTreeMap<String, BTreeMap<String, FleetSecretDistribution>>,
+}
+impl FleetData {
+	pub fn from_str(s: &str) -> anyhow::Result<Self> {
+		let mut data: Self = nixlike::parse_str(s)?;
+		if !data.host_secrets.is_empty() {
+			info!("migrating host secrets into shared secrets structure");
+			data.secrets
+				.merge_from_hosts(std::mem::take(&mut data.host_secrets));
+		}
+		Ok(data)
+	}
 }
 
 /// Returns None if recipients.is_empty()
@@ -129,27 +147,276 @@
 #[derive(Serialize, Deserialize, Clone)]
 #[serde(rename_all = "camelCase")]
 #[must_use]
-pub struct FleetHostSecret {
+pub struct FleetSecretDistribution {
 	#[serde(default)]
 	#[serde(skip_serializing_if = "Option::is_none")]
 	pub managed: Option<bool>,
+	#[serde(default)]
+	pub owners: BTreeSet<String>,
 	#[serde(flatten)]
 	pub secret: FleetSecretData,
 }
-impl FleetHostSecret {
-	pub fn needs_regeneration(&self, expectations: &Expectations) -> Option<RegenerationReason> {
-		secret_needs_regeneration(&self.secret, &expectations.owners, expectations)
+
+#[derive(Clone)]
+#[must_use]
+pub struct FleetSecretDistributions(Vec<FleetSecretDistribution>);
+
+impl Deref for FleetSecretDistributions {
+	type Target = [FleetSecretDistribution];
+
+	fn deref(&self) -> &Self::Target {
+		self.0.as_slice()
+	}
+}
+
+impl FleetSecretDistributions {
+	pub fn owners(&self) -> impl Iterator<Item = &String> {
+		self.0.iter().flat_map(|v| v.owners.iter())
+	}
+	#[allow(
+		clippy::len_without_is_empty,
+		reason = "should not be empty for a long time"
+	)]
+	pub fn len(&self) -> usize {
+		self.0.len()
+	}
+
+	pub fn get(&self, owner: &str) -> Option<&FleetSecretDistribution> {
+		self.0.iter().find(|d| d.owners.contains(owner))
+	}
+	fn entry(&mut self, owner: String) -> DistEntry<'_> {
+		let Some(idx) = self.0.iter().position(|d| d.owners.contains(&owner)) else {
+			return DistEntry::Vacant(VacantDistEntry {
+				distributions: self,
+				owner,
+			});
+		};
+		DistEntry::Occupied(OccupiedDistEntry {
+			distributions: self,
+			idx,
+			owner,
+		})
+	}
+	fn extend(&mut self, dist: FleetSecretDistribution) {
+		for owner in &dist.owners {
+			self.entry(owner.to_owned()).remove();
+		}
+		self.0.push(dist);
+	}
+	pub fn contains(&self, owner: &str) -> bool {
+		self.0.iter().any(|d| d.owners.contains(owner))
+	}
+}
+
+struct OccupiedDistEntry<'d> {
+	distributions: &'d mut FleetSecretDistributions,
+	idx: usize,
+	owner: String,
+}
+impl<'d> OccupiedDistEntry<'d> {
+	fn remove(self) -> VacantDistEntry<'d> {
+		let dist = &mut self.distributions.0[self.idx];
+		assert!(
+			dist.owners.remove(&self.owner),
+			"entry exists, as we have its reference"
+		);
+		if dist.owners.is_empty() {
+			self.distributions.0.remove(self.idx);
+		}
+		VacantDistEntry {
+			distributions: self.distributions,
+			owner: self.owner,
+		}
+	}
+	fn set(self, secret: FleetSecretData) -> Self {
+		self.remove().set(secret)
 	}
 }
+struct VacantDistEntry<'d> {
+	distributions: &'d mut FleetSecretDistributions,
+	owner: String,
+}
+impl<'d> VacantDistEntry<'d> {
+	fn set(self, secret: FleetSecretData) -> OccupiedDistEntry<'d> {
+		let Self {
+			distributions,
+			owner,
+		} = self;
+		let idx = distributions.0.len();
+		distributions.0.push(FleetSecretDistribution {
+			managed: None,
+			owners: BTreeSet::from_iter([owner.clone()]),
+			secret,
+		});
+		OccupiedDistEntry {
+			distributions,
+			owner,
+			idx,
+		}
+	}
+}
 
-#[derive(Serialize, Deserialize, Clone)]
-#[serde(rename_all = "camelCase")]
-#[must_use]
-pub struct FleetSharedSecret {
-	#[serde(default)]
-	#[serde(skip_serializing_if = "Option::is_none")]
-	pub managed: Option<bool>,
-	pub owners: BTreeSet<String>,
-	#[serde(flatten)]
-	pub secret: FleetSecretData,
+enum DistEntry<'d> {
+	Vacant(VacantDistEntry<'d>),
+	Occupied(OccupiedDistEntry<'d>),
+}
+impl DistEntry<'_> {
+	fn remove(self) -> Self {
+		match self {
+			DistEntry::Vacant(_) => self,
+			DistEntry::Occupied(o) => Self::Vacant(o.remove()),
+		}
+	}
+	fn set(self, secret: FleetSecretData) -> Self {
+		Self::Occupied(match self {
+			DistEntry::Vacant(e) => e.set(secret),
+			DistEntry::Occupied(e) => e.set(secret),
+		})
+	}
+}
+
+impl Serialize for FleetSecretDistributions {
+	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+	where
+		S: serde::Serializer,
+	{
+		let mut found_hosts = BTreeSet::new();
+		for ele in self.0.iter() {
+			if ele.owners.is_empty() {
+				panic!("consistency: secret distribution has no defined owners");
+			}
+			for ele in ele.owners.iter() {
+				if !found_hosts.insert(ele) {
+					panic!(
+						"consistency: secret distribution contains duplicate entry for the same host",
+					);
+				}
+			}
+		}
+		match self.0.len() {
+			0 => panic!("consistency: empty distributions"),
+			1 => self.0[0].serialize(serializer),
+			_ => self.0.serialize(serializer),
+		}
+	}
+}
+impl<'de> Deserialize<'de> for FleetSecretDistributions {
+	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+	where
+		D: serde::Deserializer<'de>,
+	{
+		#[derive(Deserialize)]
+		#[serde(untagged)]
+		enum Distributions {
+			One(FleetSecretDistribution),
+			Many(Vec<FleetSecretDistribution>),
+		}
+		let d = Distributions::deserialize(deserializer)?;
+		let ds = match d {
+			Distributions::One(d) => vec![d],
+			Distributions::Many(ds) => ds,
+		};
+		if ds.is_empty() {
+			return Err(de::Error::custom("consistency: empty distributions"));
+		}
+		let mut found_hosts = BTreeSet::new();
+		for ele in ds.iter() {
+			if ele.owners.is_empty() {
+				return Err(de::Error::custom(
+					"consistency: secret distribution has no defined owners",
+				));
+			}
+			for ele in ele.owners.iter() {
+				if !found_hosts.insert(ele) {
+					return Err(de::Error::custom(
+						"consistency: secret distribution contains duplicate entry for the same host",
+					));
+				}
+			}
+		}
+		Ok(Self(ds))
+	}
+}
+
+#[derive(Serialize, Deserialize, Default)]
+pub struct FleetSecrets(BTreeMap<String, FleetSecretDistributions>);
+
+impl FleetSecrets {
+	pub fn keys(&self) -> btree_map::Keys<String, FleetSecretDistributions> {
+		self.0.keys()
+	}
+
+	pub fn keys_for_owner(&self, owner: &str) -> impl Iterator<Item = &String> {
+		self.0
+			.iter()
+			.filter(|(_, d)| d.contains(owner))
+			.map(|(n, _)| n)
+	}
+
+	pub fn drop_owner_no_reencrypt(&mut self, secret: &str, owner: &str) -> bool {
+		let Entry::Occupied(mut dists) = self.0.entry(secret.to_owned()) else {
+			return false;
+		};
+		let DistEntry::Occupied(dist) = dists.get_mut().entry(owner.to_owned()) else {
+			return false;
+		};
+
+		dist.remove();
+
+		if dists.get().0.is_empty() {
+			dists.remove();
+		};
+
+		true
+	}
+	pub fn set_single_data(&mut self, secret: String, owner: String, data: FleetSecretData) {
+		let e = self
+			.0
+			.entry(secret.to_owned())
+			.or_insert_with(|| FleetSecretDistributions(Default::default()));
+		e.entry(owner.to_owned()).set(data);
+	}
+	pub fn set_data(&mut self, secret: String, data: FleetSecretDistribution) {
+		match self.0.entry(secret) {
+			Entry::Vacant(e) => {
+				e.insert(FleetSecretDistributions(vec![data]));
+			}
+			Entry::Occupied(mut e) => {
+				let dists = e.get_mut();
+				dists.extend(data)
+			}
+		}
+	}
+	pub fn get_single(&self, secret: &str, owner: &str) -> Option<&FleetSecretDistribution> {
+		let secret = self.0.get(secret)?;
+		secret.get(owner)
+	}
+	pub fn get(&self, secret: &str) -> Option<&FleetSecretDistributions> {
+		self.0.get(secret)
+	}
+
+	pub fn contains_for_owner(&self, secret: &str, owner: &str) -> bool {
+		let Some(secret) = self.0.get(secret) else {
+			return false;
+		};
+		secret.contains(owner)
+	}
+	pub fn contains(&self, secret: &str) -> bool {
+		self.0.contains_key(secret)
+	}
+	pub fn remove(&mut self, secret: &str) {
+		self.0.remove(secret);
+	}
+
+	fn merge_from_hosts(
+		&mut self,
+		host_secrets: BTreeMap<String, BTreeMap<String, FleetSecretDistribution>>,
+	) {
+		for (host, host_secrets) in host_secrets {
+			for (secret_name, mut secret_data) in host_secrets {
+				secret_data.owners.insert(host.clone());
+				self.set_data(secret_name, secret_data);
+			}
+		}
+	}
 }
modifiedcrates/fleet-base/src/host.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/host.rs
+++ b/crates/fleet-base/src/host.rs
@@ -22,7 +22,7 @@
 
 use crate::{
 	command::MyCommand,
-	fleetdata::{FleetData, FleetHostSecret, FleetSharedSecret},
+	fleetdata::{FleetData, FleetSecretData, FleetSecretDistribution, FleetSecretDistributions},
 	secret::{HostSecretDefinition, SharedSecretDefinition},
 };
 
@@ -623,80 +623,48 @@
 		let config_field = &self.config_field;
 		nix_go!(config_field.sharedSecrets).list_fields()
 	}
-	/// Shared secrets configured in fleet.nix
-	pub fn list_shared(&self) -> Vec<String> {
-		let data = self.data();
-		data.shared_secrets.keys().cloned().collect()
-	}
 	pub fn has_shared(&self, name: &str) -> bool {
 		let data = self.data();
-		data.shared_secrets.contains_key(name)
+		data.secrets.contains(name)
 	}
-	pub fn replace_shared(&self, name: String, shared: FleetSharedSecret) {
+	pub fn replace_shared(&self, name: String, shared: FleetSecretDistribution) {
 		let mut data = self.data_mut();
-		data.shared_secrets.insert(name.to_owned(), shared);
+		data.secrets.set_data(name, shared);
 	}
 	pub fn remove_shared(&self, secret: &str) {
 		let mut data = self.data_mut();
-		data.shared_secrets.remove(secret);
+		data.secrets.remove(secret);
 	}
 
-	pub fn list_secrets(&self, host: &str) -> Vec<String> {
-		let data = self.data();
-		let mut out = data
-			.host_secrets
-			.get(host)
-			.map(|s| s.keys().cloned().collect::<Vec<String>>())
-			.unwrap_or_default();
-
-		for (name, shared) in data.shared_secrets.iter() {
-			if shared.owners.contains(host) {
-				out.push(name.clone());
-			}
-		}
-
-		out
+	pub fn list_secrets_for_owner(&self, host: &str) -> Vec<String> {
+		let data = self.data_mut();
+		data.secrets.keys_for_owner(host).cloned().collect()
+	}
+	pub fn list_secrets(&self) -> Vec<String> {
+		let data = self.data_mut();
+		data.secrets.keys().cloned().collect()
 	}
 
 	pub fn has_secret(&self, host: &str, secret: &str) -> bool {
 		let data = self.data();
-		let Some(host_secrets) = data.host_secrets.get(host) else {
-			return false;
-		};
-		host_secrets.contains_key(secret)
+		data.secrets.contains_for_owner(secret, host)
 	}
-	pub fn insert_secret(&self, host: &str, secret: String, value: FleetHostSecret) {
+	pub fn insert_secret(&self, host: String, secret: String, value: FleetSecretData) {
 		let mut data = self.data_mut();
-		let host_secrets = data.host_secrets.entry(host.to_owned()).or_default();
-		host_secrets.insert(secret, value);
+		data.secrets.set_single_data(secret, host, value);
 	}
 	pub fn remove_secret(&self, host: &str, secret: &str) {
 		let mut data = self.data_mut();
-		let host_secrets = data.host_secrets.entry(host.to_owned()).or_default();
-		host_secrets.remove(secret);
+		data.secrets.drop_owner_no_reencrypt(secret, host);
 	}
 
-	pub fn host_secret(&self, host: &str, secret: &str) -> Result<FleetHostSecret> {
+	pub fn host_secret(&self, host: &str, secret: &str) -> Option<FleetSecretDistribution> {
 		let data = self.data();
-		if let Some(host_secrets) = data.host_secrets.get(host) {
-			if let Some(secret) = host_secrets.get(secret) {
-				return Ok(secret.clone());
-			}
-		};
-		let Some(shared) = data.shared_secrets.get(secret) else {
-			bail!("machine {host} has no secret {secret}");
-		};
-		if !shared.owners.contains(host) {
-			bail!("shared secret {secret} is not owned by {host}");
-		};
-		Ok(FleetHostSecret {
-			managed: shared.managed,
-			secret: shared.secret.clone(),
-		})
+		data.secrets.get_single(secret, host).cloned()
 	}
-	pub fn shared_secret(&self, secret: &str) -> Result<Option<FleetSharedSecret>> {
+	pub fn shared_secret(&self, secret: &str) -> Option<FleetSecretDistributions> {
 		let data = self.data();
-		Ok(data.shared_secrets.get(secret).cloned())
+		data.secrets.get(secret).cloned()
 	}
 	pub fn shared_secret_definition(&self, secret: &str) -> Result<SharedSecretDefinition> {
 		let config_field = &self.config_field;
modifiedcrates/fleet-base/src/opts.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/opts.rs
+++ b/crates/fleet-base/src/opts.rs
@@ -211,7 +211,7 @@
 		}
 		let bytes =
 			std::fs::read_to_string(&fleet_data_path).context("reading fleet state (fleet.nix)")?;
-		let data: Mutex<FleetData> = nixlike::parse_str(&bytes)?;
+		let data = Mutex::new(FleetData::from_str(&bytes)?);
 
 		let mut fetch_settings = FetchSettings::new();
 		fetch_settings.set(c"warn-dirty", c"false");
modifiedflake.lockdiffbeforeafterboth
--- a/flake.lock
+++ b/flake.lock
@@ -2,10 +2,10 @@
   "nodes": {
     "crane": {
       "locked": {
-        "lastModified": 1766181779,
+        "lastModified": 1767461147,
         "owner": "ipetkov",
         "repo": "crane",
-        "rev": "0263f510ba38bee5b7f817498066adaad694e50b",
+        "rev": "7d59256814085fd9666a2ae3e774dc5ee216b630",
         "type": "github"
       },
       "original": {
@@ -37,10 +37,10 @@
         ]
       },
       "locked": {
-        "lastModified": 1765835352,
+        "lastModified": 1767609335,
         "owner": "hercules-ci",
         "repo": "flake-parts",
-        "rev": "a34fae9c08a15ad73f295041fec82323541400a9",
+        "rev": "250481aafeb741edfe23d29195671c19b36b6dca",
         "type": "github"
       },
       "original": {
@@ -126,10 +126,10 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1766181714,
+        "lastModified": 1767657734,
         "owner": "nixos",
         "repo": "nixpkgs",
-        "rev": "ff2da5fee8b3248cac330f14eac98228620beab0",
+        "rev": "d4ccebf51ee4dbeb9df364dce1fe9848635c1258",
         "type": "github"
       },
       "original": {
@@ -190,10 +190,10 @@
         ]
       },
       "locked": {
-        "lastModified": 1766112155,
+        "lastModified": 1767667566,
         "owner": "oxalica",
         "repo": "rust-overlay",
-        "rev": "2a6db3fc1c27ae77f9caa553d7609b223cb770b5",
+        "rev": "056ce5b125ab32ffe78c7d3e394d9da44733c95e",
         "type": "github"
       },
       "original": {
@@ -223,10 +223,10 @@
         ]
       },
       "locked": {
-        "lastModified": 1766000401,
+        "lastModified": 1767468822,
         "owner": "numtide",
         "repo": "treefmt-nix",
-        "rev": "42d96e75aa56a3f70cab7e7dc4a32868db28e8fd",
+        "rev": "d56486eb9493ad9c4777c65932618e9c2d0468fc",
         "type": "github"
       },
       "original": {
modifiedflake.nixdiffbeforeafterboth
--- a/flake.nix
+++ b/flake.nix
@@ -128,11 +128,6 @@
               overlays = [
                 (inputs.rust-overlay.overlays.default)
                 (final: prev: {
-                  boehmgc = prev.boehmgc.overrideAttrs (prevAttrs: {
-                    configureFlags = prevAttrs.configureFlags ++ [
-                      "--enable-gc-assertions"
-                    ];
-                  });
                   # Libsecret is stupidly huge
                   # https://github.com/oxalica/rust-overlay/issues/211
                   libsecret = final.stdenv.mkDerivation {
modifiedmodules/secrets-data.nixdiffbeforeafterboth
--- a/modules/secrets-data.nix
+++ b/modules/secrets-data.nix
@@ -1,7 +1,6 @@
 {
   lib,
   fleetLib,
-  config,
   ...
 }:
 let
@@ -15,15 +14,7 @@
     submodule
     bool
     unspecified
-    ;
-  inherit (lib.attrsets)
-    mapAttrsToList
-    mapAttrs
-    filterAttrs
-    genAttrs
     ;
-  inherit (lib.lists) sort unique concatLists;
-  inherit (lib.strings) toJSON;
 
   secretDataValue = {
     options = {
@@ -71,35 +62,8 @@
         default = null;
       };
     };
-    config = { };
   };
 
-  hostSecretData = {
-    freeformType = attrsOf (submodule secretDataValue);
-    options = {
-      createdAt = mkOption {
-        type = str;
-        description = "Timestamp of secret generation/last rotation.";
-        default = null;
-      };
-      expiresAt = mkOption {
-        type = nullOr str;
-        description = "Expiration timestamp triggering mandatory secret rotation.";
-        default = null;
-      };
-      shared = mkOption {
-        type = bool;
-        description = "Indicates if secret is a shared secret, so other hosts might have the same piece of secret data.";
-        default = false;
-      };
-      generationData = mkOption {
-        type = unspecified;
-        description = "Contextual metadata associated with secret part.";
-        default = null;
-      };
-    };
-    config = { };
-  };
   managerKey = {
     options = {
       name = mkOption {
@@ -121,49 +85,11 @@
         managerKeys = mkOption {
           type = listOf (submodule managerKey);
         };
-        sharedSecrets = mkOption {
-          type = attrsOf (submodule sharedSecretData);
+        secrets = mkOption {
+          type = attrsOf (listOf submodule sharedSecretData);
           default = { };
           description = "Shared secret data.";
-        };
-        hostSecrets = mkOption {
-          type = attrsOf (attrsOf (submodule hostSecretData));
-          default = { };
-          description = "Host-specific secrets.";
-          internal = true;
         };
       };
-      config.hostSecrets =
-        let
-          hostsWithSharedSecrets = unique (
-            concatLists (mapAttrsToList (_: s: s.owners) config.sharedSecrets)
-          );
-          secretsHavingHost = host: filterAttrs (_: secret: lib.elem host secret.owners) config.sharedSecrets;
-          toHostSecret = _: secret: (removeAttrs secret [ "owners" ]) // { shared = true; };
-        in
-        genAttrs hostsWithSharedSecrets (host: mapAttrs toHostSecret (secretsHavingHost host));
     });
-  config = {
-    assertions =
-      (mapAttrsToList (name: secret: {
-        assertion =
-          secret.expectedOwners == null
-          ||
-            sort (a: b: a < b) (config.data.sharedSecrets.${name} or { owners = [ ]; }).owners
-            == sort (a: b: a < b) secret.expectedOwners;
-        message = "Shared secret ${name} is expected to be encrypted for ${toJSON secret.expectedOwners}, but it is encrypted for ${
-          toJSON (config.data.sharedSecrets.${name} or { owners = [ ]; }).owners
-        }. Run fleet secrets regenerate to fix";
-      }) config.sharedSecrets)
-
-      ++ (mapAttrsToList (name: secret: {
-        # TODO: Same assertion should be in host secrets
-        assertion =
-          (config.data.sharedSecrets.${name} or { generationData = null; }).generationData
-          == secret.expectedGenerationData;
-        message = "Shared secret ${name} has unexpected generation data ${toJSON secret.expectedGenerationData} != ${
-          toJSON (config.data.sharedSecrets.${name} or { generationData = null; }).generationData
-        }. Run fleet secrets regenerate to fix";
-      }) config.sharedSecrets);
-  };
 }
modifiedmodules/secrets.nixdiffbeforeafterboth
--- a/modules/secrets.nix
+++ b/modules/secrets.nix
@@ -1,6 +1,5 @@
 {
   lib,
-  config,
   ...
 }:
 let
@@ -18,7 +17,6 @@
     uniq
     ;
   inherit (lib.strings) concatStringsSep;
-  inherit (lib.attrsets) mapAttrs;
 
   sharedSecret =
     { config, ... }:
@@ -54,6 +52,12 @@
             Set to false if host permissions are revoked through alternative mechanisms like firewall rules.
           '';
         };
+        allowDifferent = mkOption {
+          type = bool;
+          description = ''
+            When adding owner, do not update secret value for other owners, instead creating a new distribution
+          '';
+        };
         generator = mkOption {
           type = uniq (nullOr (functionTo package));
           description = ''
@@ -84,32 +88,13 @@
 in
 {
   options = {
-    sharedSecrets = mkOption {
+    secrets = mkOption {
       type = attrsOf (submodule sharedSecret);
       default = { };
       description = "Collection of secrets shared across multiple hosts with configurable ownership";
     };
   };
   config = {
-    hosts = mapAttrs (
-      _: secretMap:
-      let
-        partsOf =
-          s:
-          removeAttrs s [
-            "createdAt"
-            "expiresAt"
-            "generationData"
-          ];
-
-      in
-      {
-        nixos.data.secrets = mapAttrs (_: s: partsOf s) secretMap;
-        # nixos.secrets = mapAttrs (
-        #   _: s: mapAttrs (_: _: {}) (partsOf s)
-        # ) secretMap;
-      }
-    ) config.data.hostSecrets;
     nixpkgs.overlays = [
       (final: prev: {
         mkSecretGenerators =