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
23 changes: 22 additions & 1 deletion api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use sled_hardware_types::BaseboardId;
use sush_common::authn::Identity;
use sush_common::jobs::{
Access, JobId, JobLimits, JobOutputStream, JobStatus, JsonJobStatusMap, Session, SessionId,
SignedJob,
SessionSignerNonce, SessionSushNonce, SignedJob,
};
use sush_common::keys::{KeyId, SshPublicKey};
use sush_common::targets::SledVersion;
Expand Down Expand Up @@ -110,6 +110,16 @@ pub trait SushApi {
headers: Header<Authorization>,
) -> Result<HttpResponseOk<Session>, HttpError>;

/// Get the Sush server nonce needed to start a new session.
///
/// The nonce will need to be sent to the signer server, which will give back its own nonce.
/// Both nonces combined (along with the baseboard ID) will form the session ID.
#[endpoint { method = POST, path = "/sessions-nonce" }]
async fn session_start_nonce(
ctx: RequestContext<Self::Context>,
headers: Header<Authorization>,
) -> Result<HttpResponseOk<SessionStartNonce>, HttpError>;

/// Start a new support session.
///
/// There may only be one session active on the rack at a time.
Expand All @@ -122,6 +132,7 @@ pub trait SushApi {
headers: Header<Authorization>,
params: PathParams<SessionIdParam>,
query: QueryParams<WaitParam>,
body: TypedBody<SessionStartBody>,
) -> Result<HttpResponseUpdatedNoContent, HttpError>;

/// End a support session.
Expand Down Expand Up @@ -312,6 +323,16 @@ pub struct JobTargetParams {
pub target: String,
}

#[derive(Serialize, JsonSchema)]
pub struct SessionStartNonce {
pub nonce: SessionSushNonce,
}

#[derive(Deserialize, JsonSchema)]
pub struct SessionStartBody {
pub signer_nonce: SessionSignerNonce,
}

/// Job parameters _not_ specified in the signed job request.
#[derive(
BorshSerialize, BorshDeserialize, Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq,
Expand Down
22 changes: 22 additions & 0 deletions client/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use sush_common::version::VersionInfo;
use crate::AuthzSigner;
use crate::commands::{CommandError, GlobalArgs};
use crate::context::{CommandContext, OutputFormat, StatusDisplayStyle};
use crate::types::SessionStartNonce;

#[derive(Clone, Debug, Default)]
pub struct Cli {
Expand Down Expand Up @@ -165,6 +166,27 @@ impl CommandContext for Cli {
}
}

fn session_start_params(
&self,
baseboard_id: BaseboardId,
nonce: SessionStartNonce,
) -> Result<(), CommandError> {
match self.get_output_format() {
OutputFormat::Json => println!(
"{}",
json!({
"baseboard_id": &baseboard_id.to_string(),
"sush_nonce": &nonce.nonce,
})
),
OutputFormat::Text => {
println!("Baseboard ID: {baseboard_id}");
println!("Sush Nonce: {}", nonce.nonce);
}
}
Ok(())
}

