mirror of
https://github.com/logos-co/logos-protocol.git
synced 2026-08-27 20:11:07 +00:00
* feat: group-shareable local sockets, stale-socket reaper, bind-failure detection
The QtRO local transport binds each module's unix socket at 0777 & ~umask
(0755) with no way for a second OS user to reach it, discards the listen
result so a failed bind surfaces only as clients hanging, and never cleans up
the socket file — a hard-killed logos_host leaks it forever.
Add a Qt-free helper (logos_socket_paths.{h,cpp}) usable from both the qt_remote
and plain transport paths:
- applySocketPerms(path): chgrp + chmod a bound socket per LOGOS_SOCKET_GROUP /
LOGOS_SOCKET_MODE (chgrp-then-chmod so a half-applied policy is only ever
too strict). No-op when unset, so default behaviour is unchanged. Connecting
to an AF_UNIX socket needs write permission, so 0660 is what lets a group
member in.
- isSocketDead(path): S_ISSOCK && owned-by-us && non-blocking connect returns
ECONNREFUSED/ENOENT. Fails closed on any other outcome, so it never reports
a live socket or a regular file dead.
- reapStaleSockets(dir, prefix): unlink only the dead sockets, never a regular
file that shares the prefix (e.g. a *.lgx build artefact).
Wire it into RemoteTransportHost::publishObject and QtRemoteRegistry:
- construct QRemoteObjectRegistryHost empty and listen via setRegistryUrl() so
a bind failure is observed and logged (with lastError() + the socket path)
instead of leaving a silently-broken host;
- apply the socket-access policy to the freshly-bound local: socket.
The env-driven policy means every process in a node's tree (daemon, logos_host
subprocesses, their children) applies the same rule to every socket it binds
without threading config through each layer — the daemon exports the vars once.
Adds test_socket_paths.cpp (8 gtests): mode/group application, no-op default,
bad-mode rejection, live/dead/regular-file classification, and the reaper
keeping live sockets and regular files while removing only dead ones.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* review: harden socket helpers (gid overflow, socket-owner check, empty-prefix guard, dedup path)
Addressing automated review feedback on the socket helpers:
- resolveGid(): validate strtoul() errno/range so an out-of-range numeric
LOGOS_SOCKET_GROUP is rejected instead of silently truncating to a wrong gid.
- applySocketPerms(): when a policy is requested, stat the path first and refuse
unless it's a socket we own (S_ISSOCK + st_uid == geteuid()), so a malformed
URL can never chmod/chown a stray file. No-op fast path when the env is unset.
- reapStaleSockets(): refuse an empty prefix (would make every dead socket the
process owns a deletion candidate).
- Extract the duplicated `localSocketFilePath()` (Qt QLocalServer name->path
rule) into a shared qt_remote/qt_socket_path.h so RemoteTransportHost and
QtRemoteRegistry can't drift.
Adds tests: non-socket path refused (mode unchanged), empty-prefix reaper no-op.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat: transport-aware token validator hook on ModuleProxy (#22)
* feat: transport-aware token validator hook on ModuleProxy
Adds an injectable authorizer so a host (the logoscore daemon) can accept tokens
the built-in issued-token scan doesn't know — specifically operator-issued named
tokens validated against a persistent store — with per-token expiry and
local_only enforced against the transport the call arrived on.
- ModuleProxy::setTokenValidator(std::function<bool(token, transportProtocol)>).
isAuthorized() consults it ONLY after the existing m_tokens + TokenManager
scan fails, so installing a validator is purely additive: it can grant, never
revoke, access the built-in path already allows. Empty (default) = today's
behaviour exactly.
- callRemoteMethod() gains a defaulted `transportProtocol` ("local"). The QtRO
local path (RemoteTransportHost) uses the default; PlainTransportHost::onCall
passes the real wire ("tcp" | "tcp_ssl", fail-closed to non-local on an
unexpected protocol) so a local_only token presented over the network is
rejected. One ModuleProxy is shared across a provider's transports, so the
transport can't be inferred — it must be threaded per call, which the defaulted
arg does without changing the QtRO replica's 3-arg call.
The daemon backs the validator with TokenStore::lookupByToken; other modules
keep the default (no validator) and are unaffected.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* review: split callRemoteMethod into explicit 3-arg + 4-arg overloads; include <utility>
Addressing review feedback:
- Replace the defaulted transportProtocol argument with two explicit Q_INVOKABLE
overloads. The Qt meta-object system matches methods by their full parameter
list and doesn't apply C++ default arguments, so the QtRO/local 3-arg call
must remain a real 3-arg method rather than relying on moc's reduced-arity
generation. The 3-arg form forwards to the transport-aware 4-arg form with
"local"; PlainTransportHost keeps calling the 4-arg form with the real wire.
- Include <utility> explicitly in module_proxy.h for std::move rather than
relying on an indirect include.
Full protocol suite green (160/160).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
172 lines
6.0 KiB
C++
172 lines
6.0 KiB
C++
#include "logos_socket_paths.h"
|
|
|
|
#include <cctype>
|
|
#include <cerrno>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <limits>
|
|
#include <vector>
|
|
|
|
#include <dirent.h>
|
|
#include <fcntl.h>
|
|
#include <grp.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/types.h>
|
|
#include <sys/un.h>
|
|
#include <unistd.h>
|
|
|
|
namespace logos {
|
|
|
|
namespace {
|
|
|
|
// Resolve a "group" env value to a gid. Accepts an all-digits string as a
|
|
// numeric gid directly, otherwise looks the name up in the group database.
|
|
bool resolveGid(const std::string& spec, gid_t& out)
|
|
{
|
|
if (!spec.empty() &&
|
|
spec.find_first_not_of("0123456789") == std::string::npos) {
|
|
errno = 0;
|
|
char* end = nullptr;
|
|
const unsigned long v = std::strtoul(spec.c_str(), &end, 10);
|
|
// Reject overflow and any value that doesn't fit gid_t — a truncated
|
|
// gid would silently chgrp to the wrong group.
|
|
if (errno != 0 || end == spec.c_str() || *end != '\0' ||
|
|
v > static_cast<unsigned long>(std::numeric_limits<gid_t>::max()))
|
|
return false;
|
|
out = static_cast<gid_t>(v);
|
|
return true;
|
|
}
|
|
|
|
// getgrnam_r with a growing buffer — thread-safe, unlike getgrnam.
|
|
std::vector<char> buf(1024);
|
|
struct group grp;
|
|
struct group* result = nullptr;
|
|
for (;;) {
|
|
int rc = ::getgrnam_r(spec.c_str(), &grp, buf.data(), buf.size(), &result);
|
|
if (rc == ERANGE && buf.size() < (1u << 20)) {
|
|
buf.resize(buf.size() * 2);
|
|
continue;
|
|
}
|
|
if (rc != 0 || result == nullptr) return false;
|
|
out = grp.gr_gid;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// Parse an octal mode like "0660" / "660". Rejects garbage and anything wider
|
|
// than the low 12 bits (setuid/setgid/sticky + rwx triplets).
|
|
bool parseOctalMode(const std::string& spec, mode_t& out)
|
|
{
|
|
if (spec.empty()) return false;
|
|
for (char c : spec) {
|
|
if (c < '0' || c > '7') return false;
|
|
}
|
|
errno = 0;
|
|
char* end = nullptr;
|
|
unsigned long v = std::strtoul(spec.c_str(), &end, 8);
|
|
if (errno != 0 || end == spec.c_str() || *end != '\0' || v > 07777) return false;
|
|
out = static_cast<mode_t>(v);
|
|
return true;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
bool applySocketPerms(const std::string& absPath, std::string* errOut)
|
|
{
|
|
auto fail = [&](const std::string& msg) {
|
|
if (errOut) *errOut = msg;
|
|
return false;
|
|
};
|
|
|
|
const char* grpEnv = std::getenv("LOGOS_SOCKET_GROUP");
|
|
const char* modeEnv = std::getenv("LOGOS_SOCKET_MODE");
|
|
const bool wantGroup = grpEnv && *grpEnv;
|
|
const bool wantMode = modeEnv && *modeEnv;
|
|
if (!wantGroup && !wantMode) return true; // policy unset: no-op, touch nothing
|
|
|
|
// Only ever change a socket we own. If a malformed URL produced a path that
|
|
// isn't the socket we just bound, refuse rather than chmod/chown a stray
|
|
// file. (Mirrors isSocketDead's owner check.)
|
|
struct stat st;
|
|
if (::lstat(absPath.c_str(), &st) != 0)
|
|
return fail("stat(" + absPath + ") failed: " + std::strerror(errno));
|
|
if (!S_ISSOCK(st.st_mode))
|
|
return fail(absPath + " is not a socket — refusing to change perms");
|
|
if (st.st_uid != ::geteuid())
|
|
return fail(absPath + " is not owned by us — refusing to change perms");
|
|
|
|
if (wantGroup) {
|
|
gid_t gid = 0;
|
|
if (!resolveGid(grpEnv, gid))
|
|
return fail(std::string("unknown group '") + grpEnv + "'");
|
|
// Non-root may chgrp a file it owns to any group it belongs to.
|
|
if (::chown(absPath.c_str(), static_cast<uid_t>(-1), gid) != 0)
|
|
return fail("chown(" + absPath + ") failed: " + std::strerror(errno));
|
|
}
|
|
|
|
if (wantMode) {
|
|
mode_t mode = 0;
|
|
if (!parseOctalMode(modeEnv, mode))
|
|
return fail(std::string("invalid LOGOS_SOCKET_MODE '") + modeEnv + "'");
|
|
if (::chmod(absPath.c_str(), mode) != 0)
|
|
return fail("chmod(" + absPath + ") failed: " + std::strerror(errno));
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool isSocketDead(const std::string& absPath)
|
|
{
|
|
struct stat st;
|
|
if (::lstat(absPath.c_str(), &st) != 0) return false; // gone / unreadable
|
|
if (!S_ISSOCK(st.st_mode)) return false; // regular file, dir, ...
|
|
if (st.st_uid != ::geteuid()) return false; // not ours to reap
|
|
|
|
struct sockaddr_un addr;
|
|
std::memset(&addr, 0, sizeof(addr));
|
|
addr.sun_family = AF_UNIX;
|
|
if (absPath.size() >= sizeof(addr.sun_path)) return false; // can't probe -> assume alive
|
|
std::memcpy(addr.sun_path, absPath.c_str(), absPath.size());
|
|
|
|
const int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
|
|
if (fd < 0) return false;
|
|
const int flags = ::fcntl(fd, F_GETFL, 0);
|
|
if (flags >= 0) ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
|
|
|
|
const int rc = ::connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
|
|
const int err = errno;
|
|
::close(fd);
|
|
|
|
if (rc == 0) return false; // a listener answered -> alive
|
|
// ECONNREFUSED: bound but nobody listening. ENOENT: vanished mid-probe.
|
|
// Everything else (EAGAIN/EINPROGRESS backlog full, EACCES, ETIMEDOUT, ...)
|
|
// is treated as alive so we never unlink a socket that might be in use.
|
|
return err == ECONNREFUSED || err == ENOENT;
|
|
}
|
|
|
|
std::size_t reapStaleSockets(const std::string& dir, const std::string& prefix)
|
|
{
|
|
// Refuse an empty prefix: it would make every dead socket the process owns
|
|
// (anywhere in `dir`) a deletion candidate. Callers always know the family
|
|
// of sockets they created ("logos_"), so this is misuse, not a valid sweep.
|
|
if (prefix.empty()) return 0;
|
|
|
|
DIR* d = ::opendir(dir.c_str());
|
|
if (!d) return 0;
|
|
|
|
std::size_t removed = 0;
|
|
while (struct dirent* ent = ::readdir(d)) {
|
|
const std::string name = ent->d_name;
|
|
if (name.size() < prefix.size() || name.compare(0, prefix.size(), prefix) != 0)
|
|
continue;
|
|
const std::string full = dir + "/" + name;
|
|
if (isSocketDead(full) && ::unlink(full.c_str()) == 0)
|
|
++removed;
|
|
}
|
|
::closedir(d);
|
|
return removed;
|
|
}
|
|
|
|
} // namespace logos
|