8000 feat!(sessions): newtype session ID, refactor store index by twitchyliquid64 · Pull Request #275 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8000
14 changes: 7 additions & 7 deletions crates/minimald/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use russh::{
server::{Msg, Session},
};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sessions::SessionId;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::task::spawn;
use uuid::Uuid;

use crate::{
connection::{ConnectionError, ConnectionHandle},
Expand Down Expand Up @@ -101,7 +101,7 @@ pub struct ListSessions;
/// An entry in the ListSessions response.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ListSessionsEntry {
pub id: Uuid,
pub id: SessionId,
pub name: Option<String>,
}

Expand Down Expand Up @@ -155,7 +155,7 @@ pub struct GetSessionRecord;
#[serde(rename_all = "snake_case")]
pub enum GetSessionRecordRequest {
Name(String),
Id(Uuid),
Id(SessionId),
}

/// The response for a [`GetSessionRecord`] RPC.
Expand Down Expand Up @@ -205,7 +205,7 @@ pub struct CreateSessionRequest {
/// The response for a [`CreateSession`] RPC.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSessionResponse {
pub id: Uuid,
pub id: SessionId,
}

impl OneshotSshRpc for CreateSession {
Expand Down Expand Up @@ -337,7 +337,7 @@ mod tests {
let mut client = server.connect().await;

let resp = client
.call::<GetSessionRecord>(&GetSessionRecordRequest::Id(Uuid::nil()))
.call::<GetSessionRecord>(&GetSessionRecordRequest::Id(SessionId::nil()))
.await;

assert!(resp.record.is_none());
Expand All @@ -364,7 +364,7 @@ mod tests {
let create_session = client
.call::<CreateSession>(&CreateSessionRequest {
record: sessions::Record {
id: Uuid::nil(),
id: SessionId::nil(),
name: Some("my session".to_string()),
username: None,
project_path: HostAbsPath::try_new("/uwu").unwrap(),
Expand All @@ -373,7 +373,7 @@ mod tests {
})
.await;

assert!(create_session.id != Uuid::nil());
assert!(create_session.id != SessionId::nil());

let get_session = client
.call::<GetSessionRecord>(&GetSessionRecordRequest::Id(create_session.id))
Expand Down
21 changes: 12 additions & 9 deletions crates/minimald/src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@ use std::collections::BTreeMap;

use crate::session::{Session, SessionHandle};
use sessions::{
SessionId,
paths::DaemonAbsPath,
store::{DiskLoader, Loader, SessionKey, SessionObject},
};
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;

/// A short summary of the metadata of a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionInfo {
pub id: Uuid,
pub id: SessionId,
pub name: Option<St 8000 ring>,
}

/// A key you can use to identify a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionKeyPredicate {
Id(Uuid),
Id(SessionId),
Name(String),
}

Expand Down Expand Up @@ -48,7 +48,7 @@ enum ManagerMessage {
List(Responder<Vec<SessionInfo>>),
GetRecord(SessionKeyPredicate, Responder<Option<sessions::Record>>),
GetSession(SessionKeyPredicate, Responder<Option<SessionHandle>>),
CreateSession(sessions::Record, Responder<Uuid>),
CreateSession(sessions::Record, Responder<SessionId>),
}

/// Manages session instances, and session state on disk.
Expand Down Expand Up @@ -82,7 +82,7 @@ impl Manager {
impl<L: Loader> Manager<L> {
fn key_for(&self, pred: &SessionKeyPredicate) -> Result<Option<L::Key>, std::io::Error> {
match pred {
SessionKeyPredicate::Id(id) => self.store.find_by_uuid(id),
SessionKeyPredicate::Id(id) => self.store.find_by_id(id),
SessionKeyPredicate::Name(name) => self.store.find_by_name(name),
}
}
Expand All @@ -102,7 +102,7 @@ impl<L: Loader> Manager<L> {
ManagerMessage::List(r) => {
r.handle(async {
self.store
.list()
.keys()
.map(|k| {
let s = self.store.get(&k)?;
let r = s.record();
Expand All @@ -121,7 +121,7 @@ impl<L: Loader> Manager<L> {
Ok::<_, ResponseError>(match pred {
SessionKeyPredicate::Id(id) => self
.store
.find_by_uuid(&id)?
.find_by_id(&id)?
.map(|k| self.store.get(&k).unwrap().record().clone()),
SessionKeyPredicate::Name(name) => self
.store
Expand Down Expand Up @@ -160,7 +160,7 @@ impl<L: Loader> Manager<L> {
ManagerMessage::CreateSession(record, r) => {
r.handle(async {
let k = self.store.create(record)?;
Ok(*k.uuid())
Ok(*k.id())
})
.await;
}
Expand Down Expand Up @@ -193,7 +193,10 @@ impl ManagerHandle {
}

/// Creates a session based on the given record.
pub async fn create_session(&self, record: sessions::Record) -> Result<Uuid, ResponseError> {
pub async fn create_session(
&self,
record: sessions::Record,
) -> Result<SessionId, ResponseError> {
let (send, recv) = Responder::channel();
// Ignore send errors - the recv will also fail.
let _ = self
Expand Down
19 changes: 8 additions & 11 deletions crates/minimald/src/sftp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ use russh::server::Session;
use russh_sftp::protocol::{
Attrs, Data, File, FileAttributes, Handle, Name, OpenFlags, Status, StatusCode,
};
use sessions::SessionId;
use sessions::paths::DaemonAbsPath;
use tokio::fs::{self, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tokio::task::spawn;
use uuid::Uuid;

use crate::connection::{ConnectionError, ConnectionHandle};
use crate::server::ServerStateHandle;
Expand Down Expand Up @@ -428,7 +428,7 @@ pub(crate) async fn handle_sftp_subsystem(
session.channel_failure(id)?;
return Ok(());
};
let Ok(session_uuid) = Uuid::parse_str(session_id_str) else {
let Ok(session_id) = SessionId::parse_str(session_id_str) else {
tracing::warn!(
value = %session_id_str,
"sftp subsystem rejected on channel {id}: {MINIMAL_SESSION_ID_ENV} is not a uuid",
Expand All @@ -438,18 +438,15 @@ pub(crate) async fn handle_sftp_subsystem(
};

let mngr = s.sessions_manager().await;
let session_handle = match mngr
.get_session(SessionKeyPredicate::Id(session_uuid))
.await
{
let session_handle = match mngr.get_session(SessionKeyPredicate::Id(session_id)).await {
Ok(Some(h)) => h,
Ok(None) => {
tracing::warn!(%session_uuid, "sftp subsystem rejected: unknown session");
tracing::warn!(%session_id, "sftp subsystem rejected: unknown session");
session.channel_failure(id)?;
return Ok(());
}
Err(e) => {
tracing::warn!(%session_uuid, error = %e, "sftp subsystem rejected: lookup failed");
tracing::warn!(%session_id, error = %e, "sftp subsystem rejected: lookup failed");
session.channel_failure(id)?;
return Ok(());
}
Expand All @@ -469,21 +466,21 @@ pub(crate) async fn handle_sftp_subsystem(
mod tests {
use russh_sftp::client::error::Error as SftpClientError;
use russh_sftp::protocol::{OpenFlags, StatusCode};
use sessions::SessionId;
use sessions::paths::HostAbsPath;
use tokio::io::AsyncWriteExt;
use uuid::Uuid;

use crate::rpc::{CreateSession, CreateSessionRequest};
use crate::test_harness::TestServer;

/// Creates a fresh session through the public CreateSession RPC and
/// returns its uuid, mirroring how a real client would set things up
/// before opening an SFTP channel.
async fn fresh_session(client: &mut crate::test_harness::TestClient) -> Uuid {
async fn fresh_session(client: &mut crate::test_harness::TestClient) -> SessionId {
client
.call::<CreateSession>(&CreateSessionRequest {
record: sessions::Record {
id: Uuid::nil(),
id: SessionId::nil(),
name: Some("sftp-test".to_string()),
username: None,
project_path: HostAbsPath::try_new("/tmp").unwrap(),
Expand Down
8 changes: 5 additions & 3 deletions crates/minimald/src/test_harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@ use std::sync::Arc;

use camino::Utf8PathBuf;
use russh::keys::ssh_key;
use sessions::SessionId;
use sessions::paths::DaemonAbsPath;
use tempfile::TempDir;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;

use uuid::Uuid;

use crate::connection::Connection;
use crate::rpc::OneshotSshRpc;
use crate::server::{Config, HostKey, ServerStateHandle};
Expand Down Expand Up @@ -142,7 +141,10 @@ impl TestClient {
/// Sets `MINIMAL_SESSION_ID` on the channel (the env-var contract the
/// server uses to scope the SFTP subsystem to a session), then requests
/// the `sftp` subsystem and hands the channel stream to the SFTP client.
pub(crate) async fn open_sftp(&mut self, session_id: Uuid) -> russh_sftp::client::SftpSession {
pub(crate) async fn open_sftp(
&mut self,
session_id: SessionId,
) -> russh_sftp::client::SftpSession {
let channel = self.handle.channel_open_session().await.unwrap();
channel
.set_env(true, "MINIMAL_SESSION_ID", session_id.to_string())
Expand Down
37 changes: 35 additions & 2 deletions crates/sessions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! shape of a Minimal session.

use std::collections::BTreeMap;
use std::fmt;

use serde::{Deserialize, Serialize};
use uuid::Uuid;
Expand All @@ -16,12 +17,44 @@ pub mod policy;
pub mod store;
pub mod vars;

/// A session ID, a newtype over a UUID.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SessionId(Uuid);

impl SessionId {
#[must_use]
pub fn nil() -> Self {
Self(Uuid::nil())
}

/// Parses the given UUID as a session ID.
///
/// # Errors
///
/// Returns an error if the given string is not a UUID.
pub fn parse_str(s: &str) -> Result<Self, uuid::Error> {
Uuid::parse_str(s).map(Self)
}
}

impl AsRef<Uuid> for SessionId {
fn as_ref(&self) -> &Uuid {
&self.0
}
}

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

/// The on-disk row/record pertaining to a session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
/// Unique ID describing this session.
#[serde(default = "Uuid::nil")]
pub id: Uuid,
#[serde(default = "SessionId::nil")]
pub id: SessionId,
/// The name a user assigned to this session, if
/// one was specifically assigned.
///
Expand Down
Loading
Loading
0