remote: Add SSH transport
Requesters and approvers on other boxes log in to the broker's box as `slop`. Each key has a forced `slop-broker remote <role> <name>`, which joins the session to the broker through a socket only `slop` can open, so the broker trusts the name like it trusts a vsock CID. A key does one job: the module refuses a key used for both roles. `slop` and `slop-approve` take `ssh:<destination>` addresses, from `SLOP_BROKER` and `SLOP_APPROVE` or else `~/.config/slop/config.toml`, and an approver connection now carries many requests. The `programs.slop` home-manager module installs both clients, a `Host` entry per key and that config file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d71bbb04db
commit
73deb0efb8
12 files changed
+603
-103
No files matched your search
@@ -34,6 +34,11 @@
|
||||
};
|
||||
};
|
||||
|
||||
homeModules = rec {
|
||||
slop = withPackage ./nix/modules/home-manager/slop.nix [ "programs" "slop" ];
|
||||
default = slop;
|
||||
};
|
||||
|
||||
# The VM test needs KVM
|
||||
checks = forSystems (pkgs: {
|
||||
package = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# The clients (`programs.slop`): `slop` and `slop-approve` reaching a broker on another box over SSH.
|
||||
{ lib, pkgs, config, ... }:
|
||||
let
|
||||
inherit (lib) mkIf mkMerge optionalAttrs;
|
||||
mkOpt' = type: default: description: lib.mkOption { inherit type default description; };
|
||||
mkBoolOpt' = default: description: mkOpt' lib.types.bool default description;
|
||||
|
||||
cfg = config.programs.slop;
|
||||
|
||||
# Each job gets its own `Host` alias, so the right key is used even with both on one box
|
||||
hostBlock = keyFile: {
|
||||
hostname = cfg.host;
|
||||
user = "slop";
|
||||
identityFile = keyFile;
|
||||
identitiesOnly = true;
|
||||
extraOptions.IdentityAgent = "none";
|
||||
};
|
||||
|
||||
# Read by every `slop` and `slop-approve`, however they were installed, so a switch
|
||||
# reaches every shell at once; `SLOP_BROKER` and `SLOP_APPROVE` still override it.
|
||||
clientConfig = (pkgs.formats.toml { }).generate "slop-config.toml" (
|
||||
optionalAttrs cfg.request.enable { broker = "ssh:slop-request"; } //
|
||||
optionalAttrs cfg.approve.enable { approve = "ssh:slop-approve"; }
|
||||
);
|
||||
|
||||
jobOpts = what: with lib.types; {
|
||||
enable = mkBoolOpt' false "Whether to ${what} over SSH.";
|
||||
keyFile = mkOpt' str "" "SSH private key for this job, configured for it in `services.slop-broker` on the broker's box.";
|
||||
};
|
||||
in
|
||||
{
|
||||
options.programs.slop = with lib.types; {
|
||||
package = lib.mkOption {
|
||||
type = package;
|
||||
default = pkgs.slop-broker;
|
||||
defaultText = lib.literalExpression "pkgs.slop-broker";
|
||||
description = "slop-broker package; the flake's modules default to its own.";
|
||||
};
|
||||
host = mkOpt' str null "Box running `slop-broker`.";
|
||||
request = jobOpts "send requests with `slop`";
|
||||
approve = jobOpts "answer requests with `slop-approve`";
|
||||
};
|
||||
|
||||
config = mkMerge [
|
||||
(mkIf (cfg.request.enable || cfg.approve.enable) {
|
||||
assertions = [
|
||||
{
|
||||
assertion = cfg.request.enable -> cfg.request.keyFile != "";
|
||||
message = "programs.slop.request needs a key file.";
|
||||
}
|
||||
{
|
||||
assertion = cfg.approve.enable -> cfg.approve.keyFile != "";
|
||||
message = "programs.slop.approve needs a key file.";
|
||||
}
|
||||
];
|
||||
|
||||
home.packages = [ cfg.package ];
|
||||
xdg.configFile."slop/config.toml".source = clientConfig;
|
||||
programs.ssh.enable = true;
|
||||
})
|
||||
(mkIf cfg.request.enable {
|
||||
programs.ssh.matchBlocks.slop-request = hostBlock cfg.request.keyFile;
|
||||
})
|
||||
(mkIf cfg.approve.enable {
|
||||
programs.ssh.matchBlocks.slop-approve = hostBlock cfg.approve.keyFile;
|
||||
})
|
||||
];
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
# The broker daemon (`services.slop-broker`): writes its TOML configuration and runs it hardened
|
||||
# as its own user.
|
||||
# The broker daemon (`services.slop-broker`): writes its TOML configuration, runs it hardened as
|
||||
# its own user, and sets up the `slop` user whose SSH keys reach it from other boxes.
|
||||
{ lib, pkgs, config, ... }:
|
||||
let
|
||||
inherit (builtins) any attrNames attrValues isAttrs isList;
|
||||
inherit (lib) mkIf mkOption mapAttrs filterAttrs optional optionals hasPrefix concatStringsSep;
|
||||
inherit (builtins) any attrValues attrNames isAttrs isList length concatLists;
|
||||
inherit (lib) mkIf mkMerge mkOption mapAttrs mapAttrsToList filterAttrs optional optionals hasPrefix hasInfix unique concatStringsSep;
|
||||
|
||||
mkOpt' = type: default: description: mkOption { inherit type default description; };
|
||||
mkBoolOpt' = default: description: mkOpt' lib.types.bool default description;
|
||||
@@ -16,6 +16,15 @@ let
|
||||
hasVsockRequesters = any (r: r.vsockCid != null) (attrValues cfg.requesters);
|
||||
missingPolicies = attrNames (filterAttrs (_: r: !(cfg.policies ? ${r.policy})) cfg.requesters);
|
||||
|
||||
# Each SSH key gets a forced command naming its owner and role
|
||||
remoteUser = "slop";
|
||||
remoteKeys = concatLists (
|
||||
mapAttrsToList (n: r: map (key: { inherit key; role = "requester"; name = n; }) r.sshKeys) cfg.requesters
|
||||
++ mapAttrsToList (n: keys: map (key: { inherit key; role = "approver"; name = n; }) keys) cfg.sshApprovers
|
||||
);
|
||||
hasRemote = remoteKeys != [ ];
|
||||
authorizedKey = k: ''restrict,command="${cfg.package}/bin/slop-broker remote ${k.role} ${k.name}" ${k.key}'';
|
||||
|
||||
# TOML has no null; leave those keys out
|
||||
dropNulls = v:
|
||||
if isAttrs v then mapAttrs (_: dropNulls) (filterAttrs (_: x: x != null) v)
|
||||
@@ -50,6 +59,7 @@ let
|
||||
options = {
|
||||
vsockCid = mkOpt' (nullOr ints.unsigned) null "CID of a VM that connects over vsock.";
|
||||
uid = mkOpt' (nullOr ints.unsigned) null "UID of a local requester.";
|
||||
sshKeys = mkOpt' (listOf str) [ ] "SSH public keys a requester on another box connects with (as `${remoteUser}`).";
|
||||
policy = mkOpt' str null "Name of the requester's policy in `policies`.";
|
||||
};
|
||||
};
|
||||
@@ -58,6 +68,7 @@ let
|
||||
requesters = mapAttrs (_: r: {
|
||||
vsock_cid = r.vsockCid;
|
||||
inherit (r) uid policy;
|
||||
remote = r.sshKeys != [ ];
|
||||
}) cfg.requesters;
|
||||
|
||||
policies = mapAttrs (_: p: {
|
||||
@@ -79,6 +90,13 @@ let
|
||||
known_hosts = "/var/lib/slop-broker/known_hosts";
|
||||
targets = mapAttrs (_: t: { inherit (t) hostname user; ssh_opts = t.sshOpts; }) cfg.ssh.targets;
|
||||
} else null;
|
||||
|
||||
remote = if hasRemote then {
|
||||
socket = "/run/slop-broker/remote.sock";
|
||||
user = remoteUser;
|
||||
approvers = attrNames cfg.sshApprovers;
|
||||
} else null;
|
||||
|
||||
home_assistant = if ha.enable then {
|
||||
inherit (ha) url;
|
||||
notify_service = ha.notifyService;
|
||||
@@ -99,7 +117,9 @@ in
|
||||
|
||||
vsockPort = mkOpt' ints.unsigned 6262 "vsock port to listen on for VM requesters.";
|
||||
timeout = mkOpt' duration "5m" "How long a request waits for an approver.";
|
||||
approvers = mkOpt' (listOf str) [ ] "Users allowed to answer requests with `slop-approve`.";
|
||||
approvers = mkOpt' (listOf str) [ ] "Local users allowed to answer requests with `slop-approve`.";
|
||||
sshApprovers = mkOpt' (attrsOf (listOf str)) { }
|
||||
"Approvers on other boxes, by name, with the SSH public keys `slop-approve` connects with.";
|
||||
policies = mkOpt' (attrsOf (submodule policyOpts)) { } "Named policies; several requesters can share one.";
|
||||
requesters = mkOpt' (attrsOf (submodule requesterOpts)) { } "Who may send requests, and which policy applies.";
|
||||
|
||||
@@ -135,22 +155,38 @@ in
|
||||
assertion = missingPolicies == [ ];
|
||||
message = "slop-broker requesters with an unknown policy: ${concatStringsSep ", " missingPolicies}.";
|
||||
}
|
||||
{
|
||||
assertion = length (unique (map (k: k.key) remoteKeys)) == length remoteKeys;
|
||||
message = "slop-broker SSH keys must be distinct; use separate keys for requesting and approving.";
|
||||
}
|
||||
{
|
||||
assertion = ha.enable -> (ha.url != "" && ha.notifyService != "" && ha.deviceId != "" && isRuntimePath ha.tokenFile);
|
||||
message = "slop-broker Home Assistant needs a URL, service, device ID and runtime token file.";
|
||||
}
|
||||
];
|
||||
|
||||
users = {
|
||||
groups = {
|
||||
slop-broker = { };
|
||||
slop-broker-approve.members = cfg.approvers;
|
||||
};
|
||||
users.slop-broker = {
|
||||
isSystemUser = true;
|
||||
group = "slop-broker";
|
||||
};
|
||||
};
|
||||
users = mkMerge [
|
||||
{
|
||||
groups = {
|
||||
slop-broker = { };
|
||||
slop-broker-approve.members = cfg.approvers;
|
||||
};
|
||||
users.slop-broker = {
|
||||
isSystemUser = true;
|
||||
group = "slop-broker";
|
||||
};
|
||||
}
|
||||
# Remote requesters and approvers log in as this user; their keys only run `slop-broker remote`
|
||||
(mkIf hasRemote {
|
||||
groups.${remoteUser} = { };
|
||||
users.${remoteUser} = {
|
||||
isSystemUser = true;
|
||||
group = remoteUser;
|
||||
shell = pkgs.bashInteractive;
|
||||
openssh.authorizedKeys.keys = map authorizedKey remoteKeys;
|
||||
};
|
||||
})
|
||||
];
|
||||
|
||||
environment.systemPackages = [ cfg.package ];
|
||||
boot.kernelModules = optional hasVsockRequesters "vhost_vsock";
|
||||
@@ -168,7 +204,7 @@ in
|
||||
|
||||
User = "slop-broker";
|
||||
Group = "slop-broker";
|
||||
SupplementaryGroups = [ "slop-broker-approve" ];
|
||||
SupplementaryGroups = [ "slop-broker-approve" ] ++ optional hasRemote remoteUser;
|
||||
RuntimeDirectory = "slop-broker";
|
||||
RuntimeDirectoryMode = "0755";
|
||||
StateDirectory = "slop-broker";
|
||||
|
||||
+34
-1
@@ -5,8 +5,10 @@ let
|
||||
inherit (pkgs) lib;
|
||||
|
||||
key = pkgs.runCommand "test-key" { nativeBuildInputs = [ pkgs.openssh ]; } ''
|
||||
mkdir $out && ssh-keygen -q -t ed25519 -N "" -f $out/key
|
||||
mkdir $out
|
||||
for k in key requester approver; do ssh-keygen -q -t ed25519 -N "" -f $out/$k; done
|
||||
'';
|
||||
publicKey = name: builtins.readFile "${key}/${name}.pub";
|
||||
in
|
||||
pkgs.testers.runNixOSTest {
|
||||
name = "slop-broker";
|
||||
@@ -20,6 +22,11 @@ pkgs.testers.runNixOSTest {
|
||||
users.users.reviewer.isNormalUser = true;
|
||||
users.users.agent.isNormalUser = true;
|
||||
environment.systemPackages = [ pkgs.util-linux ];
|
||||
programs.ssh.extraConfig = ''
|
||||
StrictHostKeyChecking no
|
||||
UserKnownHostsFile /dev/null
|
||||
LogLevel ERROR
|
||||
'';
|
||||
# Not a store path, as the module requires
|
||||
environment.etc."slop-broker-test/key".source = "${key}/key";
|
||||
|
||||
@@ -32,10 +39,19 @@ pkgs.testers.runNixOSTest {
|
||||
query.action = "auto";
|
||||
ssh = { action = "ask"; leases = [ "5m" ]; rules = [ { match.target = "denied"; action = "deny"; } ]; };
|
||||
};
|
||||
policies.workstation.ops.query.action = "auto";
|
||||
|
||||
requesters.agent = {
|
||||
vsockCid = 1;
|
||||
policy = "agent";
|
||||
};
|
||||
requesters.workstation = {
|
||||
sshKeys = [ (publicKey "requester") ];
|
||||
policy = "workstation";
|
||||
};
|
||||
|
||||
sshApprovers.laptop = [ (publicKey "approver") ];
|
||||
|
||||
ssh = {
|
||||
enable = true;
|
||||
keyFile = "/etc/slop-broker-test/key";
|
||||
@@ -102,8 +118,25 @@ pkgs.testers.runNixOSTest {
|
||||
machine.wait_until_succeeds("grep -q 'denied by approver' /tmp/out3")
|
||||
machine.wait_until_succeeds("grep -qx 125 /tmp/out3", timeout=30)
|
||||
|
||||
# Over SSH: each key names its owner and role
|
||||
for user, k in [("agent", "requester"), ("reviewer", "approver")]:
|
||||
machine.succeed(f"install -D -m600 -o {user} ${key}/{k} /home/{user}/.ssh/id_ed25519")
|
||||
remote = "SLOP_BROKER=ssh:slop@localhost"
|
||||
out = machine.succeed(f"su agent -c \"{remote} slop status local sshd.service\"")
|
||||
assert "sshd.service" in out, out
|
||||
status, out = machine.execute(f"su agent -c \"{remote} slop ssh local -- true\" 2>&1")
|
||||
assert status == 125 and "denied by policy" in out, (status, out)
|
||||
status, out = machine.execute("su agent -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve list' 2>&1")
|
||||
assert status != 0 and "for sending requests" in out, (status, out)
|
||||
|
||||
machine.execute(f"su agent -c \"{env} slop ssh other -- echo remote approval\" > /tmp/out4 2>&1 &")
|
||||
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'")
|
||||
machine.succeed("su reviewer -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve once'")
|
||||
machine.wait_until_succeeds("grep -q 'remote approval' /tmp/out4")
|
||||
|
||||
audit = machine.succeed("su reviewer -c 'slop-approve log'")
|
||||
print(audit)
|
||||
assert "agent asks: ssh local" in audit and "answered 5m by reviewer" in audit, audit
|
||||
assert "answered once by laptop (ssh)" in audit, audit
|
||||
'';
|
||||
}
|
||||
+92
-58
@@ -1,52 +1,68 @@
|
||||
//! The approver socket and the `slop-approve` client, using the same framing and encoding as
|
||||
//! requesters ([`ApproveRequest`] in, [`ApproveResponse`] out).
|
||||
use std::path::Path;
|
||||
//! Approvers' connections and the `slop-approve` client, using the same framing and encoding as
|
||||
//! requesters: any number of [`ApproveRequest`]s, each answered with an [`ApproveResponse`].
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::UnixListener;
|
||||
|
||||
use crate::audit::{Event, short};
|
||||
use crate::config::user_name;
|
||||
use crate::ops::printable;
|
||||
use crate::proto::{ApproveRequest, ApproveResponse, MAX_LOG_RECORDS, receive, send, transport};
|
||||
use crate::proto::{ApproveRequest, ApproveResponse, MAX_LOG_RECORDS, Transport, receive, send, transport};
|
||||
use crate::queue::{Decision, PendingInfo};
|
||||
use crate::remote::{Role, Stream, connect};
|
||||
use crate::server::Broker;
|
||||
|
||||
/// Socket permissions admit approvers; requesters are refused even if misconfigured into the group.
|
||||
pub const DEFAULT_ADDRESS: &str = "unix:/run/slop-broker/approve.sock";
|
||||
|
||||
/// The local approve socket. Its permissions admit approvers; requesters are refused even if
|
||||
/// misconfigured into the group.
|
||||
pub async fn listen(broker: Arc<Broker>, listener: UnixListener) -> Result<()> {
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let uid = stream.peer_cred()?.uid();
|
||||
if let Some(requester) = broker.config.requester_by_uid(uid) {
|
||||
broker.audit.log(Event::Unknown { peer: format!("requester {requester} on the approve socket") });
|
||||
continue;
|
||||
}
|
||||
|
||||
let broker = broker.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = serve(broker, stream).await;
|
||||
let _ = serve(broker, stream, user_name(uid)).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(broker: Arc<Broker>, stream: UnixStream) -> Result<()> {
|
||||
let uid = stream.peer_cred()?.uid();
|
||||
/// Answers `approver`'s requests until it disconnects.
|
||||
pub async fn serve<S: AsyncRead + AsyncWrite + Unpin>(broker: Arc<Broker>, stream: S, approver: String) -> Result<()> {
|
||||
let mut transport = transport(stream);
|
||||
let request = tokio::time::timeout(Duration::from_secs(10), receive::<_, ApproveRequest>(&mut transport)).await;
|
||||
let response = match request {
|
||||
Ok(Ok(Some(request))) => {
|
||||
answer(&broker, uid, request).unwrap_or_else(|e| ApproveResponse::Error(format!("{e:#}")))
|
||||
}
|
||||
Ok(Err(error)) => ApproveResponse::Error(format!("{error:#}")),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
send(&mut transport, &response).await
|
||||
let first = tokio::time::timeout(Duration::from_secs(10), receive::<_, ApproveRequest>(&mut transport)).await;
|
||||
let mut request = first.unwrap_or(Ok(None));
|
||||
|
||||
loop {
|
||||
let response = match request {
|
||||
Ok(Some(request)) => {
|
||||
answer(&broker, &approver, request).unwrap_or_else(|e| ApproveResponse::Error(format!("{e:#}")))
|
||||
}
|
||||
Ok(None) => return Ok(()),
|
||||
Err(error) => {
|
||||
// The stream can't be trusted after a bad frame.
|
||||
return send(&mut transport, &ApproveResponse::Error(format!("{error:#}"))).await;
|
||||
}
|
||||
};
|
||||
|
||||
send(&mut transport, &response).await?;
|
||||
request = receive(&mut transport).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn answer(broker: &Broker, uid: u32, request: ApproveRequest) -> Result<ApproveResponse> {
|
||||
if broker.config.requester_by_uid(uid).is_some() {
|
||||
bail!("requesters cannot approve");
|
||||
}
|
||||
fn answer(broker: &Broker, approver: &str, request: ApproveRequest) -> Result<ApproveResponse> {
|
||||
match request {
|
||||
ApproveRequest::List => Ok(ApproveResponse::Pending(broker.queue.list())),
|
||||
ApproveRequest::Decide { id, decision } => {
|
||||
approve(broker, &id, decision, &user_name(uid))?;
|
||||
approve(broker, &id, decision, approver)?;
|
||||
Ok(ApproveResponse::Recorded)
|
||||
}
|
||||
ApproveRequest::Log { count } => Ok(ApproveResponse::Log(broker.audit.tail(count.min(MAX_LOG_RECORDS))?)),
|
||||
@@ -66,21 +82,28 @@ pub fn approve(broker: &Broker, id: &str, decision: Decision, approver: &str) ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn call(socket: &Path, request: ApproveRequest) -> Result<ApproveResponse> {
|
||||
let stream = UnixStream::connect(socket).await.map_err(|e| anyhow!("connecting to {}: {e}", socket.display()))?;
|
||||
let mut transport = transport(stream);
|
||||
send(&mut transport, &request).await?;
|
||||
match receive(&mut transport).await? {
|
||||
Some(ApproveResponse::Error(error)) => bail!("{error}"),
|
||||
Some(response) => Ok(response),
|
||||
None => bail!("the broker closed the connection"),
|
||||
}
|
||||
}
|
||||
/// The client's one connection to the broker.
|
||||
pub struct Client(Transport<Box<dyn Stream>>);
|
||||
|
||||
async fn list(socket: &Path) -> Result<Vec<PendingInfo>> {
|
||||
match call(socket, ApproveRequest::List).await? {
|
||||
ApproveResponse::Pending(entries) => Ok(entries),
|
||||
_ => bail!("unexpected response from the broker"),
|
||||
impl Client {
|
||||
pub async fn connect(address: &str) -> Result<Client> {
|
||||
Ok(Client(transport(connect(address, Role::Approver).await?)))
|
||||
}
|
||||
|
||||
async fn call(&mut self, request: ApproveRequest) -> Result<ApproveResponse> {
|
||||
send(&mut self.0, &request).await?;
|
||||
match receive(&mut self.0).await? {
|
||||
Some(ApproveResponse::Error(error)) => bail!("{error}"),
|
||||
Some(response) => Ok(response),
|
||||
None => bail!("the broker closed the connection"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn list(&mut self) -> Result<Vec<PendingInfo>> {
|
||||
match self.call(ApproveRequest::List).await? {
|
||||
ApproveResponse::Pending(entries) => Ok(entries),
|
||||
_ => bail!("unexpected response from the broker"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,40 +149,50 @@ const USAGE: &str = "usage: slop-approve answer requests one
|
||||
slop-approve <decision> answer the only pending request
|
||||
slop-approve log [-n 50] [--json]
|
||||
recent requests, decisions and results
|
||||
IDs can be shortened to any unique prefix.";
|
||||
IDs can be shortened to any unique prefix. SLOP_APPROVE, or approve in ~/.config/slop/config.toml,
|
||||
selects the broker: unix:<path> (the default is unix:/run/slop-broker/approve.sock) or
|
||||
ssh:<destination>.";
|
||||
|
||||
pub async fn main(socket: &Path, args: &[String]) -> Result<()> {
|
||||
pub async fn main(address: &str, args: &[String]) -> Result<()> {
|
||||
use std::io::IsTerminal;
|
||||
|
||||
if let [help] = args
|
||||
&& ["help", "--help", "-h"].contains(&help.as_str())
|
||||
{
|
||||
println!("{USAGE}");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let client = &mut Client::connect(address).await?;
|
||||
match args {
|
||||
[] if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() => interactive(socket).await?,
|
||||
[] => print_list(socket).await?,
|
||||
[list] if list == "list" => print_list(socket).await?,
|
||||
[help] if help == "help" || help == "--help" || help == "-h" => println!("{USAGE}"),
|
||||
[log, options @ ..] if log == "log" => print_log(socket, options).await?,
|
||||
[] if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() => interactive(client).await?,
|
||||
[] => print_list(client).await?,
|
||||
[list] if list == "list" => print_list(client).await?,
|
||||
[log, options @ ..] if log == "log" => print_log(client, options).await?,
|
||||
[show, id] if show == "show" => {
|
||||
let entries = list(socket).await?;
|
||||
let entries = client.list().await?;
|
||||
print!("{}", printable(&format(resolve(&entries, id)?, true)));
|
||||
}
|
||||
[decision] => {
|
||||
let decision = Decision::parse(decision).map_err(|_| anyhow!("{USAGE}"))?;
|
||||
let entries = list(socket).await?;
|
||||
let entries = client.list().await?;
|
||||
let [entry] = entries.as_slice() else {
|
||||
bail!("{} requests are pending; give an ID", entries.len());
|
||||
};
|
||||
decide(socket, &entry.id, decision).await?;
|
||||
decide(client, &entry.id, decision).await?;
|
||||
}
|
||||
[id, decision] => {
|
||||
let decision = Decision::parse(decision)?;
|
||||
let entries = list(socket).await?;
|
||||
decide(socket, &resolve(&entries, id)?.id, decision).await?;
|
||||
let entries = client.list().await?;
|
||||
decide(client, &resolve(&entries, id)?.id, decision).await?;
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn print_list(socket: &Path) -> Result<()> {
|
||||
let entries = list(socket).await?;
|
||||
async fn print_list(client: &mut Client) -> Result<()> {
|
||||
let entries = client.list().await?;
|
||||
if entries.is_empty() {
|
||||
println!("No pending requests.");
|
||||
}
|
||||
@@ -170,7 +203,7 @@ async fn print_list(socket: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn print_log(socket: &Path, options: &[String]) -> Result<()> {
|
||||
async fn print_log(client: &mut Client, options: &[String]) -> Result<()> {
|
||||
let (mut count, mut json) = (50, false);
|
||||
let mut options = options.iter();
|
||||
while let Some(option) = options.next() {
|
||||
@@ -186,7 +219,8 @@ async fn print_log(socket: &Path, options: &[String]) -> Result<()> {
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
let ApproveResponse::Log(records) = call(socket, ApproveRequest::Log { count }).await? else {
|
||||
|
||||
let ApproveResponse::Log(records) = client.call(ApproveRequest::Log { count }).await? else {
|
||||
bail!("unexpected response from the broker");
|
||||
};
|
||||
|
||||
@@ -200,21 +234,21 @@ async fn print_log(socket: &Path, options: &[String]) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn decide(socket: &Path, id: &str, decision: Decision) -> Result<()> {
|
||||
call(socket, ApproveRequest::Decide { id: id.to_owned(), decision }).await?;
|
||||
async fn decide(client: &mut Client, id: &str, decision: Decision) -> Result<()> {
|
||||
client.call(ApproveRequest::Decide { id: id.to_owned(), decision }).await?;
|
||||
println!("Recorded: {} for {}.", decision.name(), short(id));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shows pending requests one at a time and asks for an answer, then waits for more.
|
||||
async fn interactive(socket: &Path) -> Result<()> {
|
||||
async fn interactive(client: &mut Client) -> Result<()> {
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
let mut input = BufReader::new(tokio::io::stdin()).lines();
|
||||
let mut skipped = std::collections::HashSet::new();
|
||||
let mut waiting = false;
|
||||
|
||||
loop {
|
||||
let entries = list(socket).await?;
|
||||
let entries = client.list().await?;
|
||||
skipped.retain(|id| entries.iter().any(|e| &e.id == id));
|
||||
let Some(entry) = entries.iter().find(|e| !skipped.contains(&e.id)) else {
|
||||
if !waiting {
|
||||
@@ -260,7 +294,7 @@ async fn interactive(socket: &Path) -> Result<()> {
|
||||
};
|
||||
|
||||
// The request may have expired or been answered elsewhere while waiting.
|
||||
if let Err(error) = decide(socket, &entry.id, decision).await {
|
||||
if let Err(error) = decide(client, &entry.id, decision).await {
|
||||
println!("{error:#}");
|
||||
}
|
||||
break;
|
||||
|
||||
+35
-10
@@ -6,7 +6,8 @@ use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use nix::sys::signal::{SigHandler, Signal, signal};
|
||||
|
||||
use slop_broker::config::{Config, credential, group_id};
|
||||
use slop_broker::config::{Config, credential, group_id, user_id};
|
||||
use slop_broker::remote::{self, Role};
|
||||
use slop_broker::server::{self, Broker};
|
||||
use slop_broker::{approve, ha};
|
||||
|
||||
@@ -20,31 +21,42 @@ enum Command {
|
||||
},
|
||||
/// Answer requests (also available as `slop-approve`).
|
||||
Approve {
|
||||
#[arg(long, default_value = DEFAULT_APPROVE_SOCKET)]
|
||||
socket: PathBuf,
|
||||
/// unix:<path> or ssh:<destination>; defaults like `slop-approve`'s.
|
||||
#[arg(long)]
|
||||
broker: Option<String>,
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Forced command for SSH keys: joins the session to the broker as the key's owner.
|
||||
Remote {
|
||||
#[arg(long, default_value = "/run/slop-broker/remote.sock")]
|
||||
socket: PathBuf,
|
||||
role: Role,
|
||||
name: String,
|
||||
},
|
||||
}
|
||||
|
||||
const DEFAULT_APPROVE_SOCKET: &str = "/run/slop-broker/approve.sock";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let mut args: Vec<String> = std::env::args().collect();
|
||||
let name = args.first().and_then(|a| a.rsplit('/').next()).unwrap_or_default().to_owned();
|
||||
|
||||
let result = if name == "slop-approve" {
|
||||
let socket =
|
||||
std::env::var_os("SLOP_APPROVE_SOCKET").map(PathBuf::from).unwrap_or(DEFAULT_APPROVE_SOCKET.into());
|
||||
approve_cli();
|
||||
approve::main(&socket, &args.split_off(1)).await
|
||||
match remote::address(Role::Approver, approve::DEFAULT_ADDRESS) {
|
||||
Ok(address) => approve::main(&address, &args.split_off(1)).await,
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
} else {
|
||||
match Command::parse() {
|
||||
Command::Serve { config } => serve(&config).await,
|
||||
Command::Approve { socket, args } => {
|
||||
Command::Approve { broker, args } => {
|
||||
approve_cli();
|
||||
approve::main(&socket, &args).await
|
||||
match broker.map_or_else(|| remote::address(Role::Approver, approve::DEFAULT_ADDRESS), Ok) {
|
||||
Ok(address) => approve::main(&address, &args).await,
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
Command::Remote { socket, role, name } => remote::bridge(&socket, role, name).await,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -85,12 +97,25 @@ async fn serve(path: &Path) -> Result<()> {
|
||||
None => None,
|
||||
};
|
||||
|
||||
let remote_listener = match &config.remote {
|
||||
Some(settings) => {
|
||||
server::check_runtime_dir(&settings.socket)?;
|
||||
// Open to the SSH user's group; connections from anyone but the user are refused.
|
||||
let (uid, gid) = user_id(&settings.user)?;
|
||||
Some((server::bind_unix(&settings.socket, 0o660, Some(gid))?, uid))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let broker = Arc::new(Broker::new(config)?);
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
tasks.spawn(approve::listen(broker.clone(), approve_listener));
|
||||
if let Some(listener) = request_listener {
|
||||
tasks.spawn(server::listen_unix(broker.clone(), listener));
|
||||
}
|
||||
if let Some((listener, uid)) = remote_listener {
|
||||
tasks.spawn(remote::listen(broker.clone(), listener, uid));
|
||||
}
|
||||
if let Some(port) = broker.config.vsock_port {
|
||||
tasks.spawn(server::listen_vsock(broker.clone(), port));
|
||||
}
|
||||
|
||||
+6
-15
@@ -5,13 +5,14 @@ use std::process::exit;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use slop_broker::proto::{
|
||||
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, HOST_CID, OpResult, Operation, PROTOCOL_VERSION, Query,
|
||||
Request, ServerMessage, decode, encode, transport,
|
||||
};
|
||||
use slop_broker::remote::{self, Role, Stream};
|
||||
use slop_broker::types::{Arg, HostName, Lines, NodeName, Since, UnitName, UserName};
|
||||
|
||||
/// Exit status when the broker didn't run the operation (denied, expired, invalid or failed).
|
||||
@@ -24,7 +25,8 @@ const GUIDE: &str = include_str!("../../slop-tools.md");
|
||||
about = "Ask the slop broker to run privileged operations",
|
||||
after_help = "Requests wait up to five minutes for an approver; don't retry them in a loop.\n\
|
||||
Exit status 125 means the broker did not run the operation.\n\
|
||||
SLOP_BROKER selects the broker: vsock:<cid>:<port> or unix:<path>."
|
||||
SLOP_BROKER, or broker in ~/.config/slop/config.toml, selects the broker:\n\
|
||||
vsock:<cid>:<port>, unix:<path> or ssh:<destination>."
|
||||
)]
|
||||
struct Cli {
|
||||
/// Who is asking and why; shown to the approver as agent-supplied.
|
||||
@@ -128,20 +130,9 @@ fn default_label() -> Option<String> {
|
||||
Some(format!("in {}", directory.file_name()?.to_string_lossy()))
|
||||
}
|
||||
|
||||
trait Stream: AsyncRead + AsyncWrite + Send + Unpin {}
|
||||
impl<T: AsyncRead + AsyncWrite + Send + Unpin> Stream for T {}
|
||||
|
||||
async fn connect() -> Result<Box<dyn Stream>> {
|
||||
let target = std::env::var("SLOP_BROKER").unwrap_or_else(|_| format!("vsock:{HOST_CID}:{DEFAULT_VSOCK_PORT}"));
|
||||
let failed = || format!("connecting to the broker at {target}");
|
||||
if let Some(path) = target.strip_prefix("unix:") {
|
||||
return Ok(Box::new(tokio::net::UnixStream::connect(path).await.with_context(failed)?));
|
||||
}
|
||||
if let Some((cid, port)) = target.strip_prefix("vsock:").and_then(|a| a.split_once(':')) {
|
||||
let address = tokio_vsock::VsockAddr::new(cid.parse()?, port.parse()?);
|
||||
return Ok(Box::new(tokio_vsock::VsockStream::connect(address).await.with_context(failed)?));
|
||||
}
|
||||
bail!("SLOP_BROKER must be vsock:<cid>:<port> or unix:<path>")
|
||||
let target = remote::address(Role::Requester, &format!("vsock:{HOST_CID}:{DEFAULT_VSOCK_PORT}"))?;
|
||||
remote::connect(&target, Role::Requester).await
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
|
||||
@@ -37,6 +37,20 @@ pub struct Config {
|
||||
pub ssh: Option<SshConfig>,
|
||||
#[serde(default)]
|
||||
pub home_assistant: Option<HomeAssistantConfig>,
|
||||
#[serde(default)]
|
||||
pub remote: Option<RemoteConfig>,
|
||||
}
|
||||
|
||||
/// Requesters and approvers on other boxes, connecting over SSH (see [`crate::remote`]).
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RemoteConfig {
|
||||
pub socket: PathBuf,
|
||||
/// The SSH user whose forced commands connect to the socket.
|
||||
pub user: String,
|
||||
/// Approvers by name; requesters opt in with `remote`.
|
||||
#[serde(default)]
|
||||
pub approvers: Vec<String>,
|
||||
}
|
||||
|
||||
fn default_timeout() -> u64 {
|
||||
@@ -54,6 +68,9 @@ pub struct Requester {
|
||||
pub vsock_cid: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub uid: Option<u32>,
|
||||
/// Connects over SSH, with a key that names it.
|
||||
#[serde(default)]
|
||||
pub remote: bool,
|
||||
/// The name of its entry in `policies`.
|
||||
pub policy: String,
|
||||
}
|
||||
@@ -147,6 +164,12 @@ pub fn credential(path: &std::path::Path) -> PathBuf {
|
||||
PathBuf::from(directory).join(path)
|
||||
}
|
||||
|
||||
/// Looks up a user's UID and primary GID by name.
|
||||
pub fn user_id(name: &str) -> anyhow::Result<(u32, u32)> {
|
||||
let user = User::from_name(name)?.with_context(|| format!("unknown user {name:?}"))?;
|
||||
Ok((user.uid.as_raw(), user.gid.as_raw()))
|
||||
}
|
||||
|
||||
/// Looks up a group's GID by name.
|
||||
pub fn group_id(name: &str) -> anyhow::Result<u32> {
|
||||
let group = Group::from_name(name)?.with_context(|| format!("unknown group {name:?}"))?;
|
||||
@@ -190,6 +213,14 @@ impl Config {
|
||||
pub fn requester_by_uid(&self, uid: u32) -> Option<&str> {
|
||||
self.requesters.iter().find(|(_, r)| r.uid == Some(uid)).map(|(n, _)| n.as_str())
|
||||
}
|
||||
|
||||
pub fn remote_requester(&self, name: &str) -> bool {
|
||||
self.remote.is_some() && self.requesters.get(name).is_some_and(|r| r.remote)
|
||||
}
|
||||
|
||||
pub fn remote_approver(&self, name: &str) -> bool {
|
||||
self.remote.as_ref().is_some_and(|r| r.approvers.iter().any(|a| a == name))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -9,5 +9,6 @@ pub mod ops;
|
||||
pub mod policy;
|
||||
pub mod proto;
|
||||
pub mod queue;
|
||||
pub mod remote;
|
||||
pub mod server;
|
||||
pub mod types;
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
//! Connections to the broker from other boxes, over SSH.
|
||||
//!
|
||||
//! A client runs `ssh <destination> request` (or `approve`). On the broker's box, `sshd` maps the
|
||||
//! client's key to a forced command, `slop-broker remote <role> <name>`, which connects to the
|
||||
//! broker's remote socket, says who the key belongs to with a [`Hello`] and then copies bytes both
|
||||
//! ways. Only the configured SSH user can open that socket, so the broker trusts the hello the
|
||||
//! same way it trusts a vsock CID.
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::audit::Event;
|
||||
use crate::proto::{decode, encode};
|
||||
use crate::server::{Broker, MAX_CONNECTIONS};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Role {
|
||||
Requester,
|
||||
Approver,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
/// The remote command a client asks for, so a key used for the wrong job fails clearly.
|
||||
pub fn command(self) -> &'static str {
|
||||
match self {
|
||||
Role::Requester => "request",
|
||||
Role::Approver => "approve",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Hello {
|
||||
pub role: Role,
|
||||
/// The requester or approver the key belongs to.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
const MAX_HELLO: usize = 4096;
|
||||
|
||||
/// Written without the codec, so nothing after it is read ahead.
|
||||
pub async fn write_hello<S: AsyncWrite + Unpin>(stream: &mut S, hello: &Hello) -> Result<()> {
|
||||
let data = encode(hello)?;
|
||||
stream.write_all(&(data.len() as u32).to_be_bytes()).await?;
|
||||
stream.write_all(&data).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_hello<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Hello> {
|
||||
let length = stream.read_u32().await? as usize;
|
||||
ensure!(length <= MAX_HELLO, "hello too large");
|
||||
let mut data = vec![0; length];
|
||||
stream.read_exact(&mut data).await?;
|
||||
decode(&data)
|
||||
}
|
||||
|
||||
/// The forced command: checks what the client asked for, then joins its SSH session to the broker.
|
||||
pub async fn bridge(socket: &Path, role: Role, name: String) -> Result<()> {
|
||||
let asked = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default();
|
||||
if asked.trim() != role.command() {
|
||||
let (job, client) = match role {
|
||||
Role::Requester => ("sending requests", "slop"),
|
||||
Role::Approver => ("answering requests", "slop-approve"),
|
||||
};
|
||||
bail!("this SSH key is for {job} as {name:?}; use it with `{client}`");
|
||||
}
|
||||
|
||||
let mut stream =
|
||||
UnixStream::connect(socket).await.with_context(|| format!("connecting to {}", socket.display()))?;
|
||||
write_hello(&mut stream, &Hello { role, name }).await?;
|
||||
let mut session = tokio::io::join(tokio::io::stdin(), tokio::io::stdout());
|
||||
tokio::io::copy_bidirectional(&mut session, &mut stream).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remote connections, from the SSH user's forced commands only.
|
||||
pub async fn listen(broker: Arc<Broker>, listener: UnixListener, ssh_uid: u32) -> Result<()> {
|
||||
let slots = Arc::new(Semaphore::new(MAX_CONNECTIONS));
|
||||
loop {
|
||||
let (mut stream, _) = listener.accept().await?;
|
||||
let uid = stream.peer_cred()?.uid();
|
||||
if uid != ssh_uid {
|
||||
broker.audit.log(Event::Unknown { peer: format!("local UID {uid} on the remote socket") });
|
||||
continue;
|
||||
}
|
||||
|
||||
let Ok(slot) = slots.clone().try_acquire_owned() else { continue };
|
||||
let broker = broker.clone();
|
||||
tokio::spawn(async move {
|
||||
let hello = tokio::time::timeout(Duration::from_secs(10), read_hello(&mut stream)).await;
|
||||
match hello {
|
||||
Ok(Ok(Hello { role: Role::Requester, name })) if broker.config.remote_requester(&name) => {
|
||||
crate::server::handle(broker, stream, name).await
|
||||
}
|
||||
Ok(Ok(Hello { role: Role::Approver, name })) if broker.config.remote_approver(&name) => {
|
||||
let _ = crate::approve::serve(broker, stream, format!("{name} (ssh)")).await;
|
||||
}
|
||||
Ok(Ok(Hello { role, name })) => {
|
||||
broker.audit.log(Event::Unknown { peer: format!("SSH key for {name} ({role:?})") })
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
drop(slot);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The client's own settings, from `~/.config/slop/config.toml` (set up by `my.slop`).
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ClientConfig {
|
||||
/// Where `slop` sends requests.
|
||||
broker: Option<String>,
|
||||
/// Where `slop-approve` answers them.
|
||||
approve: Option<String>,
|
||||
}
|
||||
|
||||
fn client_config_path() -> Option<std::path::PathBuf> {
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.filter(|d| !d.is_empty())
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|home| Path::new(&home).join(".config")))?;
|
||||
Some(base.join("slop/config.toml"))
|
||||
}
|
||||
|
||||
/// Where a client connects: `$SLOP_BROKER` (or `$SLOP_APPROVE`), else the client config file,
|
||||
/// else `fallback`.
|
||||
pub fn address(role: Role, fallback: &str) -> Result<String> {
|
||||
let variable = match role {
|
||||
Role::Requester => "SLOP_BROKER",
|
||||
Role::Approver => "SLOP_APPROVE",
|
||||
};
|
||||
if let Ok(address) = std::env::var(variable) {
|
||||
return Ok(address);
|
||||
}
|
||||
|
||||
let config = match client_config_path() {
|
||||
Some(path) if path.exists() => {
|
||||
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
|
||||
toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?
|
||||
}
|
||||
_ => ClientConfig::default(),
|
||||
};
|
||||
let configured = match role {
|
||||
Role::Requester => config.broker,
|
||||
Role::Approver => config.approve,
|
||||
};
|
||||
Ok(configured.unwrap_or_else(|| fallback.to_owned()))
|
||||
}
|
||||
|
||||
/// A stream to the broker, as a client.
|
||||
pub trait Stream: AsyncRead + AsyncWrite + Send + Unpin {}
|
||||
impl<T: AsyncRead + AsyncWrite + Send + Unpin> Stream for T {}
|
||||
|
||||
/// Connects a client to `target`: `vsock:<cid>:<port>`, `unix:<path>` or `ssh:<destination>`.
|
||||
/// Over SSH the destination is given to `ssh` as is, so a `Host` entry in the SSH configuration
|
||||
/// can choose the key; `SLOP_SSH` can replace the `ssh` command and add options instead.
|
||||
pub async fn connect(target: &str, role: Role) -> Result<Box<dyn Stream>> {
|
||||
let failed = || format!("connecting to the broker at {target}");
|
||||
if let Some(path) = target.strip_prefix("unix:") {
|
||||
return Ok(Box::new(UnixStream::connect(path).await.with_context(failed)?));
|
||||
}
|
||||
|
||||
if let Some((cid, port)) = target.strip_prefix("vsock:").and_then(|a| a.split_once(':')) {
|
||||
let address = tokio_vsock::VsockAddr::new(cid.parse()?, port.parse()?);
|
||||
return Ok(Box::new(tokio_vsock::VsockStream::connect(address).await.with_context(failed)?));
|
||||
}
|
||||
|
||||
if let Some(destination) = target.strip_prefix("ssh:") {
|
||||
ensure!(!destination.is_empty() && !destination.starts_with('-'), "invalid SSH destination {destination:?}");
|
||||
|
||||
// Like `GIT_SSH_COMMAND`: a command and options, split on whitespace.
|
||||
let command = std::env::var("SLOP_SSH").unwrap_or_else(|_| "ssh".into());
|
||||
let mut words = command.split_whitespace();
|
||||
let mut child = tokio::process::Command::new(words.next().context("SLOP_SSH is empty")?)
|
||||
.args(words)
|
||||
.args(["-T", "--", destination, role.command()])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.with_context(failed)?;
|
||||
|
||||
let (stdout, stdin) = (child.stdout.take().unwrap(), child.stdin.take().unwrap());
|
||||
// ssh exits once its stdin closes; reap it then.
|
||||
tokio::spawn(async move { child.wait().await });
|
||||
return Ok(Box::new(tokio::io::join(stdout, stdin)));
|
||||
}
|
||||
|
||||
bail!("the broker address must be vsock:<cid>:<port>, unix:<path> or ssh:<destination>")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn hello_leaves_the_rest_of_the_stream() {
|
||||
let (mut a, mut b) = tokio::io::duplex(1024);
|
||||
let hello = Hello { role: Role::Approver, name: "laptop".into() };
|
||||
write_hello(&mut a, &hello).await.unwrap();
|
||||
a.write_all(b"rest").await.unwrap();
|
||||
assert_eq!(read_hello(&mut b).await.unwrap(), hello);
|
||||
let mut rest = [0; 4];
|
||||
b.read_exact(&mut rest).await.unwrap();
|
||||
assert_eq!(&rest, b"rest");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_client_config() {
|
||||
let config: ClientConfig = toml::from_str("broker = \"ssh:slop-request\"\n").unwrap();
|
||||
assert_eq!((config.broker.as_deref(), config.approve), (Some("ssh:slop-request"), None));
|
||||
assert!(toml::from_str::<ClientConfig>("brokr = \"x\"\n").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_hellos_are_rejected() {
|
||||
let (mut a, mut b) = tokio::io::duplex(1024);
|
||||
a.write_all(&u32::MAX.to_be_bytes()).await.unwrap();
|
||||
assert!(read_hello(&mut b).await.is_err());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -37,7 +37,7 @@ impl Broker {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_CONNECTIONS: usize = 128;
|
||||
pub const MAX_CONNECTIONS: usize = 128;
|
||||
|
||||
pub async fn listen_vsock(broker: Arc<Broker>, port: u32) -> Result<()> {
|
||||
let listener = VsockListener::bind(VsockAddr::new(VMADDR_CID_ANY, port)).context("binding vsock")?;
|
||||
|
||||
+49
-2
@@ -6,16 +6,18 @@ use std::time::Duration;
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use nix::sys::signal::kill;
|
||||
use nix::unistd::Pid;
|
||||
use nix::unistd::{Pid, geteuid};
|
||||
use serde_json::json;
|
||||
use tokio::io::DuplexStream;
|
||||
|
||||
use slop_broker::config::Config;
|
||||
use slop_broker::proto::{ApproveRequest, ApproveResponse, receive, send};
|
||||
use slop_broker::proto::{
|
||||
ApprovedBy, ClientMessage, Destination, OpResult, Operation, PROTOCOL_VERSION, Query, Request, ServerMessage,
|
||||
Transport, decode, encode, transport,
|
||||
};
|
||||
use slop_broker::queue::Decision;
|
||||
use slop_broker::remote::{Hello, Role, write_hello};
|
||||
use slop_broker::server::{Broker, handle};
|
||||
use slop_broker::types::{Arg, Lines};
|
||||
|
||||
@@ -36,12 +38,13 @@ fn broker(directory: &Path, ops: serde_json::Value) -> Arc<Broker> {
|
||||
std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let config: Config = serde_json::from_value(json!({
|
||||
"requesters": { "agent": { "policy": "agent" } },
|
||||
"requesters": { "agent": { "remote": true, "policy": "agent" } },
|
||||
"policies": { "agent": { "ops": ops } },
|
||||
"timeout": 2,
|
||||
"approve_socket": "/unused",
|
||||
"approver_group": "root",
|
||||
"audit_log": directory.join("audit.jsonl"),
|
||||
"remote": { "socket": "/unused", "user": "root", "approvers": ["laptop"] },
|
||||
"ssh": {
|
||||
"ssh": ssh,
|
||||
"key": "/key",
|
||||
@@ -318,3 +321,47 @@ async fn requests_lists_pending_and_leases() {
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to the remote socket the way `slop-broker remote` does.
|
||||
async fn remote(path: &Path, role: Role, name: &str) -> Transport<tokio::net::UnixStream> {
|
||||
let mut stream = tokio::net::UnixStream::connect(path).await.unwrap();
|
||||
write_hello(&mut stream, &Hello { role, name: name.into() }).await.unwrap();
|
||||
transport(stream)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_requesters_and_approvers_use_one_socket() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
|
||||
let path = directory.path().join("remote.sock");
|
||||
let listener = tokio::net::UnixListener::bind(&path).unwrap();
|
||||
tokio::spawn(slop_broker::remote::listen(broker.clone(), listener, geteuid().as_raw()));
|
||||
|
||||
let mut requester = remote(&path, Role::Requester, "agent").await;
|
||||
let request = ClientMessage::Request(Request { version: PROTOCOL_VERSION, label: None, operation: ssh(&["true"]) });
|
||||
send(&mut requester, &request).await.unwrap();
|
||||
let Some(ServerMessage::Pending { id, .. }) = receive(&mut requester).await.unwrap() else { panic!("not pending") };
|
||||
|
||||
// One approver connection carries several requests.
|
||||
let mut approver = remote(&path, Role::Approver, "laptop").await;
|
||||
send(&mut approver, &ApproveRequest::List).await.unwrap();
|
||||
let Some(ApproveResponse::Pending(entries)) = receive(&mut approver).await.unwrap() else { panic!("no list") };
|
||||
assert_eq!(entries[0].id, id);
|
||||
|
||||
send(&mut approver, &ApproveRequest::Decide { id: id.clone(), decision: Decision::Once }).await.unwrap();
|
||||
assert!(matches!(receive(&mut approver).await.unwrap(), Some(ApproveResponse::Recorded)));
|
||||
assert!(matches!(
|
||||
receive::<_, ServerMessage>(&mut requester).await.unwrap(),
|
||||
Some(ServerMessage::Approved { by: ApprovedBy::Approver, .. })
|
||||
));
|
||||
|
||||
let events: Vec<String> = broker.audit.tail(10).unwrap().iter().map(|r| r.event.to_string()).collect();
|
||||
assert!(events.iter().any(|e| e.ends_with("answered once by laptop (ssh)")), "{events:?}");
|
||||
|
||||
// Names must be configured for the role they claim.
|
||||
for (role, name) in [(Role::Approver, "agent"), (Role::Requester, "laptop")] {
|
||||
let mut stream = remote(&path, role, name).await;
|
||||
let _ = send(&mut stream, &ApproveRequest::List).await;
|
||||
assert!(receive::<_, ApproveResponse>(&mut stream).await.map_or(true, |r| r.is_none()));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user