From e91870a2aee7dc6a87c8ac5e05892d0dd94529d8 Mon Sep 17 00:00:00 2001 From: Luis Date: Fri, 20 Nov 2026 10:47:36 -0500 Subject: [PATCH 01/53] feat: optional DNS-driven egress allowlist (separate compose file) Add egress-guard, an opt-in Linux-only sidecar that permits outbound connections from the ARTEX network only to the LLM endpoint, declared scope, and recon/package sources, while auto-allowing discovered subdomains of in-scope domains so asset discovery keeps working. Modes: monitor (default, log only) / enforce / off. Shipped as docker-compose.egress.yml; the main compose file is untouched, so it is fully opt-in. It needs NET_ADMIN and edits the host firewall (DOCKER-USER chain), documented as Linux-only in egress-guard/README.md. --- docker-compose.egress.yml | 42 ++++++++++ egress-guard/Dockerfile | 8 ++ egress-guard/README.md | 42 ++++++++++ egress-guard/entrypoint.sh | 115 +++++++++++++++++++++++++++ egress-guard/lists/base-domains.txt | 45 +++++++++++ egress-guard/lists/scope-cidrs.txt | 3 + egress-guard/lists/scope-domains.txt | 4 + egress-guard/logs/.gitignore | 2 + egress-guard/report.sh | 41 ++++++++++ 9 files changed, 302 insertions(+) create mode 100644 docker-compose.egress.yml create mode 100644 egress-guard/Dockerfile create mode 100644 egress-guard/README.md create mode 100755 egress-guard/entrypoint.sh create mode 100644 egress-guard/lists/base-domains.txt create mode 100644 egress-guard/lists/scope-cidrs.txt create mode 100644 egress-guard/lists/scope-domains.txt create mode 100644 egress-guard/logs/.gitignore create mode 100755 egress-guard/report.sh diff --git a/docker-compose.egress.yml b/docker-compose.egress.yml new file mode 100644 index 00000000..060c84b2 --- /dev/null +++ b/docker-compose.egress.yml @@ -0,0 +1,42 @@ +# Optional, Linux-only egress allowlist for the ARTEX network. See egress-guard/README.md. +# Enable by adding this overlay to every compose command: +# docker compose -f docker-compose.yml -f docker-compose.egress.yml up -d +# It needs NET_ADMIN and edits the host firewall (DOCKER-USER chain). Without +# this overlay the main compose file is unchanged, so this is fully opt-in. +services: + artex: + # Route DNS through egress-guard's dnsmasq (on the network gateway), which + # feeds the allowlist. depends_on merges with the base file's postgres entry. + dns: + - 172.31.250.1 + depends_on: + egress-guard: + condition: service_started + + egress-guard: + build: + context: ./egress-guard + image: artex-egress-guard:local + network_mode: host + cap_add: + - NET_ADMIN + - NET_RAW + environment: + # monitor (default, log only) | enforce (block) | off (DNS only) + EGRESS_MODE: ${EGRESS_MODE:-monitor} + ARTEX_SUBNET: 172.31.250.0/24 + ARTEX_GATEWAY: 172.31.250.1 + UPSTREAM_DNS: ${EGRESS_UPSTREAM_DNS:-} + volumes: + - ./egress-guard/lists:/etc/egress-guard:ro + - ./egress-guard/logs:/var/log/egress + restart: unless-stopped + +# Give the ARTEX network a fixed subnet/gateway so dnsmasq and the firewall +# rules have a known address to bind and match. +networks: + default: + ipam: + config: + - subnet: 172.31.250.0/24 + gateway: 172.31.250.1 diff --git a/egress-guard/Dockerfile b/egress-guard/Dockerfile new file mode 100644 index 00000000..b6616558 --- /dev/null +++ b/egress-guard/Dockerfile @@ -0,0 +1,8 @@ +# egress-guard: DNS-driven egress allowlist for the ARTEX network. +# Runs in the host network namespace (network_mode: host) with NET_ADMIN to manage +# an ipset + iptables rules in the DOCKER-USER chain. See README.md. +FROM alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc +RUN apk add --no-cache dnsmasq iptables ipset bash tini +COPY entrypoint.sh /usr/local/bin/egress-guard +RUN chmod +x /usr/local/bin/egress-guard +ENTRYPOINT ["/sbin/tini", "--", "/usr/local/bin/egress-guard"] diff --git a/egress-guard/README.md b/egress-guard/README.md new file mode 100644 index 00000000..b469289b --- /dev/null +++ b/egress-guard/README.md @@ -0,0 +1,42 @@ +# egress-guard + +DNS-driven egress allowlist for the ARTEX container. It blocks data from leaving +to arbitrary hosts (e.g. a malicious PoC sending the keys to an attacker) without +breaking asset discovery: any subdomain of an in-scope domain is allowed +automatically the moment it resolves. + +Opt-in and Linux-only. It is a separate compose file and needs `NET_ADMIN`; it +edits the host firewall, so read this before enabling it. + +## How it works +1. ARTEX uses `172.31.250.1` (this service's dnsmasq) as its DNS. DNS queries to + any other server (dnsx, bbot, `dig @8.8.8.8`) are redirected here. +2. Names matching a suffix in `lists/base-domains.txt` or `lists/scope-domains.txt` + have their resolved IPs added to the `artex_allow` ipset (they expire 6 h after + the last query). +3. In the `DOCKER-USER` chain, new outbound connections from the ARTEX network are + allowed only if the destination is in `artex_allow` or in `lists/scope-cidrs.txt`. + Everything else is logged (`ARTEX-EGRESS-*` in the kernel log) and, in + `enforce`, rejected. + +## Modes (`EGRESS_MODE` in `.env`) +| Mode | Effect | +|---|---| +| `monitor` (default) | only logs what would be blocked | +| `enforce` | blocks | +| `off` | no rules; DNS only | + +## Operation +- New engagement: edit `lists/scope-domains.txt` and `lists/scope-cidrs.txt`, then + `docker compose -f docker-compose.yml -f docker-compose.egress.yml restart egress-guard`. +- Calibrate: `sudo egress-guard/report.sh` (or pass `"48 hours ago"`). Lists flagged + connections and resolved names outside the allowlist. +- Turn blocking on: set `EGRESS_MODE=enforce` in `.env` and bring the service up again. +- Stopping the service removes the rules. If dnsmasq dies on its own, the rules stay + (fail-closed). + +## Known gaps +- Exfiltration through an allowed destination (a GitHub gist, OAST servers, an + in-scope host the attacker controls). +- Data hidden in DNS queries (slow; visible in `logs/dnsmasq.log`). +- CDN-shared IPs: allowing one name allows the IP for other sites on the same IP. diff --git a/egress-guard/entrypoint.sh b/egress-guard/entrypoint.sh new file mode 100755 index 00000000..3c3afdbe --- /dev/null +++ b/egress-guard/entrypoint.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# egress-guard entrypoint. +# EGRESS_MODE monitor (default: log only) | enforce (log + reject) | off (no rules, DNS only) +# ARTEX_SUBNET the ARTEX docker network (must match docker-compose.yml) +# ARTEX_GATEWAY bridge gateway IP; dnsmasq listens here +# UPSTREAM_DNS comma-separated upstream resolvers; empty = host /etc/resolv.conf +# IPSET_TIMEOUT seconds a resolved IP stays allowed after its last lookup (default 21600) +set -euo pipefail + +MODE="${EGRESS_MODE:-monitor}" +SUBNET="${ARTEX_SUBNET:?ARTEX_SUBNET required}" +GW="${ARTEX_GATEWAY:?ARTEX_GATEWAY required}" +TIMEOUT="${IPSET_TIMEOUT:-21600}" +LISTS=/etc/egress-guard +LOGDIR=/var/log/egress +CONF=/run/egress-guard/dnsmasq.conf +IPT=iptables +command -v iptables-nft >/dev/null 2>&1 && IPT=iptables-nft +[ -n "${IPTABLES_BIN:-}" ] && IPT="$IPTABLES_BIN" + +log() { echo "[egress-guard] $*"; } + +case "$MODE" in monitor|enforce|off) ;; *) log "invalid EGRESS_MODE=$MODE"; exit 1;; esac + +# Read a list file: strip comments/blank lines, lowercase, drop leading dots/wildcards. +read_list() { [ -f "$1" ] || return 0; sed -e 's/#.*//' -e 's/[[:space:]]//g' "$1" | tr 'A-Z' 'a-z' | sed -e 's/^\*\.//' -e 's/^\.//' | grep -v '^$' || true; } + +cleanup_rules() { + # filter table: detach and delete our chain + while $IPT -C DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS 2>/dev/null; do + $IPT -D DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS + done + $IPT -F ARTEX-EGRESS 2>/dev/null || true + $IPT -X ARTEX-EGRESS 2>/dev/null || true + # nat table: DNS redirect + while $IPT -t nat -C PREROUTING -s "$SUBNET" -j ARTEX-DNS 2>/dev/null; do + $IPT -t nat -D PREROUTING -s "$SUBNET" -j ARTEX-DNS + done + $IPT -t nat -F ARTEX-DNS 2>/dev/null || true + $IPT -t nat -X ARTEX-DNS 2>/dev/null || true +} + +apply_rules() { + ipset create artex_allow hash:ip timeout "$TIMEOUT" -exist + ipset create artex_scope hash:net -exist + ipset flush artex_scope + local n=0 + while read -r cidr; do ipset add artex_scope "$cidr" -exist && n=$((n+1)); done < <(read_list "$LISTS/scope-cidrs.txt") + log "scope CIDRs loaded: $n" + + [ "$MODE" = off ] && { log "mode off: no firewall rules"; return; } + + # DOCKER-USER exists whenever dockerd runs; create it only for standalone tests. + if ! $IPT -L DOCKER-USER -n >/dev/null 2>&1; then + $IPT -N DOCKER-USER; $IPT -I FORWARD -j DOCKER-USER + fi + + # Redirect every DNS query leaving the ARTEX network to dnsmasq, so tools with + # hard-coded resolvers (dnsx, bbot, dig @8.8.8.8) still populate the allowlist. + $IPT -t nat -N ARTEX-DNS + $IPT -t nat -A ARTEX-DNS -d "$GW" -j RETURN + $IPT -t nat -A ARTEX-DNS -p udp --dport 53 -j DNAT --to-destination "$GW:53" + $IPT -t nat -A ARTEX-DNS -p tcp --dport 53 -j DNAT --to-destination "$GW:53" + $IPT -t nat -I PREROUTING 1 -s "$SUBNET" -j ARTEX-DNS + + $IPT -N ARTEX-EGRESS + $IPT -A ARTEX-EGRESS -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN + $IPT -A ARTEX-EGRESS -m set --match-set artex_allow dst -j RETURN + $IPT -A ARTEX-EGRESS -m set --match-set artex_scope dst -j RETURN + $IPT -A ARTEX-EGRESS -m limit --limit 30/min --limit-burst 60 -j LOG --log-prefix "ARTEX-EGRESS-$MODE " --log-level 4 + if [ "$MODE" = enforce ]; then + $IPT -A ARTEX-EGRESS -p tcp -j REJECT --reject-with tcp-reset + $IPT -A ARTEX-EGRESS -j REJECT --reject-with icmp-port-unreachable + else + $IPT -A ARTEX-EGRESS -j RETURN + fi + $IPT -I DOCKER-USER 1 -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS + log "firewall rules applied (mode=$MODE, subnet=$SUBNET)" +} + +write_dnsmasq_conf() { + mkdir -p "$(dirname "$CONF")" "$LOGDIR" + { + echo "listen-address=$GW" + echo "bind-dynamic" + echo "except-interface=lo" + echo "no-hosts" + echo "cache-size=10000" + echo "log-queries=extra" + echo "log-facility=$LOGDIR/dnsmasq.log" + if [ -n "${UPSTREAM_DNS:-}" ]; then + echo "no-resolv" + IFS=',' read -ra ups <<< "$UPSTREAM_DNS" + for u in "${ups[@]}"; do echo "server=$u"; done + fi + } > "$CONF" + local n=0 + while read -r d; do echo "ipset=/$d/artex_allow" >> "$CONF"; n=$((n+1)); done < <(read_list "$LISTS/base-domains.txt"; read_list "$LISTS/scope-domains.txt") + log "allowed domain suffixes: $n" +} + +on_term() { log "stopping"; [ -n "${DNSMASQ_PID:-}" ] && kill "$DNSMASQ_PID" 2>/dev/null || true; cleanup_rules; exit 0; } +trap on_term TERM INT + +cleanup_rules +apply_rules +write_dnsmasq_conf +dnsmasq --test -C "$CONF" +dnsmasq -k -C "$CONF" & +DNSMASQ_PID=$! +log "dnsmasq listening on $GW:53 (pid $DNSMASQ_PID)" +wait "$DNSMASQ_PID" +# dnsmasq died unexpectedly: leave rules in place (fail closed) and let docker restart us. +log "dnsmasq exited; rules left in place" +exit 1 diff --git a/egress-guard/lists/base-domains.txt b/egress-guard/lists/base-domains.txt new file mode 100644 index 00000000..ac91398b --- /dev/null +++ b/egress-guard/lists/base-domains.txt @@ -0,0 +1,45 @@ +# Domain suffixes always allowed for the ARTEX container (a suffix covers all subdomains). +# Resolved IPs are added to the allowlist automatically. Reload: docker compose restart egress-guard + +# --- LLM providers (keep only the one you use) --- +api.deepseek.com +api.anthropic.com +api.openai.com + +# --- Passive recon sources seen in past runs --- +crt.sh +rapiddns.io +api.certspotter.com +api.hackertarget.com +api.threatminer.org +web.archive.org +archive.org +otx.alienvault.com +urlscan.io +services.nvd.nist.gov +api.osv.dev + +# --- Public code / advisories (downloads are still gated by the [hardening] approval rules) --- +github.com +api.github.com +raw.githubusercontent.com +objects.githubusercontent.com +release-assets.githubusercontent.com +codeload.github.com +gist.githubusercontent.com + +# --- Package registries (installs are gated by the approval rules) --- +pypi.org +files.pythonhosted.org +registry.npmjs.org +proxy.golang.org +deb.debian.org + +# --- Nuclei / Interactsh out-of-band testing (OAST). Remove if you do not use OAST checks: +# these servers accept arbitrary data, so they are also a possible exfiltration channel. +oast.pro +oast.live +oast.site +oast.online +oast.fun +oast.me diff --git a/egress-guard/lists/scope-cidrs.txt b/egress-guard/lists/scope-cidrs.txt new file mode 100644 index 00000000..c4628dec --- /dev/null +++ b/egress-guard/lists/scope-cidrs.txt @@ -0,0 +1,3 @@ +# Engagement scope: target IPs / CIDRs reached directly (no DNS). One per line. +# docker compose restart egress-guard +# 203.0.113.0/24 diff --git a/egress-guard/lists/scope-domains.txt b/egress-guard/lists/scope-domains.txt new file mode 100644 index 00000000..fc8257f9 --- /dev/null +++ b/egress-guard/lists/scope-domains.txt @@ -0,0 +1,4 @@ +# Engagement scope: target domain suffixes (one per line). Every subdomain is allowed, +# so newly discovered assets keep working. Edit per engagement, then: +# docker compose restart egress-guard +# example.com diff --git a/egress-guard/logs/.gitignore b/egress-guard/logs/.gitignore new file mode 100644 index 00000000..d6b7ef32 --- /dev/null +++ b/egress-guard/logs/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/egress-guard/report.sh b/egress-guard/report.sh new file mode 100755 index 00000000..0234dc9f --- /dev/null +++ b/egress-guard/report.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Calibration report for egress-guard. +# 1) destinations the firewall flagged (would be / were blocked), mapped back to DNS names +# 2) names the ARTEX container resolved that are NOT covered by the allowlist +# Usage: egress-guard/report.sh [since] (default since: "24 hours ago"; journalctl syntax) +# Reading the kernel log needs the adm/systemd-journal group or sudo. +set -euo pipefail +cd "$(dirname "$0")" +SINCE="${1:-24 hours ago}" +LOG=logs/dnsmasq.log + +suffixes() { sed -e 's/#.*//' -e 's/[[:space:]]//g' lists/base-domains.txt lists/scope-domains.txt | tr 'A-Z' 'a-z' | sed -e 's/^\*\.//' -e 's/^\.//' | grep -v '^$' || true; } + +declare -A ip2name +if [ -f "$LOG" ]; then + while read -r name ip; do ip2name[$ip]="$name"; done < <(awk '/ reply / && / is [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ {for(i=1;i<=NF;i++) if($i=="reply"){print $(i+1), $NF}}' "$LOG") +fi + +echo "=== 1) Conexões sinalizadas pelo firewall (desde: $SINCE) ===" +if journalctl -k --since "$SINCE" -q --no-pager -g 'ARTEX-EGRESS-' >/dev/null 2>&1; then + journalctl -k --since "$SINCE" -q --no-pager -g 'ARTEX-EGRESS-' \ + | grep -oE 'ARTEX-EGRESS-[a-z]+ .*DST=[0-9.]+.*PROTO=[A-Z]+( .*DPT=[0-9]+)?' \ + | sed -E 's/^ARTEX-EGRESS-([a-z]+) .*DST=([0-9.]+).*PROTO=([A-Z]+)( .*DPT=([0-9]+))?.*/\1 \2 \3 \5/' \ + | sort | uniq -c | sort -rn \ + | while read -r cnt mode ip proto port; do printf '%6s %-8s %-16s %-5s %-6s %s\n' "$cnt" "$mode" "$ip" "$proto" "${port:--}" "${ip2name[$ip]:-(sem DNS: IP direto)}"; done +else + echo "(sem acesso ao log do kernel: rode com sudo ou adicione o usuário ao grupo adm)" +fi + +echo +echo "=== 2) Nomes resolvidos fora da allowlist (candidatos a liberar ou suspeitos) ===" +if [ -f "$LOG" ]; then + mapfile -t sfx < <(suffixes) + awk '/ query\[(A|AAAA)\] / {for(i=1;i<=NF;i++) if($i ~ /^query\[/){print tolower($(i+1))}}' "$LOG" | sort | uniq -c | sort -rn \ + | while read -r cnt name; do + ok=0; for s in "${sfx[@]}"; do [[ "$name" == "$s" || "$name" == *".$s" ]] && { ok=1; break; }; done + [ $ok -eq 0 ] && printf '%6s %s\n' "$cnt" "$name" + done +else + echo "(sem $LOG ainda)" +fi From 91a6a86332d8e30780e756864181c5a94bb3d8bc Mon Sep 17 00:00:00 2001 From: Luis Date: Sat, 21 Nov 2026 12:28:46 -0500 Subject: [PATCH 02/53] fix(egress): address review on the allowlist enforcement - Flush artex_allow at startup: a host removed from the lists no longer stays reachable until the ipset timeout. - Fail-closed setup (enforce): install a blanket subnet-egress deny before the allowlist is built and remove it only after setup completes; an ERR trap (set -E) leaves it in place and exits non-zero on failure, with a FATAL log. - IPv6: document the gap, warn when unfiltered, and add an ip6tables deny when ARTEX_SUBNET6 is set. - Gateway/host-proxy bypass: document it (container->gateway goes through host INPUT, not DOCKER-USER) and add an opt-in EGRESS_FILTER_GATEWAY INPUT filter. - README: make clear the allowlist only acts in enforce; monitor is observe-only. - Add egress-guard/selftest.sh and confirm in a real container (own netns): flush, rules, enforce REJECT, DNS redirect, and fail-closed all pass (10/10). --- egress-guard/README.md | 24 +++++++-- egress-guard/entrypoint.sh | 99 +++++++++++++++++++++++++++++++++----- egress-guard/selftest.sh | 53 ++++++++++++++++++++ 3 files changed, 162 insertions(+), 14 deletions(-) create mode 100755 egress-guard/selftest.sh diff --git a/egress-guard/README.md b/egress-guard/README.md index b469289b..accfee08 100644 --- a/egress-guard/README.md +++ b/egress-guard/README.md @@ -22,9 +22,16 @@ edits the host firewall, so read this before enabling it. ## Modes (`EGRESS_MODE` in `.env`) | Mode | Effect | |---|---| -| `monitor` (default) | only logs what would be blocked | -| `enforce` | blocks | -| `off` | no rules; DNS only | +| `monitor` (default) | **observe only** — logs what would be blocked, blocks nothing | +| `enforce` | the allowlist actually blocks | +| `off` | no firewall rules; DNS redirect only | + +**The allowlist only restricts egress in `enforce`.** The default `monitor` is a +dry run for calibration — it protects nothing. Set `EGRESS_MODE=enforce` (and +bring the service up again) for the guard to have any effect. In `enforce`, +setup is **fail-closed**: a blanket deny is installed before the allowlist is +built, so if setup fails the ARTEX container loses outbound connectivity (except +DNS) until the guard restarts cleanly. ## Operation - New engagement: edit `lists/scope-domains.txt` and `lists/scope-cidrs.txt`, then @@ -36,6 +43,17 @@ edits the host firewall, so read this before enabling it. (fail-closed). ## Known gaps +- **IPv6 is not filtered.** The allowlist is IPv4-only (ipset `hash:ip`/`hash:net`). + Keep the ARTEX network IPv4-only (do not set `enable_ipv6` on it) — then the + container has no IPv6 address and the gap is latent. If you do enable IPv6, set + `ARTEX_SUBNET6` so `enforce` installs an `ip6tables` deny for it; the guard logs + a warning when IPv6 is left unfiltered. +- **Traffic to the host/gateway bypasses the filter.** Container→gateway traffic + goes through the host `INPUT` chain, not `DOCKER-USER` (`FORWARD`), so a proxy + bound on the gateway IP is reachable. Don't run a forward proxy on the gateway, + or set `EGRESS_FILTER_GATEWAY=1` to have `enforce` add an `INPUT` rule that drops + everything from the subnet to the gateway except DNS (off by default — it edits + the host `INPUT` chain). - Exfiltration through an allowed destination (a GitHub gist, OAST servers, an in-scope host the attacker controls). - Data hidden in DNS queries (slow; visible in `logs/dnsmasq.log`). diff --git a/egress-guard/entrypoint.sh b/egress-guard/entrypoint.sh index 3c3afdbe..7e41579e 100755 --- a/egress-guard/entrypoint.sh +++ b/egress-guard/entrypoint.sh @@ -1,15 +1,27 @@ #!/usr/bin/env bash # egress-guard entrypoint. -# EGRESS_MODE monitor (default: log only) | enforce (log + reject) | off (no rules, DNS only) -# ARTEX_SUBNET the ARTEX docker network (must match docker-compose.yml) -# ARTEX_GATEWAY bridge gateway IP; dnsmasq listens here -# UPSTREAM_DNS comma-separated upstream resolvers; empty = host /etc/resolv.conf -# IPSET_TIMEOUT seconds a resolved IP stays allowed after its last lookup (default 21600) -set -euo pipefail +# EGRESS_MODE monitor (default: log only) | enforce (log + reject) | off (DNS only) +# ARTEX_SUBNET the ARTEX docker network (must match docker-compose.yml) +# ARTEX_GATEWAY bridge gateway IP; dnsmasq listens here +# ARTEX_SUBNET6 optional IPv6 subnet; when set, enforce also drops its egress +# EGRESS_FILTER_GATEWAY 1 = in enforce, also drop non-DNS traffic from the subnet to the +# host/gateway (closes the host-proxy bypass). Off by default because +# it edits the host INPUT chain. See README "Known gaps". +# UPSTREAM_DNS comma-separated upstream resolvers; empty = host /etc/resolv.conf +# IPSET_TIMEOUT seconds a resolved IP stays allowed after its last lookup (default 21600) +# +# Fail-closed (enforce): a blanket deny for the subnet's egress is installed BEFORE the allowlist +# is built and removed only after setup completes. If any setup step fails, the ERR trap leaves +# that deny in place and exits non-zero, so Docker restarts the guard while traffic stays blocked. +# The operator then sees the ARTEX container lose outbound connectivity (except DNS) until the +# guard comes up cleanly. In monitor/off mode a setup failure is non-fatal by design (log only). +set -Eeuo pipefail # -E so the ERR trap fires for failures inside functions (apply_rules) MODE="${EGRESS_MODE:-monitor}" SUBNET="${ARTEX_SUBNET:?ARTEX_SUBNET required}" GW="${ARTEX_GATEWAY:?ARTEX_GATEWAY required}" +SUBNET6="${ARTEX_SUBNET6:-}" +FILTER_GW="${EGRESS_FILTER_GATEWAY:-0}" TIMEOUT="${IPSET_TIMEOUT:-21600}" LISTS=/etc/egress-guard LOGDIR=/var/log/egress @@ -17,6 +29,11 @@ CONF=/run/egress-guard/dnsmasq.conf IPT=iptables command -v iptables-nft >/dev/null 2>&1 && IPT=iptables-nft [ -n "${IPTABLES_BIN:-}" ] && IPT="$IPTABLES_BIN" +IP6T=ip6tables +command -v ip6tables-nft >/dev/null 2>&1 && IP6T=ip6tables-nft +[ -n "${IP6TABLES_BIN:-}" ] && IP6T="$IP6TABLES_BIN" + +BOOT_CMT="artex-egress-bootstrap-deny" log() { echo "[egress-guard] $*"; } @@ -25,13 +42,54 @@ case "$MODE" in monitor|enforce|off) ;; *) log "invalid EGRESS_MODE=$MODE"; exit # Read a list file: strip comments/blank lines, lowercase, drop leading dots/wildcards. read_list() { [ -f "$1" ] || return 0; sed -e 's/#.*//' -e 's/[[:space:]]//g' "$1" | tr 'A-Z' 'a-z' | sed -e 's/^\*\.//' -e 's/^\.//' | grep -v '^$' || true; } +ensure_docker_user() { + # DOCKER-USER exists whenever dockerd runs; create it only for standalone tests. + $IPT -L DOCKER-USER -n >/dev/null 2>&1 || { $IPT -N DOCKER-USER; $IPT -I FORWARD -j DOCKER-USER; } + if [ -n "$SUBNET6" ] && command -v "$IP6T" >/dev/null 2>&1; then + $IP6T -L DOCKER-USER -n >/dev/null 2>&1 || { $IP6T -N DOCKER-USER; $IP6T -I FORWARD -j DOCKER-USER; } + fi +} + +bootstrap_deny() { + # enforce only: block the subnet's egress up-front so a partial setup fails closed. + [ "$MODE" = enforce ] || return 0 + $IPT -I DOCKER-USER 1 -s "$SUBNET" ! -d "$SUBNET" -m comment --comment "$BOOT_CMT" -j DROP + if [ -n "$SUBNET6" ] && command -v "$IP6T" >/dev/null 2>&1; then + $IP6T -I DOCKER-USER 1 -s "$SUBNET6" -m comment --comment "$BOOT_CMT" -j DROP 2>/dev/null \ + || log "WARN: ip6tables unavailable; IPv6 egress NOT filtered" + elif command -v "$IP6T" >/dev/null 2>&1; then + log "WARN: ARTEX_SUBNET6 unset; IPv6 egress is NOT filtered (keep the ARTEX network IPv4-only)" + fi +} + +remove_bootstrap_deny() { + [ "$MODE" = enforce ] || return 0 + while $IPT -C DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -m comment --comment "$BOOT_CMT" -j DROP 2>/dev/null; do + $IPT -D DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -m comment --comment "$BOOT_CMT" -j DROP + done + [ -n "$SUBNET6" ] && command -v "$IP6T" >/dev/null 2>&1 && \ + while $IP6T -C DOCKER-USER -s "$SUBNET6" -m comment --comment "$BOOT_CMT" -j DROP 2>/dev/null; do + $IP6T -D DOCKER-USER -s "$SUBNET6" -m comment --comment "$BOOT_CMT" -j DROP + done + return 0 +} + cleanup_rules() { + # Leave any bootstrap deny untouched here: cleanup runs on stop (on_term), where removing it + # is correct, and on startup before setup, where re-adding happens in bootstrap_deny. + remove_bootstrap_deny # filter table: detach and delete our chain while $IPT -C DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS 2>/dev/null; do $IPT -D DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS done $IPT -F ARTEX-EGRESS 2>/dev/null || true $IPT -X ARTEX-EGRESS 2>/dev/null || true + # optional host INPUT filter for the gateway + while $IPT -C INPUT -s "$SUBNET" -d "$GW" -j ARTEX-EGRESS-HOST 2>/dev/null; do + $IPT -D INPUT -s "$SUBNET" -d "$GW" -j ARTEX-EGRESS-HOST + done + $IPT -F ARTEX-EGRESS-HOST 2>/dev/null || true + $IPT -X ARTEX-EGRESS-HOST 2>/dev/null || true # nat table: DNS redirect while $IPT -t nat -C PREROUTING -s "$SUBNET" -j ARTEX-DNS 2>/dev/null; do $IPT -t nat -D PREROUTING -s "$SUBNET" -j ARTEX-DNS @@ -42,6 +100,8 @@ cleanup_rules() { apply_rules() { ipset create artex_allow hash:ip timeout "$TIMEOUT" -exist + ipset flush artex_allow # drop IPs allowed in a previous run: a host removed from the + # lists must not stay reachable until the ipset timeout expires. ipset create artex_scope hash:net -exist ipset flush artex_scope local n=0 @@ -50,11 +110,6 @@ apply_rules() { [ "$MODE" = off ] && { log "mode off: no firewall rules"; return; } - # DOCKER-USER exists whenever dockerd runs; create it only for standalone tests. - if ! $IPT -L DOCKER-USER -n >/dev/null 2>&1; then - $IPT -N DOCKER-USER; $IPT -I FORWARD -j DOCKER-USER - fi - # Redirect every DNS query leaving the ARTEX network to dnsmasq, so tools with # hard-coded resolvers (dnsx, bbot, dig @8.8.8.8) still populate the allowlist. $IPT -t nat -N ARTEX-DNS @@ -75,6 +130,19 @@ apply_rules() { $IPT -A ARTEX-EGRESS -j RETURN fi $IPT -I DOCKER-USER 1 -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS + + # Optional: close the host-proxy bypass. Traffic from the container to the host/gateway goes + # through the host INPUT chain, not DOCKER-USER (FORWARD), so a proxy bound on the gateway is + # otherwise reachable. Off by default because it edits the host INPUT chain. + if [ "$MODE" = enforce ] && [ "$FILTER_GW" = 1 ]; then + $IPT -N ARTEX-EGRESS-HOST 2>/dev/null || $IPT -F ARTEX-EGRESS-HOST + $IPT -A ARTEX-EGRESS-HOST -p udp --dport 53 -j RETURN + $IPT -A ARTEX-EGRESS-HOST -p tcp --dport 53 -j RETURN + $IPT -A ARTEX-EGRESS-HOST -j REJECT --reject-with icmp-port-unreachable + $IPT -I INPUT 1 -s "$SUBNET" -d "$GW" -j ARTEX-EGRESS-HOST + log "gateway filter on: only DNS to $GW allowed from the subnet" + fi + log "firewall rules applied (mode=$MODE, subnet=$SUBNET)" } @@ -102,10 +170,19 @@ write_dnsmasq_conf() { on_term() { log "stopping"; [ -n "${DNSMASQ_PID:-}" ] && kill "$DNSMASQ_PID" 2>/dev/null || true; cleanup_rules; exit 0; } trap on_term TERM INT +# Setup is fail-closed in enforce: install the blanket deny first, and keep it if anything below +# throws. The ERR trap fires under `set -e` before the shell exits. +on_setup_err() { local rc=$?; log "FATAL: setup failed (rc=$rc); fail-closed deny left in place, exiting for restart"; exit "$rc"; } +trap on_setup_err ERR + cleanup_rules +ensure_docker_user +bootstrap_deny apply_rules +remove_bootstrap_deny write_dnsmasq_conf dnsmasq --test -C "$CONF" +trap - ERR # setup done; a later dnsmasq exit is handled below, not as a fatal setup error. dnsmasq -k -C "$CONF" & DNSMASQ_PID=$! log "dnsmasq listening on $GW:53 (pid $DNSMASQ_PID)" diff --git a/egress-guard/selftest.sh b/egress-guard/selftest.sh new file mode 100755 index 00000000..e766ce76 --- /dev/null +++ b/egress-guard/selftest.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# egress-guard self-test. Builds nothing; run it inside the image, in the container's +# OWN network namespace (NOT network_mode host), so it exercises the real ipset + iptables +# without touching the host firewall: +# +# docker build -t artex-egress-guard:local ./egress-guard +# docker run --rm --cap-add NET_ADMIN --cap-add NET_RAW \ +# -v "$PWD/egress-guard/selftest.sh:/selftest.sh:ro" \ +# --entrypoint bash artex-egress-guard:local /selftest.sh +# +# Checks: startup flush of a stale allow IP (#1), rules applied, enforce REJECT (#5), +# DNS redirect, and fail-closed on a setup error (#2: deny left in place, FATAL, exit 1). +set -u +IPT=iptables; command -v iptables-nft >/dev/null 2>&1 && IPT=iptables-nft +pass=0; fail=0 +ok(){ echo "PASS: $1"; pass=$((pass+1)); } +no(){ echo "FAIL: $1"; fail=$((fail+1)); } + +# dummy iface so dnsmasq can bind the gateway IP +ip link add dummy0 type dummy 2>/dev/null +ip addr add 10.123.0.1/24 dev dummy0 2>/dev/null +ip link set dummy0 up 2>/dev/null + +echo "######## TEST 1: happy path (enforce) ########" +# seed a STALE allowed IP to prove flush at startup +ipset create artex_allow hash:ip timeout 21600 -exist +ipset add artex_allow 203.0.113.99 -exist +export EGRESS_MODE=enforce ARTEX_SUBNET=10.123.0.0/24 ARTEX_GATEWAY=10.123.0.1 UPSTREAM_DNS=1.1.1.1 +/usr/local/bin/egress-guard >/tmp/g.log 2>&1 & +GP=$! +sleep 3 +if ipset list artex_allow 2>/dev/null | grep -q 203.0.113.99; then no "stale IP flushed at startup"; else ok "stale IP flushed at startup (#1)"; fi +$IPT -S DOCKER-USER 2>/dev/null | grep -q 'ARTEX-EGRESS' && ok "DOCKER-USER jumps to ARTEX-EGRESS" || no "DOCKER-USER jump present" +$IPT -S DOCKER-USER 2>/dev/null | grep -q 'bootstrap-deny' && no "bootstrap-deny removed after clean setup" || ok "bootstrap-deny removed after clean setup (#2)" +$IPT -S ARTEX-EGRESS 2>/dev/null | grep -q 'match-set artex_allow dst' && ok "allow ipset rule present" || no "allow ipset rule present" +$IPT -S ARTEX-EGRESS 2>/dev/null | grep -qi 'REJECT' && ok "enforce REJECT present (#5)" || no "enforce REJECT present" +$IPT -t nat -S ARTEX-DNS 2>/dev/null | grep -q 'DNAT' && ok "DNS redirect (DNAT) present" || no "DNS redirect present" +kill -TERM $GP 2>/dev/null; sleep 1 +$IPT -S ARTEX-EGRESS 2>/dev/null | grep -q . && no "chain removed on stop" || ok "chain removed on stop (cleanup)" + +echo "######## TEST 2: fail-closed (setup error after bootstrap) ########" +# invalid IPSET_TIMEOUT makes apply_rules fail right after bootstrap_deny is installed +export IPSET_TIMEOUT=notanumber +/usr/local/bin/egress-guard >/tmp/g2.log 2>&1 +rc=$? +[ "$rc" -ne 0 ] && ok "setup failure is fatal (exit $rc, #2 fail-closed)" || no "setup failure fatal" +$IPT -S DOCKER-USER 2>/dev/null | grep -q 'bootstrap-deny.*DROP' && ok "fail-closed DROP left in place (#2)" || no "fail-closed DROP present" +grep -q 'FATAL: setup failed' /tmp/g2.log && ok "operator sees FATAL message (#2 documented)" || no "FATAL message logged" +# cleanup +unset IPSET_TIMEOUT +$IPT -F DOCKER-USER 2>/dev/null; $IPT -X ARTEX-EGRESS 2>/dev/null +echo "=== guard log test1 ==="; cat /tmp/g.log; echo "=== guard log test2 ==="; cat /tmp/g2.log +echo "######## RESULT: pass=$pass fail=$fail ########" From 371ee1370bb33529e1efe0b492846ddc91335c42 Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:54:56 +0000 Subject: [PATCH 03/53] fix(server): do not return database errors from the skill endpoints Recent skill calls and missing-skill stats put pgx text in the HTTP body. The server now logs that error and returns a fixed message. --- CHANGELOG.md | 1 + server/server_mgmt.go | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5af6fb65..fa807d5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **Skill endpoints no longer return database driver text**: a failure loading skill usage or missing-skill stats is logged on the server and the client receives a fixed message. - **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450). ## [0.7.0] - 2026-11-21 diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 732f99a7..e1c550f2 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -1227,7 +1227,8 @@ func (s *Server) fsSkillUsage(w http.ResponseWriter, r *http.Request) { limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) calls, err := pg.RecentSkillCalls(name, limit) if err != nil { - writeErr(w, 500, err.Error()) + log.Printf("[skills] recent calls for %s: %v", name, err) + writeErr(w, 500, "failed to load skill usage") return } writeJSON(w, 200, map[string]any{"calls": calls}) @@ -1243,7 +1244,8 @@ func (s *Server) fsMissingSkills(w http.ResponseWriter, r *http.Request) { limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) missing, err := pg.MissingSkillStats(limit) if err != nil { - writeErr(w, 500, err.Error()) + log.Printf("[skills] missing skills: %v", err) + writeErr(w, 500, "failed to load missing skills") return } writeJSON(w, 200, map[string]any{"missing": missing}) From 7625473c045b179f5399ce107058d83e51626428 Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:55:30 +0000 Subject: [PATCH 04/53] fix(extension): bound in-flight capture requests Requests that never finish stayed in the debugger map with their full post body. The map now drops the oldest entry past 500, and a stored body is cut at the ingest limit. --- CHANGELOG.md | 1 + extension/background.js | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5af6fb65..9c6905e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a stored request body is cut at the same 256 KiB limit as ingest. - **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450). ## [0.7.0] - 2026-11-21 diff --git a/extension/background.js b/extension/background.js index f6d0312d..a3bcfc50 100644 --- a/extension/background.js +++ b/extension/background.js @@ -9,6 +9,7 @@ const FLUSH_AT = 10; // entries per batch const MAX_BODY = 256 * 1024; // matches the server-side ingest cap +const MAX_TRACKED = 500; // unfinished requests kept in memory const SKIP_MIME = ["image/", "font/", "audio/", "video/", "application/octet-stream"]; let session = { @@ -167,12 +168,18 @@ async function flush() { chrome.debugger.onEvent.addListener((source, method, params) => { if (!session.capturing || !source.tabId || source.tabId !== session.tabId) return; if (method === "Network.requestWillBeSent") { + let postData = params.request.postData || ""; + if (postData.length > MAX_BODY) postData = postData.slice(0, MAX_BODY); + if (!session.requests.has(params.requestId) && session.requests.size >= MAX_TRACKED) { + const oldest = session.requests.keys().next().value; + session.requests.delete(oldest); + } session.requests.set(params.requestId, { requestId: params.requestId, method: params.request.method, url: params.request.url, headers: params.request.headers, - postData: params.request.postData || "", + postData, }); } else if (method === "Network.responseReceived") { const info = session.requests.get(params.requestId); From 7ac5b629f8d10d4890f762be16c8dab8c14bf790 Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:13:03 +0000 Subject: [PATCH 05/53] fix(server): hide driver errors on the skill visibility endpoints Skill usage and missing-skill stats already returned a fixed message. Skill visibility and its toggle still sent err.Error() to the client. Those two now log the driver text and return a fixed message. A closed pool test covers all four handlers. --- CHANGELOG.md | 2 +- server/server_mgmt.go | 6 ++- server/skill_error_test.go | 84 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 3 deletions(-) create mode 100644 server/skill_error_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d4a63770..d066f7cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed -- **Skill endpoints no longer return database driver text**: a failure loading skill usage or missing-skill stats is logged on the server and the client receives a fixed message. +- **Skill endpoints no longer return database driver text**: a failure loading skill usage, missing-skill stats, or skill visibility is logged on the server and the client receives a fixed message. - **Live log subscribers can no longer crash the process**: a client disconnect closes its log channel. The sink now delivers a line while it still holds the subscriber lock, so that close cannot land in the middle of the send. - **Notification delivery ignores HTTP_PROXY**: the dial guard checks the address it connects to. An environment proxy made that address the proxy, so a link-local target could still be reached. Notification HTTP now connects directly. - **Captured traffic blobs are owner-only**: HTTP and raw-stream bodies spilled out of the database are written `0600`, and their bucket directory is `0700`. An existing blob is tightened when it is seen again. diff --git a/server/server_mgmt.go b/server/server_mgmt.go index e1c550f2..90c8ceb9 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -2031,7 +2031,8 @@ func (s *Server) pgSkillVisibility(w http.ResponseWriter, r *http.Request) { } agents, err := pg.SkillAgents(r.PathValue("name")) if err != nil { - writeErr(w, 500, err.Error()) + log.Printf("[skills] visibility for %s: %v", r.PathValue("name"), err) + writeErr(w, 500, "failed to load skill visibility") return } writeJSON(w, 200, map[string]any{"agents": idStrings(agents)}) @@ -2052,7 +2053,8 @@ func (s *Server) pgToggleSkillVisibility(w http.ResponseWriter, r *http.Request) return } if err := pg.ToggleSkillVisibility(body.AgentID, body.SkillName, body.Visible); err != nil { - writeErr(w, 500, err.Error()) + log.Printf("[skills] toggle visibility for %s: %v", body.SkillName, err) + writeErr(w, 500, "failed to update skill visibility") return } writeJSON(w, 200, map[string]any{"ok": true}) diff --git a/server/skill_error_test.go b/server/skill_error_test.go new file mode 100644 index 00000000..bc0161a7 --- /dev/null +++ b/server/skill_error_test.go @@ -0,0 +1,84 @@ +package server + +import ( + "database/sql" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func TestSkillEndpointsHideDriverErrors(t *testing.T) { + raw, err := sql.Open("pgx", "postgres://127.0.0.1:1/none?sslmode=disable") + if err != nil { + t.Fatal(err) + } + if err := raw.Close(); err != nil { + t.Fatal(err) + } + s := &Server{m: &Manager{pg: &db.DB{DB: raw}}} + + cases := []struct { + name string + req *http.Request + h http.HandlerFunc + want string + }{ + { + name: "usage", + req: skillErrReq(http.MethodGet, "/api/skills/recon/usage", "name", "recon", ""), + h: s.fsSkillUsage, + want: "failed to load skill usage", + }, + { + name: "missing", + req: httptest.NewRequest(http.MethodGet, "/api/skills/missing", nil), + h: s.fsMissingSkills, + want: "failed to load missing skills", + }, + { + name: "visibility", + req: skillErrReq(http.MethodGet, "/api/visibility/skill/recon", "name", "recon", ""), + h: s.pgSkillVisibility, + want: "failed to load skill visibility", + }, + { + name: "toggle", + req: skillErrReq(http.MethodPost, "/api/visibility/skill/toggle", "", "", `{"agent_id":"1","skill_name":"recon","visible":true}`), + h: s.pgToggleSkillVisibility, + want: "failed to update skill visibility", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + tc.h(rec, tc.req) + if rec.Code != 500 { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body["error"] != tc.want || strings.Contains(rec.Body.String(), "database") { + t.Fatalf("body = %s, want %q", rec.Body.String(), tc.want) + } + }) + } +} + +func skillErrReq(method, target, key, val, jsonBody string) *http.Request { + var r *http.Request + if jsonBody == "" { + r = httptest.NewRequest(method, target, nil) + } else { + r = httptest.NewRequest(method, target, strings.NewReader(jsonBody)) + } + if key != "" { + r.SetPathValue(key, val) + } + return r +} From cdd7e9ad5474810101204cc77bfcc4b5a72a5850 Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:13:47 +0000 Subject: [PATCH 06/53] fix(extension): mark a truncated capture body and drop failed requests A body cut to exactly MAX_BODY looked complete, so the later truncate call did nothing. The stored body now goes through truncate and keeps the marker. Network.loadingFailed removes the request instead of leaving it until the map evicts it. The cap counts JavaScript characters, not bytes. --- CHANGELOG.md | 2 +- extension/background.js | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6db6ab1..d687fe9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed -- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a stored request body is cut at the same 256 KiB limit as ingest. +- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a request that fails to load is dropped instead of waiting for eviction. A stored body longer than 256K JavaScript characters is cut and marked `[truncated by extension]`. That count is UTF-16 code units, not bytes; the server still enforces its byte cap on ingest. - **Live log subscribers can no longer crash the process**: a client disconnect closes its log channel. The sink now delivers a line while it still holds the subscriber lock, so that close cannot land in the middle of the send. - **Notification delivery ignores HTTP_PROXY**: the dial guard checks the address it connects to. An environment proxy made that address the proxy, so a link-local target could still be reached. Notification HTTP now connects directly. - **Captured traffic blobs are owner-only**: HTTP and raw-stream bodies spilled out of the database are written `0600`, and their bucket directory is `0700`. An existing blob is tightened when it is seen again. diff --git a/extension/background.js b/extension/background.js index a3bcfc50..7eb9b6df 100644 --- a/extension/background.js +++ b/extension/background.js @@ -8,7 +8,9 @@ // the acceptable failure mode for a manual capture session. const FLUSH_AT = 10; // entries per batch -const MAX_BODY = 256 * 1024; // matches the server-side ingest cap +// JavaScript string length, in UTF-16 code units, not bytes. The server +// ingest cap is 256 KiB of bytes and remains the backstop. +const MAX_BODY = 256 * 1024; const MAX_TRACKED = 500; // unfinished requests kept in memory const SKIP_MIME = ["image/", "font/", "audio/", "video/", "application/octet-stream"]; @@ -116,7 +118,6 @@ async function queueExchange(info, response) { { requestId: info.requestId } ); if (body && !body.base64Encoded) { - reqBody = truncate(reqBody); respBody = truncate(body.body || ""); } } catch (_) { @@ -168,8 +169,7 @@ async function flush() { chrome.debugger.onEvent.addListener((source, method, params) => { if (!session.capturing || !source.tabId || source.tabId !== session.tabId) return; if (method === "Network.requestWillBeSent") { - let postData = params.request.postData || ""; - if (postData.length > MAX_BODY) postData = postData.slice(0, MAX_BODY); + const postData = truncate(params.request.postData || ""); if (!session.requests.has(params.requestId) && session.requests.size >= MAX_TRACKED) { const oldest = session.requests.keys().next().value; session.requests.delete(oldest); @@ -184,6 +184,8 @@ chrome.debugger.onEvent.addListener((source, method, params) => { } else if (method === "Network.responseReceived") { const info = session.requests.get(params.requestId); if (info) info.response = params.response; + } else if (method === "Network.loadingFailed") { + session.requests.delete(params.requestId); } else if (method === "Network.loadingFinished") { const info = session.requests.get(params.requestId); session.requests.delete(params.requestId); From 07df390b8e2475e4be2d211971c2d650685fdaa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BA=91=E5=91=A8?= <154221037+YunzhouLi-hub@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:32:16 +0800 Subject: [PATCH 07/53] fix(web): distinguish unavailable and stale noise status --- .../system/settings/noise-profile-card.tsx | 70 +++++++++++++------ web/src/i18n/locales/tr.json | 4 ++ web/src/i18n/locales/zh-CN.json | 4 ++ 3 files changed, 58 insertions(+), 20 deletions(-) diff --git a/web/src/app/(main)/system/settings/noise-profile-card.tsx b/web/src/app/(main)/system/settings/noise-profile-card.tsx index ab31521f..feeab0de 100644 --- a/web/src/app/(main)/system/settings/noise-profile-card.tsx +++ b/web/src/app/(main)/system/settings/noise-profile-card.tsx @@ -41,23 +41,39 @@ const profiles: { value: NoiseProfileName; label: string; limits: string }[] = [ }, ]; +type NoiseReading = + | { state: "loading"; status: NoiseStatus | null } + | { state: "ready"; status: NoiseStatus } + | { state: "error"; status: NoiseStatus | null; message: string }; + // NoiseProfileCard sets the target noise profile and shows the per-host // counters of the current minute. export function NoiseProfileCard() { - const [status, setStatus] = React.useState(null); - const [loading, setLoading] = React.useState(false); + const [reading, setReading] = React.useState({ state: "loading", status: null }); const [saving, setSaving] = React.useState(false); + const latestRequest = React.useRef(0); - const refresh = React.useCallback(() => { - setLoading(true); - api - .noiseStatus() - .then(setStatus) - .catch((e) => toast.error(t("Failed to load the noise counters: {error}", { error: (e as Error).message }))) - .finally(() => setLoading(false)); + const refresh = React.useCallback(async () => { + const request = ++latestRequest.current; + setReading(({ status }) => ({ state: "loading", status })); + try { + const status = await api.noiseStatus(); + if (!status || !profiles.some((profile) => profile.value === status.profile) || !Array.isArray(status.hosts)) { + throw new Error(t("Invalid noise status response.")); + } + if (request === latestRequest.current) setReading({ state: "ready", status }); + } catch (error) { + if (request === latestRequest.current) { + const message = error instanceof Error ? error.message : String(error); + setReading(({ status }) => ({ state: "error", status, message })); + } + } }, []); React.useEffect(() => { - refresh(); + void refresh(); + return () => { + latestRequest.current += 1; + }; }, [refresh]); const save = (value: NoiseProfileName) => { @@ -68,13 +84,15 @@ export function NoiseProfileCard() { toast.success( t("Noise profile set to {profile}", { profile: profiles.find((p) => p.value === value)?.label ?? value }), ); - refresh(); + return refresh(); }) .catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message }))) .finally(() => setSaving(false)); }; - const current = profiles.find((p) => p.value === status?.profile) ?? profiles[0]; + const { status } = reading; + const loading = reading.state === "loading"; + const current = profiles.find((p) => p.value === status?.profile); return ( @@ -95,11 +113,11 @@ export function NoiseProfileCard() { -