fn session_started(&mut self, session: Session) -> Result<(), CommandError> {
let session_id = session.session_id().to_owned();
*self.session.lock().unwrap() = Some(session);
Expand Down
177 changes: 125 additions & 52 deletions client/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ use sush_common::jobs::JobOutputStream::{self, Stderr, Stdout};
use sush_common::jobs::JobStartRequest;
use sush_common::jobs::{
Access, JobId, JobLimits, JobOutputHash, JobOutputState, JobStatus, JobStatusMap, Session,
SessionId, SignedJob, Streaming, job_status_try_from_json_map,
SessionId, SessionSignerNonce, SignedJob, Streaming, job_status_try_from_json_map,
};
use sush_common::keys::{KeyError, KeyId, Signer as _};
use sush_common::targets::{SledId, Target};
Expand All @@ -64,7 +64,7 @@ use crate::interactive::interactive_job;
use crate::permslip::{PermslipError, PermslipSigner};
use crate::repl::Repl;
use crate::tls;
use crate::types::Error as ApiError;
use crate::types::{Error as ApiError, SessionStartBody};
use crate::{Client, Error as ClientError};

// Names of environment variables for argument defaults
Expand Down Expand Up @@ -491,11 +491,28 @@ pub enum SessionCommand {
key_id: KeyId,
},

/// Get the parameters to send to the signer server to start a session.
StartParams,

/// Start a new support session.
Start {
/// The session to start.
#[arg(requires = "nonce")]
session_id: Option<SessionId>,

/// The signer nonce for the session.
nonce: Option<SessionSignerNonce>,

/// Use `permslip` to sign sessions and jobs with this key name.
#[cfg(feature = "permslip")]
#[arg(short, long, env = SUSH_PERMSLIP_KEY, value_name = "KEY_NAME")]
permslip: Option<String>,

/// The `permslip` server to contact for signing.
#[cfg(feature = "permslip")]
#[arg(long, env = PERMSLIP_URL, requires = "permslip", value_name = "URL")]
permslip_url: Option<String>,

/// Wait for the session to become active.
#[arg(short, long)]
wait: bool,
Expand Down Expand Up @@ -600,9 +617,6 @@ pub struct JobStartArgs {
/// Be sure to quote spaces and characters special to your shell!
command: Option<String>,

/// Job ID within the session.
job_id: Option<JobId>,

/// Job output is binary, not UTF-8 encoded text.
#[arg(short, long, default_value_t = false, requires = "wait")]
binary: bool,
Expand Down Expand Up @@ -980,26 +994,86 @@ async fn session(
Ok(())
}

(SessionCommand::Start { session_id, wait }, Some(client)) => {
let session = if let Some(session_id) = session_id {
Session::new(session_id)
} else {
Session::new(SessionId::random())
};
with_login(ctx, client, async || {
client
.session_start()
.session_id(session.session_id())
.wait(wait)
.send()
.await
(SessionCommand::StartParams, Some(client)) => {
let (baseboard_id, nonce) = with_login(ctx, client, async || {
Ok((
client.target().send().await?.into_inner(),
client.session_start_nonce().send().await?.into_inner(),
))
})
.await?
.into_inner();
ctx.session_started(session)?;
.await?;
ctx.session_start_params(baseboard_id, nonce)?;
Ok(())
}

#[cfg(feature = "permslip")]
(
SessionCommand::Start {
session_id,
nonce,
permslip,
permslip_url,
wait,
},
Some(client),
) => {
let (session_id, nonce) =
if let (Some(session_id), Some(nonce)) = (session_id, nonce) {
(session_id, nonce)
} else {
use sush_common::codephrases::InvalidCodephrase;

let Some(permslip_url) = permslip_url else {
return Err(CommandError::MissingPermslipUrl);
};
let Some(permslip_key) = permslip else {
return Err(CommandError::MissingKeyName);
};
let signer = PermslipSigner::new(permslip_key, &permslip_url).await?;

let (baseboard_id, nonce) = with_login(ctx, client, async || {
Ok((
client.target().send().await?.into_inner(),
client.session_start_nonce().send().await?.into_inner(),
))
})
.await?;

let created = signer.create_session(&baseboard_id, nonce.nonce).await?;

(
created.session_id.to_string().parse().map_err(
|e: InvalidCodephrase| {
CommandError::UnsupportedPermslipResponse(e.to_string())
},
)?,
created.signer_nonce.to_string().parse().map_err(
|e: InvalidCodephrase| {
CommandError::UnsupportedPermslipResponse(e.to_string())
},
)?,
)
};
session_start(ctx, client, session_id, nonce, wait).await
}

#[cfg(not(feature = "permslip"))]
(
SessionCommand::Start {
session_id,
nonce,
wait,
},
Some(client),
) => {
let (session_id, nonce) = if let (Some(session_id), Some(nonce)) = (session_id, nonce) {
(session_id, nonce)
} else {
return Err(CommandError::SigningUnavailable);
};
session_start(ctx, client, session_id, nonce, wait).await
}

(SessionCommand::Allow { key_id, write }, Some(client)) => {
let Some(session_id) = ctx.session_id() else {
return Err(CommandError::MissingSession);
Expand Down Expand Up @@ -1098,7 +1172,6 @@ async fn job(
ref start_args @ JobStartArgs {
command: Some(ref command),
permslip: Some(ref key_name),
ref job_id,
ref permslip_url,
ref interactive,
ref streaming,
Expand All @@ -1108,39 +1181,13 @@ async fn job(
},
client,
) => {
let job_id = if let Some(job_id) = job_id {
job_id.to_owned()
} else {
// Ensure we have a session for the job.
if ctx.session_id().is_none()
&& let Some(client) = client
{
let session =
match with_login(ctx, client, async || client.session().send().await).await
{
Ok(resp) => resp.into_inner(),
Err(CommandError::NotFound(_)) => {
let session = Session::new(SessionId::random());
with_login(ctx, client, async || {
client
.session_start()
.session_id(session.session_id())
.send()
.await
})
.await?;
session
}
Err(err) => return Err(err),
};
ctx.session_started(session)?;
}
ctx.next_job_id()?
let Some(session_id) = ctx.session_id() else {
return Err(CommandError::MissingSession);
};

let Some(permslip_url) = permslip_url else {
return Err(CommandError::MissingPermslipUrl);
};
let job_id = ctx.next_job_id()?;
let target = match target {
TargetArg::Target(target) => target.clone(),
abbreviated => {
Expand Down Expand Up @@ -1180,8 +1227,9 @@ async fn job(
let mut signer = PermslipSigner::new(key_name, permslip_url).await?;
let mut interval = interval(SIGNING_UPDATE_INTERVAL);
interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
let sign = signer.sign(JobStartRequest::new(
let sign = signer.sign_job_request(JobStartRequest::new(
job_id.to_owned(),
session_id,
command,
*interactive,
streaming,
Expand Down Expand Up @@ -1522,6 +1570,28 @@ async fn job_start(
Ok(())
}

async fn session_start(
ctx: &mut impl CommandContext,
client: &Client,
session_id: SessionId,
signer_nonce: SessionSignerNonce,
wait: bool,
) -> Result<(), CommandError> {
let session = Session::new(session_id);
with_login(ctx, client, async || {
client
.session_start()
.session_id(session.session_id())
.wait(wait)
.body(SessionStartBody { signer_nonce })
.send()
.await
})
.await?
.into_inner();
ctx.session_started(session)
}

async fn job_stop(
ctx: &mut impl CommandContext,
client: &Client,
Expand Down Expand Up @@ -2305,6 +2375,9 @@ pub enum CommandError {
Utf8(#[from] std::string::FromUtf8Error),
#[error("❌ WebSocket error: {0}")]
WebSocket(#[from] WebSocketError),
#[cfg(feature = "permslip")]
#[error("❌ Unsupported permslip response: {0}")]
UnsupportedPermslipResponse(String),
}

impl CommandError {
Expand Down
6 changes: 6 additions & 0 deletions client/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use sush_common::version::VersionInfo;

use crate::AuthzSigner;
use crate::commands::{CommandError, GlobalArgs};
use crate::types::SessionStartNonce;

/// Authorization state: the credentials that authenticated us, and the
/// ephemeral key that binds each request we make.
Expand Down Expand Up @@ -115,6 +116,11 @@ pub trait CommandContext: Clone + Send + Sync {
}
fn session_id(&self) -> Option<SessionId>;
fn next_job_id(&self) -> Result<JobId, CommandError>;
fn session_start_params(
&self,
baseboard_id: BaseboardId,
nonce: SessionStartNonce,
) -> Result<(), CommandError>;
fn session_started(&mut self, session: Session) -> Result<(), CommandError>;
fn session_stopped(&mut self, session_id: &SessionId) -> Result<(), CommandError>;
fn attach_allowed(&mut self, key_id: &KeyId, access: Access);
Expand Down
2 changes: 2 additions & 0 deletions client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ progenitor::generate_api!(
KeyId = sush_common::keys::KeyId,
Signature = sush_common::keys::Signature,
SignedForJobStartRequest = sush_common::jobs::SignedJob,
SessionSignerNonce = sush_common::jobs::SessionSignerNonce,
SessionSushNonce = sush_common::jobs::SessionSushNonce,
SledVersion = sush_common::targets::SledVersion,
Streaming = sush_common::jobs::Streaming,
VersionInfo = sush_common::version::VersionInfo,
Expand Down
Loading
Loading