security: the authorization model holds where the model writes the input
A review found the tool classes - the core of the harness - bypassable in
several places where model output was pasted into a shell or trusted as an id.
Each fix below has a test that reproduces the original failure.
No shell for model data
- webfetch put the URL between '...' and ran it through popen: a quote in the
URL ran any command, from a tool that needed no consent. curl is now exec'd
with an argv, http(s) only, HTML stripped in C, stderr off the curses screen.
- webfetch is mutate: with read free, "read a key, fetch evil/?k=..." left the
machine without anybody being asked. websearch stays read (fixed host).
- kids: the parent-approval command got the model's arguments inside '...'
via system(); they are now "$1". The domain check reads the URL with the
same parser as the tool (duplicate keys) and refuses user@host URLs.
- delegate: the two copies of the child argv are one (exec_delegate). The ssh
path exec'd splinter with "ssh" as argv[0]; it now runs ssh and quotes every
word for the remote shell. A single delegate to a host now really runs there.
Approvals (ack)
- The id was the pid: a late yes stayed on disk and approved the next request
unseen. Ids are random, requests 0600 with O_EXCL, deleted when answered or
expired; an answer is refused after expiry; the first answer wins (link(2)).
- An ack dir owned by someone else or writable by others is refused.
- --ack accepted every word but "no" as yes ("nein" approved). Now strict.
- The terminal thread blocked in fgets after a phone answer; it is stoppable.
Secrets
- API key and Telegram token were in curl's argv, readable via ps. src/curl.c
passes URL and auth headers as a -K config on stdin (transport, telegram,
tg-ask.sh; its dead eval fallback is gone).
- 'run' and task_start no longer inherit splinter's keys ("run env"). 'run' got
its own process group, stdin /dev/null and SPLINTER_RUN_TIMEOUT (300 s).
MCP server
- Beyond 127.x it refuses to start without SPLINTER_MCP_TOKEN; connections
must begin with "AUTH <token>". SIGPIPE ignored, idle connections closed.
Crashes
- task_kill sent kill(-0) - SIGTERM to splinter's own process group - because
popen gave no pid. Tasks now have a pid and a process group; integer ids work.
- ui: a 3- or 4-byte UTF-8 character overflowed char[2] on every redraw
(now sp_ui_ascii_char, tested); the scroll offset was taken from one buffer
and applied to another, reading past its end.
Repo
- The test binaries are no longer tracked (.gitignore already said so).
make check: 23 test binaries, green, also under ASan/UBSan.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aa7d04bfca
commit
6fe30f4787
40 files changed
+1802
-419
No files matched your search
@@ -23,7 +23,7 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
|
||||
LIB = libsplinter.so
|
||||
LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \
|
||||
src/json.o src/sse.o src/openai.o src/transport_openai.o src/builtin.o \
|
||||
src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/interview.o src/ack.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o
|
||||
src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/interview.o src/ack.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o src/curl.o
|
||||
BIN = splinter
|
||||
BINOBJ = src/main.o src/ui.o
|
||||
PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
|
||||
@@ -32,7 +32,7 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
|
||||
plugins/kids/kids.so plugins/status/status.so plugins/tasks/tasks.so
|
||||
TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \
|
||||
tests/test_transport tests/test_agent tests/test_openai \
|
||||
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor
|
||||
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor tests/test_secrets
|
||||
|
||||
RPATH = -Wl,-rpath,'$$ORIGIN'
|
||||
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
|
||||
@@ -107,14 +107,15 @@ src/conv.o: include/splinter.h
|
||||
src/json.o: vendor/libmcp/mcp.h
|
||||
src/sse.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/openai.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/transport_openai.o: include/splinter.h
|
||||
src/transport_openai.o: include/splinter.h src/curl.h src/log.h
|
||||
src/curl.o: src/curl.h include/splinter.h
|
||||
src/builtin.o: include/splinter.h
|
||||
src/theme.o: src/theme.h src/palettes.h include/splinter.h
|
||||
src/palettes.o: src/palettes.h
|
||||
src/decomp.o: src/decomp.h
|
||||
src/i18n.o: src/i18n.h include/splinter.h
|
||||
src/delegate.o: src/config.h include/splinter.h
|
||||
src/telegram.o: include/splinter.h
|
||||
src/telegram.o: include/splinter.h src/curl.h src/ack.h
|
||||
src/log.o: src/log.h
|
||||
src/cmdscript.o: src/cmdscript.h include/splinter.h
|
||||
src/folder.o: src/folder.h include/splinter.h
|
||||
@@ -174,6 +175,8 @@ tests/test_cli: tests/test_cli.c $(LIB) $(PLUGIN)
|
||||
|
||||
tests/test_compactor: tests/test_compactor.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_compactor.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_secrets: tests/test_secrets.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_secrets.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_plugin.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
|
||||
|
||||
@@ -351,6 +351,16 @@ parameters; the class is `mutate`, because a server can do anything and the
|
||||
harness does not pretend to know better. Proven against a test server: the model
|
||||
called `mcp_add(17, 25)` and answered 42.
|
||||
|
||||
The other direction, splinter as the server, is `--mcp-server-listen IP`:
|
||||
newline-delimited JSON-RPC over TCP, read tools only unless `--autonomous`.
|
||||
On 127.x it needs nothing; on any other address it refuses to start without
|
||||
`SPLINTER_MCP_TOKEN`, and every connection must begin with the line
|
||||
`AUTH <token>`. There is no TLS: across a network you do not own, tunnel it.
|
||||
|
||||
SPLINTER_MCP_TOKEN=$(cat ~/.splinter/mcp.token) \
|
||||
splinter --mcp-server-listen 0.0.0.0
|
||||
(echo "AUTH $(cat ~/.splinter/mcp.token)"; cat requests.jsonl) | nc host 8098
|
||||
|
||||
## Tools
|
||||
|
||||
Every tool declares its class, and the loop enforces it - never the model, never
|
||||
@@ -364,6 +374,11 @@ the prompt.
|
||||
- `edit` (mutate): replaces exactly one occurrence; a non-unique `old` is an
|
||||
error, because an ambiguous edit is a wrong edit waiting to happen.
|
||||
- `run` (destructive): a shell command; the exit status is an observation.
|
||||
Its own process group, stdin `/dev/null`, killed after `SPLINTER_RUN_TIMEOUT`
|
||||
seconds (default 300), and an environment without splinter's API keys and
|
||||
tokens, so `run env` cannot hand them to the model.
|
||||
- `webfetch` (mutate): http(s) only, curl started without a shell. Not read:
|
||||
a URL the model picks is a message out of the machine.
|
||||
- `echo` (read), `clock` (read).
|
||||
|
||||
Mutate and destructive tools ask first, unless `--autonomous` is set. In the
|
||||
|
||||
+18
-4
@@ -196,8 +196,8 @@ mehrere Kanaele sein, und die erste Antwort gewinnt.
|
||||
Der Mechanismus ist zwei Dateien, damit nicht zwei Prozesse um dieselben
|
||||
Telegram-Updates streiten:
|
||||
|
||||
~/.splinter/ack/pending/<id> die Anfrage
|
||||
~/.splinter/ack/<id>.answer die Antwort
|
||||
~/.splinter/ack/pending/<id> die Anfrage (0600)
|
||||
~/.splinter/ack/pending/<id>.answer die Antwort (0600)
|
||||
|
||||
Der blockierte Prozess wartet nur auf die Datei. Kanaele sind Melder: sie stossen
|
||||
die Anfrage nach draussen (ein Kommando pro Kanal), und wer die Antwort liest -
|
||||
@@ -210,8 +210,22 @@ das Gateway, ein Telefon, ein Skript - legt die Antwortdatei ab.
|
||||
|
||||
Antworten, aus jedem Prozess:
|
||||
|
||||
splinter --ack 4711 yes
|
||||
splinter --ack 4711 no
|
||||
splinter --ack 482915307 yes # yes, y, ok, ja
|
||||
splinter --ack 482915307 no # no, n, nein - jedes andere Wort ist ein Fehler
|
||||
splinter --ack-list
|
||||
|
||||
Ein Timeout ist ein Nein. Stille ist keine Zustimmung.
|
||||
|
||||
Regeln, die der Code durchsetzt:
|
||||
|
||||
- Die Id ist zufaellig (6-9 Ziffern) und wird nie wiederverwendet; sie ist nicht
|
||||
die pid. Eine Antwort gilt genau einer Anfrage.
|
||||
- Nur die erste Antwort zaehlt; eine zweite wird abgewiesen.
|
||||
- Ist die Anfrage beantwortet oder abgelaufen, wird sie geloescht. Eine spaete
|
||||
Antwort scheitert mit "no open request", statt auf die naechste Anfrage zu
|
||||
warten.
|
||||
- Ein ack-Verzeichnis, das nicht dem Benutzer gehoert oder fuer andere
|
||||
schreibbar ist, wird abgelehnt: dort koennte jeder ein Ja hinlegen.
|
||||
- Grenze: Jeder Prozess unter derselben uid kann antworten. Wer das Kind am
|
||||
selben Konto vom Zustimmen abhalten will, braucht eine eigene uid fuer splinter
|
||||
(oder einen Kanal, dessen Antwort der lokale Benutzer nicht schreiben kann).
|
||||
+7
-1
@@ -45,7 +45,7 @@ int sp_json_escape(struct sp_buf *, const char *);
|
||||
|
||||
enum sp_auth {
|
||||
SP_AUTH_READ = 0, /* may run without asking */
|
||||
SP_AUTH_MUTATE, /* changes files: needs operator consent */
|
||||
SP_AUTH_MUTATE, /* changes files or sends data out: consent */
|
||||
SP_AUTH_DESTRUCTIVE /* runs commands: needs operator consent */
|
||||
};
|
||||
|
||||
@@ -256,6 +256,12 @@ int sp_agent_run(struct sp_agent *, const char *user_text,
|
||||
|
||||
/* builtin.c */
|
||||
int sp_builtin_register(struct sp_registry *);
|
||||
/*
|
||||
* Environment names the 'run' tool's shell does not inherit (API keys,
|
||||
* tokens). A trailing '*' makes a prefix. sp_secret_env_is takes "NAME=value".
|
||||
*/
|
||||
int sp_secret_env_add(const char *name);
|
||||
int sp_secret_env_is(const char *entry);
|
||||
struct sp_config;
|
||||
int sp_delegate_register(struct sp_registry *, const struct sp_config *,
|
||||
struct sp_host *);
|
||||
|
||||
+71
-15
@@ -19,16 +19,19 @@
|
||||
* - a timeout is a NO. A parent who is not looking does not approve anything.
|
||||
* - the whitelist matches the tool and its arguments, never the mood.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "ack.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define KIDS_RULES 64
|
||||
#define KIDS_RULE_LEN 256
|
||||
@@ -206,6 +209,29 @@ whitelisted(const char *tool, const char *args)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* sh -c '<cmd>' sh '<arg>': the command string is parsed, the argument is not.
|
||||
* Returns the wait status, like system(3).
|
||||
*/
|
||||
static int
|
||||
run_with_arg(const char *cmd, const char *arg)
|
||||
{
|
||||
pid_t child;
|
||||
int status;
|
||||
|
||||
child = fork();
|
||||
if (child < 0)
|
||||
return -1;
|
||||
if (child == 0) {
|
||||
execl("/bin/sh", "sh", "-c", cmd, "sh", arg, (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
while (waitpid(child, &status, 0) < 0)
|
||||
if (errno != EINTR)
|
||||
return -1;
|
||||
return status;
|
||||
}
|
||||
|
||||
/*
|
||||
* Ask the parent. The command gets the request as one argument and answers with
|
||||
* its exit status; anything but 0 - including a timeout - means no.
|
||||
@@ -213,7 +239,7 @@ whitelisted(const char *tool, const char *args)
|
||||
static int
|
||||
ask_parent(const char *tool, const char *args, char *reason, size_t reason_len)
|
||||
{
|
||||
char cmd[1024];
|
||||
char cmd[1024], request[1024];
|
||||
int rc;
|
||||
|
||||
/*
|
||||
@@ -243,9 +269,16 @@ ask_parent(const char *tool, const char *args, char *reason, size_t reason_len)
|
||||
return 0;
|
||||
}
|
||||
|
||||
snprintf(cmd, sizeof(cmd), "%s 'Anfrage: %s %s'",
|
||||
approve_cmd, tool, args != NULL ? args : "");
|
||||
rc = system(cmd);
|
||||
/*
|
||||
* The command is the operator's and may carry its own arguments, so it
|
||||
* still goes through sh. The request is the model's and must not: it is
|
||||
* handed over as "$1", a positional parameter the shell never parses. A
|
||||
* quote in the tool arguments is then just a quote.
|
||||
*/
|
||||
snprintf(cmd, sizeof(cmd), "%s \"$1\"", approve_cmd);
|
||||
snprintf(request, sizeof(request), "Anfrage: %s %s", tool,
|
||||
args != NULL ? args : "");
|
||||
rc = run_with_arg(cmd, request);
|
||||
if (rc == 0)
|
||||
return 1;
|
||||
snprintf(reason, reason_len, "ein Erwachsener hat nicht zugestimmt (%s)",
|
||||
@@ -265,20 +298,27 @@ ask_parent(const char *tool, const char *args, char *reason, size_t reason_len)
|
||||
* webfetch additionally only reaches hosts listed in ~/.splinter/kids/domains,
|
||||
* because "the model picked this link" is not a safety argument.
|
||||
*/
|
||||
/* the url out of the tool arguments, without dragging the JSON parser in */
|
||||
/*
|
||||
* The url out of the tool arguments, read with the same parser the tool itself
|
||||
* uses. A hand-rolled strstr took the first "url" key while the tool took the
|
||||
* one the parser picks, so two keys meant: check one host, fetch another.
|
||||
*/
|
||||
static void
|
||||
arg_url(const char *args, char *buf, size_t len)
|
||||
{
|
||||
const char *p = args != NULL ? strstr(args, "\"url\":\"") : NULL;
|
||||
size_t i = 0;
|
||||
mcp_json *v;
|
||||
const char *u;
|
||||
|
||||
buf[0] = '\0';
|
||||
if (p == NULL)
|
||||
if (args == NULL || args[0] != '{')
|
||||
return;
|
||||
p += 7;
|
||||
while (*p != '\0' && *p != '"' && i + 1 < len)
|
||||
buf[i++] = *p++;
|
||||
buf[i] = '\0';
|
||||
v = mcp_parse(args);
|
||||
if (v == NULL)
|
||||
return;
|
||||
u = mcp_arg_string(v, "url");
|
||||
if (u != NULL && strlen(u) < len)
|
||||
snprintf(buf, len, "%s", u);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
|
||||
static int
|
||||
@@ -291,8 +331,24 @@ host_allowed(const char *url)
|
||||
|
||||
if (url == NULL)
|
||||
return 0;
|
||||
host = strstr(url, "://");
|
||||
host = host != NULL ? host + 3 : url;
|
||||
if (strncmp(url, "http://", 7) == 0)
|
||||
host = url + 7;
|
||||
else if (strncmp(url, "https://", 8) == 0)
|
||||
host = url + 8;
|
||||
else
|
||||
return 0;
|
||||
/*
|
||||
* "https://allowed.org:x@evil.example/" names evil.example: whatever is
|
||||
* before an '@' is a user name, not the host. Rather than parse userinfo
|
||||
* correctly, a URL that has any is not on the list.
|
||||
*/
|
||||
{
|
||||
size_t auth = strcspn(host, "/?#");
|
||||
const char *at = memchr(host, '@', auth);
|
||||
|
||||
if (at != NULL || memchr(host, '\\', auth) != NULL)
|
||||
return 0;
|
||||
}
|
||||
f = fopen(domains_file, "r");
|
||||
if (f == NULL)
|
||||
return 0;
|
||||
@@ -303,7 +359,7 @@ host_allowed(const char *url)
|
||||
if (line[0] == '#' || line[0] == '\0')
|
||||
continue;
|
||||
n = strlen(line);
|
||||
hlen = strcspn(host, "/:");
|
||||
hlen = strcspn(host, "/:?#");
|
||||
if (hlen == n && strncmp(host, line, n) == 0) {
|
||||
ok = 1;
|
||||
break;
|
||||
|
||||
+101
-21
@@ -23,6 +23,8 @@
|
||||
* `run` is: the gate and the approval path see it like any other change.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
@@ -30,8 +32,10 @@
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define TASKS_MAX 16
|
||||
@@ -115,16 +119,31 @@ refresh_widget(struct sp_host *h)
|
||||
(void)sp_host_widget_text(h, "tasks", text);
|
||||
}
|
||||
|
||||
extern char **environ;
|
||||
|
||||
/*
|
||||
* Run the task in its own process group, so task_kill can stop the shell and
|
||||
* everything it started. popen() gave no pid: t->pid stayed 0, and
|
||||
* kill(-0, SIGTERM) is "every process in my group" - task_kill killed
|
||||
* splinter itself. stdin is /dev/null (a task must not read the terminal), and
|
||||
* the environment loses splinter's keys, as for the 'run' tool.
|
||||
*/
|
||||
static void *
|
||||
task_run(void *arg)
|
||||
{
|
||||
struct task *t = arg;
|
||||
FILE *p;
|
||||
char chunk[2048];
|
||||
size_t got;
|
||||
char **envp;
|
||||
ssize_t got;
|
||||
size_t n, i, j;
|
||||
int fds[2], st = 0;
|
||||
pid_t child;
|
||||
|
||||
p = popen(t->cmd, "r");
|
||||
if (p == NULL) {
|
||||
for (n = 0; environ != NULL && environ[n] != NULL; n++)
|
||||
;
|
||||
envp = calloc(n + 1, sizeof(*envp));
|
||||
if (envp == NULL || pipe(fds) != 0) {
|
||||
free(envp);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: %s", strerror(errno));
|
||||
t->status = 127;
|
||||
@@ -133,14 +152,62 @@ task_run(void *arg)
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
return NULL;
|
||||
}
|
||||
while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) {
|
||||
for (i = 0, j = 0; i < n; i++)
|
||||
if (!sp_secret_env_is(environ[i]))
|
||||
envp[j++] = environ[i];
|
||||
envp[j] = NULL;
|
||||
child = fork();
|
||||
if (child == 0) {
|
||||
int dn = open("/dev/null", O_RDONLY);
|
||||
|
||||
(void)setpgid(0, 0);
|
||||
if (dn >= 0) {
|
||||
(void)dup2(dn, STDIN_FILENO);
|
||||
if (dn != STDIN_FILENO)
|
||||
close(dn);
|
||||
}
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
(void)dup2(fds[1], STDERR_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
execle("/bin/sh", "sh", "-c", t->cmd, (char *)NULL, envp);
|
||||
_exit(127);
|
||||
}
|
||||
close(fds[1]);
|
||||
free(envp);
|
||||
if (child < 0) {
|
||||
close(fds[0]);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: fork: %s", strerror(errno));
|
||||
t->status = 127;
|
||||
t->running = 0;
|
||||
t->ended = time(NULL);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
return NULL;
|
||||
}
|
||||
(void)setpgid(child, child);
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->pid = child;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
for (;;) {
|
||||
got = read(fds[0], chunk, sizeof(chunk));
|
||||
if (got < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (got <= 0)
|
||||
break;
|
||||
pthread_mutex_lock(&t->lock);
|
||||
if (t->out.len < (1u << 20)) /* 1 MiB, stated */
|
||||
(void)sp_buf_add(&t->out, chunk, got);
|
||||
(void)sp_buf_add(&t->out, chunk, (size_t)got);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
}
|
||||
close(fds[0]);
|
||||
while (waitpid(child, &st, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->pid = 0; /* reaped: the id may be reused */
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
t->status = pclose(p);
|
||||
t->status = st;
|
||||
t->running = 0;
|
||||
t->ended = time(NULL);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
@@ -158,26 +225,30 @@ find(int id)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* the JSON value of a string argument, without pulling in the whole parser */
|
||||
/*
|
||||
* The value of an argument, with the parser the rest of splinter uses. The old
|
||||
* strstr() only matched "key":"..." - the schema declares 'id' an integer, so
|
||||
* {"id":3} came out empty and every task_kill said "no such task".
|
||||
*/
|
||||
static void
|
||||
arg_str(const char *args, const char *key, char *buf, size_t len)
|
||||
{
|
||||
char pat[64];
|
||||
const char *p;
|
||||
size_t i = 0;
|
||||
mcp_json *v;
|
||||
const char *sv;
|
||||
|
||||
buf[0] = '\0';
|
||||
snprintf(pat, sizeof(pat), "\"%s\":\"", key);
|
||||
p = args != NULL ? strstr(args, pat) : NULL;
|
||||
if (p == NULL)
|
||||
if (args == NULL || args[0] != '{' || (v = mcp_parse(args)) == NULL)
|
||||
return;
|
||||
p += strlen(pat);
|
||||
while (*p != '\0' && *p != '"' && i + 1 < len) {
|
||||
if (*p == '\\' && p[1] != '\0')
|
||||
p++;
|
||||
buf[i++] = *p++;
|
||||
sv = mcp_arg_string(v, key);
|
||||
if (sv != NULL)
|
||||
snprintf(buf, len, "%s", sv);
|
||||
else {
|
||||
int n = mcp_arg_int(v, key, INT_MIN);
|
||||
|
||||
if (n != INT_MIN)
|
||||
snprintf(buf, len, "%d", n);
|
||||
}
|
||||
buf[i] = '\0';
|
||||
mcp_json_free(v);
|
||||
}
|
||||
|
||||
static struct sp_host *host_ref;
|
||||
@@ -374,7 +445,16 @@ tool_task_kill(const char *args, struct sp_buf *out, void *ctx)
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "already finished");
|
||||
}
|
||||
/* the shell is what we know: kill its process group */
|
||||
/*
|
||||
* Only a task with a process group of its own. A task opened by
|
||||
* ops_begin (a delegate on another host) has none here, and a pid of 0
|
||||
* or 1 would make kill(-pid) hit splinter's own group or everything.
|
||||
*/
|
||||
if (t->pid <= 1) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: this task has no local process "
|
||||
"to stop");
|
||||
}
|
||||
(void)kill(-(t->pid), SIGTERM);
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "kill signal sent");
|
||||
|
||||
@@ -40,9 +40,21 @@ static char ack_root[512];
|
||||
static int
|
||||
ensure_dir(const char *path)
|
||||
{
|
||||
if (mkdir(path, 0700) == 0)
|
||||
return 0;
|
||||
return errno == EEXIST ? 0 : -1;
|
||||
struct stat st;
|
||||
|
||||
if (mkdir(path, 0700) != 0 && errno != EEXIST)
|
||||
return -1;
|
||||
/*
|
||||
* An answer file is a yes. A directory that someone else owns, or that
|
||||
* others may write into, lets them write that yes: refuse it instead of
|
||||
* trusting it. lstat, so a symlink planted in its place is refused too.
|
||||
*/
|
||||
if (lstat(path, &st) != 0 || !S_ISDIR(st.st_mode) ||
|
||||
st.st_uid != getuid() || (st.st_mode & 022) != 0) {
|
||||
errno = EPERM;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
@@ -70,36 +82,100 @@ ack_id_path(char *buf, size_t len, int id, const char *suffix)
|
||||
if (root == NULL)
|
||||
return -1;
|
||||
snprintf(dir, sizeof(dir), "%s/pending", root);
|
||||
(void)ensure_dir(root);
|
||||
(void)ensure_dir(dir);
|
||||
if (ensure_dir(root) != 0 || ensure_dir(dir) != 0)
|
||||
return -1;
|
||||
snprintf(buf, len, "%s/%d%s", dir, id, suffix);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Write the request. The id is the pid and a counter, so two processes asking at
|
||||
* the same time cannot take each other's answer.
|
||||
* An id nobody can guess and nobody reuses. It used to be the pid, so the next
|
||||
* request of the same process - or of a later process with a recycled pid -
|
||||
* found the previous answer waiting and was approved by it. Nine digits at most,
|
||||
* because a human types it into a phone.
|
||||
*/
|
||||
static int
|
||||
new_id(void)
|
||||
{
|
||||
unsigned char r[4] = { 0, 0, 0, 0 };
|
||||
unsigned long v;
|
||||
int fd = open("/dev/urandom", O_RDONLY);
|
||||
|
||||
if (fd >= 0) {
|
||||
if (read(fd, r, sizeof(r)) != (ssize_t)sizeof(r))
|
||||
memset(r, 0, sizeof(r));
|
||||
close(fd);
|
||||
}
|
||||
v = ((unsigned long)r[0] << 24) | ((unsigned long)r[1] << 16) |
|
||||
((unsigned long)r[2] << 8) | (unsigned long)r[3];
|
||||
if (v == 0) /* no randomness: refuse, do not guess */
|
||||
return -1;
|
||||
return (int)(100000 + v % 900000000UL);
|
||||
}
|
||||
|
||||
/* the expiry recorded in a request file, or 0 when there is none */
|
||||
static long
|
||||
request_expires(const char *path)
|
||||
{
|
||||
FILE *f = fopen(path, "r");
|
||||
char line[256];
|
||||
long exp = 0;
|
||||
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
while (fgets(line, sizeof(line), f) != NULL)
|
||||
if (strncmp(line, "expires=", 8) == 0)
|
||||
exp = atol(line + 8);
|
||||
fclose(f);
|
||||
return exp;
|
||||
}
|
||||
|
||||
/*
|
||||
* Write the request under a fresh random id. O_EXCL, so two requests never share
|
||||
* a file, and 0600, because the arguments may be what is being protected.
|
||||
*/
|
||||
int
|
||||
sp_ack_request(const char *tool, const char *args, const char *why, int ttl)
|
||||
{
|
||||
char path[700];
|
||||
FILE *f;
|
||||
int id = (int)getpid();
|
||||
FILE *f = NULL;
|
||||
int id = -1, fd = -1, tries;
|
||||
time_t now = time(NULL);
|
||||
|
||||
if (ack_id_path(path, sizeof(path), id, "") != 0)
|
||||
return -1;
|
||||
f = fopen(path, "w");
|
||||
if (f == NULL)
|
||||
for (tries = 0; tries < 8 && fd < 0; tries++) {
|
||||
id = new_id();
|
||||
if (id < 0 || ack_id_path(path, sizeof(path), id, "") != 0)
|
||||
return -1;
|
||||
fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
|
||||
if (fd < 0 && errno != EEXIST)
|
||||
return -1;
|
||||
}
|
||||
if (fd < 0 || (f = fdopen(fd, "w")) == NULL) {
|
||||
if (fd >= 0)
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
/*
|
||||
* An answer that raced the end of an earlier request with this id
|
||||
* may still lie here. It belongs to nobody; it must not become the
|
||||
* answer to this one.
|
||||
*/
|
||||
char ans[700];
|
||||
|
||||
if (ack_id_path(ans, sizeof(ans), id, ".answer") == 0)
|
||||
(void)unlink(ans);
|
||||
}
|
||||
fprintf(f, "id=%d\n", id);
|
||||
fprintf(f, "tool=%s\n", tool != NULL ? tool : "");
|
||||
fprintf(f, "args=%s\n", args != NULL ? args : "");
|
||||
fprintf(f, "why=%s\n", why != NULL ? why : "");
|
||||
fprintf(f, "pid=%d\n", (int)getpid());
|
||||
fprintf(f, "expires=%ld\n", (long)now + (ttl > 0 ? ttl : 120));
|
||||
fclose(f);
|
||||
if (fclose(f) != 0) {
|
||||
(void)unlink(path);
|
||||
return -1;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -146,20 +222,21 @@ sp_ack_notify(int id, struct sp_buf *log)
|
||||
int
|
||||
sp_ack_wait(int id, int ttl, char *who, size_t who_len)
|
||||
{
|
||||
char path[700];
|
||||
char path[700], req[700];
|
||||
time_t end = time(NULL) + (ttl > 0 ? ttl : 120);
|
||||
int ok = 0;
|
||||
|
||||
if (ack_id_path(path, sizeof(path), id, ".answer") != 0 ||
|
||||
ack_id_path(req, sizeof(req), id, "") != 0)
|
||||
return 0;
|
||||
for (;;) {
|
||||
FILE *f;
|
||||
char line[256];
|
||||
|
||||
if (ack_id_path(path, sizeof(path), id, ".answer") == 0 &&
|
||||
(f = fopen(path, "r")) != NULL) {
|
||||
int ok = 0;
|
||||
|
||||
if ((f = fopen(path, "r")) != NULL) {
|
||||
if (fgets(line, sizeof(line), f) != NULL) {
|
||||
line[strcspn(line, "\r\n")] = '\0';
|
||||
ok = strncmp(line, "yes", 3) == 0;
|
||||
ok = strncmp(line, "yes ", 4) == 0;
|
||||
if (who != NULL) {
|
||||
char *sp = strchr(line, ' ');
|
||||
|
||||
@@ -168,44 +245,65 @@ sp_ack_wait(int id, int ttl, char *who, size_t who_len)
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
(void)unlink(path);
|
||||
return ok;
|
||||
break;
|
||||
}
|
||||
if (time(NULL) >= end)
|
||||
return 0; /* silence is not consent */
|
||||
break; /* silence is not consent */
|
||||
{
|
||||
struct timespec ts = { 0, 200 * 1000 * 1000 };
|
||||
|
||||
(void)nanosleep(&ts, NULL);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Answered or not, the request is over. Removing it is what makes a late
|
||||
* answer fail ("no such request") instead of lying in wait for the next one.
|
||||
*/
|
||||
(void)unlink(req);
|
||||
(void)unlink(path);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* Any process may answer: the gateway, a helper, a script. */
|
||||
/*
|
||||
* Any process may answer, once, while the request is still open. The answer is
|
||||
* written to a private temp file and then link(2)ed into place: link fails when
|
||||
* the name exists, so the first answer wins and a waiter never reads half a
|
||||
* file.
|
||||
*/
|
||||
int
|
||||
sp_ack_answer(int id, int yes, const char *who)
|
||||
{
|
||||
char path[700];
|
||||
char req[700], path[700], tmp[760];
|
||||
long exp;
|
||||
int fd, rc;
|
||||
FILE *f;
|
||||
|
||||
if (ack_id_path(path, sizeof(path), id, "") != 0)
|
||||
if (id <= 0 || ack_id_path(req, sizeof(req), id, "") != 0 ||
|
||||
ack_id_path(path, sizeof(path), id, ".answer") != 0)
|
||||
return -1;
|
||||
exp = request_expires(req);
|
||||
if (exp < 0)
|
||||
return -1; /* no such request */
|
||||
if (exp > 0 && (long)time(NULL) >= exp)
|
||||
return -1; /* too late: the request was a no already */
|
||||
snprintf(tmp, sizeof(tmp), "%s.%ld", path, (long)getpid());
|
||||
fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0600);
|
||||
if (fd < 0 || (f = fdopen(fd, "w")) == NULL) {
|
||||
if (fd >= 0) {
|
||||
close(fd);
|
||||
(void)unlink(tmp);
|
||||
}
|
||||
return -1;
|
||||
{
|
||||
FILE *req = fopen(path, "r");
|
||||
|
||||
if (req == NULL)
|
||||
return -1; /* no such request */
|
||||
fclose(req);
|
||||
}
|
||||
if (ack_id_path(path, sizeof(path), id, ".answer") != 0)
|
||||
return -1;
|
||||
f = fopen(path, "w");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
fprintf(f, "%s %s\n", yes ? "yes" : "no",
|
||||
who != NULL && *who != '\0' ? who : "unknown");
|
||||
fclose(f);
|
||||
return 0;
|
||||
if (fclose(f) != 0) {
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
rc = link(tmp, path);
|
||||
(void)unlink(tmp);
|
||||
return rc == 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
int
|
||||
@@ -228,7 +326,7 @@ sp_ack_list(struct sp_buf *out)
|
||||
char path[1024], line[256];
|
||||
FILE *f;
|
||||
|
||||
if (ents[i]->d_name[0] == '.') {
|
||||
if (strchr(ents[i]->d_name, '.') != NULL) { /* answers, temp files */
|
||||
free(ents[i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
+56
-28
@@ -20,20 +20,26 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "ack.h"
|
||||
#include "log.h"
|
||||
#include <pthread.h>
|
||||
|
||||
#include "ack.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include <pthread.h>
|
||||
|
||||
#include "ack.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
/*
|
||||
* The terminal as one more approval channel. It must be stoppable: when the
|
||||
* phone answers first, or the request times out, the agent goes on, and a
|
||||
* thread still sitting in fgets() would hold it until somebody pressed Enter.
|
||||
* So it polls the terminal together with a pipe, and a byte on the pipe ends it.
|
||||
*/
|
||||
struct ack_thread {
|
||||
int id;
|
||||
FILE *in;
|
||||
int stop; /* read end of the stop pipe */
|
||||
};
|
||||
|
||||
static void *
|
||||
@@ -41,13 +47,28 @@ ack_stdin_thread(void *arg)
|
||||
{
|
||||
struct ack_thread *at = arg;
|
||||
char line[64];
|
||||
struct pollfd pfd[2];
|
||||
|
||||
if (fgets(line, sizeof(line), at->in) == NULL) {
|
||||
free(at);
|
||||
return NULL;
|
||||
pfd[0].fd = fileno(at->in);
|
||||
pfd[0].events = POLLIN;
|
||||
pfd[1].fd = at->stop;
|
||||
pfd[1].events = POLLIN;
|
||||
for (;;) {
|
||||
pfd[0].revents = pfd[1].revents = 0;
|
||||
if (poll(pfd, 2, -1) < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (pfd[1].revents != 0)
|
||||
break; /* answered elsewhere or expired */
|
||||
if (pfd[0].revents != 0) {
|
||||
if (fgets(line, sizeof(line), at->in) != NULL)
|
||||
(void)sp_ack_answer(at->id,
|
||||
line[0] == 'y' || line[0] == 'Y', "terminal");
|
||||
break;
|
||||
}
|
||||
}
|
||||
(void)sp_ack_answer(at->id, line[0] == 'y' || line[0] == 'Y', "terminal");
|
||||
free(at);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -67,6 +88,8 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
int id, ttl, yes;
|
||||
pthread_t th;
|
||||
int th_started = 0;
|
||||
int stop[2] = { -1, -1 };
|
||||
struct ack_thread at;
|
||||
|
||||
if (chans == NULL || *chans == '\0')
|
||||
return -1;
|
||||
@@ -75,8 +98,13 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
ttl = 120;
|
||||
id = sp_ack_request(t->name, args,
|
||||
t->auth == SP_AUTH_MUTATE ? "mutate" : "destructive", ttl);
|
||||
if (id < 0)
|
||||
if (id < 0) {
|
||||
/* fail closed, but say why: a silent "denied" sends people hunting */
|
||||
fprintf(stderr, "splinter: cannot file an approval request in %s "
|
||||
"(missing, not yours, or writable by others): %s denied\n",
|
||||
sp_ack_dir() != NULL ? sp_ack_dir() : "(no ack dir)", t->name);
|
||||
return 0;
|
||||
}
|
||||
if (sp_buf_init(&log) == 0) {
|
||||
(void)sp_ack_notify(id, &log);
|
||||
if (log.p != NULL && *log.p != '\0')
|
||||
@@ -94,21 +122,22 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
fflush(a->cfg->approval_out);
|
||||
|
||||
/* the terminal is one more channel, not a special case */
|
||||
if (a->cfg->approval_in != NULL) {
|
||||
struct ack_thread *at = calloc(1, sizeof(*at));
|
||||
|
||||
if (at != NULL) {
|
||||
at->id = id;
|
||||
at->in = a->cfg->approval_in;
|
||||
if (pthread_create(&th, NULL, ack_stdin_thread, at) == 0)
|
||||
th_started = 1;
|
||||
else
|
||||
free(at);
|
||||
}
|
||||
if (a->cfg->approval_in != NULL && pipe(stop) == 0) {
|
||||
at.id = id;
|
||||
at.in = a->cfg->approval_in;
|
||||
at.stop = stop[0];
|
||||
if (pthread_create(&th, NULL, ack_stdin_thread, &at) == 0)
|
||||
th_started = 1;
|
||||
}
|
||||
yes = sp_ack_wait(id, ttl, who, sizeof(who));
|
||||
if (th_started)
|
||||
if (th_started) {
|
||||
(void)write(stop[1], "x", 1);
|
||||
(void)pthread_join(th, NULL);
|
||||
}
|
||||
if (stop[0] >= 0) {
|
||||
close(stop[0]);
|
||||
close(stop[1]);
|
||||
}
|
||||
if (yes && who[0] != '\0')
|
||||
fprintf(stderr, "splinter: zugestimmt von %s\n", who);
|
||||
return yes;
|
||||
@@ -211,8 +240,7 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
|
||||
|
||||
sp_buf_clear(answer);
|
||||
/* the turn counter is what a plugin like 'focus' schedules against */
|
||||
if (a->host != NULL)
|
||||
/*
|
||||
/*
|
||||
* A turn gate runs before the model does. Kid mode ends the day here: the
|
||||
* child gets a sentence, the model gets nothing to answer.
|
||||
*/
|
||||
|
||||
+314
-57
@@ -14,6 +14,10 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <time.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
@@ -67,17 +71,86 @@ tool_echo(const char *args, struct sp_buf *out, void *ctx)
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
* Secrets the shell of the 'run' tool must not see.
|
||||
*
|
||||
* splinter holds API keys and tokens in its environment (that is how they reach
|
||||
* it and how a delegate child gets its own). Everything 'run' starts inherited
|
||||
* them, so "run env" printed them into the conversation - and from there to
|
||||
* whichever endpoint gets the next request. The names below are taken out of
|
||||
* the child's environment; the config adds the key_env names it uses. A name
|
||||
* ending in '*' is a prefix.
|
||||
*/
|
||||
#define SECRET_MAX 32
|
||||
|
||||
static char secret_env[SECRET_MAX][96] = {
|
||||
"SPLINTER_API_KEY", "SPLINTER_TELEGRAM_TOKEN", "SPLINTER_MEM_KEY",
|
||||
"SPLINTER_DELEGATE_KEY_*", "CLAUDE_CODE_OAUTH_TOKEN", "OLLAMA_KEY"
|
||||
};
|
||||
static size_t nsecret_env = 6;
|
||||
|
||||
int
|
||||
sp_secret_env_add(const char *name)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (name == NULL || *name == '\0')
|
||||
return 0;
|
||||
for (i = 0; i < nsecret_env; i++)
|
||||
if (strcmp(secret_env[i], name) == 0)
|
||||
return 0;
|
||||
if (nsecret_env == SECRET_MAX || strlen(name) >= sizeof(secret_env[0]))
|
||||
return -1;
|
||||
snprintf(secret_env[nsecret_env++], sizeof(secret_env[0]), "%s", name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* "NAME=value" is secret when NAME is on the list */
|
||||
int
|
||||
sp_secret_env_is(const char *entry)
|
||||
{
|
||||
size_t i, nlen = strcspn(entry, "=");
|
||||
|
||||
for (i = 0; i < nsecret_env; i++) {
|
||||
size_t l = strlen(secret_env[i]);
|
||||
|
||||
if (l > 0 && secret_env[i][l - 1] == '*') {
|
||||
if (nlen >= l - 1 && strncmp(entry, secret_env[i], l - 1) == 0)
|
||||
return 1;
|
||||
} else if (l == nlen && strncmp(entry, secret_env[i], l) == 0)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern char **environ;
|
||||
|
||||
#define RUN_MAX_OUTPUT (1u << 20)
|
||||
#define RUN_TIMEOUT_S 300
|
||||
|
||||
/*
|
||||
* Run a shell command for the model.
|
||||
*
|
||||
* fork/exec instead of popen(), for three reasons popen cannot give:
|
||||
* - a timeout: the child gets its own process group, and when it outlives
|
||||
* SPLINTER_RUN_TIMEOUT (default 300 s) the whole group is killed - a
|
||||
* 'sleep 1000' or an editor waiting for input no longer holds the agent;
|
||||
* - stdin is /dev/null: a command that reads input used to read the curses
|
||||
* terminal, stealing the operator's keystrokes;
|
||||
* - the environment is filtered: see secret_env above.
|
||||
* stdout and stderr share one pipe, so the model sees the error it caused.
|
||||
*/
|
||||
static int
|
||||
tool_run(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
FILE *p;
|
||||
char chunk[4096];
|
||||
size_t got, total = 0;
|
||||
int status;
|
||||
|
||||
struct sp_buf keep;
|
||||
const char *cmd;
|
||||
int rc;
|
||||
struct sp_buf keep;
|
||||
const char *cmd, *tmo_s;
|
||||
char chunk[4096];
|
||||
char **envp;
|
||||
size_t total = 0, n, i, j;
|
||||
int fds[2], status = 0, timeout_s, timed_out = 0, cut = 0;
|
||||
pid_t child;
|
||||
time_t end;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0)
|
||||
@@ -87,43 +160,100 @@ tool_run(const char *args, struct sp_buf *out, void *ctx)
|
||||
sp_buf_free(&keep);
|
||||
return sp_buf_puts(out, "error: empty command");
|
||||
}
|
||||
/*
|
||||
* stderr of the child belongs in the answer, not on the terminal: a curses
|
||||
* screen that suddenly contains a shell error is broken, and the error is
|
||||
* exactly what the model needs to see.
|
||||
*/
|
||||
{
|
||||
struct sp_buf wrapped = { 0 };
|
||||
tmo_s = getenv("SPLINTER_RUN_TIMEOUT");
|
||||
timeout_s = tmo_s != NULL && *tmo_s != '\0' ? atoi(tmo_s) : RUN_TIMEOUT_S;
|
||||
if (timeout_s <= 0)
|
||||
timeout_s = RUN_TIMEOUT_S;
|
||||
|
||||
if (sp_buf_init(&wrapped) == 0 &&
|
||||
sp_buf_printf(&wrapped, "{ %s\n} 2>&1", cmd) == 0) {
|
||||
p = popen(wrapped.p, "r");
|
||||
sp_buf_free(&wrapped);
|
||||
} else
|
||||
p = popen(cmd, "r");
|
||||
}
|
||||
if (p == NULL) {
|
||||
rc = sp_buf_printf(out, "error: popen: %s", strerror(errno));
|
||||
for (n = 0; environ != NULL && environ[n] != NULL; n++)
|
||||
;
|
||||
envp = calloc(n + 1, sizeof(*envp));
|
||||
if (envp == NULL) {
|
||||
sp_buf_free(&keep);
|
||||
return rc;
|
||||
return -1;
|
||||
}
|
||||
while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) {
|
||||
if (total > 1u << 20) { /* 1 MiB cap, stated not silent */
|
||||
sp_buf_puts(out, "\n[output truncated at 1 MiB]");
|
||||
for (i = 0, j = 0; i < n; i++)
|
||||
if (!sp_secret_env_is(environ[i]))
|
||||
envp[j++] = environ[i];
|
||||
envp[j] = NULL;
|
||||
|
||||
if (pipe(fds) != 0) {
|
||||
free(envp);
|
||||
sp_buf_free(&keep);
|
||||
return sp_buf_printf(out, "error: pipe: %s", strerror(errno));
|
||||
}
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
free(envp);
|
||||
sp_buf_free(&keep);
|
||||
return sp_buf_printf(out, "error: fork: %s", strerror(errno));
|
||||
}
|
||||
if (child == 0) {
|
||||
int dn = open("/dev/null", O_RDONLY);
|
||||
|
||||
(void)setpgid(0, 0);
|
||||
if (dn >= 0) {
|
||||
(void)dup2(dn, STDIN_FILENO);
|
||||
if (dn != STDIN_FILENO)
|
||||
close(dn);
|
||||
}
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
(void)dup2(fds[1], STDERR_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
execle("/bin/sh", "sh", "-c", cmd, (char *)NULL, envp);
|
||||
_exit(127);
|
||||
}
|
||||
(void)setpgid(child, child); /* both sides: no race with the exec */
|
||||
close(fds[1]);
|
||||
free(envp);
|
||||
end = time(NULL) + timeout_s;
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
ssize_t got;
|
||||
long left = (long)(end - time(NULL));
|
||||
int pr;
|
||||
|
||||
if (left <= 0) {
|
||||
timed_out = 1;
|
||||
break;
|
||||
}
|
||||
if (sp_buf_add(out, chunk, got) != 0) {
|
||||
pclose(p);
|
||||
return -1;
|
||||
pfd.fd = fds[0];
|
||||
pfd.events = POLLIN;
|
||||
pr = poll(&pfd, 1, (int)(left > 1000 ? 1000000 : left * 1000));
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
total += got;
|
||||
if (pr == 0)
|
||||
continue;
|
||||
got = read(fds[0], chunk, sizeof(chunk));
|
||||
if (got < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (got <= 0)
|
||||
break;
|
||||
if (total + (size_t)got > RUN_MAX_OUTPUT) {
|
||||
cut = 1;
|
||||
break;
|
||||
}
|
||||
if (sp_buf_add(out, chunk, (size_t)got) != 0)
|
||||
break;
|
||||
total += (size_t)got;
|
||||
}
|
||||
status = pclose(p);
|
||||
if (timed_out || cut)
|
||||
(void)kill(-child, SIGKILL);
|
||||
close(fds[0]);
|
||||
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
sp_buf_free(&keep);
|
||||
if (status < 0) {
|
||||
return sp_buf_printf(out, "\n[exit status unknown: %s]",
|
||||
strerror(errno));
|
||||
}
|
||||
if (cut)
|
||||
sp_buf_puts(out, "\n[output truncated at 1 MiB]");
|
||||
if (timed_out)
|
||||
return sp_buf_printf(out, "\n[timed out after %d s, killed]",
|
||||
timeout_s);
|
||||
if (WIFEXITED(status))
|
||||
return sp_buf_printf(out, "\n[exit status %d]",
|
||||
WEXITSTATUS(status));
|
||||
@@ -760,35 +890,156 @@ url_encode(const char *in, char *out, size_t len)
|
||||
out[o] = '\0';
|
||||
}
|
||||
|
||||
#define WEB_MAX_RAW (2 * 1024 * 1024) /* what curl may hand us */
|
||||
#define WEB_MAX_TEXT 20000 /* what the model gets */
|
||||
|
||||
/*
|
||||
* Only http and https. Anything else - file://, gopher://, dict:// - turns a
|
||||
* "fetch a page" tool into "read this machine", and curl knows all of them.
|
||||
*/
|
||||
static int
|
||||
web_url_ok(const char *url)
|
||||
{
|
||||
return strncmp(url, "http://", 7) == 0 ||
|
||||
strncmp(url, "https://", 8) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* HTML to text, the same rules the old sed pipeline had: a tag becomes a space,
|
||||
* becomes a space, runs of blanks collapse, blank lines go. Written in C
|
||||
* because the pipeline needed a shell, and a shell is where the URL used to be
|
||||
* pasted between quotes.
|
||||
*/
|
||||
static void
|
||||
html_to_text(const char *in, size_t n, struct sp_buf *out)
|
||||
{
|
||||
size_t i, start = out->len, line_start = out->len;
|
||||
int in_tag = 0, blank = 0, line_has_text = 0;
|
||||
|
||||
for (i = 0; i < n && out->len - start < WEB_MAX_TEXT; i++) {
|
||||
char c = in[i];
|
||||
|
||||
if (in_tag) {
|
||||
if (c == '>')
|
||||
in_tag = 0;
|
||||
continue;
|
||||
}
|
||||
if (c == '<') {
|
||||
in_tag = 1;
|
||||
c = ' ';
|
||||
} else if (c == '&' && n - i >= 6 &&
|
||||
strncmp(in + i, " ", 6) == 0) {
|
||||
i += 5;
|
||||
c = ' ';
|
||||
} else if (c == '\t' || c == '\r')
|
||||
c = ' ';
|
||||
if (c == '\0')
|
||||
continue;
|
||||
if (c == '\n') {
|
||||
if (!line_has_text) {
|
||||
/* a line of blanks only: drop it */
|
||||
out->len = line_start;
|
||||
out->p[out->len] = '\0';
|
||||
} else
|
||||
(void)sp_buf_add(out, "\n", 1);
|
||||
line_start = out->len;
|
||||
line_has_text = 0;
|
||||
blank = 0;
|
||||
continue;
|
||||
}
|
||||
if (c == ' ') {
|
||||
if (blank)
|
||||
continue;
|
||||
blank = 1;
|
||||
} else {
|
||||
blank = 0;
|
||||
line_has_text = 1;
|
||||
}
|
||||
(void)sp_buf_add(out, &c, 1);
|
||||
}
|
||||
if (!line_has_text) {
|
||||
out->len = line_start;
|
||||
if (out->p != NULL)
|
||||
out->p[out->len] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Fetch a URL with curl(1), started directly with an argument vector. The URL
|
||||
* is one argv entry: there is no shell that could read a quote in it, and
|
||||
* --url keeps a URL that starts with '-' from being taken for an option.
|
||||
* stdin and stderr go to /dev/null, so a curses screen stays a curses screen.
|
||||
*/
|
||||
static int
|
||||
curl_text(const char *url, struct sp_buf *out)
|
||||
{
|
||||
struct sp_buf cmd = { 0 };
|
||||
FILE *p;
|
||||
int fds[2], devnull, status;
|
||||
pid_t child;
|
||||
struct sp_buf raw;
|
||||
char chunk[4096];
|
||||
size_t got, total = 0;
|
||||
ssize_t got;
|
||||
int cut = 0;
|
||||
|
||||
if (sp_buf_init(&cmd) != 0)
|
||||
return -1;
|
||||
if (sp_buf_printf(&cmd,
|
||||
"curl -sSL --max-time 25 -A 'splinter/0.1' '%s' "
|
||||
"| sed -e 's/<[^>]*>/ /g' -e 's/ / /g' "
|
||||
"| tr -s ' \t' ' ' | grep -v '^ *$' | head -c 20000", url) != 0) {
|
||||
sp_buf_free(&cmd);
|
||||
if (!web_url_ok(url))
|
||||
return sp_buf_puts(out, "error: only http:// and https:// URLs "
|
||||
"can be fetched");
|
||||
if (sp_buf_init(&raw) != 0)
|
||||
return -1;
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_free(&raw);
|
||||
return sp_buf_printf(out, "error: pipe: %s", strerror(errno));
|
||||
}
|
||||
p = popen(cmd.p, "r");
|
||||
sp_buf_free(&cmd);
|
||||
if (p == NULL)
|
||||
return sp_buf_printf(out, "error: curl: %s", strerror(errno));
|
||||
while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) {
|
||||
total += got;
|
||||
(void)sp_buf_add(out, chunk, got);
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
sp_buf_free(&raw);
|
||||
return sp_buf_printf(out, "error: fork: %s", strerror(errno));
|
||||
}
|
||||
(void)pclose(p);
|
||||
if (total == 0)
|
||||
if (child == 0) {
|
||||
char *argv[] = {
|
||||
"curl", "-sL", "--max-time", "25", "-A", "splinter/0.1",
|
||||
"--proto", "=http,https", "--proto-redir", "=http,https",
|
||||
"--url", (char *)url, NULL
|
||||
};
|
||||
|
||||
devnull = open("/dev/null", O_RDWR);
|
||||
if (devnull >= 0) {
|
||||
(void)dup2(devnull, STDIN_FILENO);
|
||||
(void)dup2(devnull, STDERR_FILENO);
|
||||
if (devnull > STDERR_FILENO)
|
||||
close(devnull);
|
||||
}
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
execvp("curl", argv);
|
||||
_exit(127);
|
||||
}
|
||||
close(fds[1]);
|
||||
while ((got = read(fds[0], chunk, sizeof(chunk))) != 0) {
|
||||
if (got < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (raw.len + (size_t)got > WEB_MAX_RAW) {
|
||||
cut = 1;
|
||||
break;
|
||||
}
|
||||
if (sp_buf_add(&raw, chunk, (size_t)got) != 0)
|
||||
break;
|
||||
}
|
||||
close(fds[0]); /* a child still writing gets SIGPIPE */
|
||||
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
html_to_text(raw.p, raw.len, out);
|
||||
if (raw.len == 0)
|
||||
sp_buf_puts(out, "(no answer - check the connection or "
|
||||
"SPLINTER_SEARCH_URL)");
|
||||
else if (cut)
|
||||
sp_buf_puts(out, "\n[page larger than 2 MiB, cut]");
|
||||
sp_buf_free(&raw);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -877,7 +1128,13 @@ sp_builtin_register(struct sp_registry *r)
|
||||
t.params = "{\"type\":\"object\",\"properties\":{\"url\":"
|
||||
"{\"type\":\"string\",\"description\":\"http or https URL\"}},"
|
||||
"\"required\":[\"url\"]}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
/*
|
||||
* Not read. The URL is chosen by the model, and a URL is a message: with
|
||||
* 'read' free, "read ~/.ssh/id_ed25519, then fetch evil.example/?k=..."
|
||||
* would leave the machine without anybody being asked. websearch stays
|
||||
* read because its host is fixed by the operator, not by the model.
|
||||
*/
|
||||
t.auth = SP_AUTH_MUTATE;
|
||||
t.run = tool_webfetch;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
return -1;
|
||||
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* splinter -- curl(1) without secrets on its command line.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Every argument of a process is readable by every user of the machine
|
||||
* (/proc/<pid>/cmdline, ps -ef). An API key in "-H 'Authorization: Bearer ...'"
|
||||
* or a Telegram token in the URL was therefore public for as long as the request
|
||||
* ran. curl reads a config from stdin with "-K -"; the URL and the secret
|
||||
* headers go there, and argv keeps only what may be seen.
|
||||
*
|
||||
* It is also the end of building curl command lines as shell strings: no quote
|
||||
* in a URL can change what runs.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include "curl.h"
|
||||
|
||||
#define CURL_MAX_ARGS 32
|
||||
|
||||
int
|
||||
sp_curl_config_line(struct sp_buf *b, const char *key, const char *value)
|
||||
{
|
||||
const char *s;
|
||||
|
||||
if (sp_buf_printf(b, "%s = \"", key) != 0)
|
||||
return -1;
|
||||
for (s = value; *s != '\0'; s++) {
|
||||
const char *esc = NULL;
|
||||
|
||||
switch (*s) {
|
||||
case '"': esc = "\\\""; break;
|
||||
case '\\': esc = "\\\\"; break;
|
||||
case '\n': esc = "\\n"; break;
|
||||
case '\r': esc = "\\r"; break;
|
||||
case '\t': esc = "\\t"; break;
|
||||
}
|
||||
if (esc != NULL ? sp_buf_puts(b, esc) : sp_buf_add(b, s, 1))
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(b, "\"\n");
|
||||
}
|
||||
|
||||
static int
|
||||
write_all(int fd, const char *p, size_t n)
|
||||
{
|
||||
while (n > 0) {
|
||||
ssize_t w = write(fd, p, n);
|
||||
|
||||
if (w < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
p += w;
|
||||
n -= (size_t)w;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_curl_start(const char *const *args, const char *url,
|
||||
const char *const *headers, int quiet, pid_t *pid, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf cfg;
|
||||
char *argv[CURL_MAX_ARGS + 4];
|
||||
int in[2], out[2], n = 0, i, failed;
|
||||
pid_t child;
|
||||
|
||||
if (sp_buf_init(&cfg) != 0)
|
||||
return -1;
|
||||
failed = sp_curl_config_line(&cfg, "url", url != NULL ? url : "");
|
||||
for (i = 0; !failed && headers != NULL && headers[i] != NULL; i++)
|
||||
failed = sp_curl_config_line(&cfg, "header", headers[i]);
|
||||
if (failed) {
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_puts(err, "curl: out of memory");
|
||||
return -1;
|
||||
}
|
||||
|
||||
argv[n++] = "curl";
|
||||
for (i = 0; args != NULL && args[i] != NULL; i++) {
|
||||
if (i >= CURL_MAX_ARGS) {
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_puts(err, "curl: too many arguments");
|
||||
return -1;
|
||||
}
|
||||
argv[n++] = (char *)args[i];
|
||||
}
|
||||
argv[n++] = "-K";
|
||||
argv[n++] = "-";
|
||||
argv[n] = NULL;
|
||||
|
||||
if (pipe(in) != 0) {
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_printf(err, "curl: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (pipe(out) != 0) {
|
||||
close(in[0]);
|
||||
close(in[1]);
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_printf(err, "curl: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
close(in[0]);
|
||||
close(in[1]);
|
||||
close(out[0]);
|
||||
close(out[1]);
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_printf(err, "curl: fork: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
(void)dup2(in[0], STDIN_FILENO);
|
||||
(void)dup2(out[1], STDOUT_FILENO);
|
||||
if (quiet) {
|
||||
int dn = open("/dev/null", O_WRONLY);
|
||||
|
||||
if (dn >= 0) {
|
||||
(void)dup2(dn, STDERR_FILENO);
|
||||
close(dn);
|
||||
}
|
||||
}
|
||||
close(in[0]);
|
||||
close(in[1]);
|
||||
close(out[0]);
|
||||
close(out[1]);
|
||||
execvp("curl", argv);
|
||||
_exit(127);
|
||||
}
|
||||
close(in[0]);
|
||||
close(out[1]);
|
||||
/*
|
||||
* The config is a few hundred bytes, far below a pipe's buffer, and curl
|
||||
* reads all of it before it starts: writing first cannot deadlock.
|
||||
*/
|
||||
if (write_all(in[1], cfg.p, cfg.len) != 0) {
|
||||
sp_buf_printf(err, "curl: writing the config: %s",
|
||||
strerror(errno));
|
||||
close(in[1]);
|
||||
close(out[0]);
|
||||
(void)kill(child, SIGKILL);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
sp_buf_free(&cfg);
|
||||
return -1;
|
||||
}
|
||||
close(in[1]);
|
||||
/* the copy in memory holds the key too: do not leave it lying around */
|
||||
memset(cfg.p, 0, cfg.cap);
|
||||
sp_buf_free(&cfg);
|
||||
*pid = child;
|
||||
return out[0];
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* splinter -- curl(1) without secrets on its command line.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_CURL_H
|
||||
#define SPLINTER_CURL_H
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* Start curl and return the read end of its stdout, or -1.
|
||||
*
|
||||
* args options that anybody may see in ps(1), NULL-terminated, without
|
||||
* "curl" itself; may be NULL
|
||||
* url the URL; it travels on stdin, because a Telegram URL is the token
|
||||
* headers header lines that are secret ("Authorization: Bearer ..."),
|
||||
* NULL-terminated; may be NULL
|
||||
* quiet nonzero sends curl's stderr to /dev/null (a curses screen)
|
||||
*
|
||||
* stdin of curl is the config pipe, so it never reads the terminal.
|
||||
*/
|
||||
int sp_curl_start(const char *const *args, const char *url,
|
||||
const char *const *headers, int quiet, pid_t *pid, struct sp_buf *err);
|
||||
|
||||
/* Append key = "value" in curl's config syntax; exposed for the tests. */
|
||||
int sp_curl_config_line(struct sp_buf *b, const char *key, const char *value);
|
||||
|
||||
#endif /* SPLINTER_CURL_H */
|
||||
+120
-119
@@ -254,6 +254,123 @@ choose(const struct sp_config *cfg, const char *task, const char *wanted,
|
||||
return best;
|
||||
}
|
||||
|
||||
/*
|
||||
* Append 's' to 'b' as one word for a POSIX shell: '...' with every ' written
|
||||
* as '\''. Inside single quotes nothing is special, so the word arrives as it
|
||||
* was - whatever the model put into the task.
|
||||
*/
|
||||
static int
|
||||
shell_quote(struct sp_buf *b, const char *s)
|
||||
{
|
||||
if (sp_buf_puts(b, "'") != 0)
|
||||
return -1;
|
||||
for (; *s != '\0'; s++) {
|
||||
if (*s == '\'') {
|
||||
if (sp_buf_puts(b, "'\\''") != 0)
|
||||
return -1;
|
||||
} else if (sp_buf_add(b, s, 1) != 0)
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(b, "'");
|
||||
}
|
||||
|
||||
/*
|
||||
* The child side of every delegation, single or parallel: build the argument
|
||||
* vector and exec. It used to be written twice, and the two copies had drifted
|
||||
* apart - one ignored 'host' entirely, the other put "ssh" into argv[0] and then
|
||||
* exec'd splinter with it.
|
||||
*
|
||||
* Locally the argv goes straight to execv. Remotely ssh joins its arguments
|
||||
* into one command line for the remote shell, so each one is quoted on the way
|
||||
* and the task cannot become a command over there either. Keys stay home: the
|
||||
* remote host has its own.
|
||||
*/
|
||||
static void
|
||||
exec_delegate(const struct del_ctx *c, const struct sp_delegate *d,
|
||||
const char *task, const char *key_env)
|
||||
{
|
||||
char *argv[24];
|
||||
int n = 0, i;
|
||||
int cli = strcmp(d->kind, "cli") == 0;
|
||||
int remote = d->host[0] != '\0';
|
||||
char maxbuf[32], envname[96], plug[600];
|
||||
|
||||
snprintf(maxbuf, sizeof(maxbuf), "%d", DELEGATE_MAX_BYTES);
|
||||
argv[n++] = (char *)c->self;
|
||||
argv[n++] = "--no-config";
|
||||
argv[n++] = "-p";
|
||||
argv[n++] = (char *)task;
|
||||
/*
|
||||
* A cli delegate is a program, not an endpoint: the child runs the cli
|
||||
* transport with the configured command, and the token travels in the
|
||||
* environment where the program expects it.
|
||||
*/
|
||||
if (cli) {
|
||||
char *slash;
|
||||
|
||||
snprintf(plug, sizeof(plug), "%s", c->self);
|
||||
slash = strrchr(plug, '/');
|
||||
if (slash != NULL)
|
||||
*slash = '\0';
|
||||
snprintf(plug + strlen(plug), sizeof(plug) - strlen(plug),
|
||||
"/plugins/cli/cli.so");
|
||||
if (d->cmd[0] != '\0')
|
||||
(void)setenv("SPLINTER_CLI_CMD", d->cmd, 1);
|
||||
if (d->key[0] != '\0' && !remote)
|
||||
(void)setenv("CLAUDE_CODE_OAUTH_TOKEN", d->key, 1);
|
||||
argv[n++] = "--transport";
|
||||
argv[n++] = "cli";
|
||||
argv[n++] = "--plugin";
|
||||
argv[n++] = plug;
|
||||
} else {
|
||||
argv[n++] = "--endpoint";
|
||||
argv[n++] = (char *)d->endpoint;
|
||||
argv[n++] = "--model";
|
||||
argv[n++] = (char *)d->model;
|
||||
}
|
||||
argv[n++] = "--max-bytes";
|
||||
argv[n++] = maxbuf;
|
||||
argv[n++] = "--autonomous";
|
||||
if (remote)
|
||||
; /* the remote host has its own keys */
|
||||
else if (key_env != NULL) {
|
||||
argv[n++] = "--api-key-env";
|
||||
argv[n++] = (char *)key_env;
|
||||
} else if (d->key[0] != '\0' && !cli) {
|
||||
/* the literal key goes through the environment, never argv */
|
||||
snprintf(envname, sizeof(envname), "SPLINTER_DELEGATE_KEY_%ld",
|
||||
(long)getpid());
|
||||
(void)setenv(envname, d->key, 1);
|
||||
argv[n++] = "--api-key-env";
|
||||
argv[n++] = envname;
|
||||
}
|
||||
argv[n] = NULL;
|
||||
|
||||
if (remote) {
|
||||
struct sp_buf line;
|
||||
char *sshv[8];
|
||||
|
||||
if (sp_buf_init(&line) != 0)
|
||||
_exit(127);
|
||||
for (i = 0; i < n; i++) {
|
||||
if ((i > 0 && sp_buf_puts(&line, " ") != 0) ||
|
||||
shell_quote(&line, argv[i]) != 0)
|
||||
_exit(127);
|
||||
}
|
||||
sshv[0] = "ssh";
|
||||
sshv[1] = "-o";
|
||||
sshv[2] = "BatchMode=yes";
|
||||
sshv[3] = "--";
|
||||
sshv[4] = (char *)d->host;
|
||||
sshv[5] = line.p;
|
||||
sshv[6] = NULL;
|
||||
execvp("ssh", sshv);
|
||||
_exit(127);
|
||||
}
|
||||
execv(c->self, argv);
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
/* Run the child and collect its answer. */
|
||||
static void copy_answer(struct sp_buf *dst, const struct sp_buf *src);
|
||||
|
||||
@@ -264,7 +381,6 @@ run_child(const struct del_ctx *c, const struct sp_delegate *d,
|
||||
int fds[2];
|
||||
pid_t child;
|
||||
const char *key_env = d->key_env[0] != '\0' ? d->key_env : NULL;
|
||||
char maxbuf[32];
|
||||
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_printf(err, "delegate: pipe: %s", strerror(errno));
|
||||
@@ -278,70 +394,11 @@ run_child(const struct del_ctx *c, const struct sp_delegate *d,
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
char *argv[24];
|
||||
int n = 0, remote = 0;
|
||||
int cli = strcmp(d->kind, "cli") == 0;
|
||||
char envname[96];
|
||||
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
(void)dup2(fds[1], STDERR_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
snprintf(maxbuf, sizeof(maxbuf), "%d", DELEGATE_MAX_BYTES);
|
||||
argv[n++] = (char *)c->self;
|
||||
argv[n++] = "--no-config";
|
||||
argv[n++] = "-p";
|
||||
argv[n++] = (char *)task;
|
||||
/*
|
||||
* A cli delegate is a program, not an endpoint: the child runs the
|
||||
* cli transport with the configured command, and the token travels
|
||||
* in the environment where the program expects it.
|
||||
*/
|
||||
if (cli) {
|
||||
char plug[600];
|
||||
|
||||
snprintf(plug, sizeof(plug), "%s", c->self);
|
||||
{
|
||||
char *slash = strrchr(plug, '/');
|
||||
|
||||
if (slash != NULL)
|
||||
*slash = '\0';
|
||||
}
|
||||
snprintf(plug + strlen(plug),
|
||||
sizeof(plug) - strlen(plug), "/plugins/cli/cli.so");
|
||||
if (d->cmd[0] != '\0')
|
||||
(void)setenv("SPLINTER_CLI_CMD", d->cmd, 1);
|
||||
if (d->key[0] != '\0')
|
||||
(void)setenv("CLAUDE_CODE_OAUTH_TOKEN", d->key, 1);
|
||||
argv[n++] = "--transport";
|
||||
argv[n++] = "cli";
|
||||
argv[n++] = "--plugin";
|
||||
argv[n++] = plug;
|
||||
} else {
|
||||
argv[n++] = "--endpoint";
|
||||
argv[n++] = (char *)d->endpoint;
|
||||
argv[n++] = "--model";
|
||||
argv[n++] = (char *)d->model;
|
||||
}
|
||||
argv[n++] = "--max-bytes";
|
||||
argv[n++] = maxbuf;
|
||||
argv[n++] = "--autonomous";
|
||||
if (remote)
|
||||
; /* the remote host has its own keys */
|
||||
else if (key_env != NULL) {
|
||||
argv[n++] = "--api-key-env";
|
||||
argv[n++] = (char *)key_env;
|
||||
} else if (d->key[0] != '\0') {
|
||||
/* the literal key goes through the environment, never argv */
|
||||
snprintf(envname, sizeof(envname), "SPLINTER_DELEGATE_KEY_%ld",
|
||||
(long)getpid());
|
||||
(void)setenv(envname, d->key, 1);
|
||||
argv[n++] = "--api-key-env";
|
||||
argv[n++] = envname;
|
||||
}
|
||||
argv[n] = NULL;
|
||||
execv(c->self, argv);
|
||||
_exit(127);
|
||||
exec_delegate(c, d, task, key_env);
|
||||
}
|
||||
close(fds[1]);
|
||||
{
|
||||
@@ -594,68 +651,12 @@ spawn_job(const struct del_ctx *c, const struct sp_delegate *d,
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
char *argv[24];
|
||||
int n = 0, remote = 0;
|
||||
int cli = strcmp(d->kind, "cli") == 0;
|
||||
char maxbuf[32];
|
||||
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
(void)dup2(fds[1], STDERR_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
snprintf(maxbuf, sizeof(maxbuf), "%d", DELEGATE_MAX_BYTES);
|
||||
if (d->host[0] != '\0') {
|
||||
argv[n++] = "ssh";
|
||||
argv[n++] = "-o";
|
||||
argv[n++] = "BatchMode=yes";
|
||||
argv[n++] = (char *)d->host;
|
||||
argv[n++] = "--";
|
||||
remote = 1;
|
||||
}
|
||||
argv[n++] = (char *)c->self;
|
||||
argv[n++] = "--no-config";
|
||||
argv[n++] = "-p";
|
||||
argv[n++] = (char *)task;
|
||||
if (cli) {
|
||||
char plug[600];
|
||||
char *slash;
|
||||
|
||||
snprintf(plug, sizeof(plug), "%s", c->self);
|
||||
slash = strrchr(plug, '/');
|
||||
if (slash != NULL)
|
||||
*slash = '\0';
|
||||
snprintf(plug + strlen(plug),
|
||||
sizeof(plug) - strlen(plug), "/plugins/cli/cli.so");
|
||||
if (d->cmd[0] != '\0')
|
||||
(void)setenv("SPLINTER_CLI_CMD", d->cmd, 1);
|
||||
if (d->key[0] != '\0')
|
||||
(void)setenv("CLAUDE_CODE_OAUTH_TOKEN",
|
||||
d->key, 1);
|
||||
argv[n++] = "--transport";
|
||||
argv[n++] = "cli";
|
||||
argv[n++] = "--plugin";
|
||||
argv[n++] = plug;
|
||||
} else {
|
||||
argv[n++] = "--endpoint";
|
||||
argv[n++] = (char *)d->endpoint;
|
||||
argv[n++] = "--model";
|
||||
argv[n++] = (char *)d->model;
|
||||
}
|
||||
argv[n++] = "--max-bytes";
|
||||
argv[n++] = maxbuf;
|
||||
argv[n++] = "--autonomous";
|
||||
if (d->key[0] != '\0' && !cli && !remote) {
|
||||
char envname[96];
|
||||
|
||||
snprintf(envname, sizeof(envname),
|
||||
"SPLINTER_DELEGATE_KEY_%ld", (long)getpid());
|
||||
(void)setenv(envname, d->key, 1);
|
||||
argv[n++] = "--api-key-env";
|
||||
argv[n++] = envname;
|
||||
}
|
||||
argv[n] = NULL;
|
||||
execv(c->self, argv);
|
||||
_exit(127);
|
||||
exec_delegate(c, d, task,
|
||||
d->key_env[0] != '\0' ? d->key_env : NULL);
|
||||
}
|
||||
close(fds[1]);
|
||||
/* non-blocking, so a finished child is noticed at once */
|
||||
|
||||
+47
-3
@@ -59,7 +59,9 @@ usage(FILE *f)
|
||||
" --interview ask the first-run questions and write the "
|
||||
"profile\n"
|
||||
" --mcp-server-listen IP serve MCP on IP (tools of this "
|
||||
"registry)\n"
|
||||
"registry);\n"
|
||||
" beyond 127.x it needs "
|
||||
"SPLINTER_MCP_TOKEN\n"
|
||||
" --mcp-listen-port N MCP port, default 8098\n"
|
||||
" --autonomous run mutating tools without asking\n"
|
||||
" --steps N tool rounds per turn (default 8)\n"
|
||||
@@ -283,8 +285,30 @@ main(int argc, char **argv)
|
||||
} else if (!strcmp(argv[i], "--daemon")) {
|
||||
daemon_mode = 1;
|
||||
} else if (!strcmp(argv[i], "--ack") && i + 2 < argc) {
|
||||
const char *w;
|
||||
|
||||
ack_id = atoi(argv[++i]);
|
||||
ack_yes = strcmp(argv[++i], "no") != 0;
|
||||
w = argv[++i];
|
||||
/*
|
||||
* Only a word that means yes is a yes. "nein" used to
|
||||
* approve, because everything but "no" did.
|
||||
*/
|
||||
if (!strcmp(w, "yes") || !strcmp(w, "y") ||
|
||||
!strcmp(w, "ok") || !strcmp(w, "ja"))
|
||||
ack_yes = 1;
|
||||
else if (!strcmp(w, "no") || !strcmp(w, "n") ||
|
||||
!strcmp(w, "nein"))
|
||||
ack_yes = 0;
|
||||
else {
|
||||
fprintf(stderr, "splinter: --ack wants yes or "
|
||||
"no, not '%s'\n", w);
|
||||
return 2;
|
||||
}
|
||||
if (ack_id <= 0) {
|
||||
fprintf(stderr, "splinter: --ack wants a "
|
||||
"request id\n");
|
||||
return 2;
|
||||
}
|
||||
} else if (!strcmp(argv[i], "--ack-list")) {
|
||||
acklist = 1;
|
||||
} else if (!strcmp(argv[i], "--interview")) {
|
||||
@@ -479,6 +503,25 @@ main(int argc, char **argv)
|
||||
"environment\n", auto_added);
|
||||
}
|
||||
|
||||
/*
|
||||
* Every variable that holds a key is taken out of the 'run' tool's
|
||||
* environment, so the model cannot print splinter's credentials. The
|
||||
* numbered variants of the env providers (OLLAMA_KEY_2, ...) are prefixes.
|
||||
*/
|
||||
{
|
||||
size_t k;
|
||||
|
||||
(void)sp_secret_env_add(key_env);
|
||||
(void)sp_secret_env_add(conf.key_env);
|
||||
(void)sp_secret_env_add(conf.memory_key_env);
|
||||
(void)sp_secret_env_add("OLLAMA_KEY_*");
|
||||
(void)sp_secret_env_add("CLAUDE_CODE_OAUTH_TOKEN_*");
|
||||
for (k = 0; k < conf.ndelegates; k++)
|
||||
(void)sp_secret_env_add(conf.delegate[k].key_env);
|
||||
for (k = 0; k < conf.nexits; k++)
|
||||
(void)sp_secret_env_add(conf.exit[k].key_env);
|
||||
}
|
||||
|
||||
if (choose_text != NULL) {
|
||||
char id[64], why[192];
|
||||
int score = 0;
|
||||
@@ -602,7 +645,8 @@ main(int argc, char **argv)
|
||||
}
|
||||
if (ack_id != 0) {
|
||||
if (sp_ack_answer(ack_id, ack_yes, getenv("SPLINTER_ACK_BY")) != 0) {
|
||||
fprintf(stderr, "splinter: no such request %d\n", ack_id);
|
||||
fprintf(stderr, "splinter: no open request %d "
|
||||
"(unknown, answered or expired)\n", ack_id);
|
||||
return 1;
|
||||
}
|
||||
printf("%s %d\n", ack_yes ? "yes" : "no", ack_id);
|
||||
|
||||
+67
-7
@@ -7,7 +7,8 @@
|
||||
* The other direction of plugins/mcp: here splinter *is* the server, so another
|
||||
* agent can use its tools over MCP.
|
||||
*
|
||||
* splinter --mcp-server-listen 0.0.0.0 --mcp-listen-port 8098
|
||||
* splinter --mcp-server-listen 127.0.0.1 --mcp-listen-port 8098
|
||||
* SPLINTER_MCP_TOKEN=... splinter --mcp-server-listen 0.0.0.0 ...
|
||||
*
|
||||
* Speaks newline-delimited JSON-RPC over TCP - the same framing MCP uses on
|
||||
* stdio, just on a socket. Handles initialize, tools/list and tools/call, plus
|
||||
@@ -15,7 +16,16 @@
|
||||
*
|
||||
* Authorization is the point: a read tool is served, a mutating or destructive
|
||||
* one is refused unless the server was started with --autonomous. A remote agent
|
||||
* does not get to run shell commands on this machine because it asked nicely.
|
||||
* does not get to run shell commands on this machine because it asked nicely. *
|
||||
* Who may connect at all is the step before that. 'read' alone hands out every
|
||||
* file this user can open, so an address other than loopback needs a token:
|
||||
* SPLINTER_MCP_TOKEN, and every connection starts with the line
|
||||
*
|
||||
* AUTH <token>
|
||||
*
|
||||
* before any JSON-RPC; anything else closes it. Without a token the server
|
||||
* refuses to listen beyond 127.0.0.0/8. There is no TLS - put it behind ssh or
|
||||
* a tunnel when the network is not yours.
|
||||
*/
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
@@ -25,6 +35,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -279,11 +290,25 @@ handle_line(int fd, const struct sp_registry *reg, const char *line,
|
||||
/* a notification has no id and gets no answer */
|
||||
}
|
||||
|
||||
/* compare without stopping at the first difference: no timing hint */
|
||||
static int
|
||||
token_equal(const char *a, const char *b)
|
||||
{
|
||||
size_t la = strlen(a), lb = strlen(b), i;
|
||||
unsigned char d = la != lb;
|
||||
|
||||
for (i = 0; i < la; i++)
|
||||
d |= (unsigned char)(a[i] ^ b[i % (lb > 0 ? lb : 1)]);
|
||||
return d == 0;
|
||||
}
|
||||
|
||||
static void
|
||||
serve_conn(int fd, const struct sp_registry *reg, int allow_mutate)
|
||||
serve_conn(int fd, const struct sp_registry *reg, int allow_mutate,
|
||||
const char *token)
|
||||
{
|
||||
char line[16384];
|
||||
size_t used = 0;
|
||||
int authed = token == NULL;
|
||||
|
||||
for (;;) {
|
||||
ssize_t got = read(fd, line + used, sizeof(line) - used - 1);
|
||||
@@ -302,7 +327,19 @@ serve_conn(int fd, const struct sp_registry *reg, int allow_mutate)
|
||||
if (nl == NULL)
|
||||
break;
|
||||
*nl = '\0';
|
||||
if (line[0] == '{')
|
||||
if (!authed) {
|
||||
size_t l = strlen(line);
|
||||
|
||||
if (l > 0 && line[l - 1] == '\r')
|
||||
line[l - 1] = '\0';
|
||||
if (strncmp(line, "AUTH ", 5) != 0 ||
|
||||
!token_equal(line + 5, token)) {
|
||||
reply_error(fd, 0, -32001,
|
||||
"authentication required");
|
||||
return;
|
||||
}
|
||||
authed = 1;
|
||||
} else if (line[0] == '{')
|
||||
handle_line(fd, reg, line, allow_mutate);
|
||||
len = (size_t)(nl - line) + 1;
|
||||
memmove(line, line + len, used - len + 1);
|
||||
@@ -320,8 +357,18 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port,
|
||||
int s, one = 1;
|
||||
struct sockaddr_in addr;
|
||||
|
||||
const char *token = getenv("SPLINTER_MCP_TOKEN");
|
||||
|
||||
if (ip == NULL || *ip == '\0')
|
||||
ip = "127.0.0.1";
|
||||
if (token != NULL && *token == '\0')
|
||||
token = NULL;
|
||||
if (token == NULL && strncmp(ip, "127.", 4) != 0) {
|
||||
sp_buf_printf(err, "mcp: refusing to serve on %s without "
|
||||
"SPLINTER_MCP_TOKEN: 'read' alone would give the network "
|
||||
"every file of this user", ip);
|
||||
return -1;
|
||||
}
|
||||
s = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (s < 0) {
|
||||
sp_buf_printf(err, "mcp: socket: %s", strerror(errno));
|
||||
@@ -349,8 +396,11 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port,
|
||||
}
|
||||
(void)signal(SIGINT, on_signal);
|
||||
(void)signal(SIGTERM, on_signal);
|
||||
fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools, %s)\n", ip,
|
||||
port, reg->len, allow_mutate ? "mutating allowed" : "read only");
|
||||
/* a client that hangs up mid-reply is a closed connection, not our death */
|
||||
(void)signal(SIGPIPE, SIG_IGN);
|
||||
fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools, %s, %s)\n",
|
||||
ip, port, reg->len, allow_mutate ? "mutating allowed" : "read only",
|
||||
token != NULL ? "token required" : "loopback, no token");
|
||||
|
||||
while (!mcp_stop) {
|
||||
int c = accept(s, NULL, NULL);
|
||||
@@ -360,7 +410,17 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port,
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
serve_conn(c, reg, allow_mutate);
|
||||
{
|
||||
/*
|
||||
* One connection at a time, so an idle one must not hold
|
||||
* the server forever: five quiet minutes and it is closed.
|
||||
*/
|
||||
struct timeval tv = { 300, 0 };
|
||||
|
||||
(void)setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv,
|
||||
sizeof(tv));
|
||||
}
|
||||
serve_conn(c, reg, allow_mutate, token);
|
||||
close(c);
|
||||
}
|
||||
close(s);
|
||||
|
||||
+20
-38
@@ -32,6 +32,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#include "ack.h"
|
||||
#include "curl.h"
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "log.h"
|
||||
@@ -108,9 +109,9 @@ on_signal(int sig)
|
||||
/*
|
||||
* Run curl with the URL built here and return its stdout.
|
||||
*
|
||||
* The token is part of the URL, so the command string is never logged and the
|
||||
* process is exec'd directly instead of through a shell: a token with a quote in
|
||||
* it would otherwise change the command.
|
||||
* The token is part of the URL, and an argument is readable by every user of
|
||||
* the machine. So the URL goes to curl on stdin (sp_curl_start), and argv holds
|
||||
* nothing that would let anybody else drive the bot.
|
||||
*/
|
||||
static int
|
||||
tg_curl(const char *url, const char *post_body, struct sp_buf *out,
|
||||
@@ -118,43 +119,24 @@ tg_curl(const char *url, const char *post_body, struct sp_buf *out,
|
||||
{
|
||||
int fds[2];
|
||||
pid_t child;
|
||||
const char *args[12];
|
||||
int n = 0;
|
||||
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_printf(err, "telegram: pipe: %s", strerror(errno));
|
||||
args[n++] = "-sS";
|
||||
args[n++] = "-m";
|
||||
args[n++] = "60";
|
||||
if (post_body != NULL) {
|
||||
args[n++] = "-X";
|
||||
args[n++] = "POST";
|
||||
args[n++] = "-H";
|
||||
args[n++] = "Content-Type: application/json";
|
||||
args[n++] = "--data-binary";
|
||||
args[n++] = post_body;
|
||||
}
|
||||
args[n] = NULL;
|
||||
fds[0] = sp_curl_start(args, url, NULL, 0, &child, err);
|
||||
if (fds[0] < 0)
|
||||
return -1;
|
||||
}
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
sp_buf_printf(err, "telegram: fork: %s", strerror(errno));
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
char *argv[10];
|
||||
int n = 0;
|
||||
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
argv[n++] = "curl";
|
||||
argv[n++] = "-sS";
|
||||
argv[n++] = "-m";
|
||||
argv[n++] = "60";
|
||||
if (post_body != NULL) {
|
||||
argv[n++] = "-X";
|
||||
argv[n++] = "POST";
|
||||
argv[n++] = "-H";
|
||||
argv[n++] = "Content-Type: application/json";
|
||||
argv[n++] = "--data-binary";
|
||||
argv[n++] = (char *)post_body;
|
||||
}
|
||||
argv[n++] = (char *)url;
|
||||
argv[n] = NULL;
|
||||
execvp("curl", argv);
|
||||
_exit(127);
|
||||
}
|
||||
close(fds[1]);
|
||||
{
|
||||
struct pollfd pfd;
|
||||
char chunk[4096];
|
||||
|
||||
+46
-40
@@ -24,6 +24,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "curl.h"
|
||||
#include "log.h"
|
||||
|
||||
struct openai_ctx {
|
||||
@@ -72,40 +73,58 @@ read_all_cancel(FILE *f, struct sp_buf *out, const volatile int *cancel,
|
||||
}
|
||||
|
||||
/*
|
||||
* Run a command with its stdout on a pipe.
|
||||
* Start the POST and hand back curl's stdout.
|
||||
*
|
||||
* popen() was the obvious tool and the wrong one: it hands back a stream, not a
|
||||
* process id, so a cancellation could only take effect once the command had
|
||||
* finished by itself - the opposite of cancelling. fork/exec keeps the pid, and
|
||||
* the read loop can kill it.
|
||||
* finished by itself. sp_curl_start keeps the pid, so the read loop can kill it;
|
||||
* and it keeps the key out of argv, where every user of the machine could read
|
||||
* it in ps(1).
|
||||
*/
|
||||
static FILE *
|
||||
spawn_cmd(const char *cmd, pid_t *pid, struct sp_buf *err)
|
||||
openai_curl(const struct openai_ctx *c, const char *body_path, int stream,
|
||||
pid_t *pid, struct sp_buf *err)
|
||||
{
|
||||
int fds[2];
|
||||
pid_t child;
|
||||
char tmo[32], data[600], auth[sizeof(c->key) + 32];
|
||||
const char *args[16];
|
||||
const char *hdrs[2] = { NULL, NULL };
|
||||
int n = 0, fd;
|
||||
FILE *f;
|
||||
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_printf(err, "openai: pipe: %s", strerror(errno));
|
||||
snprintf(tmo, sizeof(tmo), "%ld", c->timeout_s);
|
||||
snprintf(data, sizeof(data), "@%s", body_path);
|
||||
args[n++] = "-sS";
|
||||
if (stream)
|
||||
args[n++] = "-N";
|
||||
args[n++] = "-m";
|
||||
args[n++] = tmo;
|
||||
args[n++] = "-X";
|
||||
args[n++] = "POST";
|
||||
args[n++] = "-H";
|
||||
args[n++] = "Content-Type: application/json";
|
||||
args[n++] = "--data-binary";
|
||||
args[n++] = data;
|
||||
if (!stream) {
|
||||
args[n++] = "-w";
|
||||
args[n++] = "\\n%{http_code}";
|
||||
}
|
||||
args[n] = NULL;
|
||||
if (c->key[0] != '\0') {
|
||||
snprintf(auth, sizeof(auth), "Authorization: Bearer %s", c->key);
|
||||
hdrs[0] = auth;
|
||||
}
|
||||
fd = sp_curl_start(args, c->url, hdrs, 0, pid, err);
|
||||
memset(auth, 0, sizeof(auth));
|
||||
if (fd < 0)
|
||||
return NULL;
|
||||
f = fdopen(fd, "r");
|
||||
if (f == NULL) {
|
||||
close(fd);
|
||||
(void)kill(*pid, SIGKILL);
|
||||
(void)waitpid(*pid, NULL, 0);
|
||||
sp_buf_printf(err, "openai: fdopen: %s", strerror(errno));
|
||||
}
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
sp_buf_printf(err, "openai: fork: %s", strerror(errno));
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
return NULL;
|
||||
}
|
||||
if (child == 0) {
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
close(fds[1]);
|
||||
*pid = child;
|
||||
return fdopen(fds[0], "r");
|
||||
return f;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -185,14 +204,7 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
goto out;
|
||||
}
|
||||
|
||||
sp_buf_printf(&cmd, "curl -sS -m %ld -X POST -H 'Content-Type: "
|
||||
"application/json'", c->timeout_s);
|
||||
if (c->key[0] != '\0')
|
||||
sp_buf_printf(&cmd, " -H 'Authorization: Bearer %s'", c->key);
|
||||
sp_buf_printf(&cmd, " --data-binary @%s -w '\\n%%{http_code}' '%s'",
|
||||
path, c->url);
|
||||
|
||||
p = spawn_cmd(cmd.p, &child, err);
|
||||
p = openai_curl(c, path, 0, &child, err);
|
||||
if (p == NULL) {
|
||||
unlink(path);
|
||||
goto out;
|
||||
@@ -303,13 +315,7 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
goto out;
|
||||
}
|
||||
|
||||
sp_buf_printf(&cmd, "curl -sS -N -m %ld -X POST -H 'Content-Type: "
|
||||
"application/json'", c->timeout_s);
|
||||
if (c->key[0] != '\0')
|
||||
sp_buf_printf(&cmd, " -H 'Authorization: Bearer %s'", c->key);
|
||||
sp_buf_printf(&cmd, " --data-binary @%s '%s'", path, c->url);
|
||||
|
||||
p = spawn_cmd(cmd.p, &child, err);
|
||||
p = openai_curl(c, path, 1, &child, err);
|
||||
if (p == NULL) {
|
||||
unlink(path);
|
||||
goto out;
|
||||
|
||||
@@ -641,6 +641,51 @@ md_strip(const char *in, char *out, size_t cap, unsigned char *attr)
|
||||
attr[o] = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* One character of 's', UTF-8 or not, as ASCII in 'out'; returns how many bytes
|
||||
* of 's' it took (at least 1 unless *s is NUL).
|
||||
*
|
||||
* A UTF-8 character is one unit. Handing sp_ui_ascii a single byte of a two-byte
|
||||
* sequence produced '??hler' where 'Zaehler' belonged - the transliteration
|
||||
* needs the whole character. The copy of that character used to live in a
|
||||
* char[2] on md_draw's stack, and a three- or four-byte character ('...', an
|
||||
* emoji) wrote past it on every redraw.
|
||||
*/
|
||||
size_t
|
||||
sp_ui_ascii_char(const char *s, char *out, size_t cap)
|
||||
{
|
||||
char one[5]; /* four UTF-8 bytes and the NUL */
|
||||
size_t len = 1, k;
|
||||
unsigned char c = (unsigned char)s[0];
|
||||
|
||||
if (cap == 0)
|
||||
return c != 0 ? 1 : 0;
|
||||
out[0] = '\0';
|
||||
if (c == 0)
|
||||
return 0;
|
||||
if (c < 0x80) {
|
||||
if (cap > 1) {
|
||||
out[0] = (char)c;
|
||||
out[1] = '\0';
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
if ((c & 0xe0) == 0xc0)
|
||||
len = 2;
|
||||
else if ((c & 0xf0) == 0xe0)
|
||||
len = 3;
|
||||
else if ((c & 0xf8) == 0xf0)
|
||||
len = 4;
|
||||
for (k = 0; k < len && s[k] != '\0'; k++)
|
||||
one[k] = s[k];
|
||||
one[k] = '\0';
|
||||
if (sp_ui_ascii(one, out, cap) != 0 && cap > 1) {
|
||||
out[0] = '?';
|
||||
out[1] = '\0';
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
/* draw one prepared markdown string, wrapping at 'cols', for at most 'maxrows' */
|
||||
static int
|
||||
md_draw(int y, int cols, int maxrows, const char *text, const unsigned char *attr)
|
||||
@@ -650,7 +695,6 @@ md_draw(int y, int cols, int maxrows, const char *text, const unsigned char *att
|
||||
|
||||
for (i = 0; text[i] != '\0' && row < maxrows; i++) {
|
||||
char out[8];
|
||||
char one[2];
|
||||
unsigned a = attr[i];
|
||||
|
||||
if (text[i] == '\n') {
|
||||
@@ -666,30 +710,7 @@ md_draw(int y, int cols, int maxrows, const char *text, const unsigned char *att
|
||||
if (row >= maxrows)
|
||||
break;
|
||||
}
|
||||
/*
|
||||
* A UTF-8 character is one unit. Handing sp_ui_ascii a single byte of
|
||||
* a two-byte sequence produced '??hler' where 'Zaehler' belonged -
|
||||
* the transliteration needs the whole character.
|
||||
*/
|
||||
if ((unsigned char)text[i] < 0x80) {
|
||||
out[0] = text[i];
|
||||
out[1] = '\0';
|
||||
} else {
|
||||
size_t len = 1, k;
|
||||
|
||||
if (((unsigned char)text[i] & 0xe0) == 0xc0)
|
||||
len = 2;
|
||||
else if (((unsigned char)text[i] & 0xf0) == 0xe0)
|
||||
len = 3;
|
||||
else if (((unsigned char)text[i] & 0xf8) == 0xf0)
|
||||
len = 4;
|
||||
for (k = 0; k < len && text[i + k] != '\0'; k++)
|
||||
one[k] = text[i + k];
|
||||
one[k] = '\0';
|
||||
if (sp_ui_ascii(one, out, sizeof(out)) != 0)
|
||||
out[0] = '?', out[1] = '\0';
|
||||
i += k - 1;
|
||||
}
|
||||
i += sp_ui_ascii_char(text + i, out, sizeof(out)) - 1;
|
||||
|
||||
attrset(COLOR_PAIR(PAIR_MAIN));
|
||||
if (a & MD_BOLD)
|
||||
@@ -802,11 +823,6 @@ draw_history(struct ui_state *s, int reserve)
|
||||
break;
|
||||
snprintf(render, len, "%s%s", prefix, e->text);
|
||||
|
||||
off = (long)align_utf8(render, strlen(render),
|
||||
(size_t)(skip * cols));
|
||||
if (off > (long)strlen(render))
|
||||
off = (long)strlen(render);
|
||||
skip = 0;
|
||||
|
||||
wmove(ui_hist, y, 1);
|
||||
if (strcmp(e->role, "you") == 0)
|
||||
@@ -822,6 +838,17 @@ draw_history(struct ui_state *s, int reserve)
|
||||
unsigned char attr[4096];
|
||||
|
||||
md_strip(render, plain, sizeof(plain), attr);
|
||||
/*
|
||||
* The offset is into what gets drawn. It used to be taken
|
||||
* from 'render', which still has the markdown markers and
|
||||
* is not capped at sizeof(plain), and then applied to
|
||||
* 'plain': past its end for a long answer.
|
||||
*/
|
||||
off = (long)align_utf8(plain, strlen(plain),
|
||||
(size_t)(skip * cols));
|
||||
if (off > (long)strlen(plain))
|
||||
off = (long)strlen(plain);
|
||||
skip = 0;
|
||||
(void)md_draw(y, cols, rows - y,
|
||||
plain + (off > 0 ? off : 0), attr +
|
||||
(off > 0 ? off : 0));
|
||||
|
||||
@@ -21,4 +21,10 @@ int sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model,
|
||||
*/
|
||||
int sp_ui_ascii(const char *in, char *out, size_t cap);
|
||||
|
||||
/*
|
||||
* The first character of 's' (one to four UTF-8 bytes) as ASCII in 'out'.
|
||||
* Returns the bytes consumed: 0 only at the NUL, never more than are there.
|
||||
*/
|
||||
size_t sp_ui_ascii_char(const char *s, char *out, size_t cap);
|
||||
|
||||
#endif /* SPLINTER_UI_H */
|
||||
@@ -84,6 +84,47 @@ main(void)
|
||||
}
|
||||
(void)sp_ack_answer(id, 0, "test");
|
||||
|
||||
/*
|
||||
* ---- an answer belongs to one request, once, in time ----
|
||||
* The id used to be the pid: a "yes" that came too late stayed on disk
|
||||
* and approved the next request of the same process unseen.
|
||||
*/
|
||||
{
|
||||
int a, b;
|
||||
|
||||
a = sp_ack_request("run", "first", "destructive", 1);
|
||||
b = sp_ack_request("run", "second", "destructive", 1);
|
||||
CHECK(a > 0 && b > 0 && a != b,
|
||||
"two requests of one process get two ids");
|
||||
CHECK(a != (int)getpid(), "the id is not the pid");
|
||||
(void)sp_ack_answer(b, 0, "test");
|
||||
(void)sp_ack_wait(b, 1, who, sizeof(who));
|
||||
|
||||
CHECK(sp_ack_wait(a, 1, who, sizeof(who)) == 0,
|
||||
"an unanswered request times out as no");
|
||||
CHECK(sp_ack_answer(a, 1, "late") != 0,
|
||||
"an answer after the timeout is refused");
|
||||
id = sp_ack_request("run", "third", "destructive", 1);
|
||||
CHECK(sp_ack_wait(id, 1, who, sizeof(who)) == 0,
|
||||
"a late yes does not approve the next request");
|
||||
|
||||
id = sp_ack_request("run", "fourth", "destructive", 5);
|
||||
CHECK(sp_ack_answer(id, 0, "first") == 0, "the first answer counts");
|
||||
CHECK(sp_ack_answer(id, 1, "second") != 0,
|
||||
"a second answer to the same request is refused");
|
||||
CHECK(sp_ack_wait(id, 5, who, sizeof(who)) == 0 &&
|
||||
strcmp(who, "first") == 0, "the first answer wins");
|
||||
}
|
||||
|
||||
/* ---- a directory others may write into is not trusted with a yes ---- */
|
||||
(void)system("rm -rf /var/tmp/splinter_test_ack_open");
|
||||
(void)system("mkdir -p /var/tmp/splinter_test_ack_open && "
|
||||
"chmod 0777 /var/tmp/splinter_test_ack_open");
|
||||
(void)setenv("SPLINTER_ACK_DIR", "/var/tmp/splinter_test_ack_open", 1);
|
||||
CHECK(sp_ack_request("run", "x", "destructive", 1) < 0,
|
||||
"a world-writable ack directory is refused");
|
||||
(void)system("rm -rf /var/tmp/splinter_test_ack_open");
|
||||
|
||||
printf("\n%d checks, %d failures\n", checks, fails);
|
||||
(void)system("rm -rf /var/tmp/splinter_test_ack");
|
||||
return fails == 0 ? 0 : 1;
|
||||
|
||||
Binary file not shown.
@@ -70,6 +70,30 @@ main(void)
|
||||
CHECK(strlen(small) < sizeof(small));
|
||||
}
|
||||
|
||||
/*
|
||||
* ---- one character at a time, as the history window draws it ----
|
||||
* A three- or four-byte character used to be copied into a char[2].
|
||||
* Under -fsanitize=address this block is what catches it.
|
||||
*/
|
||||
{
|
||||
const char *dash = "\xe2\x80\x94x"; /* em dash, 3 bytes */
|
||||
const char *ell = "\xe2\x80\xa6"; /* ellipsis */
|
||||
const char *emoji = "\xf0\x9f\x98\x80y"; /* U+1F600, 4 bytes */
|
||||
const char *cut = "\xf0\x9f"; /* truncated */
|
||||
char one[8];
|
||||
|
||||
CHECK(sp_ui_ascii_char(dash, one, sizeof(one)) == 3);
|
||||
CHECK(one[0] != '\0' && strlen(one) < sizeof(one));
|
||||
CHECK(sp_ui_ascii_char(ell, one, sizeof(one)) == 3);
|
||||
CHECK(no_questions(one));
|
||||
CHECK(sp_ui_ascii_char(emoji, one, sizeof(one)) == 4);
|
||||
CHECK(sp_ui_ascii_char(emoji + 4, one, sizeof(one)) == 1);
|
||||
CHECK(strcmp(one, "y") == 0);
|
||||
CHECK(sp_ui_ascii_char(cut, one, sizeof(one)) == 2);
|
||||
CHECK(sp_ui_ascii_char("", one, sizeof(one)) == 0);
|
||||
CHECK(sp_ui_ascii_char("\xc3\xbc", one, sizeof(one)) == 2);
|
||||
}
|
||||
|
||||
if (failures == 0)
|
||||
printf("test_ascii: ok\n");
|
||||
return failures == 0 ? 0 : 1;
|
||||
|
||||
Binary file not shown.
@@ -160,6 +160,35 @@ main(void)
|
||||
CHECK(tool(&r, "read")->run("{}", &out, NULL) == 0);
|
||||
CHECK(strstr(out.p, "required") != NULL);
|
||||
|
||||
/*
|
||||
* ---- webfetch: the URL is the model's, so it is data, never shell ----
|
||||
* The quote used to close curl's '...' and run the rest as a command,
|
||||
* from a tool that needed nobody's consent.
|
||||
*/
|
||||
{
|
||||
char mark[700];
|
||||
struct stat st;
|
||||
|
||||
CHECK(tool(&r, "webfetch")->auth != SP_AUTH_READ);
|
||||
snprintf(mark, sizeof(mark), "%s/pwned", dir);
|
||||
snprintf(big, sizeof(big), "{\"url\":\"http://127.0.0.1:9/'; "
|
||||
"touch %s; echo '\"}", mark);
|
||||
sp_buf_clear(&out);
|
||||
CHECK(tool(&r, "webfetch")->run(big, &out, NULL) == 0);
|
||||
CHECK(stat(mark, &st) != 0);
|
||||
|
||||
sp_buf_clear(&out);
|
||||
CHECK(tool(&r, "webfetch")->run("{\"url\":\"file:///etc/passwd\"}",
|
||||
&out, NULL) == 0);
|
||||
CHECK(strstr(out.p, "only http") != NULL);
|
||||
CHECK(strstr(out.p, "root:") == NULL);
|
||||
|
||||
sp_buf_clear(&out);
|
||||
CHECK(tool(&r, "webfetch")->run("{\"url\":\"-K/etc/passwd\"}",
|
||||
&out, NULL) == 0);
|
||||
CHECK(strstr(out.p, "only http") != NULL);
|
||||
}
|
||||
|
||||
copy = out.p;
|
||||
CHECK(copy != NULL);
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -6,7 +6,10 @@
|
||||
* decided it.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "config.h"
|
||||
@@ -90,6 +93,84 @@ main(void)
|
||||
CHECK(sp_delegate_choose(&c, "code", NULL, id, sizeof(id), why,
|
||||
sizeof(why), &score) != 0);
|
||||
|
||||
/*
|
||||
* ---- a remote delegate: the task reaches the far side as one word ----
|
||||
* ssh joins its arguments into a command line for the remote shell. A
|
||||
* fake ssh in PATH plays that shell: it re-splits the line with eval,
|
||||
* which runs anything an unquoted task would smuggle in, and records the
|
||||
* words it got.
|
||||
*/
|
||||
{
|
||||
char tdir[] = "/var/tmp/splinter-del-XXXXXX";
|
||||
char path[600], mark[600], words[600], fake[1600];
|
||||
char task[700], args[1200], line[800];
|
||||
const char *oldpath = getenv("PATH");
|
||||
struct sp_registry r;
|
||||
struct sp_buf out;
|
||||
struct stat st;
|
||||
FILE *f;
|
||||
int n = 0, task_ok = 0;
|
||||
|
||||
CHECK(mkdtemp(tdir) != NULL);
|
||||
snprintf(mark, sizeof(mark), "%s/pwned", tdir);
|
||||
snprintf(words, sizeof(words), "%s/words", tdir);
|
||||
snprintf(path, sizeof(path), "%s/ssh", tdir);
|
||||
snprintf(fake, sizeof(fake), "#!/bin/sh\n"
|
||||
"[ \"$3\" = -- ] && [ \"$4\" = farhost ] || exit 3\n"
|
||||
"eval \"set -- $5\"\n"
|
||||
"printf '%%s\\n' \"$@\" > '%s'\n"
|
||||
"echo fertig\n", words);
|
||||
f = fopen(path, "w");
|
||||
CHECK(f != NULL);
|
||||
if (f != NULL) {
|
||||
fputs(fake, f);
|
||||
fclose(f);
|
||||
}
|
||||
(void)chmod(path, 0755);
|
||||
snprintf(line, sizeof(line), "%s:%s", tdir,
|
||||
oldpath != NULL ? oldpath : "/usr/bin:/bin");
|
||||
(void)setenv("PATH", line, 1);
|
||||
|
||||
memset(&c, 0, sizeof(c));
|
||||
add(&c, "far", "remote", "far");
|
||||
snprintf(c.delegate[0].host, sizeof(c.delegate[0].host), "farhost");
|
||||
c.delegate[0].max_parallel = 1;
|
||||
memset(&r, 0, sizeof(r));
|
||||
CHECK(sp_delegate_register(&r, &c, NULL) == 0);
|
||||
snprintf(task, sizeof(task), "it's x'; touch %s; echo '", mark);
|
||||
snprintf(args, sizeof(args), "{\"task\":\"%s\",\"tags\":\"far\"}",
|
||||
task);
|
||||
CHECK(sp_buf_init(&out) == 0);
|
||||
{
|
||||
const struct sp_tool *t = sp_registry_find(&r, "delegate");
|
||||
|
||||
CHECK(t != NULL);
|
||||
if (t != NULL)
|
||||
(void)t->run(args, &out, t->ctx);
|
||||
}
|
||||
|
||||
CHECK(stat(mark, &st) != 0);
|
||||
if (getenv("TEST_VERBOSE") != NULL)
|
||||
fprintf(stderr, "delegate said: %s\n", out.p);
|
||||
f = fopen(words, "r");
|
||||
CHECK(f != NULL);
|
||||
if (f != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
line[strcspn(line, "\n")] = '\0';
|
||||
if (n == 3 && strcmp(line, task) == 0)
|
||||
task_ok = 1;
|
||||
n++;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
CHECK(task_ok);
|
||||
sp_buf_free(&out);
|
||||
sp_registry_free(&r);
|
||||
(void)setenv("PATH", oldpath != NULL ? oldpath : "/usr/bin:/bin", 1);
|
||||
snprintf(line, sizeof(line), "rm -rf '%s'", tdir);
|
||||
(void)system(line);
|
||||
}
|
||||
|
||||
if (failures == 0)
|
||||
printf("test_delegate: ok\n");
|
||||
return failures == 0 ? 0 : 1;
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,328 @@
|
||||
/*
|
||||
* splinter -- secrets stay out of argv and out of the model's shell, the MCP
|
||||
* server does not talk to strangers, and task_kill does not kill splinter.
|
||||
*
|
||||
* Each block is the failure it guards against, as it was found.
|
||||
*/
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <netinet/in.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "curl.h"
|
||||
#include "mcpserver.h"
|
||||
|
||||
static int failures;
|
||||
|
||||
#define CHECK(cond) do { \
|
||||
if (!(cond)) { \
|
||||
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
|
||||
failures++; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
static char dir[] = "/var/tmp/splinter-secrets-XXXXXX";
|
||||
|
||||
static char *
|
||||
slurp(const char *path)
|
||||
{
|
||||
static char buf[8192];
|
||||
FILE *f = fopen(path, "r");
|
||||
size_t n;
|
||||
|
||||
buf[0] = '\0';
|
||||
if (f == NULL)
|
||||
return buf;
|
||||
n = fread(buf, 1, sizeof(buf) - 1, f);
|
||||
buf[n] = '\0';
|
||||
fclose(f);
|
||||
return buf;
|
||||
}
|
||||
|
||||
static void
|
||||
run_tool(struct sp_registry *r, const char *name, const char *args,
|
||||
struct sp_buf *out)
|
||||
{
|
||||
const struct sp_tool *t = sp_registry_find(r, name);
|
||||
|
||||
sp_buf_clear(out);
|
||||
CHECK(t != NULL);
|
||||
if (t != NULL)
|
||||
(void)t->run(args, out, t->ctx);
|
||||
}
|
||||
|
||||
/* ---- 'run': no keys in its environment, no terminal, no forever ---- */
|
||||
static void
|
||||
test_run(void)
|
||||
{
|
||||
struct sp_registry r;
|
||||
struct sp_buf out;
|
||||
time_t t0;
|
||||
|
||||
memset(&r, 0, sizeof(r));
|
||||
CHECK(sp_builtin_register(&r) == 0);
|
||||
CHECK(sp_buf_init(&out) == 0);
|
||||
|
||||
setenv("SPLINTER_API_KEY", "sk-geheim-1", 1);
|
||||
setenv("MY_PROVIDER_KEY", "sk-geheim-2", 1);
|
||||
setenv("SPLINTER_DELEGATE_KEY_4711", "sk-geheim-3", 1);
|
||||
setenv("HARMLESS_VALUE", "sichtbar", 1);
|
||||
CHECK(sp_secret_env_add("MY_PROVIDER_KEY") == 0);
|
||||
run_tool(&r, "run", "{\"command\":\"env\"}", &out);
|
||||
CHECK(strstr(out.p, "sk-geheim") == NULL);
|
||||
CHECK(strstr(out.p, "HARMLESS_VALUE=sichtbar") != NULL);
|
||||
CHECK(strstr(out.p, "[exit status 0]") != NULL);
|
||||
|
||||
/* stdin is /dev/null: cat ends at once instead of reading the terminal */
|
||||
run_tool(&r, "run", "{\"command\":\"cat; echo done\"}", &out);
|
||||
CHECK(strstr(out.p, "done") != NULL);
|
||||
|
||||
/* stderr is part of the observation */
|
||||
run_tool(&r, "run", "{\"command\":\"echo oops >&2; exit 3\"}", &out);
|
||||
CHECK(strstr(out.p, "oops") != NULL);
|
||||
CHECK(strstr(out.p, "[exit status 3]") != NULL);
|
||||
|
||||
/* a command that does not end is ended */
|
||||
setenv("SPLINTER_RUN_TIMEOUT", "1", 1);
|
||||
t0 = time(NULL);
|
||||
run_tool(&r, "run", "{\"command\":\"sleep 30 & sleep 30\"}", &out);
|
||||
CHECK(strstr(out.p, "timed out") != NULL);
|
||||
CHECK(time(NULL) - t0 < 10);
|
||||
unsetenv("SPLINTER_RUN_TIMEOUT");
|
||||
|
||||
sp_buf_free(&out);
|
||||
sp_registry_free(&r);
|
||||
}
|
||||
|
||||
/* ---- curl: the key travels on stdin, never in argv ---- */
|
||||
static void
|
||||
test_curl(void)
|
||||
{
|
||||
char fake[700], argsf[700], cfgf[700], line[1600];
|
||||
const char *oldpath = getenv("PATH");
|
||||
const char *args[] = { "-sS", "-m", "5", NULL };
|
||||
const char *hdrs[] = { "Authorization: Bearer sk-geheim-4", NULL };
|
||||
struct sp_buf err, cfg;
|
||||
pid_t pid;
|
||||
int fd, st;
|
||||
FILE *f;
|
||||
char buf[256];
|
||||
|
||||
snprintf(argsf, sizeof(argsf), "%s/curl.args", dir);
|
||||
snprintf(cfgf, sizeof(cfgf), "%s/curl.cfg", dir);
|
||||
snprintf(fake, sizeof(fake), "%s/curl", dir);
|
||||
f = fopen(fake, "w");
|
||||
CHECK(f != NULL);
|
||||
if (f == NULL)
|
||||
return;
|
||||
fprintf(f, "#!/bin/sh\nprintf '%%s\\n' \"$@\" > '%s'\ncat > '%s'\n"
|
||||
"echo hello\n", argsf, cfgf);
|
||||
fclose(f);
|
||||
(void)chmod(fake, 0755);
|
||||
snprintf(line, sizeof(line), "%s:%s", dir,
|
||||
oldpath != NULL ? oldpath : "/usr/bin:/bin");
|
||||
setenv("PATH", line, 1);
|
||||
|
||||
CHECK(sp_buf_init(&err) == 0);
|
||||
fd = sp_curl_start(args,
|
||||
"https://api.example/bot123:tok\"en/send", hdrs, 1, &pid, &err);
|
||||
CHECK(fd >= 0);
|
||||
if (fd >= 0) {
|
||||
ssize_t n = read(fd, buf, sizeof(buf) - 1);
|
||||
|
||||
buf[n > 0 ? n : 0] = '\0';
|
||||
close(fd);
|
||||
(void)waitpid(pid, &st, 0);
|
||||
CHECK(strncmp(buf, "hello", 5) == 0);
|
||||
}
|
||||
CHECK(strstr(slurp(argsf), "geheim") == NULL);
|
||||
CHECK(strstr(slurp(argsf), "bot123") == NULL);
|
||||
CHECK(strstr(slurp(argsf), "-K") != NULL);
|
||||
CHECK(strstr(slurp(cfgf), "header = \"Authorization: Bearer "
|
||||
"sk-geheim-4\"") != NULL);
|
||||
/* a quote in the value is escaped, not the end of the string */
|
||||
CHECK(strstr(slurp(cfgf), "url = \"https://api.example/bot123:tok\\\"en"
|
||||
"/send\"") != NULL);
|
||||
|
||||
CHECK(sp_buf_init(&cfg) == 0);
|
||||
CHECK(sp_curl_config_line(&cfg, "k", "a\\b\nc") == 0);
|
||||
CHECK(strcmp(cfg.p, "k = \"a\\\\b\\nc\"\n") == 0);
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_free(&err);
|
||||
setenv("PATH", oldpath != NULL ? oldpath : "/usr/bin:/bin", 1);
|
||||
}
|
||||
|
||||
/* ---- MCP server: loopback or a token, and the token is checked ---- */
|
||||
static int
|
||||
mcp_exchange(int port, const char *send_text, char *reply, size_t cap)
|
||||
{
|
||||
struct sockaddr_in a;
|
||||
struct timeval tv = { 5, 0 };
|
||||
int s, tries;
|
||||
size_t used = 0;
|
||||
|
||||
for (tries = 0; tries < 50; tries++) {
|
||||
s = socket(AF_INET, SOCK_STREAM, 0);
|
||||
memset(&a, 0, sizeof(a));
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_port = htons((unsigned short)port);
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
if (connect(s, (struct sockaddr *)&a, sizeof(a)) == 0)
|
||||
break;
|
||||
close(s);
|
||||
s = -1;
|
||||
{
|
||||
struct timespec ts = { 0, 100 * 1000 * 1000 };
|
||||
|
||||
(void)nanosleep(&ts, NULL);
|
||||
}
|
||||
}
|
||||
if (s < 0)
|
||||
return -1;
|
||||
(void)setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||
(void)write(s, send_text, strlen(send_text));
|
||||
(void)shutdown(s, SHUT_WR);
|
||||
for (;;) {
|
||||
ssize_t n = read(s, reply + used, cap - used - 1);
|
||||
|
||||
if (n <= 0)
|
||||
break;
|
||||
used += (size_t)n;
|
||||
}
|
||||
reply[used] = '\0';
|
||||
close(s);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
test_mcp(void)
|
||||
{
|
||||
struct sp_registry r;
|
||||
struct sp_buf err;
|
||||
char reply[8192];
|
||||
int port = 20000 + (int)(getpid() % 20000);
|
||||
pid_t srv;
|
||||
|
||||
memset(&r, 0, sizeof(r));
|
||||
CHECK(sp_builtin_register(&r) == 0);
|
||||
CHECK(sp_buf_init(&err) == 0);
|
||||
|
||||
unsetenv("SPLINTER_MCP_TOKEN");
|
||||
CHECK(sp_mcp_serve(&r, "0.0.0.0", port, 0, &err) != 0);
|
||||
CHECK(strstr(err.p, "SPLINTER_MCP_TOKEN") != NULL);
|
||||
|
||||
setenv("SPLINTER_MCP_TOKEN", "richtig", 1);
|
||||
srv = fork();
|
||||
if (srv == 0) {
|
||||
struct sp_buf e;
|
||||
|
||||
(void)sp_buf_init(&e);
|
||||
_exit(sp_mcp_serve(&r, "127.0.0.1", port, 0, &e) == 0 ? 0 : 1);
|
||||
}
|
||||
CHECK(srv > 0);
|
||||
|
||||
CHECK(mcp_exchange(port, "{\"jsonrpc\":\"2.0\",\"id\":1,"
|
||||
"\"method\":\"tools/list\"}\n", reply, sizeof(reply)) == 0);
|
||||
CHECK(strstr(reply, "authentication required") != NULL);
|
||||
CHECK(strstr(reply, "\"read\"") == NULL);
|
||||
|
||||
CHECK(mcp_exchange(port, "AUTH falsch\n{\"jsonrpc\":\"2.0\",\"id\":1,"
|
||||
"\"method\":\"tools/list\"}\n", reply, sizeof(reply)) == 0);
|
||||
CHECK(strstr(reply, "authentication required") != NULL);
|
||||
|
||||
CHECK(mcp_exchange(port, "AUTH richtig\n{\"jsonrpc\":\"2.0\",\"id\":1,"
|
||||
"\"method\":\"tools/list\"}\n", reply, sizeof(reply)) == 0);
|
||||
CHECK(strstr(reply, "\"read\"") != NULL);
|
||||
|
||||
if (srv > 0) {
|
||||
(void)kill(srv, SIGTERM);
|
||||
(void)waitpid(srv, NULL, 0);
|
||||
}
|
||||
unsetenv("SPLINTER_MCP_TOKEN");
|
||||
sp_buf_free(&err);
|
||||
sp_registry_free(&r);
|
||||
}
|
||||
|
||||
/* ---- tasks: task_kill stops the task, and only the task ---- */
|
||||
static void
|
||||
test_tasks(void)
|
||||
{
|
||||
struct sp_registry r;
|
||||
struct sp_agent ag;
|
||||
struct sp_host *host;
|
||||
struct sp_buf err, out;
|
||||
int i;
|
||||
|
||||
memset(&r, 0, sizeof(r));
|
||||
memset(&ag, 0, sizeof(ag));
|
||||
CHECK(sp_buf_init(&err) == 0);
|
||||
CHECK(sp_buf_init(&out) == 0);
|
||||
host = sp_host_new(&r, &ag, NULL);
|
||||
CHECK(host != NULL);
|
||||
if (host == NULL)
|
||||
return;
|
||||
CHECK(sp_plugin_load(host, "plugins/tasks/tasks.so", &err) == 0);
|
||||
|
||||
run_tool(&r, "task_start", "{\"command\":\"sleep 30\",\"label\":\"s\"}",
|
||||
&out);
|
||||
CHECK(strstr(out.p, "1") != NULL);
|
||||
for (i = 0; i < 20; i++) { /* let the thread fork */
|
||||
struct timespec ts = { 0, 50 * 1000 * 1000 };
|
||||
|
||||
(void)nanosleep(&ts, NULL);
|
||||
}
|
||||
/*
|
||||
* The old code sent SIGTERM to splinter's own process group here, so
|
||||
* this test would have died on the next line. An integer id, as the
|
||||
* schema declares it.
|
||||
*/
|
||||
run_tool(&r, "task_kill", "{\"id\":1}", &out);
|
||||
CHECK(strstr(out.p, "kill signal sent") != NULL);
|
||||
for (i = 0; i < 40; i++) {
|
||||
struct timespec ts = { 0, 50 * 1000 * 1000 };
|
||||
|
||||
run_tool(&r, "task_list", "{}", &out);
|
||||
if (strstr(out.p, "exit") != NULL || strstr(out.p, "fertig") != NULL)
|
||||
break;
|
||||
(void)nanosleep(&ts, NULL);
|
||||
}
|
||||
run_tool(&r, "task_kill", "{\"id\":99}", &out);
|
||||
CHECK(strstr(out.p, "no such task") != NULL);
|
||||
|
||||
sp_host_free(host);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&err);
|
||||
}
|
||||
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
char cmd[700];
|
||||
|
||||
/* a background child that dies must not take the test with it */
|
||||
(void)signal(SIGPIPE, SIG_IGN);
|
||||
if (mkdtemp(dir) == NULL) {
|
||||
perror("mkdtemp");
|
||||
return 1;
|
||||
}
|
||||
test_run();
|
||||
test_curl();
|
||||
test_mcp();
|
||||
test_tasks();
|
||||
snprintf(cmd, sizeof(cmd), "rm -rf '%s'", dir);
|
||||
(void)system(cmd);
|
||||
if (failures == 0)
|
||||
printf("test_secrets: ok\n");
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+14
-12
@@ -14,7 +14,7 @@
|
||||
# sees "ok <id>" or "no <id>". Two pollers on one chat would eat each other's
|
||||
# updates - that is why this script only writes.
|
||||
#
|
||||
# SPLINTER_TELEGRAM_TOKEN bot token (else read from splinter.conf's key_env)
|
||||
# SPLINTER_TELEGRAM_TOKEN bot token (else ~/.splinter/telegram.token)
|
||||
# SPLINTER_ACK_CHAT chat id of the parent
|
||||
#
|
||||
set -u
|
||||
@@ -22,15 +22,10 @@ set -u
|
||||
msg="${1:-Zustimmung angefordert}"
|
||||
|
||||
token="${SPLINTER_TELEGRAM_TOKEN:-}"
|
||||
if [ -z "$token" ]; then
|
||||
conf="${HOME}/.splinter/splinter.conf"
|
||||
if [ -r "$conf" ]; then
|
||||
key_env=$(sed -n 's/^[[:space:]]*key_env[[:space:]]*=[[:space:]]*//p' "$conf" \
|
||||
| head -1)
|
||||
if [ -n "${key_env:-}" ]; then
|
||||
eval "token=\${$key_env:-}"
|
||||
fi
|
||||
fi
|
||||
# the same file the gateway reads; the old key_env lookup matched a line that
|
||||
# splinter.conf does not allow, and fed it to eval
|
||||
if [ -z "$token" ] && [ -r "${HOME}/.splinter/telegram.token" ]; then
|
||||
token=$(head -n 1 "${HOME}/.splinter/telegram.token")
|
||||
fi
|
||||
|
||||
chat="${SPLINTER_ACK_CHAT:-}"
|
||||
@@ -44,10 +39,17 @@ if [ -z "$token" ]; then
|
||||
fi
|
||||
|
||||
# The message carries the id, so the reply can name it.
|
||||
out=$(curl -sS --max-time 15 \
|
||||
# The URL carries the token, and argv is readable by every user (ps -ef): curl
|
||||
# gets the URL as a config on stdin instead. A token has no quotes or
|
||||
# backslashes; one that does is refused rather than escaped.
|
||||
case "$token" in
|
||||
*'"'*|*\\*) echo "tg-ask: the token contains a quote or backslash" >&2; exit 1 ;;
|
||||
esac
|
||||
out=$(printf 'url = "https://api.telegram.org/bot%s/sendMessage"\n' "$token" |
|
||||
curl -sS --max-time 15 \
|
||||
--data-urlencode "chat_id=${chat}" \
|
||||
--data-urlencode "text=${msg}" \
|
||||
"https://api.telegram.org/bot${token}/sendMessage" 2>&1) || {
|
||||
-K - 2>&1) || {
|
||||
echo "tg-ask: curl failed: ${out}" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user