{current.limits}

+ {reading.state === "error" && ( +

+ {t("Failed to load the noise counters: {error}", { error: reading.message })} +

+ )} + {status && reading.state !== "ready" && ( +

+ {t("Showing the last successfully loaded noise profile and counters.")} +

+ )} + {current &&

{current.limits}

}
- {t("Hosts, current minute")} - @@ -145,11 +175,11 @@ export function NoiseProfileCard() { ))} - ) : ( + ) : reading.state === "ready" ? (

- {status?.profile === "off" ? t("Off counts no request.") : t("No paced request yet.")} + {reading.status.profile === "off" ? t("Off counts no request.") : t("No paced request yet.")}

- )} + ) : null} ); diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.json index 90bfc3b1..aa5a9ccd 100644 --- a/web/src/i18n/locales/tr.json +++ b/web/src/i18n/locales/tr.json @@ -1185,6 +1185,7 @@ "Interval ms": "Aralık (ms)", "Invalid CIDR format, e.g. 192.168.0.0/16": "Geçersiz CIDR biçimi, ör. 192.168.0.0/16", "Invalid headers JSON": "Geçersiz başlık JSON'u", + "Invalid noise status response.": "Gürültü durumu yanıtı geçersiz.", "Invalid parameter JSON Schema": "Geçersiz parametre JSON Schema'sı", "Invalid regex syntax": "Geçersiz regex sözdizimi", "Invalid request": "Geçersiz istek", @@ -1211,6 +1212,7 @@ "Last {count} calls": "Son {count} çağrı", "Last {count} Q&A exchanges verbatim": "Son {count} soru-cevap aynen", "Last activity": "Son etkinlik", + "Last available host counters": "Son alınan ana makine sayaçları", "Last called": "Son çağrı", "Latency": "Gecikme", "Latest details read on send · Up to 10 records": "Gönderimde en güncel ayrıntılar okunur · En fazla 10 kayıt", @@ -1527,6 +1529,7 @@ "Node #{id}": "Düğüm #{id}", "Noise counters per host": "Ana makine başına gürültü sayaçları", "Noise profile set to {profile}": "Gürültü profili {profile} olarak ayarlandı", + "Noise status unavailable": "Gürültü durumu alınamadı", "none": "yok", "None of them is high risk.": "Hiçbiri yüksek riskli değil.", "Not assessed": "Değerlendirilmedi", @@ -2119,6 +2122,7 @@ "shell/command/script/http, {count} / {total} matching; click a card to edit": "shell/command/script/http, {count} / {total} eşleşme; düzenlemek için bir karta tıklayın", "Show more (+{count})": "Daha fazla göster (+{count})", "Showing {count}, scroll down for more": "{count} kayıt gösteriliyor, daha fazlası için aşağı kaydırın", + "Showing the last successfully loaded noise profile and counters.": "Son başarıyla yüklenen gürültü profili ve sayaçlar gösteriliyor.", "Side question": "Yan soru", "Side question panel": "Yan soru paneli", "Sidebar": "Kenar Çubuğu", diff --git a/web/src/i18n/locales/zh-CN.json b/web/src/i18n/locales/zh-CN.json index 5ca5af25..10307ae0 100644 --- a/web/src/i18n/locales/zh-CN.json +++ b/web/src/i18n/locales/zh-CN.json @@ -1185,6 +1185,7 @@ "Interval ms": "间隔 ms", "Invalid CIDR format, e.g. 192.168.0.0/16": "CIDR 格式无效,形如 192.168.0.0/16", "Invalid headers JSON": "headers JSON 格式错误", + "Invalid noise status response.": "请求强度状态响应无效。", "Invalid parameter JSON Schema": "参数 JSON Schema 格式错误", "Invalid regex syntax": "正则表达式语法无效", "Invalid request": "无效请求", @@ -1211,6 +1212,7 @@ "Last {count} calls": "最近 {count} 次调用", "Last {count} Q&A exchanges verbatim": "最近 {count} 轮问答原文", "Last activity": "最近活动", + "Last available host counters": "上次取得的主机统计", "Last called": "最近调用", "Latency": "延迟", "Latest details read on send · Up to 10 records": "发送时读取最新详情 · 最多 10 条", @@ -1527,6 +1529,7 @@ "Node #{id}": "节点 #{id}", "Noise counters per host": "各主机请求强度统计", "Noise profile set to {profile}": "请求强度策略已设为 {profile}", + "Noise status unavailable": "无法读取请求强度状态", "none": "无", "None of them is high risk.": "其中没有高风险项。", "Not assessed": "未评估", @@ -2119,6 +2122,7 @@ "shell/command/script/http, {count} / {total} matching; click a card to edit": "shell/command/script/http,匹配 {count} / {total} 项;点击卡片可编辑", "Show more (+{count})": "显示更多(+{count})", "Showing {count}, scroll down for more": "已显示 {count} 项,向下滚动加载更多", + "Showing the last successfully loaded noise profile and counters.": "正在显示上次成功加载的请求强度策略和统计数据。", "Side question": "旁路提问", "Side question panel": "旁路提问面板", "Sidebar": "侧边栏", From eef870ef19f10bbe65d3747eb18f8fe2f835ecbe Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:32:52 +0000 Subject: [PATCH 08/53] ci: retrigger checks for the capture truncation fix From b5d103218e3f3d495007699780d8217690ded9de Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:32:52 +0000 Subject: [PATCH 09/53] ci: retrigger checks for the skill visibility fix From 2ea9a02b346d11870b702807fdd5b325a2d19a32 Mon Sep 17 00:00:00 2001 From: Rahul Remany <63519586+rahulremany@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:31:30 -0800 Subject: [PATCH 10/53] chore: migrate log.Printf to log/slog in llmpool, llmrec, intercept and db Follow-up to #488. Replaces the remaining 18 log.Printf calls in these four packages with structured slog calls, keeping the [tag] prefix that the log sink uses. Format arguments become key/value attributes. --- db/activity_outbox.go | 4 ++-- db/companies.go | 4 ++-- db/notification.go | 10 +++++----- db/secrets.go | 6 +++--- intercept/intercept.go | 4 ++-- llmpool/pool.go | 18 +++++++++--------- llmrec/context_telemetry.go | 4 ++-- llmrec/llmrec.go | 6 +++--- 8 files changed, 28 insertions(+), 28 deletions(-) diff --git a/db/activity_outbox.go b/db/activity_outbox.go index b49f234f..d43fe878 100644 --- a/db/activity_outbox.go +++ b/db/activity_outbox.go @@ -3,7 +3,7 @@ package db import ( "encoding/json" "fmt" - "log" + "log/slog" ) // activityOutboxMaxAttempts is how many times a row may fail AppendActivity @@ -94,7 +94,7 @@ func (s *ExplorationStore) FlushActivityOutbox() (int, error) { _ = tx.Rollback() next := it.attempts + 1 if next >= activityOutboxMaxAttempts { - log.Printf("[activity] outbox %d for exploration %d dropped after %d attempts: %v", it.id, s.expID, next, err) + slog.Error("[activity] outbox entry dropped", "outbox_id", it.id, "exploration_id", s.expID, "attempts", next, "err", err) if _, delErr := s.db.Exec(`DELETE FROM activity_outbox WHERE id=$1`, it.id); delErr != nil { return stored, delErr } diff --git a/db/companies.go b/db/companies.go index ad5d2395..2020f413 100644 --- a/db/companies.go +++ b/db/companies.go @@ -4,7 +4,7 @@ import ( "database/sql" "errors" "fmt" - "log" + "log/slog" "net" "strings" "unicode/utf8" @@ -583,7 +583,7 @@ const malformedIPAssetsSampled = 5 // per-request response (company deletion, scopesentry sync, agent asset writes). func logAttributionWarning(warning string) { if warning != "" { - log.Printf("[assets] %s", warning) + slog.Warn("[assets] " + warning) } } diff --git a/db/notification.go b/db/notification.go index da150b85..3c1a6787 100644 --- a/db/notification.go +++ b/db/notification.go @@ -6,7 +6,7 @@ import ( "encoding/json" "errors" "fmt" - "log" + "log/slog" "strings" "time" @@ -247,19 +247,19 @@ func (d *DB) DeleteNotificationChannel(ctx context.Context, id int64) error { func RecordNotificationEventTx(ctx context.Context, tx *sql.Tx, kind string, findingID int64, snap notify.Snapshot) bool { raw, err := json.Marshal(snap) if err != nil { - log.Printf("[notify] failed to serialize delivery event finding=%d: %v", findingID, err) + slog.Error("[notify] failed to serialize delivery event", "finding", findingID, "err", err) return false } if _, err := tx.ExecContext(ctx, `SAVEPOINT notify_event`); err != nil { - log.Printf("[notify] failed to create savepoint finding=%d: %v", findingID, err) + slog.Error("[notify] failed to create savepoint", "finding", findingID, "err", err) return false } if _, err := tx.ExecContext(ctx, `INSERT INTO notification_events(kind,finding_id,snapshot) VALUES($1,$2,$3)`, kind, findingID, string(raw)); err != nil { - log.Printf("[notify] failed to write delivery event finding=%d (finding record unaffected): %v", findingID, err) + slog.Error("[notify] failed to write delivery event (finding record unaffected)", "finding", findingID, "err", err) // Roll back to the savepoint, rescuing the transaction from the aborted state. if _, rbErr := tx.ExecContext(ctx, `ROLLBACK TO SAVEPOINT notify_event`); rbErr != nil { - log.Printf("[notify] failed to roll back to savepoint finding=%d: %v", findingID, rbErr) + slog.Error("[notify] failed to roll back to savepoint", "finding", findingID, "err", rbErr) } return false } diff --git a/db/secrets.go b/db/secrets.go index 2a47e58a..4db88b27 100644 --- a/db/secrets.go +++ b/db/secrets.go @@ -14,7 +14,7 @@ import ( "encoding/json" "errors" "fmt" - "log" + "log/slog" "os" "path/filepath" "strings" @@ -306,7 +306,7 @@ func (d *DB) InitSecrets(keyDir string) error { if err != nil { return err } - log.Printf("[secrets] at-rest encryption ready; backfill encrypted %d plaintext value(s)", n) + slog.Info("[secrets] at-rest encryption ready", "backfilled_plaintext_values", n) activeSecretBox.Store(box) sub := deriveSubKey(key, trafficTraceDomain) trafficTraceKey.Store(&sub) @@ -362,7 +362,7 @@ func loadSecretKey(ctx context.Context, conn *sql.Conn, keyDir string) ([]byte, _ = os.Remove(path) return nil, fmt.Errorf("write secret key: %w", err) } - log.Printf("[secrets] new secret key written to %s", path) + slog.Info("[secrets] new secret key written", "path", path) return key, nil } diff --git a/intercept/intercept.go b/intercept/intercept.go index 456bd366..89f71118 100644 --- a/intercept/intercept.go +++ b/intercept/intercept.go @@ -16,7 +16,7 @@ import ( "encoding/json" "errors" "fmt" - "log" + "log/slog" "net" "regexp" "strconv" @@ -309,7 +309,7 @@ func (i *Interceptor) loadLocked() error { if err != nil { if !i.loadFailed { i.loadFailed = true - log.Printf("[intercept] the rule store cannot be read; every tool call is denied until it can: %v", err) + slog.Error("[intercept] the rule store cannot be read; every tool call is denied until it can", "err", err) } return err } diff --git a/llmpool/pool.go b/llmpool/pool.go index 39840f49..dd912d25 100644 --- a/llmpool/pool.go +++ b/llmpool/pool.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" "iter" - "log" + "log/slog" "regexp" "strconv" "strings" @@ -106,18 +106,18 @@ func (p *Pool) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[ } lastErr = failed if tripped, msg := p.health.RecordCall(ctx, m.ID, true, false, failed); tripped { - log.Printf("[llmpool] profile %q(%s) breaker tripped: %s", m.Name, m.Model, msg) + slog.Warn("[llmpool] profile breaker tripped", "profile", m.Name, "model", m.Model, "reason", msg) } if i+1 < len(order) { n := order[i+1] - log.Printf("[llmpool] LLM failover: %q(%s) → %q(%s), reason: %s", - m.Name, m.Model, n.Name, n.Model, trimErr(failed)) + slog.Warn("[llmpool] LLM failover", "from_profile", m.Name, "from_model", m.Model, + "to_profile", n.Name, "to_model", n.Model, "reason", trimErr(failed)) } } if lastErr == nil { lastErr = ErrExhausted } - log.Printf("[llmpool] failover chain exhausted (all %d profiles failed), last error: %s", len(order), trimErr(lastErr)) + slog.Error("[llmpool] failover chain exhausted, all profiles failed", "profiles", len(order), "last_err", trimErr(lastErr)) yield(llm.StreamEvent{}, fmt.Errorf("%w: %v", ErrExhausted, lastErr)) } } @@ -145,18 +145,18 @@ func (p *Pool) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Mes } lastErr = err if tripped, msg := p.health.RecordCall(ctx, m.ID, false, false, err); tripped { - log.Printf("[llmpool] profile %q(%s) breaker tripped: %s", m.Name, m.Model, msg) + slog.Warn("[llmpool] profile breaker tripped", "profile", m.Name, "model", m.Model, "reason", msg) } if i+1 < len(order) { n := order[i+1] - log.Printf("[llmpool] LLM failover: %q(%s) → %q(%s), reason: %s", - m.Name, m.Model, n.Name, n.Model, trimErr(err)) + slog.Warn("[llmpool] LLM failover", "from_profile", m.Name, "from_model", m.Model, + "to_profile", n.Name, "to_model", n.Model, "reason", trimErr(err)) } } if lastErr == nil { lastErr = ErrExhausted } - log.Printf("[llmpool] failover chain exhausted (all %d profiles failed), last error: %s", len(order), trimErr(lastErr)) + slog.Error("[llmpool] failover chain exhausted, all profiles failed", "profiles", len(order), "last_err", trimErr(lastErr)) return llm.Message{}, "", llm.Usage{}, fmt.Errorf("%w: %v", ErrExhausted, lastErr) } diff --git a/llmrec/context_telemetry.go b/llmrec/context_telemetry.go index edfc1acf..b4e14533 100644 --- a/llmrec/context_telemetry.go +++ b/llmrec/context_telemetry.go @@ -2,7 +2,7 @@ package llmrec import ( "encoding/json" - "log" + "log/slog" "os" "strings" @@ -169,6 +169,6 @@ func (r *Recorder) recordContext(taskID, worker string, m ContextMetrics, usage Status: status, }) if err != nil { - log.Printf("[llmcontext] insert: %v", err) + slog.Error("[llmcontext] insert failed", "err", err) } } diff --git a/llmrec/llmrec.go b/llmrec/llmrec.go index 0eb75da1..23f2abd6 100644 --- a/llmrec/llmrec.go +++ b/llmrec/llmrec.go @@ -8,7 +8,7 @@ import ( "encoding/json" "errors" "iter" - "log" + "log/slog" "strings" "time" @@ -363,7 +363,7 @@ func (r *Recorder) recordUsage(ctx context.Context, taskID string, expID int64, Status: status, }) if err != nil { - log.Printf("[llmusage] insert: %v", err) + slog.Error("[llmusage] insert failed", "err", err) } } @@ -424,7 +424,7 @@ func (r *Recorder) record(req llm.CompletionRequest, session, taskID, worker, re } if err := r.pg.InsertLLMRecord(rec); err != nil { - log.Printf("[llmrec] insert: %v", err) + slog.Error("[llmrec] insert failed", "err", err) } } From 58bafdbf760bfd481134004460786493ea5f65a1 Mon Sep 17 00:00:00 2001 From: shiv Date: Sat, 21 Nov 2026 16:33:15 +0530 Subject: [PATCH 11/53] feat(chatbridge): inbound chat bridge core with a Telegram long-poll transport First part of #5: the transport-agnostic bridge core, the Telegram adapter, the mandatory chat allowlist, storage, API and settings page. Task commands, main-agent routing and remote approvals follow in separate PRs on top of this one. - chatbridge: Transport interface and Router. The router enforces the allowlist (an unknown chat gets one refusal naming its chat ID, then silence, bounded memory), drops updates older than two minutes so a backlog is never executed, ignores bot senders and commands addressed to another bot, and dispatches commands (/help, /whoami for now). - Telegram transport: getUpdates long polling (no inbound port), plain-text sendMessage truncated to the Bot API limit, getMe for the identity. It reuses notify's dial guard and redirect policy through small exported wrappers, and its errors never carry the token. - Storage: migration 0015 adds chat_bridges, one row per kind. config is sealed at rest (added to secretColumns) and masked in the API with the notification-channel convention. The update cursor is committed before a batch is acted on, only moves forward, and is written only for the config_version the poller read, so a poll of a replaced token can never move the new bot's cursor. A token change clears it. - Server: one loop per transport started by server.New; it re-reads its row each round and Reload interrupts a poll in flight, so saving the form applies without a restart. Exponential backoff on errors, honours Telegram's retry_after, logs under [tgbot] without message text. - API: GET /api/chat-bridges, PUT /api/chat-bridges/{kind}, POST /api/chat-bridges/{kind}/test. A bridge may run with an empty allowlist: it then serves no chat and only sends the one-time refusal naming the chat ID, which is how an operator finds the ID to add. - Web: System -> Chat bot page with live status, zh-CN and tr strings. - Docs: docs/chat-bridge.md; README lists the token among stored secrets. The migration test lists 0015; the pre-0012 test rolls it back with the others and it re-applies (the migration is idempotent). Co-authored-by: krad <222954346+dar1k0@users.noreply.github.com> --- README.md | 2 + chatbridge/bridge.go | 128 +++++++ chatbridge/config.go | 73 ++++ chatbridge/router.go | 197 ++++++++++ chatbridge/router_test.go | 152 ++++++++ chatbridge/telegram.go | 265 +++++++++++++ chatbridge/telegram_test.go | 222 +++++++++++ db/chat_bridges.go | 105 ++++++ db/chat_bridges_test.go | 79 ++++ db/migrate_test.go | 7 +- db/migrations/0015_chat_bridges.sql | 25 ++ db/secrets.go | 6 +- docs/chat-bridge.md | 63 ++++ notify/http.go | 25 ++ server/chatbridge.go | 351 ++++++++++++++++++ server/chatbridge_api.go | 215 +++++++++++ server/chatbridge_test.go | 291 +++++++++++++++ server/server.go | 10 + .../app/(main)/system/chat-bridge/page.tsx | 259 +++++++++++++ web/src/i18n/locales/tr.json | 21 +- web/src/i18n/locales/zh-CN.json | 21 +- web/src/lib/api.ts | 14 + web/src/lib/types.ts | 29 ++ web/src/navigation/sidebar/sidebar-items.ts | 2 + 24 files changed, 2555 insertions(+), 7 deletions(-) create mode 100644 chatbridge/bridge.go create mode 100644 chatbridge/config.go create mode 100644 chatbridge/router.go create mode 100644 chatbridge/router_test.go create mode 100644 chatbridge/telegram.go create mode 100644 chatbridge/telegram_test.go create mode 100644 db/chat_bridges.go create mode 100644 db/chat_bridges_test.go create mode 100644 db/migrations/0015_chat_bridges.sql create mode 100644 docs/chat-bridge.md create mode 100644 server/chatbridge.go create mode 100644 server/chatbridge_api.go create mode 100644 server/chatbridge_test.go create mode 100644 web/src/app/(main)/system/chat-bridge/page.tsx diff --git a/README.md b/README.md index a11b4f34..5f14f676 100644 --- a/README.md +++ b/README.md @@ -772,6 +772,7 @@ gunzip -c backups/artex-db-.sql.gz | docker compose exec -T postgres ``` Stored secrets (LLM API keys, proxies and gateway custom headers, MCP env, task credentials, notification channel config, +the chat bot token, Brave/Tavily search keys, web search and global proxies, the execution spec of custom tools, the capture-proxy rewrite rules) are encrypted in the database with the key in `keys/secret.key` (generated at first start, mode 0600, @@ -960,6 +961,7 @@ Please report vulnerabilities privately through GitHub Security Advisories; see Operational security properties: - **Secrets at rest**: LLM keys/proxies/gateway headers, MCP environment, task credentials, notification config, + the chat bot token, search keys, proxies, custom-tool execution specs, capture-proxy rewrite rules and traffic evidence snapshots are encrypted with AES-256-GCM using `keys/secret.key` (or `ARTEX_SECRET_KEY`). ARTEX refuses to start when diff --git a/chatbridge/bridge.go b/chatbridge/bridge.go new file mode 100644 index 00000000..4978ac6c --- /dev/null +++ b/chatbridge/bridge.go @@ -0,0 +1,128 @@ +// Package chatbridge is the inbound side of the chat-app integration: an +// operator talks to ARTEX from a chat app (Telegram first) instead of the web +// UI. The outbound side, pushing findings, stays in package notify. +// +// The package is transport-agnostic. A Transport only knows how to fetch new +// updates, send a text reply and identify the bot; the Router owns every rule +// that does not depend on the chat app: the chat allowlist, the one-line +// refusal for unknown chats, dropping stale updates and command parsing. +// +// Like notify, the package imports nothing from db or server and transports +// are stateless: the configuration arrives as map[string]any (the decrypted +// chat_bridges.config row) on every call, so a token rotation takes effect on +// the next call without a restart. +package chatbridge + +import ( + "context" + "fmt" + "sort" + "strings" + "time" +) + +// Update is one inbound event from a chat app, already normalized. +type Update struct { + // ID is the transport's cursor. The next Poll asks for updates after it. + ID int64 + // ChatID identifies the conversation (a private chat or a group). It is the + // unit the allowlist works on. + ChatID string + // ChatType is the transport's own label, for example "private" or "group". + ChatType string + // UserID and UserName identify the sender inside the chat. They are kept + // for attribution in logs; the allowlist does not look at them. + UserID string + UserName string + // FromBot is set when the sender is itself a bot. Bot messages are ignored + // so two bots in one group cannot drive each other. + FromBot bool + // Text is the message text. Empty for updates that carry no text (stickers, + // photos, joins); those are ignored. + Text string + // Date is when the chat app received the message. + Date time.Time +} + +// Identity describes the bot account behind a configuration. +type Identity struct { + ID string `json:"id"` + UserName string `json:"username"` + Name string `json:"name"` +} + +// Transport is one chat app. +type Transport interface { + // Kind is the stable identifier stored in chat_bridges.kind. + Kind() string + // Validate checks a configuration before it is saved or used. + Validate(cfg map[string]any) error + // SecretKeys names the configuration fields that are credentials. They + // are sealed at rest by the db layer and masked in API responses. + SecretKeys() []string + // DestinationKeys names the fields that decide where the credentials are + // sent. Changing one requires re-entering every secret. + DestinationKeys() []string + // ValidateChatID checks one allowlist entry. + ValidateChatID(id string) error + // Identity asks the chat app which bot the configuration belongs to. + Identity(ctx context.Context, cfg map[string]any) (Identity, error) + // Poll returns the updates after cursor offset. It may block up to the + // transport's long-poll window and returns early when ctx ends. + Poll(ctx context.Context, cfg map[string]any, offset int64) ([]Update, error) + // Send delivers a plain-text reply to a chat. Transports truncate text + // that exceeds the chat app's message limit. + Send(ctx context.Context, cfg map[string]any, chatID, text string) error +} + +var registry = map[string]Transport{ + KindTelegram: telegramTransport{}, +} + +// Get returns the transport of a kind. +func Get(kind string) (Transport, bool) { + t, ok := registry[kind] + return t, ok +} + +// Kinds lists the registered transport kinds in a stable order. +func Kinds() []string { + out := make([]string, 0, len(registry)) + for k := range registry { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// MaxAllowedChats caps the allowlist. The bridge is an operator console, not +// a broadcast channel; a long list is more likely a mistake than a need. +const MaxAllowedChats = 50 + +// NormalizeAllowedChats trims, validates and de-duplicates an allowlist, +// keeping the operator's order. +func NormalizeAllowedChats(t Transport, ids []string) ([]string, error) { + out := make([]string, 0, len(ids)) + seen := map[string]bool{} + for _, raw := range ids { + id := strings.TrimSpace(raw) + if id == "" || seen[id] { + continue + } + if err := t.ValidateChatID(id); err != nil { + return nil, fmt.Errorf("chat id %q: %w", id, err) + } + seen[id] = true + out = append(out, id) + } + if len(out) > MaxAllowedChats { + return nil, fmt.Errorf("at most %d chats can be allowed", MaxAllowedChats) + } + return out, nil +} + +// The allowlist is mandatory in the sense that matters: the Router serves only +// listed chats, and every other chat gets one refusal and then silence. An +// empty allowlist is therefore a valid, closed state rather than an error: the +// bridge runs, serves nobody, and answers each chat with the refusal that names +// its chat ID. That is how an operator learns the ID to add. diff --git a/chatbridge/config.go b/chatbridge/config.go new file mode 100644 index 00000000..ed481662 --- /dev/null +++ b/chatbridge/config.go @@ -0,0 +1,73 @@ +package chatbridge + +import ( + "errors" + "fmt" + + "github.com/Autumn-27/artex/notify" +) + +// The masking convention is the one the notification channels use, so the UI +// handles both forms the same way: a credential is echoed as +// notify.MaskedPrefix plus its last characters, sending the masked value back +// unchanged keeps the stored secret, and an empty string clears the field. + +// MaskConfig returns a copy of cfg with the transport's credential fields +// masked. An unknown kind yields an empty map rather than the raw config. +func MaskConfig(kind string, cfg map[string]any) map[string]any { + t, ok := Get(kind) + if !ok { + return map[string]any{} + } + secrets := map[string]bool{} + for _, k := range t.SecretKeys() { + secrets[k] = true + } + out := make(map[string]any, len(cfg)) + for k, v := range cfg { + if !secrets[k] { + out[k] = v + continue + } + if s, ok := v.(string); ok && s != "" { + out[k] = notify.MaskedValue(s) + } + } + return out +} + +// PrepareConfigUpdate merges an incoming configuration from the API into the +// stored one. +// +// A masked secret keeps the stored value. When a destination field changes +// (for example base_url, which decides where the bot token is sent) every +// secret must be supplied again in clear: a masked value would otherwise send +// the old token to the new address. +func PrepareConfigUpdate(kind string, stored, incoming map[string]any) (map[string]any, error) { + t, ok := Get(kind) + if !ok { + return nil, fmt.Errorf("chat bridge kind %q is not registered", kind) + } + if stored == nil { + stored = map[string]any{} + } + changed := false + for _, k := range t.DestinationKeys() { + in, present := incoming[k] + if !present { + continue + } + if fmt.Sprint(in) != fmt.Sprint(stored[k]) && !(in == "" && stored[k] == nil) { + changed = true + } + } + if changed { + for _, k := range t.SecretKeys() { + s, _ := incoming[k].(string) + if s == "" || notify.IsMasked(s) { + return nil, errors.New("the API address changed: enter the bot token again") + } + } + } + return notify.MergeConfig(stored, incoming), nil +} diff --git a/chatbridge/router.go b/chatbridge/router.go new file mode 100644 index 00000000..2e48077c --- /dev/null +++ b/chatbridge/router.go @@ -0,0 +1,197 @@ +package chatbridge + +import ( + "context" + "fmt" + "sort" + "strings" + "sync" + "time" +) + +// MaxUpdateAge is how old an update may be and still be acted on. +// +// Chat apps queue updates while the bridge is offline (Telegram keeps them for +// a day). Executing a backlog after a restart or an outage would run commands +// the operator typed long ago and has likely given up on, such as resuming a +// task they meant to keep paused. Anything older than this is dropped and +// logged instead. +const MaxUpdateAge = 2 * time.Minute + +// maxRefusedChats bounds the memory of chats that were already refused once. +const maxRefusedChats = 1024 + +// Request is one authorized message handed to a command. +type Request struct { + Kind string // transport kind + ChatID string + UserID string + UserName string + Command string // lower-case command name without the slash; "" for plain text + Args string // text after the command, or the whole text when Command is "" +} + +// CommandFunc handles one command and returns the reply text. An empty reply +// sends nothing. +type CommandFunc func(ctx context.Context, req Request) string + +// Command is one entry of the command table. +type Command struct { + Name string // without the slash, lower case + Usage string // argument hint shown by /help, for example "" + Summary string // one line shown by /help + Run CommandFunc +} + +// Decision is what the Router did with an update, for logging and tests. +type Decision int + +const ( + DecisionIgnored Decision = iota // no text, a bot sender, or a command for another bot + DecisionStale // older than MaxUpdateAge + DecisionRefused // unknown chat, refusal sent + DecisionMuted // unknown chat, already refused once + DecisionHandled // allowed chat, a command or text handler ran +) + +func (d Decision) String() string { + switch d { + case DecisionStale: + return "stale" + case DecisionRefused: + return "refused" + case DecisionMuted: + return "muted" + case DecisionHandled: + return "handled" + default: + return "ignored" + } +} + +// Router applies the transport-independent rules to an update and picks the +// handler. It is safe for concurrent use. +type Router struct { + // BotUserName, when set, lets the router tell "/help@this_bot" from + // "/help@another_bot" in a group. Commands addressed to another bot are + // ignored. + BotUserName string + // Commands is the command table. /help is built in. + Commands []Command + // Text handles a message that is not a command. Nil replies with a hint to + // use /help. + Text CommandFunc + // Now is the clock; nil uses time.Now. + Now func() time.Time + + mu sync.Mutex + refused map[string]bool +} + +// Route decides what to do with an update from an allowed or unknown chat and +// returns the reply to send (possibly empty). +func (r *Router) Route(ctx context.Context, kind string, allowed []string, u Update) (Decision, string) { + if u.FromBot || strings.TrimSpace(u.Text) == "" { + return DecisionIgnored, "" + } + now := time.Now + if r.Now != nil { + now = r.Now + } + if !u.Date.IsZero() && now().Sub(u.Date) > MaxUpdateAge { + return DecisionStale, "" + } + if !contains(allowed, u.ChatID) { + return r.refuse(u.ChatID) + } + + name, args, forOther := parseCommand(u.Text, r.BotUserName) + if forOther { + return DecisionIgnored, "" + } + req := Request{Kind: kind, ChatID: u.ChatID, UserID: u.UserID, UserName: u.UserName, Command: name, Args: args} + if name == "" { + if r.Text == nil { + return DecisionHandled, "Send /help to see what this bot can do." + } + return DecisionHandled, r.Text(ctx, req) + } + if name == "help" || name == "start" { + return DecisionHandled, r.help() + } + for _, c := range r.Commands { + if c.Name == name { + return DecisionHandled, c.Run(ctx, req) + } + } + return DecisionHandled, fmt.Sprintf("Unknown command /%s. Send /help to see the commands.", name) +} + +// refuse answers an unknown chat once per process and then stays silent, so a +// stranger who found the bot cannot use it to make it talk. The chat id is in +// the refusal so the operator can add it to the allowlist when the chat is +// their own; it is the chat's own identifier and reveals nothing else. +func (r *Router) refuse(chatID string) (Decision, string) { + r.mu.Lock() + defer r.mu.Unlock() + if r.refused == nil { + r.refused = map[string]bool{} + } + if r.refused[chatID] { + return DecisionMuted, "" + } + if len(r.refused) >= maxRefusedChats { + // A flood of distinct chats: stop answering any new one rather than + // grow without bound or forget earlier refusals. + return DecisionMuted, "" + } + r.refused[chatID] = true + return DecisionRefused, "This chat is not allowed to use this ARTEX bot. If it is yours, add chat ID " + chatID + " to the allowlist in ARTEX (System → Chat bot)." +} + +func (r *Router) help() string { + var b strings.Builder + b.WriteString("ARTEX bot commands:\n/help - this list") + cmds := append([]Command(nil), r.Commands...) + sort.Slice(cmds, func(i, j int) bool { return cmds[i].Name < cmds[j].Name }) + for _, c := range cmds { + b.WriteString("\n/") + b.WriteString(c.Name) + if c.Usage != "" { + b.WriteString(" ") + b.WriteString(c.Usage) + } + if c.Summary != "" { + b.WriteString(" - ") + b.WriteString(c.Summary) + } + } + return b.String() +} + +// parseCommand splits "/name@bot args". It returns name "" for plain text, +// and forOther when the command is addressed to a different bot. +func parseCommand(text, botUserName string) (name, args string, forOther bool) { + text = strings.TrimSpace(text) + if !strings.HasPrefix(text, "/") { + return "", text, false + } + head, rest, _ := strings.Cut(text[1:], " ") + head, target, addressed := strings.Cut(head, "@") + if head == "" { + return "", text, false + } + if addressed && botUserName != "" && !strings.EqualFold(target, botUserName) { + return "", "", true + } + return strings.ToLower(head), strings.TrimSpace(rest), false +} + +func contains(list []string, v string) bool { + for _, s := range list { + if s == v { + return true + } + } + return false +} diff --git a/chatbridge/router_test.go b/chatbridge/router_test.go new file mode 100644 index 00000000..5d4ea434 --- /dev/null +++ b/chatbridge/router_test.go @@ -0,0 +1,152 @@ +package chatbridge + +import ( + "context" + "strings" + "testing" + "time" +) + +var testNow = time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + +func testRouter() *Router { + return &Router{ + BotUserName: "artex_bot", + Now: func() time.Time { return testNow }, + Commands: []Command{{ + Name: "echo", Usage: "", Summary: "repeat the text", + Run: func(_ context.Context, req Request) string { return "echo:" + req.Args + ":" + req.UserName }, + }}, + } +} + +func msg(chat, text string) Update { + return Update{ID: 1, ChatID: chat, UserID: "7", UserName: "op", Text: text, Date: testNow.Add(-time.Second)} +} + +func TestRouteAllowedCommand(t *testing.T) { + r := testRouter() + d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/echo hello world ")) + if d != DecisionHandled || reply != "echo:hello world:op" { + t.Fatalf("got %v %q", d, reply) + } +} + +func TestRouteCommandAddressedToThisOrOtherBot(t *testing.T) { + r := testRouter() + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/ECHO@Artex_Bot x")); d != DecisionHandled || !strings.HasPrefix(reply, "echo:x") { + t.Fatalf("own bot: got %v %q", d, reply) + } + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/echo@other_bot x")); d != DecisionIgnored || reply != "" { + t.Fatalf("other bot: got %v %q", d, reply) + } +} + +func TestRouteUnknownChatRefusedOnceThenMuted(t *testing.T) { + r := testRouter() + d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("555", "/echo hi")) + if d != DecisionRefused || !strings.Contains(reply, "555") { + t.Fatalf("first contact: got %v %q", d, reply) + } + if strings.Contains(reply, "echo") { + t.Fatalf("refusal must not run the command: %q", reply) + } + for i := 0; i < 3; i++ { + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("555", "hello?")); d != DecisionMuted || reply != "" { + t.Fatalf("repeat %d: got %v %q", i, d, reply) + } + } +} + +func TestRouteEmptyAllowlistRefusesEveryone(t *testing.T) { + r := testRouter() + if d, _ := r.Route(context.Background(), KindTelegram, nil, msg("100", "/help")); d != DecisionRefused { + t.Fatalf("got %v, want refused", d) + } +} + +func TestRouteRefusalMemoryIsBounded(t *testing.T) { + r := testRouter() + for i := 0; i < maxRefusedChats; i++ { + r.Route(context.Background(), KindTelegram, nil, msg("c"+itoa(i), "hi")) + } + if d, reply := r.Route(context.Background(), KindTelegram, nil, msg("brand-new", "hi")); d != DecisionMuted || reply != "" { + t.Fatalf("over the cap: got %v %q", d, reply) + } + if len(r.refused) > maxRefusedChats { + t.Fatalf("refused set grew to %d", len(r.refused)) + } +} + +func TestRouteDropsStaleAndBotAndEmpty(t *testing.T) { + r := testRouter() + old := msg("100", "/echo late") + old.Date = testNow.Add(-MaxUpdateAge - time.Second) + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, old); d != DecisionStale || reply != "" { + t.Fatalf("stale: got %v %q", d, reply) + } + // A stale message from an unknown chat is dropped before the refusal, so + // a backlog never produces a burst of refusals. + old.ChatID = "999" + if d, _ := r.Route(context.Background(), KindTelegram, []string{"100"}, old); d != DecisionStale { + t.Fatalf("stale unknown chat: got %v", d) + } + b := msg("100", "/echo x") + b.FromBot = true + if d, _ := r.Route(context.Background(), KindTelegram, []string{"100"}, b); d != DecisionIgnored { + t.Fatalf("bot sender: got %v", d) + } + if d, _ := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", " ")); d != DecisionIgnored { + t.Fatalf("empty text: got %v", d) + } +} + +func TestRouteHelpAndUnknownAndPlainText(t *testing.T) { + r := testRouter() + _, help := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/start")) + if !strings.Contains(help, "/echo - repeat the text") || !strings.Contains(help, "/help") { + t.Fatalf("help = %q", help) + } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/nope")); !strings.Contains(reply, "Unknown command /nope") { + t.Fatalf("unknown = %q", reply) + } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "status please")); !strings.Contains(reply, "/help") { + t.Fatalf("plain text without handler = %q", reply) + } + r.Text = func(_ context.Context, req Request) string { return "text:" + req.Args } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "status please")); reply != "text:status please" { + t.Fatalf("plain text handler = %q", reply) + } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/")); reply != "text:/" { + t.Fatalf("bare slash = %q", reply) + } +} + +func TestNormalizeAllowedChats(t *testing.T) { + tr, _ := Get(KindTelegram) + got, err := NormalizeAllowedChats(tr, []string{" 123 ", "", "-1001234567890", "123"}) + if err != nil || strings.Join(got, ",") != "123,-1001234567890" { + t.Fatalf("got %v %v", got, err) + } + if _, err := NormalizeAllowedChats(tr, []string{"@channel"}); err == nil { + t.Fatal("a username must be refused: updates carry numeric ids") + } + many := make([]string, MaxAllowedChats+1) + for i := range many { + many[i] = itoa(i + 1) + } + if _, err := NormalizeAllowedChats(tr, many); err == nil { + t.Fatal("over the cap must be refused") + } +} + +func itoa(i int) string { + if i == 0 { + return "0" + } + var b []byte + for ; i > 0; i /= 10 { + b = append([]byte{byte('0' + i%10)}, b...) + } + return string(b) +} diff --git a/chatbridge/telegram.go b/chatbridge/telegram.go new file mode 100644 index 00000000..dd602158 --- /dev/null +++ b/chatbridge/telegram.go @@ -0,0 +1,265 @@ +package chatbridge + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/Autumn-27/artex/notify" +) + +// KindTelegram is the Telegram Bot API transport. +const KindTelegram = "telegram" + +const ( + telegramDefaultBase = "https://api.telegram.org" + // telegramPollWindow is the long-poll timeout sent to getUpdates. The + // client timeout must stay above it, or every idle poll ends as an error. + telegramPollWindow = 25 * time.Second + telegramClientWindow = telegramPollWindow + 15*time.Second + // telegramPollLimit caps one getUpdates batch. + telegramPollLimit = 50 + // telegramTextLimit is the Bot API message limit (4096 characters). The + // reply is cut a little earlier to leave room for the ellipsis. + telegramTextLimit = 4000 + // telegramBodyLimit caps a response body; 50 text updates fit well inside. + telegramBodyLimit = 1 << 20 +) + +// telegramClient is shared by every Telegram call of the bridge. It carries +// notify's dial guard and refuses cross-host redirects: the bot token is in +// the URL path, so following a redirect to another host would hand it over. +var telegramClient = notify.NewGuardedClient(telegramClientWindow) + +// A bot token is ":". Rejecting anything else keeps a pasted +// value with a slash or whitespace from changing the request path. +var telegramTokenRe = regexp.MustCompile(`^[0-9]{1,20}:[A-Za-z0-9_-]{20,100}$`) + +// Chat ids are signed integers; groups and channels are negative. +var telegramChatIDRe = regexp.MustCompile(`^-?[0-9]{1,20}$`) + +type telegramTransport struct{} + +func (telegramTransport) Kind() string { return KindTelegram } + +// The bot token is the whole credential. base_url decides where it is sent, so +// changing base_url requires entering the token again. +func (telegramTransport) SecretKeys() []string { return []string{"bot_token"} } +func (telegramTransport) DestinationKeys() []string { return []string{"base_url"} } + +func (telegramTransport) Validate(cfg map[string]any) error { + token := cfgString(cfg, "bot_token") + if token == "" { + return errors.New("missing bot token") + } + if !telegramTokenRe.MatchString(token) { + return errors.New(`the bot token should look like "123456789:AA…" as BotFather shows it`) + } + if base := cfgString(cfg, "base_url"); base != "" { + if err := notify.ValidateEndpointURL(base); err != nil { + return fmt.Errorf("invalid API URL: %w", err) + } + } + return nil +} + +func (telegramTransport) ValidateChatID(id string) error { + if !telegramChatIDRe.MatchString(id) { + return errors.New("a Telegram chat id is a number, for example 123456789 or -1001234567890") + } + return nil +} + +type telegramUser struct { + ID int64 `json:"id"` + IsBot bool `json:"is_bot"` + UserName string `json:"username"` + FirstName string `json:"first_name"` +} + +type telegramUpdate struct { + UpdateID int64 `json:"update_id"` + Message *struct { + Date int64 `json:"date"` + Chat struct { + ID int64 `json:"id"` + Type string `json:"type"` + } `json:"chat"` + From *telegramUser `json:"from"` + Text string `json:"text"` + } `json:"message"` +} + +type telegramResponse[T any] struct { + OK bool `json:"ok"` + Result T `json:"result"` + ErrorCode int `json:"error_code"` + Description string `json:"description"` + Parameters *struct { + RetryAfter int `json:"retry_after"` + } `json:"parameters"` +} + +func (t telegramTransport) Identity(ctx context.Context, cfg map[string]any) (Identity, error) { + var me telegramUser + if err := t.call(ctx, cfg, "getMe", nil, &me); err != nil { + return Identity{}, err + } + return Identity{ID: strconv.FormatInt(me.ID, 10), UserName: me.UserName, Name: me.FirstName}, nil +} + +func (t telegramTransport) Poll(ctx context.Context, cfg map[string]any, offset int64) ([]Update, error) { + req := map[string]any{ + "timeout": int(telegramPollWindow / time.Second), + "limit": telegramPollLimit, + "allowed_updates": []string{"message"}, + } + if offset > 0 { + req["offset"] = offset + } + var raw []telegramUpdate + if err := t.call(ctx, cfg, "getUpdates", req, &raw); err != nil { + return nil, err + } + out := make([]Update, 0, len(raw)) + for _, r := range raw { + u := Update{ID: r.UpdateID} + if m := r.Message; m != nil { + u.ChatID = strconv.FormatInt(m.Chat.ID, 10) + u.ChatType = m.Chat.Type + u.Text = m.Text + u.Date = time.Unix(m.Date, 0) + if m.From != nil { + u.UserID = strconv.FormatInt(m.From.ID, 10) + u.UserName = m.From.UserName + u.FromBot = m.From.IsBot + } + } + // Updates without a message still advance the cursor; the Router + // ignores them because they carry no text. + out = append(out, u) + } + return out, nil +} + +func (t telegramTransport) Send(ctx context.Context, cfg map[string]any, chatID, text string) error { + if err := t.ValidateChatID(chatID); err != nil { + return err + } + body := map[string]any{ + "chat_id": chatID, + "text": truncateRunes(text, telegramTextLimit), + // Plain text on purpose: no parse_mode, so agent output can never be + // rejected for a stray markup character or render as a link. + "link_preview_options": map[string]any{"is_disabled": true}, + } + return t.call(ctx, cfg, "sendMessage", body, nil) +} + +// call performs one Bot API method. Every error it returns is safe to log and +// to show in the UI: it never contains the request URL, and so never the token. +func (t telegramTransport) call(ctx context.Context, cfg map[string]any, method string, payload, result any) error { + if err := t.Validate(cfg); err != nil { + return err + } + base := strings.TrimRight(cfgString(cfg, "base_url"), "/") + if base == "" { + base = telegramDefaultBase + } + endpoint := base + "/bot" + cfgString(cfg, "bot_token") + "/" + method + + var body io.Reader + if payload != nil { + raw, err := json.Marshal(payload) + if err != nil { + return fmt.Errorf("telegram %s: build request: %w", method, err) + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body) + if err != nil { + return fmt.Errorf("telegram %s: invalid API address", method) + } + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := telegramClient.Do(req) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return fmt.Errorf("telegram %s: %s", method, notify.RedactTransportError(err)) + } + defer resp.Body.Close() + raw, err := io.ReadAll(io.LimitReader(resp.Body, telegramBodyLimit)) + if err != nil { + return fmt.Errorf("telegram %s: read response: %w", method, err) + } + + var env telegramResponse[json.RawMessage] + if err := json.Unmarshal(raw, &env); err != nil { + return fmt.Errorf("telegram %s: HTTP %d, response is not Bot API JSON: %s", method, resp.StatusCode, notify.OneLine(string(raw), 120)) + } + if !env.OK { + return telegramError(method, resp.StatusCode, env) + } + if result == nil { + return nil + } + if err := json.Unmarshal(env.Result, result); err != nil { + return fmt.Errorf("telegram %s: unexpected result: %w", method, err) + } + return nil +} + +// RetryAfterError asks the caller to wait before the next call. +type RetryAfterError struct { + After time.Duration + Msg string +} + +func (e *RetryAfterError) Error() string { return e.Msg } + +func telegramError(method string, status int, env telegramResponse[json.RawMessage]) error { + code := env.ErrorCode + if code == 0 { + code = status + } + desc := notify.OneLine(env.Description, 200) + switch code { + case http.StatusUnauthorized, http.StatusNotFound: + return fmt.Errorf("telegram %s: the bot token was rejected (%d %s)", method, code, desc) + case http.StatusConflict: + return fmt.Errorf("telegram %s: another poller or a webhook is using this bot token (%s); give ARTEX its own bot or remove the webhook", method, desc) + case http.StatusTooManyRequests: + after := 5 * time.Second + if env.Parameters != nil && env.Parameters.RetryAfter > 0 { + after = time.Duration(env.Parameters.RetryAfter) * time.Second + } + return &RetryAfterError{After: after, Msg: fmt.Sprintf("telegram %s: rate limited, retry after %s", method, after)} + } + return fmt.Errorf("telegram %s: %d %s", method, code, desc) +} + +func cfgString(cfg map[string]any, key string) string { + s, _ := cfg[key].(string) + return strings.TrimSpace(s) +} + +// truncateRunes cuts s to at most n runes, marking the cut. +func truncateRunes(s string, n int) string { + if utf8.RuneCountInString(s) <= n { + return s + } + r := []rune(s) + return string(r[:n-1]) + "…" +} diff --git a/chatbridge/telegram_test.go b/chatbridge/telegram_test.go new file mode 100644 index 00000000..8973c398 --- /dev/null +++ b/chatbridge/telegram_test.go @@ -0,0 +1,222 @@ +package chatbridge + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Autumn-27/artex/notify" +) + +const testToken = "123456789:AAtest_token-abcdefghijklmnop" + +// fakeTelegram records calls and answers from a per-method table. +type fakeTelegram struct { + mu sync.Mutex + calls []string + bodies map[string]map[string]any + answers map[string]func(w http.ResponseWriter) +} + +func newFakeTelegram(t *testing.T) (*fakeTelegram, map[string]any) { + t.Helper() + t.Setenv(notify.AllowLocalTargetsEnv, "1") // httptest listens on 127.0.0.1 + f := &fakeTelegram{bodies: map[string]map[string]any{}, answers: map[string]func(http.ResponseWriter){}} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + prefix := "/bot" + testToken + "/" + if !strings.HasPrefix(r.URL.Path, prefix) { + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, `{"ok":false,"error_code":404,"description":"Not Found"}`) + return + } + method := strings.TrimPrefix(r.URL.Path, prefix) + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + f.mu.Lock() + f.calls = append(f.calls, method) + f.bodies[method] = body + answer := f.answers[method] + f.mu.Unlock() + if answer == nil { + _, _ = io.WriteString(w, `{"ok":true,"result":true}`) + return + } + answer(w) + })) + t.Cleanup(srv.Close) + return f, map[string]any{"bot_token": testToken, "base_url": srv.URL} +} + +func (f *fakeTelegram) on(method, body string, status int) { + f.mu.Lock() + defer f.mu.Unlock() + f.answers[method] = func(w http.ResponseWriter) { + w.WriteHeader(status) + _, _ = io.WriteString(w, body) + } +} + +func TestTelegramValidate(t *testing.T) { + tr := telegramTransport{} + cases := map[string]map[string]any{ + "missing token": {}, + "malformed token": {"bot_token": "not-a-token"}, + "path injection": {"bot_token": "123:abcdefghijklmnopqrstuvwxyz/../x"}, + "bad base url": {"bot_token": testToken, "base_url": "ftp://example.com"}, + } + for name, cfg := range cases { + if err := tr.Validate(cfg); err == nil { + t.Errorf("%s: want error", name) + } + } + if err := tr.Validate(map[string]any{"bot_token": testToken}); err != nil { + t.Fatalf("valid config refused: %v", err) + } +} + +func TestTelegramPollParsesAndSendsOffset(t *testing.T) { + f, cfg := newFakeTelegram(t) + f.on("getUpdates", `{"ok":true,"result":[ + {"update_id":41,"message":{"date":1763726400,"chat":{"id":-100123,"type":"group"},"from":{"id":7,"is_bot":false,"username":"op"},"text":"/help"}}, + {"update_id":42,"my_chat_member":{}} + ]}`, 200) + got, err := telegramTransport{}.Poll(context.Background(), cfg, 41) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 { + t.Fatalf("want 2 updates (the second only advances the cursor), got %d", len(got)) + } + u := got[0] + if u.ID != 41 || u.ChatID != "-100123" || u.ChatType != "group" || u.UserID != "7" || u.UserName != "op" || u.Text != "/help" || u.FromBot { + t.Fatalf("update = %+v", u) + } + if !u.Date.Equal(time.Unix(1763726400, 0)) { + t.Fatalf("date = %v", u.Date) + } + if got[1].ID != 42 || got[1].Text != "" { + t.Fatalf("non-message update = %+v", got[1]) + } + body := f.bodies["getUpdates"] + if body["offset"] != float64(41) || body["timeout"] != float64(25) { + t.Fatalf("getUpdates body = %v", body) + } + if au, _ := body["allowed_updates"].([]any); len(au) != 1 || au[0] != "message" { + t.Fatalf("allowed_updates = %v", body["allowed_updates"]) + } +} + +func TestTelegramSendIsPlainTextAndTruncated(t *testing.T) { + f, cfg := newFakeTelegram(t) + long := strings.Repeat("é", telegramTextLimit+50) + if err := (telegramTransport{}).Send(context.Background(), cfg, "100", long); err != nil { + t.Fatal(err) + } + body := f.bodies["sendMessage"] + if _, ok := body["parse_mode"]; ok { + t.Fatal("replies must be sent as plain text") + } + text, _ := body["text"].(string) + if n := len([]rune(text)); n != telegramTextLimit || !strings.HasSuffix(text, "…") { + t.Fatalf("text has %d runes, suffix %q", n, text[len(text)-3:]) + } + if body["chat_id"] != "100" { + t.Fatalf("chat_id = %v", body["chat_id"]) + } + if err := (telegramTransport{}).Send(context.Background(), cfg, "@someone", "x"); err == nil { + t.Fatal("a non-numeric chat id must be refused") + } +} + +func TestTelegramIdentity(t *testing.T) { + f, cfg := newFakeTelegram(t) + f.on("getMe", `{"ok":true,"result":{"id":123456789,"is_bot":true,"username":"artex_bot","first_name":"ARTEX"}}`, 200) + id, err := telegramTransport{}.Identity(context.Background(), cfg) + if err != nil || id.UserName != "artex_bot" || id.ID != "123456789" || id.Name != "ARTEX" { + t.Fatalf("identity = %+v, %v", id, err) + } +} + +func TestTelegramErrorsNeverCarryTheToken(t *testing.T) { + f, cfg := newFakeTelegram(t) + f.on("getMe", `{"ok":false,"error_code":401,"description":"Unauthorized"}`, 401) + _, err := telegramTransport{}.Identity(context.Background(), cfg) + if err == nil || !strings.Contains(err.Error(), "token was rejected") { + t.Fatalf("401: %v", err) + } + f.on("getUpdates", `{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request"}`, 409) + _, err = telegramTransport{}.Poll(context.Background(), cfg, 0) + if err == nil || !strings.Contains(err.Error(), "another poller") { + t.Fatalf("409: %v", err) + } + f.on("sendMessage", `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":7}}`, 429) + err = telegramTransport{}.Send(context.Background(), cfg, "1", "x") + var ra *RetryAfterError + if !errors.As(err, &ra) || ra.After != 7*time.Second { + t.Fatalf("429: %v", err) + } + + // A transport failure: nothing listens on this address. The error must + // name the host but never the path that carries the token. + dead := map[string]any{"bot_token": testToken, "base_url": "http://127.0.0.1:1"} + _, err = telegramTransport{}.Identity(context.Background(), dead) + if err == nil { + t.Fatal("want a dial error") + } + for _, e := range []error{err} { + if strings.Contains(e.Error(), "AAtest_token") || strings.Contains(e.Error(), "/bot") { + t.Fatalf("error leaks the token: %v", e) + } + } +} + +func TestTelegramPollHonoursCancel(t *testing.T) { + f, cfg := newFakeTelegram(t) + release := make(chan struct{}) + f.mu.Lock() + f.answers["getUpdates"] = func(w http.ResponseWriter) { <-release } + f.mu.Unlock() + defer close(release) + ctx, cancel := context.WithCancel(context.Background()) + go func() { time.Sleep(50 * time.Millisecond); cancel() }() + start := time.Now() + _, err := telegramTransport{}.Poll(ctx, cfg, 0) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } + if time.Since(start) > 5*time.Second { + t.Fatal("cancel did not interrupt the long poll") + } +} + +func TestConfigMaskAndPrepare(t *testing.T) { + stored := map[string]any{"bot_token": testToken} + masked := MaskConfig(KindTelegram, stored) + if s, _ := masked["bot_token"].(string); !notify.IsMasked(s) || strings.Contains(s, "AAtest") { + t.Fatalf("masked = %v", masked) + } + // Masked value sent back keeps the stored token. + got, err := PrepareConfigUpdate(KindTelegram, stored, map[string]any{"bot_token": masked["bot_token"]}) + if err != nil || got["bot_token"] != testToken { + t.Fatalf("keep: %v %v", got, err) + } + // Changing base_url with a masked token is refused. + if _, err := PrepareConfigUpdate(KindTelegram, stored, map[string]any{"bot_token": masked["bot_token"], "base_url": "https://tg.example.com"}); err == nil { + t.Fatal("destination change with a masked token must be refused") + } + // ...and accepted with the token in clear. + got, err = PrepareConfigUpdate(KindTelegram, stored, map[string]any{"bot_token": testToken, "base_url": "https://tg.example.com"}) + if err != nil || got["base_url"] != "https://tg.example.com" { + t.Fatalf("destination change: %v %v", got, err) + } + if m := MaskConfig("nope", stored); len(m) != 0 { + t.Fatalf("unknown kind must mask to empty, got %v", m) + } +} diff --git a/db/chat_bridges.go b/db/chat_bridges.go new file mode 100644 index 00000000..9461d6bf --- /dev/null +++ b/db/chat_bridges.go @@ -0,0 +1,105 @@ +package db + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "time" +) + +// ChatBridge is the stored configuration of one inbound chat bridge +// (migration 0015). Config is the decrypted JSON; parsing it is left to +// package chatbridge, like notification channel configs. +type ChatBridge struct { + ID int64 `json:"id"` + Kind string `json:"kind"` + Enabled bool `json:"enabled"` + Config json.RawMessage `json:"config"` + AllowedChats []string `json:"allowed_chats"` + PollOffset int64 `json:"poll_offset"` + // ConfigVersion grows on every save; SetChatBridgeOffset only writes for + // the version the poller read. + ConfigVersion int64 `json:"config_version"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// ErrChatBridgeNotFound is returned when no row exists for a kind. +var ErrChatBridgeNotFound = errors.New("chat bridge not configured") + +const chatBridgeCols = `id, kind, enabled, config, allowed_chats, poll_offset, config_version, created_at, updated_at` + +func scanChatBridge(sc interface{ Scan(...any) error }) (*ChatBridge, error) { + var b ChatBridge + var cfg, allowed string + if err := sc.Scan(&b.ID, &b.Kind, &b.Enabled, &cfg, &allowed, &b.PollOffset, &b.ConfigVersion, &b.CreatedAt, &b.UpdatedAt); err != nil { + return nil, err + } + plain, err := openSecret(colChatBridgeConfig, cfg) + if err != nil { + return nil, err + } + b.Config = json.RawMessage(plain) + if err := json.Unmarshal([]byte(allowed), &b.AllowedChats); err != nil { + return nil, err + } + if b.AllowedChats == nil { + b.AllowedChats = []string{} + } + return &b, nil +} + +// ChatBridgeByKind returns the bridge of a transport kind. +func (d *DB) ChatBridgeByKind(ctx context.Context, kind string) (*ChatBridge, error) { + row := d.QueryRowContext(ctx, `SELECT `+chatBridgeCols+` FROM chat_bridges WHERE kind=$1`, kind) + b, err := scanChatBridge(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrChatBridgeNotFound + } + return b, err +} + +// SaveChatBridge creates or replaces the configuration of b.Kind and bumps its +// config version. resetOffset clears the update cursor in the same statement; +// the caller sets it when the bot token changed, because update ids are per +// bot and the old cursor means nothing to the new one. +func (d *DB) SaveChatBridge(ctx context.Context, b *ChatBridge, resetOffset bool) (*ChatBridge, error) { + if b.Config == nil { + b.Config = json.RawMessage(`{}`) + } + if b.AllowedChats == nil { + b.AllowedChats = []string{} + } + cfg, err := sealSecret(colChatBridgeConfig, string(b.Config)) + if err != nil { + return nil, err + } + allowed, err := json.Marshal(b.AllowedChats) + if err != nil { + return nil, err + } + row := d.QueryRowContext(ctx, `INSERT INTO chat_bridges(kind, enabled, config, allowed_chats) +VALUES($1, $2, $3::jsonb, $4::jsonb) +ON CONFLICT (kind) DO UPDATE SET + enabled=EXCLUDED.enabled, config=EXCLUDED.config, allowed_chats=EXCLUDED.allowed_chats, + poll_offset=CASE WHEN $5 THEN 0 ELSE chat_bridges.poll_offset END, + config_version=chat_bridges.config_version+1, updated_at=NOW() +RETURNING `+chatBridgeCols, b.Kind, b.Enabled, cfg, string(allowed), resetOffset) + return scanChatBridge(row) +} + +// SetChatBridgeOffset records the transport cursor for the configuration +// version the poller read. It only moves forward, and it does nothing once +// the configuration was saved again, so neither a slow writer nor a poller +// of a replaced token can move the cursor of the current bot. It reports +// whether the cursor was written. +func (d *DB) SetChatBridgeOffset(ctx context.Context, kind string, version, offset int64) (bool, error) { + res, err := d.ExecContext(ctx, `UPDATE chat_bridges SET poll_offset=$3 +WHERE kind=$1 AND config_version=$2 AND poll_offset < $3`, kind, version, offset) + if err != nil { + return false, err + } + n, _ := res.RowsAffected() + return n > 0, nil +} diff --git a/db/chat_bridges_test.go b/db/chat_bridges_test.go new file mode 100644 index 00000000..ee1541e8 --- /dev/null +++ b/db/chat_bridges_test.go @@ -0,0 +1,79 @@ +package db + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestChatBridgeSaveSealedAndOffset(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + t.Cleanup(func() { _ = d.Close() }) + ctx := context.Background() + const kind = "t-bridge" + t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) }) + + if _, err := d.ChatBridgeByKind(ctx, kind); !errors.Is(err, ErrChatBridgeNotFound) { + t.Fatalf("missing row: err = %v", err) + } + + const token = "123456789:AAsecret-bot-token-value" + b, err := d.SaveChatBridge(ctx, &ChatBridge{ + Kind: kind, + Enabled: true, + Config: json.RawMessage(`{"bot_token":"` + token + `"}`), + AllowedChats: []string{"100", "-1001"}, + }, false) + if err != nil { + t.Fatalf("SaveChatBridge: %v", err) + } + if !b.Enabled || b.PollOffset != 0 || b.ConfigVersion != 1 || strings.Join(b.AllowedChats, ",") != "100,-1001" || !strings.Contains(string(b.Config), token) { + t.Fatalf("saved = %+v (config %s)", b, b.Config) + } + + // The token never sits in clear in the table. + var raw string + if err := d.QueryRow(`SELECT config::text FROM chat_bridges WHERE kind=$1`, kind).Scan(&raw); err != nil { + t.Fatal(err) + } + if strings.Contains(raw, "AAsecret") || !strings.Contains(raw, sealedJSONKey) { + t.Fatalf("chat_bridges.config is not sealed at rest: %q", raw) + } + + // The cursor only moves forward. + if ok, err := d.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, 42); err != nil || !ok { + t.Fatalf("set 42: %v %v", ok, err) + } + if ok, err := d.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, 7); err != nil || ok { + t.Fatalf("rewind to 7 must be a no-op: %v %v", ok, err) + } + got, err := d.ChatBridgeByKind(ctx, kind) + if err != nil || got.PollOffset != 42 || !got.UpdatedAt.Equal(b.UpdatedAt) { + t.Fatalf("after cursor writes = %+v, %v; want offset 42 and updated_at unchanged", got, err) + } + + // Saving again updates in place, keeps the cursor and bumps the version. + b2, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: false, Config: json.RawMessage(`{"bot_token":"` + token + `"}`)}, false) + if err != nil { + t.Fatal(err) + } + if b2.ID != b.ID || b2.Enabled || b2.PollOffset != 42 || b2.ConfigVersion != 2 || len(b2.AllowedChats) != 0 { + t.Fatalf("update = %+v", b2) + } + + // A poller still holding version 1 cannot move the cursor any more. + if ok, err := d.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, 99); err != nil || ok { + t.Fatalf("stale version write must be a no-op: %v %v", ok, err) + } + + // A token change clears the cursor in the same save. + b3, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Config: json.RawMessage(`{"bot_token":"987654321:AAother-bot-token-value"}`)}, true) + if err != nil || b3.PollOffset != 0 || b3.ConfigVersion != 3 { + t.Fatalf("reset save = %+v, %v", b3, err) + } +} diff --git a/db/migrate_test.go b/db/migrate_test.go index bdbd6a42..d346638b 100644 --- a/db/migrate_test.go +++ b/db/migrate_test.go @@ -123,7 +123,7 @@ func readApplied(t *testing.T, d *DB) []appliedMigration { // embedded migration is recorded with the SHA-256 of its file. func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration { t.Helper() - for _, table := range []string{"llm_records", "llm_usage", "llm_context", "traffic_tamper_hooks", "traffic_tamper_hook_versions"} { + for _, table := range []string{"llm_records", "llm_usage", "llm_context", "traffic_tamper_hooks", "traffic_tamper_hook_versions", "chat_bridges"} { var exists bool if err := d.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, table).Scan(&exists); err != nil { t.Fatal(err) @@ -140,9 +140,10 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration { {5, "0005_traffic_rewrite_rules.sql"}, {6, "0006_activity_outbox.sql"}, {7, "0007_finding_report_state.sql"}, {8, "0008_traffic_evidence_rewrite_flag.sql"}, {9, "0009_llm_context.sql"}, {10, "0010_dashboard_usage_indexes.sql"}, {11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"}, - {13, "0013_lesson_evidence_history.sql"}, {14, "0014_bedrock_gateway_profiles.sql"}} + {13, "0013_lesson_evidence_history.sql"}, {14, "0014_bedrock_gateway_profiles.sql"}, + {15, "0015_chat_bridges.sql"}} if len(applied) != len(want) { - t.Fatalf("schema_migrations = %+v, want versions 1 to 14", applied) + t.Fatalf("schema_migrations = %+v, want versions 1 to 15", applied) } for i, w := range want { content, err := fs.ReadFile(migrationsFS(), w.name) diff --git a/db/migrations/0015_chat_bridges.sql b/db/migrations/0015_chat_bridges.sql new file mode 100644 index 00000000..b7ca83da --- /dev/null +++ b/db/migrations/0015_chat_bridges.sql @@ -0,0 +1,25 @@ +-- Inbound chat bridges (issue #5): an operator drives ARTEX from a chat app. +-- One row per transport kind ('telegram' first). Global configuration: not +-- part of a task archive. +-- +-- config is sealed at rest by db/secrets.go (it holds the bot token) and +-- masked in API responses. allowed_chats is the mandatory allowlist of chat +-- ids, a JSON array of strings; the server refuses to enable a bridge while +-- it is empty. poll_offset is the transport's update cursor, committed before +-- an update is acted on so a restart never replays a command. +-- +-- config_version grows on every save. The poller writes its cursor only for +-- the version it read, so a cursor of the old bot can never land on a row +-- whose token was just replaced. updated_at is the time of the last save, +-- set by SaveChatBridge rather than a trigger, so cursor writes leave it alone. +CREATE TABLE IF NOT EXISTS chat_bridges ( + id BIGSERIAL PRIMARY KEY, + kind TEXT NOT NULL UNIQUE, + enabled BOOLEAN NOT NULL DEFAULT false, + config JSONB NOT NULL DEFAULT '{}'::jsonb, + allowed_chats JSONB NOT NULL DEFAULT '[]'::jsonb, + poll_offset BIGINT NOT NULL DEFAULT 0, + config_version BIGINT NOT NULL DEFAULT 1, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); diff --git a/db/secrets.go b/db/secrets.go index 2a47e58a..0c15fa8b 100644 --- a/db/secrets.go +++ b/db/secrets.go @@ -83,7 +83,9 @@ var ( colMCPEnv = secretColumn{"mcp_servers", "env", true, ""} colCredPass = secretColumn{"task_credentials", "password", false, ""} colNotifConfig = secretColumn{"notification_channels", "config", true, ""} - colToolExec = secretColumn{"tools", "exec", true, ""} // system=false rows: headers, proxy, body, code, command + // Inbound chat bridges: the config carries the bot token. + colChatBridgeConfig = secretColumn{"chat_bridges", "config", true, ""} + colToolExec = secretColumn{"tools", "exec", true, ""} // system=false rows: headers, proxy, body, code, command // Evidence head blocks carry the captured Cookie and Authorization headers. colEvReqHead = secretColumn{"traffic_evidence_snapshots", "req_head", false, ""} colEvRespHead = secretColumn{"traffic_evidence_snapshots", "resp_head", false, ""} @@ -96,7 +98,7 @@ var ( colHookSource = secretColumn{"traffic_tamper_hooks", "source", false, ""} colHookVerMatchers = secretColumn{"traffic_tamper_hook_versions", "matchers", true, ""} colHookVerSource = secretColumn{"traffic_tamper_hook_versions", "source", false, ""} - secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) + secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colChatBridgeConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) ) // secretSettingKeys are the settings stored encrypted, AAD "settings.". diff --git a/docs/chat-bridge.md b/docs/chat-bridge.md new file mode 100644 index 00000000..2f164e0e --- /dev/null +++ b/docs/chat-bridge.md @@ -0,0 +1,63 @@ +# Chat Bot (Inbound Chat Bridge) + +The chat bot lets an operator talk to ARTEX from a chat app instead of the web UI. Telegram is the +first transport. This page describes the bridge core: connecting a bot, the chat allowlist and how +updates are processed. Task commands, the main-agent conversation and remote approvals build on it +([issue #5](https://github.com/BaaRai/ARTEX/issues/5)). + +Outbound notifications (pushing findings to a chat) are a separate feature under +**System → Notifications** and keep working without the bot. + +--- + +## Setup + +1. Create a bot with [@BotFather](https://t.me/BotFather) and copy its token. Give ARTEX a bot of + its own: Telegram allows one consumer per token, so a token already used by another poller or by + a webhook fails with a conflict error. +2. Open **System → Chat bot**, paste the token, switch the bot on and save. **Test connection** asks + Telegram which bot the token belongs to; it sends no message. The status card shows **Online** + and the bot's username once it is polling. +3. With the allowlist still empty the bot serves no chat. From each chat you want to use (a private + chat or a group), send the bot any message: it answers once with a refusal that names the chat ID. +4. Add those chat IDs to **Allowed chat IDs** and save. The change applies at once. +5. Send `/help` to see the commands. `/whoami` shows the chat ID and your user ID. + +## Security model + +- **Only allowlisted chats are served.** A chat that is not listed gets one refusal line, naming its + chat ID, and is then ignored for the life of the process. An empty allowlist serves no chat at all; + that is the state a new bot starts in while you collect chat IDs. Allowing a group allows every + member of that group. +- **No inbound port.** The bot uses long polling (`getUpdates`) over outbound HTTPS. +- **The token is a secret.** It is encrypted at rest with `keys/secret.key` like other stored + secrets, shown masked in the UI and API, and never written to logs or error messages (errors keep + only the scheme and host of the API address). Changing the API address requires entering the + token again, so a stored token is never sent to a new host. +- **Same network guard as notifications.** Calls refuse loopback and link-local addresses (including + cloud metadata) unless `ARTEX_NOTIFY_ALLOW_LOCAL=1`, and never follow a cross-host redirect. +- **No replays.** The update cursor is committed before a batch is acted on, so a crash loses a + batch rather than running it twice. Messages older than two minutes when they reach ARTEX (for + example a backlog queued while ARTEX was down) are dropped and logged instead of executed. +- **Message text is not logged.** Logs (tag `[tgbot]`) record the chat, the sender and the decision. + +## Configuration changes + +Saving the form takes effect immediately, without a restart: a poll in progress is interrupted and +the new configuration is read. A new token clears the update cursor, because Telegram update IDs +are per bot. A batch fetched under a configuration that was replaced during the poll is dropped. + +## API + +All routes require the administrator JWT. + +| Method | Path | Purpose | +| --- | --- | --- | +| `GET` | `/api/chat-bridges` | Every transport with its masked configuration, allowlist and live status | +| `PUT` | `/api/chat-bridges/{kind}` | Save `enabled`, `config` and `allowed_chats`; omitted fields keep their stored value | +| `POST` | `/api/chat-bridges/{kind}/test` | Check the stored token and return the bot identity | + +`config` follows the notification channel convention: a masked value sent back unchanged keeps the +stored secret, and an empty string clears a field. Telegram's fields are `bot_token` and the +optional `base_url` (for a self-hosted Bot API server). The live `status.state` is `off`, +`connecting`, `online` or `error`, with `last_error` when it fails. diff --git a/notify/http.go b/notify/http.go index 8188af62..5056cbf1 100644 --- a/notify/http.go +++ b/notify/http.go @@ -299,3 +299,28 @@ func redactURLsInText(s string) string { } return b.String() } + +// The helpers below let the inbound chat bridge (package chatbridge) talk to the +// same chat platforms with the same protections as delivery: the dial guard, +// the redirect policy and the credential-safe error text. They are wrappers, +// not copies, so a fix to the guard reaches both directions at once. + +// NewGuardedClient returns a client with the delivery dial guard and redirect +// policy and its own timeout. Long polling needs a timeout longer than the +// 15 seconds a delivery gets. +func NewGuardedClient(timeout time.Duration) *http.Client { + return &http.Client{ + Timeout: timeout, + Transport: notifyTransport, + CheckRedirect: httpClient.CheckRedirect, + } +} + +// RedactTransportError returns the text of a transport error with any URL +// reduced to scheme and host, so a credential carried in the URL never +// reaches a log line or an API response. +func RedactTransportError(err error) string { return redactTransportError(err) } + +// ValidateEndpointURL checks a configured platform address the way the +// channels do: http(s) only, a host, and no loopback or link-local literal. +func ValidateEndpointURL(raw string) error { return validateHTTPURL(raw) } diff --git a/server/chatbridge.go b/server/chatbridge.go new file mode 100644 index 00000000..6de9ee29 --- /dev/null +++ b/server/chatbridge.go @@ -0,0 +1,351 @@ +package server + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log" + "sync" + "time" + + "github.com/Autumn-27/artex/chatbridge" + "github.com/Autumn-27/artex/db" +) + +// The inbound chat bridge (issue #5): one long-poll loop per registered +// transport kind, started by server.New. The loop re-reads its row on every +// round, so saving the configuration (a new token, a new allowlist, enabling +// or disabling) takes effect without a restart; Reload interrupts a poll that +// is waiting so the change applies at once instead of after the poll window. +// +// Order of work for a batch: commit the cursor, then act. If ARTEX crashes in +// between, the updates of that batch are lost rather than executed twice. For +// an operator console that is the safe side: a lost "/pause" is retyped, a +// replayed one acts on a task the operator may have resumed since. + +const ( + // chatBridgeIdleWait is how long a disabled or unconfigured bridge sleeps + // before it looks at its row again. Saving the row wakes it earlier. + chatBridgeIdleWait = 30 * time.Second + chatBridgeMinRetry = 2 * time.Second + chatBridgeMaxRetry = time.Minute + chatBridgeSendWait = 15 * time.Second +) + +// chatBridgeStatus is the live state shown in the UI ("bot online"). +type chatBridgeStatus struct { + // State is off (disabled or not configured), connecting, online or error. + State string `json:"state"` + Bot *chatbridge.Identity `json:"bot,omitempty"` + LastError string `json:"last_error,omitempty"` + LastErrorAt *time.Time `json:"last_error_at,omitempty"` + LastPollAt *time.Time `json:"last_poll_at,omitempty"` + LastUpdateAt *time.Time `json:"last_update_at,omitempty"` +} + +type chatBridgeState struct { + wake chan struct{} + cancel context.CancelFunc // cancels the poll in flight; nil when none + status chatBridgeStatus + router *chatbridge.Router + sig string // hash of the config the router and identity were built for + retry time.Duration +} + +type chatBridgeRunner struct { + pg *db.DB + // transport resolves a kind; tests substitute a fake. + transport func(kind string) (chatbridge.Transport, bool) + // commands builds the command table of a bridge; the server's commands + // are added here as they land. + commands func(kind string) []chatbridge.Command + + mu sync.Mutex + state map[string]*chatBridgeState +} + +func newChatBridgeRunner(pg *db.DB) *chatBridgeRunner { + return &chatBridgeRunner{ + pg: pg, + transport: chatbridge.Get, + commands: defaultChatBridgeCommands, + state: map[string]*chatBridgeState{}, + } +} + +// defaultChatBridgeCommands is the command table. /help is built into the +// router. Task and approval commands follow in later changes. +func defaultChatBridgeCommands(string) []chatbridge.Command { + return []chatbridge.Command{{ + Name: "whoami", + Summary: "show this chat's ID and your user ID", + Run: func(_ context.Context, req chatbridge.Request) string { + return fmt.Sprintf("Chat ID: %s\nYour user ID: %s", req.ChatID, req.UserID) + }, + }} +} + +func (r *chatBridgeRunner) get(kind string) *chatBridgeState { + r.mu.Lock() + defer r.mu.Unlock() + st := r.state[kind] + if st == nil { + st = &chatBridgeState{wake: make(chan struct{}, 1), status: chatBridgeStatus{State: "off"}} + r.state[kind] = st + } + return st +} + +// Status returns a copy of a bridge's live state. +func (r *chatBridgeRunner) Status(kind string) chatBridgeStatus { + if r == nil { + return chatBridgeStatus{State: "off"} + } + st := r.get(kind) + r.mu.Lock() + defer r.mu.Unlock() + out := st.status + if out.Bot != nil { + b := *out.Bot + out.Bot = &b + } + return out +} + +// Reload makes the loop of kind re-read its configuration now, interrupting +// a poll in flight. +func (r *chatBridgeRunner) Reload(kind string) { + if r == nil { + return + } + st := r.get(kind) + r.mu.Lock() + if st.cancel != nil { + st.cancel() + } + st.sig = "" // rebuild identity and router from the saved row + st.retry = 0 + r.mu.Unlock() + select { + case st.wake <- struct{}{}: + default: + } +} + +// Run starts one loop per registered transport and returns when ctx ends. +func (r *chatBridgeRunner) Run(ctx context.Context) { + if r == nil || r.pg == nil { + return + } + var wg sync.WaitGroup + for _, kind := range chatbridge.Kinds() { + wg.Add(1) + go func(kind string) { + defer wg.Done() + r.loop(ctx, kind) + }(kind) + } + wg.Wait() +} + +func (r *chatBridgeRunner) loop(ctx context.Context, kind string) { + st := r.get(kind) + for ctx.Err() == nil { + wait := r.step(ctx, kind) + if wait <= 0 { + continue + } + t := time.NewTimer(wait) + select { + case <-ctx.Done(): + t.Stop() + return + case <-st.wake: + t.Stop() + case <-t.C: + } + } +} + +// step runs one round for kind: load the row, make sure the bot identity is +// known, poll once and act on the batch. It returns how long to wait before +// the next round (0 = poll again at once). +func (r *chatBridgeRunner) step(ctx context.Context, kind string) time.Duration { + tag := chatBridgeLogTag(kind) + tr, ok := r.transport(kind) + if !ok { + return chatBridgeIdleWait + } + b, err := r.pg.ChatBridgeByKind(ctx, kind) + if errors.Is(err, db.ErrChatBridgeNotFound) || (err == nil && !b.Enabled) { + r.setOff(kind) + return chatBridgeIdleWait + } + if err != nil { + return r.fail(kind, fmt.Errorf("load configuration: %w", err)) + } + var cfg map[string]any + if err := json.Unmarshal(b.Config, &cfg); err != nil { + return r.fail(kind, fmt.Errorf("configuration is not valid JSON: %w", err)) + } + if err := tr.Validate(cfg); err != nil { + return r.fail(kind, err) + } + + st := r.get(kind) + sig := configSig(b.Config) + r.mu.Lock() + known := st.sig == sig && st.router != nil + router := st.router + r.mu.Unlock() + if !known { + r.setState(kind, "connecting") + me, err := tr.Identity(ctx, cfg) + if err != nil { + return r.fail(kind, err) + } + router = &chatbridge.Router{BotUserName: me.UserName, Commands: r.commands(kind)} + r.mu.Lock() + st.sig, st.router = sig, router + st.status.Bot = &me + r.mu.Unlock() + log.Printf("%s online as @%s, %d allowed chat(s)", tag, me.UserName, len(b.AllowedChats)) + } + + pollCtx, cancel := context.WithCancel(ctx) + r.mu.Lock() + st.cancel = cancel + r.mu.Unlock() + updates, err := tr.Poll(pollCtx, cfg, b.PollOffset) + r.mu.Lock() + st.cancel = nil + r.mu.Unlock() + cancel() + if err != nil { + if ctx.Err() != nil { + return 0 + } + if errors.Is(err, context.Canceled) { + return 0 // Reload interrupted the poll: re-read the row at once + } + var ra *chatbridge.RetryAfterError + if errors.As(err, &ra) { + r.fail(kind, err) + return ra.After + } + return r.fail(kind, err) + } + now := time.Now() + r.mu.Lock() + st.status.State, st.status.LastPollAt, st.retry = "online", &now, 0 + r.mu.Unlock() + if len(updates) == 0 { + return 0 + } + + next := b.PollOffset + for _, u := range updates { + if u.ID >= next { + next = u.ID + 1 + } + } + wrote, err := r.pg.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, next) + if err != nil { + // Acting without a committed cursor would repeat the batch on the + // next poll. Skip it and try again. + return r.fail(kind, fmt.Errorf("save update cursor: %w", err)) + } + if !wrote { + // The configuration was saved while this poll ran (a new token, a + // new allowlist, or the bridge was disabled). The batch belongs to + // the old configuration: drop it and start over from the saved row. + log.Printf("%s configuration changed during a poll, %d update(s) dropped", tag, len(updates)) + return 0 + } + r.mu.Lock() + st.status.LastUpdateAt = &now + r.mu.Unlock() + + for _, u := range updates { + decision, reply := router.Route(ctx, kind, b.AllowedChats, u) + switch decision { + case chatbridge.DecisionRefused: + log.Printf("%s refused chat %s (user %s @%s): not in the allowlist", tag, u.ChatID, u.UserID, u.UserName) + case chatbridge.DecisionStale: + log.Printf("%s dropped a message from chat %s sent %s ago (older than %s)", tag, u.ChatID, now.Sub(u.Date).Round(time.Second), chatbridge.MaxUpdateAge) + case chatbridge.DecisionHandled: + // The message text is not logged: it can carry anything the + // operator typed, including target details. + log.Printf("%s handled a message in chat %s from user %s", tag, u.ChatID, u.UserID) + } + if reply == "" { + continue + } + sendCtx, cancelSend := context.WithTimeout(ctx, chatBridgeSendWait) + if err := tr.Send(sendCtx, cfg, u.ChatID, reply); err != nil { + log.Printf("%s reply to chat %s failed: %v", tag, u.ChatID, err) + } + cancelSend() + } + return 0 +} + +func (r *chatBridgeRunner) setOff(kind string) { + st := r.get(kind) + r.mu.Lock() + defer r.mu.Unlock() + st.status = chatBridgeStatus{State: "off"} + st.sig, st.router, st.retry = "", nil, 0 +} + +func (r *chatBridgeRunner) setState(kind, state string) { + st := r.get(kind) + r.mu.Lock() + st.status.State = state + r.mu.Unlock() +} + +// fail records an error and returns the backoff before the next round: +// doubling from chatBridgeMinRetry up to chatBridgeMaxRetry, reset by the +// next successful poll or a Reload. +func (r *chatBridgeRunner) fail(kind string, err error) time.Duration { + st := r.get(kind) + now := time.Now() + r.mu.Lock() + first := st.status.LastError != err.Error() + st.status.State = "error" + st.status.LastError = err.Error() + st.status.LastErrorAt = &now + if st.retry == 0 { + st.retry = chatBridgeMinRetry + } else if st.retry < chatBridgeMaxRetry { + st.retry *= 2 + if st.retry > chatBridgeMaxRetry { + st.retry = chatBridgeMaxRetry + } + } + wait := st.retry + r.mu.Unlock() + if first { + // Log a changed error once rather than on every retry. + log.Printf("%s %v (retrying in %s)", chatBridgeLogTag(kind), err, wait) + } + return wait +} + +func configSig(cfg []byte) string { + sum := sha256.Sum256(cfg) + return hex.EncodeToString(sum[:8]) +} + +// chatBridgeLogTag is the log prefix of a bridge: [tgbot] for Telegram as +// issue #5 proposes, [chatbridge:] for later transports. +func chatBridgeLogTag(kind string) string { + if kind == chatbridge.KindTelegram { + return "[tgbot]" + } + return "[chatbridge:" + kind + "]" +} diff --git a/server/chatbridge_api.go b/server/chatbridge_api.go new file mode 100644 index 00000000..67eabab7 --- /dev/null +++ b/server/chatbridge_api.go @@ -0,0 +1,215 @@ +package server + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/Autumn-27/artex/chatbridge" + "github.com/Autumn-27/artex/db" +) + +// HTTP API of the inbound chat bridges. Mounted behind requireAuth like the +// other admin APIs. A bridge is addressed by its transport kind; v1 has one +// bot per deployment, so there is one row per kind. + +// chatBridgeDTO is the external form of a bridge. Config is masked: the bot +// token comes back as a masked hint, and sending that hint back unchanged +// keeps the stored token (same convention as notification channels). +type chatBridgeDTO struct { + Kind string `json:"kind"` + Configured bool `json:"configured"` + Enabled bool `json:"enabled"` + Config map[string]any `json:"config"` + AllowedChats []string `json:"allowed_chats"` + SecretKeys []string `json:"secret_keys"` + Status chatBridgeStatus `json:"status"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +type chatBridgeRequest struct { + Enabled *bool `json:"enabled"` + Config map[string]any `json:"config"` + AllowedChats *[]string `json:"allowed_chats"` +} + +func (s *Server) chatBridgeDTO(kind string, b *db.ChatBridge) chatBridgeDTO { + tr, _ := chatbridge.Get(kind) + out := chatBridgeDTO{ + Kind: kind, + Config: map[string]any{}, + AllowedChats: []string{}, + SecretKeys: tr.SecretKeys(), + Status: s.chatBridges.Status(kind), + } + if b == nil { + return out + } + var cfg map[string]any + _ = json.Unmarshal(b.Config, &cfg) + out.Configured = true + out.Enabled = b.Enabled + out.Config = chatbridge.MaskConfig(kind, cfg) + out.AllowedChats = b.AllowedChats + updated := b.UpdatedAt + out.UpdatedAt = &updated + return out +} + +// chatBridgeKind reads and checks the {kind} path value. +func chatBridgeKind(w http.ResponseWriter, r *http.Request) (chatbridge.Transport, bool) { + kind := r.PathValue("kind") + tr, ok := chatbridge.Get(kind) + if !ok { + writeErr(w, 404, fmt.Sprintf("unknown chat bridge %q, available: %s", kind, strings.Join(chatbridge.Kinds(), ", "))) + return nil, false + } + return tr, true +} + +func (s *Server) chatBridgeList(w http.ResponseWriter, r *http.Request) { + pg := s.pg(w) + if pg == nil { + return + } + out := []chatBridgeDTO{} + for _, kind := range chatbridge.Kinds() { + b, err := pg.ChatBridgeByKind(r.Context(), kind) + if err != nil && !errors.Is(err, db.ErrChatBridgeNotFound) { + writeErr(w, 500, err.Error()) + return + } + out = append(out, s.chatBridgeDTO(kind, b)) + } + writeJSON(w, 200, out) +} + +func (s *Server) chatBridgeSave(w http.ResponseWriter, r *http.Request) { + pg := s.pg(w) + if pg == nil { + return + } + tr, ok := chatBridgeKind(w, r) + if !ok { + return + } + kind := tr.Kind() + var req chatBridgeRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&req); err != nil { + writeErr(w, 400, "request body is not valid JSON: "+err.Error()) + return + } + + stored, err := pg.ChatBridgeByKind(r.Context(), kind) + if err != nil && !errors.Is(err, db.ErrChatBridgeNotFound) { + writeErr(w, 500, err.Error()) + return + } + storedCfg := map[string]any{} + allowed := []string{} + enabled := false + if stored != nil { + _ = json.Unmarshal(stored.Config, &storedCfg) + allowed = stored.AllowedChats + enabled = stored.Enabled + } + + cfg := storedCfg + if req.Config != nil { + cfg, err = chatbridge.PrepareConfigUpdate(kind, storedCfg, req.Config) + if err != nil { + writeErr(w, 400, err.Error()) + return + } + } + if req.AllowedChats != nil { + allowed, err = chatbridge.NormalizeAllowedChats(tr, *req.AllowedChats) + if err != nil { + writeErr(w, 400, err.Error()) + return + } + } + if req.Enabled != nil { + enabled = *req.Enabled + } + // A disabled bridge may hold a partial configuration (the form is saved + // before the token is at hand); an enabled one must be complete. + if enabled || cfgHas(cfg, tr.SecretKeys()) { + if err := tr.Validate(cfg); err != nil { + writeErr(w, 400, err.Error()) + return + } + } + + raw, err := json.Marshal(cfg) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + // Update ids are per bot: a new token makes the old cursor meaningless, + // so it is cleared in the same statement that stores the token. + saved, err := pg.SaveChatBridge(r.Context(), &db.ChatBridge{Kind: kind, Enabled: enabled, Config: raw, AllowedChats: allowed}, secretsChanged(tr, storedCfg, cfg)) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + s.chatBridges.Reload(kind) + writeJSON(w, 200, s.chatBridgeDTO(kind, saved)) +} + +// chatBridgeTest asks the chat app which bot the stored configuration +// belongs to. It checks the token without sending any message. +func (s *Server) chatBridgeTest(w http.ResponseWriter, r *http.Request) { + pg := s.pg(w) + if pg == nil { + return + } + tr, ok := chatBridgeKind(w, r) + if !ok { + return + } + b, err := pg.ChatBridgeByKind(r.Context(), tr.Kind()) + if errors.Is(err, db.ErrChatBridgeNotFound) { + writeErr(w, 400, "save the bot token first") + return + } + if err != nil { + writeErr(w, 500, err.Error()) + return + } + var cfg map[string]any + _ = json.Unmarshal(b.Config, &cfg) + if err := tr.Validate(cfg); err != nil { + writeErr(w, 400, err.Error()) + return + } + start := time.Now() + me, err := tr.Identity(r.Context(), cfg) + if err != nil { + // Transport errors are already free of the token (see chatbridge.telegramTransport.call). + writeErr(w, 502, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"ok": true, "bot": me, "latency_ms": time.Since(start).Milliseconds()}) +} + +func cfgHas(cfg map[string]any, keys []string) bool { + for _, k := range keys { + if s, _ := cfg[k].(string); strings.TrimSpace(s) != "" { + return true + } + } + return false +} + +func secretsChanged(tr chatbridge.Transport, before, after map[string]any) bool { + for _, k := range tr.SecretKeys() { + if fmt.Sprint(before[k]) != fmt.Sprint(after[k]) { + return true + } + } + return false +} diff --git a/server/chatbridge_test.go b/server/chatbridge_test.go new file mode 100644 index 00000000..3720aae8 --- /dev/null +++ b/server/chatbridge_test.go @@ -0,0 +1,291 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/Autumn-27/artex/chatbridge" + "github.com/Autumn-27/artex/db" +) + +// fakeBridgeTransport is an in-memory chat app. The runner tests use their +// own kind so they never read or write the real "telegram" row. +type fakeBridgeTransport struct { + mu sync.Mutex + updates []chatbridge.Update + offsets []int64 + sent map[string][]string + pollErr error + identity int +} + +const fakeBridgeKind = "t-fake-bridge" + +func (f *fakeBridgeTransport) Kind() string { return fakeBridgeKind } +func (f *fakeBridgeTransport) Validate(map[string]any) error { return nil } +func (f *fakeBridgeTransport) SecretKeys() []string { return []string{"bot_token"} } +func (f *fakeBridgeTransport) DestinationKeys() []string { return nil } +func (f *fakeBridgeTransport) ValidateChatID(string) error { return nil } +func (f *fakeBridgeTransport) Identity(context.Context, map[string]any) (chatbridge.Identity, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.identity++ + return chatbridge.Identity{ID: "1", UserName: "fake_bot"}, nil +} +func (f *fakeBridgeTransport) Poll(_ context.Context, _ map[string]any, offset int64) ([]chatbridge.Update, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.offsets = append(f.offsets, offset) + if f.pollErr != nil { + return nil, f.pollErr + } + out := f.updates + f.updates = nil + return out, nil +} +func (f *fakeBridgeTransport) Send(_ context.Context, _ map[string]any, chatID, text string) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.sent == nil { + f.sent = map[string][]string{} + } + f.sent[chatID] = append(f.sent[chatID], text) + return nil +} + +func bridgeTestDB(t *testing.T) *db.DB { + t.Helper() + skipWithoutDSN(t) + // NewManager opens the database and loads the secrets key, as at startup. + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = m.pg.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, fakeBridgeKind) + m.Close() + }) + return m.pg +} + +func TestChatBridgeRunnerStep(t *testing.T) { + pg := bridgeTestDB(t) + ctx := context.Background() + fake := &fakeBridgeTransport{} + r := newChatBridgeRunner(pg) + r.transport = func(kind string) (chatbridge.Transport, bool) { return fake, kind == fakeBridgeKind } + + // Not configured: the bridge is off and sleeps. + if wait := r.step(ctx, fakeBridgeKind); wait != chatBridgeIdleWait || r.Status(fakeBridgeKind).State != "off" { + t.Fatalf("unconfigured: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } + + saved, err := pg.SaveChatBridge(ctx, &db.ChatBridge{ + Kind: fakeBridgeKind, Enabled: true, + Config: json.RawMessage(`{"bot_token":"x"}`), + AllowedChats: []string{"100"}, + }, false) + if err != nil { + t.Fatal(err) + } + + now := time.Now() + fake.updates = []chatbridge.Update{ + {ID: 10, ChatID: "100", UserID: "7", Text: "/whoami", Date: now}, + {ID: 11, ChatID: "666", UserID: "9", Text: "/whoami", Date: now}, + {ID: 12, ChatID: "666", UserID: "9", Text: "again", Date: now}, + {ID: 13, ChatID: "100", UserID: "7", Text: "/whoami", Date: now.Add(-time.Hour)}, + } + if wait := r.step(ctx, fakeBridgeKind); wait != 0 { + t.Fatalf("online step: wait %v, status %+v", wait, r.Status(fakeBridgeKind)) + } + st := r.Status(fakeBridgeKind) + if st.State != "online" || st.Bot == nil || st.Bot.UserName != "fake_bot" { + t.Fatalf("status = %+v", st) + } + if got := fake.sent["100"]; len(got) != 1 || !strings.Contains(got[0], "Chat ID: 100") { + t.Fatalf("allowed chat replies = %q (the stale /whoami must not be answered)", got) + } + if got := fake.sent["666"]; len(got) != 1 || !strings.Contains(got[0], "not allowed") || strings.Contains(got[0], "Your user ID") { + t.Fatalf("unknown chat replies = %q, want one refusal", got) + } + b, _ := pg.ChatBridgeByKind(ctx, fakeBridgeKind) + if b.PollOffset != 14 { + t.Fatalf("cursor = %d, want 14", b.PollOffset) + } + + // The next poll asks from the committed cursor, and the identity is reused. + r.step(ctx, fakeBridgeKind) + if last := fake.offsets[len(fake.offsets)-1]; last != 14 || fake.identity != 1 { + t.Fatalf("second poll offset %d, identity calls %d", last, fake.identity) + } + + // A save during a poll: the cursor write is refused for the old version + // and the batch is dropped, not acted on. + fake.updates = []chatbridge.Update{{ID: 20, ChatID: "100", UserID: "7", Text: "/whoami", Date: time.Now()}} + fake.pollErr = nil + r.transport = func(kind string) (chatbridge.Transport, bool) { + return &saveDuringPoll{fakeBridgeTransport: fake, pg: pg, saved: saved}, true + } + before := len(fake.sent["100"]) + r.step(ctx, fakeBridgeKind) + if len(fake.sent["100"]) != before { + t.Fatal("a batch polled under a replaced configuration was acted on") + } + + // An empty allowlist: the bridge runs but serves no chat. Every chat, + // including one that was allowed a moment ago, gets the refusal with its + // chat ID and no command runs. + r.transport = func(kind string) (chatbridge.Transport, bool) { return fake, true } + if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: true, Config: saved.Config}, false); err != nil { + t.Fatal(err) + } + fake.sent = nil + fake.updates = []chatbridge.Update{ + {ID: 30, ChatID: "100", UserID: "7", Text: "/whoami", Date: time.Now()}, + {ID: 31, ChatID: "777", UserID: "8", Text: "/whoami", Date: time.Now()}, + } + if wait := r.step(ctx, fakeBridgeKind); wait != 0 || r.Status(fakeBridgeKind).State != "online" { + t.Fatalf("empty allowlist: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } + for _, chat := range []string{"100", "777"} { + got := fake.sent[chat] + if len(got) != 1 || !strings.Contains(got[0], "chat ID "+chat) || strings.Contains(got[0], "Your user ID") { + t.Fatalf("empty allowlist, chat %s replies = %q, want one refusal naming the chat ID", chat, got) + } + } + + // Disabling turns the bridge off. + if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: false, Config: json.RawMessage(`{}`)}, false); err != nil { + t.Fatal(err) + } + if wait := r.step(ctx, fakeBridgeKind); wait != chatBridgeIdleWait || r.Status(fakeBridgeKind).State != "off" { + t.Fatalf("disabled: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } +} + +// saveDuringPoll saves the row while the poll is "in flight". +type saveDuringPoll struct { + *fakeBridgeTransport + pg *db.DB + saved *db.ChatBridge +} + +func (s *saveDuringPoll) Poll(ctx context.Context, cfg map[string]any, offset int64) ([]chatbridge.Update, error) { + out, err := s.fakeBridgeTransport.Poll(ctx, cfg, offset) + if _, serr := s.pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: true, Config: s.saved.Config, AllowedChats: s.saved.AllowedChats}, false); serr != nil { + return nil, serr + } + return out, err +} + +func TestChatBridgeRunnerBackoff(t *testing.T) { + pg := bridgeTestDB(t) + ctx := context.Background() + fake := &fakeBridgeTransport{pollErr: &chatbridge.RetryAfterError{After: 9 * time.Second, Msg: "rate limited"}} + r := newChatBridgeRunner(pg) + r.transport = func(string) (chatbridge.Transport, bool) { return fake, true } + if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{}`), AllowedChats: []string{"1"}}, false); err != nil { + t.Fatal(err) + } + if wait := r.step(ctx, fakeBridgeKind); wait != 9*time.Second { + t.Fatalf("retry-after wait = %v", wait) + } + fake.pollErr = context.DeadlineExceeded + w1 := r.step(ctx, fakeBridgeKind) + w2 := r.step(ctx, fakeBridgeKind) + if !(w2 > w1) || w2 > chatBridgeMaxRetry { + t.Fatalf("backoff did not grow: %v then %v", w1, w2) + } + if st := r.Status(fakeBridgeKind); st.State != "error" || st.LastError == "" { + t.Fatalf("status = %+v", st) + } + r.Reload(fakeBridgeKind) + fake.pollErr = nil + if wait := r.step(ctx, fakeBridgeKind); wait != 0 || r.Status(fakeBridgeKind).State != "online" { + t.Fatalf("after reload: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } +} + +func TestChatBridgeAPI(t *testing.T) { + s, _, request := trafficEvidenceServer(t) + pg := s.m.pg + ctx := context.Background() + if _, err := pg.ChatBridgeByKind(ctx, chatbridge.KindTelegram); err == nil { + t.Skip("a telegram bridge is already configured in this test database; not touching it") + } + t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, chatbridge.KindTelegram) }) + + const token = "123456789:AAapi-test-token-abcdefghij" + + w := request(http.MethodGet, "/api/chat-bridges", "") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"kind":"telegram"`) || !strings.Contains(w.Body.String(), `"configured":false`) { + t.Fatalf("list = %d %s", w.Code, w.Body) + } + + // Enabling with an empty allowlist is allowed: the bridge serves no chat + // and only answers with the refusal that names the chat ID, which is how + // the operator finds the ID to add. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"enabled":true,"config":{"bot_token":"`+token+`"}}`) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"allowed_chats":[]`) { + t.Fatalf("enable with an empty allowlist = %d %s", w.Code, w.Body) + } + // A malformed chat id is refused. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"allowed_chats":["@me"]}`) + if w.Code != 400 { + t.Fatalf("bad chat id = %d %s", w.Code, w.Body) + } + // Unknown kind. + if w = request(http.MethodPut, "/api/chat-bridges/carrier-pigeon", `{}`); w.Code != 404 { + t.Fatalf("unknown kind = %d", w.Code) + } + + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"enabled":false,"config":{"bot_token":"`+token+`"},"allowed_chats":["100"," 100 ","-1001"]}`) + if w.Code != 200 { + t.Fatalf("save = %d %s", w.Code, w.Body) + } + if strings.Contains(w.Body.String(), "AAapi-test") { + t.Fatalf("the token leaked into the response: %s", w.Body) + } + var dto chatBridgeDTO + if err := json.Unmarshal(w.Body.Bytes(), &dto); err != nil { + t.Fatal(err) + } + masked, _ := dto.Config["bot_token"].(string) + if !dto.Configured || strings.Join(dto.AllowedChats, ",") != "100,-1001" || !strings.HasPrefix(masked, "__masked__") { + t.Fatalf("dto = %+v", dto) + } + + // Sending the masked token back keeps the stored one and enables the bridge. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"enabled":true,"config":{"bot_token":"`+masked+`"}}`) + if w.Code != 200 { + t.Fatalf("enable = %d %s", w.Code, w.Body) + } + b, err := pg.ChatBridgeByKind(ctx, chatbridge.KindTelegram) + if err != nil || !b.Enabled || !strings.Contains(string(b.Config), token) { + t.Fatalf("stored = %+v %v", b, err) + } + + // Changing the API address with the masked token is refused. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"config":{"bot_token":"`+masked+`","base_url":"https://tg.example.com"}}`) + if w.Code != 400 || !strings.Contains(w.Body.String(), "bot token again") { + t.Fatalf("destination change = %d %s", w.Code, w.Body) + } + + // A new token clears the update cursor. + if _, err := pg.SetChatBridgeOffset(ctx, chatbridge.KindTelegram, b.ConfigVersion, 500); err != nil { + t.Fatal(err) + } + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"config":{"bot_token":"987654321:AAanother-token-abcdefghij"}}`) + if w.Code != 200 { + t.Fatalf("token change = %d %s", w.Code, w.Body) + } + if b, _ = pg.ChatBridgeByKind(ctx, chatbridge.KindTelegram); b.PollOffset != 0 { + t.Fatalf("cursor after token change = %d", b.PollOffset) + } +} diff --git a/server/server.go b/server/server.go index d2d85f57..74450e7b 100644 --- a/server/server.go +++ b/server/server.go @@ -59,6 +59,8 @@ type Server struct { execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own isolation IsolationStatus // result of the startup isolation self-test (isolation.go); zero when not run + chatBridges *chatBridgeRunner // inbound chat bridges (issue #5); nil without PostgreSQL + setupMu sync.Mutex setupToken string // one-time token POST /api/auth/init requires; empty when none is active // pwdVersion is auth.password_version, a counter. Zero means no password @@ -290,6 +292,10 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi // Vulnerability IM push delivery engine. Sits beside the Scheduler but independent: push latency demands (3s) // differ from the triggers' business cadence, and neither's failures drag the other down — a stuck push must not affect agent triggers. go newNotifier(s).Run(s.ctx) + // Inbound chat bridges: an operator drives ARTEX from a chat app. Off until a bridge is enabled + // with a non-empty chat allowlist; long polling only, so no inbound port is opened. + s.chatBridges = newChatBridgeRunner(m.pg) + go s.chatBridges.Run(s.ctx) logSink.SetDB(ctx, m.pg) // restore last 100 log rows and enable async persistence } // precedence: persisted DB config > env. @@ -937,6 +943,10 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /api/notify/channels/{id}/test", s.notifyTestChannel) mux.HandleFunc("GET /api/notify/deliveries", s.notifyListDeliveries) mux.HandleFunc("POST /api/notify/deliveries/{id}/retry", s.notifyRetryDelivery) + // Inbound chat bridges, one per transport kind (telegram). + mux.HandleFunc("GET /api/chat-bridges", s.chatBridgeList) + mux.HandleFunc("PUT /api/chat-bridges/{kind}", s.chatBridgeSave) + mux.HandleFunc("POST /api/chat-bridges/{kind}/test", s.chatBridgeTest) mux.HandleFunc("POST /api/settings/web-search/test", s.testWebSearch) mux.HandleFunc("GET /api/report", s.getReport) mux.HandleFunc("GET /api/chat/mentions", s.searchChatMentions) diff --git a/web/src/app/(main)/system/chat-bridge/page.tsx b/web/src/app/(main)/system/chat-bridge/page.tsx new file mode 100644 index 00000000..6797bd56 --- /dev/null +++ b/web/src/app/(main)/system/chat-bridge/page.tsx @@ -0,0 +1,259 @@ +"use client"; + +import * as React from "react"; + +import { PlugZapIcon, SaveIcon } from "lucide-react"; +import { toast } from "sonner"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { Textarea } from "@/components/ui/textarea"; +import { t } from "@/i18n"; +import { api } from "@/lib/api"; +import type { ChatBridge, ChatBridgeStatus } from "@/lib/types"; + +// v1 ships one transport. The page is written against the kind so a second chat app only needs +// its own fields here; the backend is already transport-agnostic. +const KIND = "telegram"; +// How often the live status ("bot online") is refreshed while the page is open. +const STATUS_POLL_MS = 5000; + +interface Form { + enabled: boolean; + token: string; // empty = keep the stored token + baseURL: string; + chats: string; // one chat ID per line +} + +function formFrom(b: ChatBridge | undefined): Form { + return { + enabled: b?.enabled ?? false, + token: "", + baseURL: typeof b?.config.base_url === "string" ? b.config.base_url : "", + chats: (b?.allowed_chats ?? []).join("\n"), + }; +} + +function parseChats(raw: string): string[] { + return raw + .split(/[\s,]+/) + .map((s) => s.trim()) + .filter(Boolean); +} + +function StatusBadge({ status }: { status: ChatBridgeStatus }) { + switch (status.state) { + case "online": + return {t("Online")}; + case "connecting": + return {t("Connecting")}; + case "error": + return {t("Error")}; + default: + return {t("Off")}; + } +} + +export default function ChatBridgePage() { + const [bridge, setBridge] = React.useState(); + const [form, setForm] = React.useState
(formFrom(undefined)); + const [loaded, setLoaded] = React.useState(false); + const [saving, setSaving] = React.useState(false); + const [testing, setTesting] = React.useState(false); + + const load = React.useCallback(async (resetForm: boolean) => { + const list = await api.chatBridges(); + const b = list.find((x) => x.kind === KIND); + setBridge(b); + if (resetForm) setForm(formFrom(b)); + setLoaded(true); + }, []); + + React.useEffect(() => { + load(true).catch((e) => + toast.error(t("Failed to load the chat bot settings: {error}", { error: (e as Error).message })), + ); + // Only the status is refreshed; the form keeps what the operator is typing. + const id = window.setInterval(() => { + load(false).catch(() => { + // A missed refresh is retried on the next tick; the status card keeps its last value. + }); + }, STATUS_POLL_MS); + return () => window.clearInterval(id); + }, [load]); + + const storedToken = typeof bridge?.config.bot_token === "string" ? bridge.config.bot_token : ""; + + async function save() { + const config: Record = { base_url: form.baseURL.trim() }; + // An empty token field keeps the stored token: the masked value tells the server "unchanged". + config.bot_token = form.token.trim() || storedToken; + setSaving(true); + try { + const saved = await api.chatBridgeSave(KIND, { + enabled: form.enabled, + config, + allowed_chats: parseChats(form.chats), + }); + setBridge(saved); + setForm(formFrom(saved)); + toast.success(t("Saved")); + } catch (e) { + toast.error(t("Save failed: {error}", { error: (e as Error).message })); + } finally { + setSaving(false); + } + } + + async function test() { + setTesting(true); + try { + const r = await api.chatBridgeTest(KIND); + toast.success(t("Connected to @{bot} in {ms} ms", { bot: r.bot.username, ms: String(r.latency_ms) })); + } catch (e) { + toast.error(t("Connection test failed: {error}", { error: (e as Error).message })); + } finally { + setTesting(false); + } + } + + const status: ChatBridgeStatus = bridge?.status ?? { state: "off" }; + const chatCount = parseChats(form.chats).length; + + return ( +
+
+

{t("Chat bot")}

+

+ {t( + "Talk to ARTEX from Telegram. Only the chats you allow below can use the bot; every other chat gets one refusal and is then ignored.", + )} +

+
+ + + + + {t("Status")} + + + + + {status.bot && ( +

+ {t("Bot")}: @{status.bot.username} +

+ )} + {status.state === "off" && ( +

{t("The bot is off. Enter a token and switch it on.")}

+ )} + {status.last_poll_at && ( +

+ {t("Last poll: {time}", { time: new Date(status.last_poll_at).toLocaleString() })} +

+ )} + {status.state === "error" && status.last_error && ( +

{status.last_error}

+ )} +
+
+ + + + Telegram + + +
+ setForm((f) => ({ ...f, enabled: v }))} + /> + +
+ +
+ + setForm((f) => ({ ...f, token: e.target.value }))} + /> +

+ {t( + "Create a bot with @BotFather and paste its token. Give ARTEX its own bot: a token used by another poller or a webhook cannot be shared.", + )} +

+
+ +
+ +