use serde::{Deserialize, Serialize};
use crate::{
ActionContract, ActionKind, ActionParam, ConfirmationPolicy, OperationKind, ParamType,
ResultSpec, RiskLevel,
};
use {crate::ActionAddress, crate::remote::RemoteActionTarget};
pub const PROVIDER: &str = "tilo.device";
pub const RESOURCE: &str = "devices";
pub const ISSUE: &str = "issue";
pub const RENAME: &str = "rename";
pub const REVOKE: &str = "revoke";
pub const IDENTITIES: &str = "identities";
pub const USE_IDENTITY: &str = "useIdentity";
pub const REMOVE_IDENTITY: &str = "removeIdentity";
pub const PROTECT_IDENTITY: &str = "protectIdentity";
pub const IDENTITY_STEPS: [&str; 4] = [IDENTITIES, USE_IDENTITY, REMOVE_IDENTITY, PROTECT_IDENTITY];
pub fn device_in(args: &serde_json::Value) -> Result<Option<[u8; 32]>, String> {
let Some(text) = args
.get("device")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|text| !text.is_empty())
else {
return Ok(None);
};
let mut key = [0; 32];
hex::decode_to_slice(text, &mut key)
.map_err(|_| format!("{text} is not a device's key: `tilo device ls` lists them"))?;
Ok(Some(key))
}
#[must_use]
pub fn target(action: &str) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, action),
}
}
pub const HANDED_ON: [&str; 7] = [
ISSUE,
RENAME,
REVOKE,
IDENTITIES,
USE_IDENTITY,
REMOVE_IDENTITY,
PROTECT_IDENTITY,
];
#[must_use]
pub fn descriptor(action: &str) -> Option<crate::ActionDescriptor> {
let (label, description, kind, mut contract, params) = listed(action)?;
if matches!(action, ISSUE | REVOKE) {
contract.tags.push(crate::ROOT_ONLY_TAG.to_owned());
}
Some(crate::ActionDescriptor {
did: None,
semantic_identity: None,
address: ActionAddress::new(RESOURCE, action),
resource_kind: "device".to_owned(),
resource_label: "Devices".to_owned(),
action_label: label.to_owned(),
keywords: Vec::new(),
state: crate::ActionState::default(),
icon: None,
description: Some(description.to_owned()),
locus: crate::ExecutionLocus::ClientLocal,
kind,
contract,
input: crate::InputSpec::None,
params,
view: None,
})
}
type Listed = (
&'static str,
&'static str,
OperationKind,
ActionContract,
Vec<ActionParam>,
);
const DEVICE: ActionParam =
ActionParam::required("device", ParamType::Text, "The device's key, in hex.");
fn object(required: &[&str]) -> ResultSpec {
ResultSpec::Json {
schema: serde_json::json!({ "type": "object", "required": required }),
}
}
fn effect(result: ResultSpec) -> ActionContract {
ActionContract {
kind: ActionKind::Outside,
result,
..ActionContract::default()
}
}
fn confirmed(result: ResultSpec) -> ActionContract {
ActionContract {
risk: RiskLevel::Privileged,
confirmation: ConfirmationPolicy::Confirm,
..effect(result)
}
}
fn identity(label: &'static str, description: &'static str) -> Listed {
(
label,
description,
OperationKind::Effect,
confirmed(object(&["id"])),
vec![
ActionParam::required("id", ParamType::Text, "The identity's id, as listed."),
ActionParam::required("confirm", ParamType::Boolean, "You confirm the change."),
],
)
}
fn listed(action: &str) -> Option<Listed> {
Some(match action {
ISSUE => (
"Add a device",
"Print a one-use ticket another computer logs in with as one of the person's \
devices.",
OperationKind::Effect,
effect(object(&["ticket"])),
vec![
ActionParam::optional(
"wait",
ParamType::Boolean,
"Wait for the computer to log in with the ticket.",
),
ActionParam::optional(
"plan",
ParamType::Text,
"The planned machine's entry in your Servers workspace, which the \
computer's certification takes into its own.",
),
ActionParam::optional(
"server",
ParamType::Boolean,
"The computer is a server, which keeps your workspaces: it gets an entry \
in your Servers workspace.",
),
],
),
RENAME => (
"Rename a device",
"Name one of the person's devices in every list of them.",
OperationKind::Effect,
effect(object(&["device", "name"])),
vec![
DEVICE,
ActionParam::required("name", ParamType::Text, "What the device is called."),
],
),
REVOKE => (
"Revoke a device",
"Take one of the person's devices back for good: every device of theirs refuses \
it from now on.",
OperationKind::Effect,
confirmed(object(&["device", "revoked"])),
vec![
DEVICE,
ActionParam::optional(
"reason",
ParamType::Text,
"lost, stolen, retired or compromised (retired when none is given).",
),
],
),
IDENTITIES => (
"List the identities",
"The person's identities this device keeps, without secrets, and which one new \
apps sign in as.",
OperationKind::View,
ActionContract {
result: ResultSpec::Json {
schema: serde_json::json!({ "type": "array", "items": { "type": "object" } }),
},
..ActionContract::view()
},
Vec::new(),
),
USE_IDENTITY => identity(
"Use an identity for new apps",
"Sign apps opened from now on in as this identity.",
),
REMOVE_IDENTITY => identity(
"Remove an identity",
"Delete an identity, with its key, from this device.",
),
PROTECT_IDENTITY => identity(
"Protect an identity's key",
"Move an identity's key from a plain file into protected storage.",
),
_ => return None,
})
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Revoke {
pub device: String,
pub reason: String,
}
impl Revoke {
#[must_use]
pub fn retired(device: &str) -> Self {
Self {
device: device.to_owned(),
reason: "retired".to_owned(),
}
}
#[must_use]
pub fn argument(&self) -> crate::remote::InvokeArgument {
match serde_json::to_value(self) {
Ok(serde_json::Value::Object(named)) => crate::remote::InvokeArgument::Json(named),
_ => crate::remote::InvokeArgument::None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FleetDevice {
pub label: String,
pub key_hex: String,
pub fingerprint: String,
pub current: bool,
pub revoked: bool,
#[serde(default)]
pub kind: KeyKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub browser: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub issued_ms: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_ms: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_active_ms: Option<i64>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub online: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum KeyKind {
#[default]
Device,
Agent,
Script,
Placing,
}
impl KeyKind {
#[must_use]
pub fn of(placing: bool, server_key: bool, agent: bool) -> Self {
if placing {
Self::Placing
} else if server_key {
Self::Script
} else if agent {
Self::Agent
} else {
Self::Device
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Device => "device",
Self::Agent => "agent",
Self::Script => "script",
Self::Placing => "placing",
}
}
}