| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use super::record::invalid; | |
| use crate::{ConfigurationStore, Result, TransactionMode}; | |
| use rusqlite::{Connection, OptionalExtension, params}; | |
| use serde::{Deserialize, Serialize}; | |
| use std::collections::BTreeMap; | |
| use time::{OffsetDateTime, format_description::well_known::Rfc3339}; | |
| /// Canonical identity of the remote endpoint, as named by its transport. | |
| /// Constructing this value does not authenticate the endpoint. | |
| #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] | |
| pub struct PeerId(String); | |
| impl PeerId { | |
| pub fn new(id: String) -> Result<Self> { | |
| if id.is_empty() { | |
| return Err(invalid("empty transport peer identity")); | |
| } | |
| Ok(Self(id)) | |
| } | |
| pub fn as_str(&self) -> &str { | |
| &self.0 | |
| } | |
| } | |
| #[derive(Clone, Copy, PartialEq, Eq)] | |
| pub enum PeerAccessSync { | |
| Snapshot, | |
| Delta, | |
| } | |
| /// A directory Host grant is bound to both the deployment and the peer’s source Root. | |
| #[derive(PartialEq, Eq)] | |
| pub enum PeerGrant { | |
| Device, | |
| Root(String), | |
| } | |
| impl PeerGrant { | |
| fn root_prefix(deployment: &str) -> String { | |
| format!("{deployment}:root:") | |
| } | |
| pub fn for_deployment(grant: &str, deployment: &str) -> Option<Self> { | |
| if grant == deployment { | |
| return Some(Self::Device); | |
| } | |
| grant | |
| .strip_prefix(&Self::root_prefix(deployment)) | |
| .filter(|root| !root.is_empty()) | |
| .map(|root| Self::Root(root.into())) | |
| } | |
| } | |
| impl ConfigurationStore { | |
| pub async fn migrate_host_peer_grants( | |
| &self, | |
| legacy: String, | |
| device_grant: String, | |
| ) -> Result<()> { | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| migrate_device_grants(tx, &legacy, &device_grant) | |
| }) | |
| .await | |
| } | |
| pub async fn prepare_host_peer_access( | |
| &self, | |
| publication_grant: String, | |
| device_grant: String, | |
| ) -> Result<()> { | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| migrate_device_grants(tx, &publication_grant, &device_grant)?; | |
| prune_pairing_invites(tx, &publication_grant) | |
| }) | |
| .await | |
| } | |
| pub async fn grant_host_peer_access(&self, peer: PeerId, host_grant: String) -> Result<()> { | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| clear_local_revocation(tx, &peer)?; | |
| tx.prepare_cached( | |
| "INSERT INTO host_peer_access (peer_id, host_grant) VALUES (?, ?) | |
| ON CONFLICT (peer_id) DO UPDATE SET | |
| host_grant = excluded.host_grant, directory_managed = 0 | |
| WHERE host_peer_access.host_grant <> excluded.host_grant OR directory_managed = 1", | |
| )? | |
| .execute(params![peer.as_str(), host_grant])?; | |
| Ok(()) | |
| }) | |
| .await | |
| } | |
| pub async fn has_host_peer_access(&self, peer: PeerId, host_grant: String) -> Result<bool> { | |
| self.transaction(TransactionMode::Deferred, move |tx| { | |
| Ok(tx | |
| .prepare_cached( | |
| "SELECT EXISTS(SELECT 1 FROM host_peer_access WHERE peer_id = ? AND host_grant = ?)", | |
| )? | |
| .query_row(params![peer.as_str(), host_grant], |row| row.get(0))?) | |
| }) | |
| .await | |
| } | |
| pub async fn host_peer_grant( | |
| &self, | |
| peer: PeerId, | |
| deployment: String, | |
| ) -> Result<Option<PeerGrant>> { | |
| self.transaction(TransactionMode::Deferred, move |tx| { | |
| let grant: Option<String> = tx | |
| .prepare_cached("SELECT host_grant FROM host_peer_access WHERE peer_id = ?")? | |
| .query_row([peer.as_str()], |row| row.get(0)) | |
| .optional()?; | |
| Ok(grant.and_then(|grant| PeerGrant::for_deployment(&grant, &deployment))) | |
| }) | |
| .await | |
| } | |
| pub async fn record_host_peer_activity( | |
| &self, | |
| peer: PeerId, | |
| deployment: String, | |
| at: String, | |
| ) -> Result<bool> { | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| Ok(tx.prepare_cached( | |
| "UPDATE host_peer_access SET last_active_at = ?1 | |
| WHERE peer_id = ?2 AND (host_grant = ?3 OR substr(host_grant, 1, length(?4)) = ?4)", | |
| )?.execute(params![at, peer.as_str(), deployment, PeerGrant::root_prefix(&deployment)])? != 0) | |
| }).await | |
| } | |
| pub async fn revoke_host_peer_access(&self, peer: PeerId) -> Result<bool> { | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| let removed = tx | |
| .prepare_cached("DELETE FROM host_peer_access WHERE peer_id = ?")? | |
| .execute([peer.as_str()])? | |
| != 0; | |
| if removed { | |
| tx.prepare_cached("INSERT INTO host_peer_local_revocations (peer_id) VALUES (?)")? | |
| .execute([peer.as_str()])?; | |
| } | |
| Ok(removed) | |
| }) | |
| .await | |
| } | |
| /// Reconcile directory grants. Return peers whose existing grant changed or was removed. | |
| pub async fn sync_host_peer_access( | |
| &self, | |
| host_grant: String, | |
| mode: PeerAccessSync, | |
| devices: Vec<PeerId>, | |
| hosts: BTreeMap<PeerId, String>, | |
| revoked: Vec<PeerId>, | |
| ) -> Result<Vec<PeerId>> { | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| let mut removed = Vec::new(); | |
| if mode == PeerAccessSync::Snapshot { | |
| let peers: Vec<_> = devices | |
| .iter() | |
| .chain(hosts.keys()) | |
| .map(PeerId::as_str) | |
| .collect(); | |
| let peers = serde_json::to_string(&peers)?; | |
| removed = tx | |
| .prepare_cached( | |
| "DELETE FROM host_peer_access | |
| WHERE directory_managed = 1 AND peer_id NOT IN (SELECT value FROM json_each(?)) | |
| RETURNING peer_id", | |
| )? | |
| .query_map([peers], |row| row.get(0).map(PeerId))? | |
| .collect::<rusqlite::Result<_>>()?; | |
| } | |
| let mut update = tx.prepare_cached( | |
| "UPDATE host_peer_access SET host_grant = ?2, directory_managed = 1 | |
| WHERE peer_id = ?1 AND (directory_managed = 1 OR ?3) | |
| AND (host_grant <> ?2 OR directory_managed = 0) | |
| RETURNING peer_id", | |
| )?; | |
| let mut insert = tx.prepare_cached( | |
| "INSERT INTO host_peer_access (peer_id, host_grant, directory_managed) | |
| SELECT ?1, ?2, 1 WHERE NOT EXISTS ( | |
| SELECT 1 FROM host_peer_local_revocations WHERE peer_id = ?1 | |
| ) | |
| ON CONFLICT (peer_id) DO NOTHING", | |
| )?; | |
| let root_prefix = PeerGrant::root_prefix(&host_grant); | |
| let grants = devices | |
| .iter() | |
| .filter(|peer| !hosts.contains_key(*peer)) | |
| .map(|peer| (peer, None)) | |
| .chain(hosts.iter().map(|(peer, root)| (peer, Some(root)))); | |
| for (peer, root) in grants { | |
| let root_grant = root.map(|root| format!("{root_prefix}{root}")); | |
| let grant = root_grant.as_deref().unwrap_or(&host_grant); | |
| let changed = update | |
| .query_row(params![peer.as_str(), grant, root.is_some()], |row| { | |
| row.get(0).map(PeerId) | |
| }) | |
| .optional()?; | |
| if let Some(peer) = changed { | |
| removed.push(peer); | |
| } else { | |
| insert.execute(params![peer.as_str(), grant])?; | |
| } | |
| } | |
| let mut remove = tx.prepare_cached( | |
| "DELETE FROM host_peer_access WHERE peer_id = ? AND directory_managed = 1", | |
| )?; | |
| for peer in revoked { | |
| if remove.execute([peer.as_str()])? != 0 { | |
| removed.push(peer); | |
| } | |
| } | |
| Ok(removed) | |
| }) | |
| .await | |
| } | |
| } | |
| fn clear_local_revocation(db: &Connection, peer: &PeerId) -> rusqlite::Result<()> { | |
| db.prepare_cached("DELETE FROM host_peer_local_revocations WHERE peer_id = ?")? | |
| .execute([peer.as_str()])?; | |
| Ok(()) | |
| } | |
| pub struct NewHostPeerPairingInvite { | |
| pub invite_id: String, | |
| pub secret_hash: [u8; 32], | |
| pub host_grant: String, | |
| pub label: Option<String>, | |
| pub expires_at_ms: u64, | |
| pub created_at: String, | |
| } | |
| #[derive(Debug, Serialize, Deserialize)] | |
| #[serde(rename_all = "camelCase", deny_unknown_fields)] | |
| pub struct HostPeerAccess { | |
| pub peer_id: String, | |
| pub grant: String, | |
| pub label: String, | |
| pub created_at: String, | |
| pub last_active_at: Option<String>, | |
| } | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | |
| #[serde(rename_all = "camelCase")] | |
| pub enum PairingInviteState { | |
| Pending, | |
| Expired, | |
| // No row remains for this grant. Pruning can also remove an expired row. | |
| Consumed, | |
| } | |
| fn sqlite_ms(ms: u64) -> Result<i64> { | |
| i64::try_from(ms).map_err(|_| invalid("pairing timestamp overflows SQLite INTEGER")) | |
| } | |
| impl ConfigurationStore { | |
| pub async fn create_host_peer_pairing_invite( | |
| &self, | |
| invite: NewHostPeerPairingInvite, | |
| now_ms: u64, | |
| ) -> Result<()> { | |
| let expires_at = sqlite_ms(invite.expires_at_ms)?; | |
| let now_ms = sqlite_ms(now_ms)?; | |
| if expires_at <= now_ms { | |
| return Err(invalid("pairing invite must expire in the future")); | |
| } | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| tx.prepare_cached("DELETE FROM host_peer_pairing_invites WHERE expires_at_ms <= ?")? | |
| .execute([now_ms])?; | |
| tx.prepare_cached( | |
| "INSERT INTO host_peer_pairing_invites | |
| (invite_id, secret_hash, host_grant, label, expires_at_ms, created_at) | |
| VALUES (?, ?, ?, ?, ?, ?)", | |
| )? | |
| .execute(params![ | |
| invite.invite_id, | |
| invite.secret_hash.as_slice(), | |
| invite.host_grant, | |
| invite.label, | |
| expires_at, | |
| invite.created_at, | |
| ])?; | |
| Ok(()) | |
| }) | |
| .await | |
| } | |
| pub async fn host_peer_pairing_invite_state( | |
| &self, | |
| invite_id: String, | |
| host_grant: String, | |
| now_ms: u64, | |
| ) -> Result<PairingInviteState> { | |
| let now_ms = sqlite_ms(now_ms)?; | |
| self.transaction(TransactionMode::Deferred, move |tx| { | |
| let expires_at: Option<i64> = tx | |
| .prepare_cached( | |
| "SELECT expires_at_ms FROM host_peer_pairing_invites | |
| WHERE invite_id = ? AND host_grant = ?", | |
| )? | |
| .query_row(params![invite_id, host_grant], |row| row.get(0)) | |
| .optional()?; | |
| Ok(match expires_at { | |
| Some(expires_at) if expires_at > now_ms => PairingInviteState::Pending, | |
| Some(_) => PairingInviteState::Expired, | |
| None => PairingInviteState::Consumed, | |
| }) | |
| }) | |
| .await | |
| } | |
| pub async fn redeem_host_peer_pairing_invite( | |
| &self, | |
| secret_hash: [u8; 32], | |
| peer: PeerId, | |
| publication_grant: String, | |
| device_grant: String, | |
| device_label: Option<String>, | |
| ) -> Result<bool> { | |
| if device_label.as_ref().is_some_and(|label| label.len() > 128) { | |
| return Err(invalid("device label must be at most 128 bytes")); | |
| } | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| let now = OffsetDateTime::now_utc(); | |
| let now_ms = u64::try_from(now.unix_timestamp_nanos().div_euclid(1_000_000)) | |
| .map_err(|_| invalid("pairing timestamp is outside the Unix clock range"))?; | |
| let now_ms = sqlite_ms(now_ms)?; | |
| let label = tx | |
| .prepare_cached( | |
| "DELETE FROM host_peer_pairing_invites | |
| WHERE secret_hash = ? AND host_grant = ? AND expires_at_ms > ? | |
| RETURNING label", | |
| )? | |
| .query_row( | |
| params![secret_hash.as_slice(), publication_grant, now_ms], | |
| |row| row.get::<_, Option<String>>(0), | |
| ) | |
| .optional()?; | |
| let Some(label) = label else { | |
| return Ok(false); | |
| }; | |
| clear_local_revocation(tx, &peer)?; | |
| let created_at = now | |
| .format(&Rfc3339) | |
| .map_err(|error| invalid(&error.to_string()))?; | |
| tx.prepare_cached( | |
| "INSERT INTO host_peer_access (peer_id, host_grant, label, created_at, last_active_at) | |
| VALUES (?1, ?2, ?3, ?4, ?4) | |
| ON CONFLICT (peer_id) DO UPDATE SET | |
| host_grant = excluded.host_grant, label = excluded.label, | |
| created_at = excluded.created_at, last_active_at = excluded.last_active_at, | |
| directory_managed = 0", | |
| )? | |
| .execute(params![ | |
| peer.as_str(), | |
| device_grant, | |
| label.or(device_label).unwrap_or_default(), | |
| created_at, | |
| ])?; | |
| Ok(true) | |
| }) | |
| .await | |
| } | |
| pub async fn list_host_peer_access(&self) -> Result<Vec<HostPeerAccess>> { | |
| self.transaction(TransactionMode::Deferred, |tx| { | |
| Ok(tx | |
| .prepare_cached( | |
| "SELECT peer_id, host_grant, label, created_at, last_active_at | |
| FROM host_peer_access ORDER BY peer_id", | |
| )? | |
| .query_map([], |row| { | |
| Ok(HostPeerAccess { | |
| peer_id: row.get(0)?, | |
| grant: row.get(1)?, | |
| label: row.get(2)?, | |
| created_at: row.get(3)?, | |
| last_active_at: row.get(4)?, | |
| }) | |
| })? | |
| .collect::<rusqlite::Result<_>>()?) | |
| }) | |
| .await | |
| } | |
| pub async fn prune_host_peer_pairing_invites(&self, publication_grant: String) -> Result<()> { | |
| self.transaction(TransactionMode::Immediate, move |tx| { | |
| prune_pairing_invites(tx, &publication_grant) | |
| }) | |
| .await | |
| } | |
| } | |
| fn migrate_device_grants( | |
| tx: &rusqlite::Connection, | |
| legacy: &str, | |
| device_grant: &str, | |
| ) -> Result<()> { | |
| tx.prepare_cached("UPDATE host_peer_access SET host_grant = ? WHERE host_grant = ?")? | |
| .execute(params![device_grant, legacy])?; | |
| // Do not let a later publication change revive legacy authorizations. | |
| tx.prepare_cached("DELETE FROM host_peer_access WHERE host_grant GLOB 'application.owner:*'")? | |
| .execute([])?; | |
| Ok(()) | |
| } | |
| fn prune_pairing_invites(tx: &rusqlite::Connection, publication_grant: &str) -> Result<()> { | |
| tx.prepare_cached("DELETE FROM host_peer_pairing_invites WHERE host_grant <> ?")? | |
| .execute([publication_grant])?; | |
| Ok(()) | |
| } |