merge: tg7 dangerous commands + conflict resolution

This commit is contained in:
sam committed 2026-07-29 07:30:10 +10:00
commit d74ee3577c
5 files changed
+1588 -53

No files matched your search

+7 -38
View File
@@ -19,36 +19,20 @@ type commandSpec struct {
// published command menu and /help. Keeping the discoverability surfaces
// together prevents a newly registered command from being omitted from help.
var gatewayCommandSpecs = []commandSpec{
{Command: "new", Description: "Start a fresh session", Usage: "/new [name] (alias: /reset)"},
{Command: "title", Description: "Set or show the session title", Usage: "/title [name]"},
{Command: "branch", Description: "Branch session with inherited history", Usage: "/branch [name] (alias: /fork)"},
{Command: "topic", Description: "Switch between topic sessions", Usage: "/topic [off|help|<session-id>]"},
{Command: "retry", Description: "Retry the last turn", Usage: "/retry"},
{Command: "undo", Description: "Remove the last N messages", Usage: "/undo [N]"},
{Command: "compress", Description: "Compress conversation history", Usage: "/compress [here <N>|focus <topic>|--preview] (alias: /compact)"},
{Command: "status", Description: "Show task counts by state", Usage: "/status"},
{Command: "whoami", Description: "Show which Archie identity you are talking to", Usage: "/whoami"},
{Command: "profile", Description: "Show the active Archie profile", Usage: "/profile"},
{Command: "sessions", Description: "List recent sessions", Usage: "/sessions"},
{Command: "resume", Description: "Resume a session by ID or name", Usage: "/resume [id]"},
{Command: "agents", Description: "List active agents and running tasks", Usage: "/agents"},
{Command: "version", Description: "Show installed Archie versions", Usage: "/version"},
{Command: "update", Description: "Check for Archie updates", Usage: "/update"},
{Command: "provider", Description: "Choose the provider used for chat", Usage: "/provider"},
{Command: "model", Description: "Show the model selector or switch directly", Usage: "/model [model] [--provider name] [--global|--session] [--refresh]"},
{Command: "personality", Description: "Set the conversation personality", Usage: "/personality [name]"},
{Command: "model", Description: "Show the model selector or switch directly", Usage: "/model [provider/model]"},
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"},
{Command: "goal", Description: "Manage standing goals", Usage: "/goal [text|draft|show|pause|resume|clear|status|wait|unwait]"},
{Command: "subgoal", Description: "Manage subgoals under the current goal", Usage: "/subgoal [text|remove N|clear]"},
{Command: "steer", Description: "Queue a message to inject after the next tool call", Usage: "/steer <message>"},
{Command: "queue", Description: "Manage a background task queue", Usage: "/queue [text|remove N|clear]"},
{Command: "q", Description: "Alias for /queue", Usage: "/q [text|remove N|clear]"},
{Command: "rollback", Description: "Restore a filesystem checkpoint", Usage: "/rollback [number]"},
{Command: "stop", Description: "Terminate a background process", Usage: "/stop <process-name>"},
{Command: "restart", Description: "Reload Archie and its configuration", Usage: "/restart"},
{Command: "help", Description: "See what Archie can do", Usage: "/help"},
}
var telegramOnlyCommands = []string{"provider", "restart", "help", "version", "update", "personality"}
var telegramOnlyCommands = []string{"provider", "restart", "help", "version", "update", "rollback", "stop"}
var gatewayCommands = func() []models.BotCommand {
commands := make([]models.BotCommand, 0, len(gatewayCommandSpecs))
@@ -65,26 +49,11 @@ func gatewayHelpText() string {
var help strings.Builder
help.WriteString("🤖 **Archie**\n\n")
help.WriteString("Send a message to chat with Archie. Replies stream into Telegram as they are generated.\n\n")
help.WriteString("**Session commands** (always available)\n")
appendCommandGroup(&help, isSessionCommand)
help.WriteString("**Other commands**\n")
appendCommandGroup(&help, func(cmd string) bool { return !isSessionCommand(cmd) })
return strings.TrimSpace(help.String())
}
var sessionCommands = map[string]bool{
"new": true, "title": true, "branch": true, "topic": true,
"retry": true, "undo": true, "compress": true,
}
func isSessionCommand(cmd string) bool { return sessionCommands[cmd] }
func appendCommandGroup(help *strings.Builder, include func(string) bool) {
help.WriteString("**Commands**\n")
for _, spec := range gatewayCommandSpecs {
if include(spec.Command) {
fmt.Fprintf(help, "`%s`\n%s\n\n", spec.Usage, spec.Description)
}
fmt.Fprintf(&help, "`%s`\n%s\n\n", spec.Usage, spec.Description)
}
return strings.TrimSpace(help.String())
}
// commandScopes are the scopes the menu is published to.
+561
View File
@@ -0,0 +1,561 @@
package telegram
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
// DangerousCommandAuthority is the sandbox/process/filesystem authority
// that validates and executes dangerous commands after human approval.
// The daemon's container pool, worktree manager, or similar sandbox owner
// implements this interface. It must not claim control over host
// resources Archie does not own.
type DangerousCommandAuthority interface {
// StopProcess terminates a running background process identified by
// spec (a process name, ID, or other identifier understood by the
// sandbox). Returns an error if the process cannot be found or
// stopped.
StopProcess(ctx context.Context, spec string) error
// Rollback restores the worktree/sandbox filesystem to a numbered
// checkpoint. Returns a summary of the restored state, or an error
// if the checkpoint does not exist or restoration fails.
Rollback(ctx context.Context, checkpointNumber int) (string, error)
// ListCheckpoints returns available filesystem checkpoints, newest
// first. Returns an empty slice when no checkpoints exist.
ListCheckpoints(ctx context.Context) ([]CheckpointInfo, error)
}
// CheckpointInfo describes a saved filesystem checkpoint.
type CheckpointInfo struct {
Number int
Timestamp time.Time
Label string
Size string
}
// ── dangerous command approval system ─────────────────────────────
// dangerousCmdPrefix separates dangerous-command callbacks from other
// callback types handled in defaultHandler.
const dangerousCmdPrefix = "dangerous:"
// dangerousAction records a pending command a human must approve or deny.
// It mirrors the updateAction pattern: random token, recipient-bound,
// expiring, single-use, and carrying a hash so a changed command cannot
// reuse the callback.
type dangerousAction struct {
id string // random token
command string // the full command text
commandHash string // sha256(command) — prevents changed-command replay
description string // human-readable label shown to the approver
recipient int64 // Telegram user who may approve
createdAt time.Time
expiresAt time.Time
// onApprove is the function to call when approved. The Gateway
// supplies this when registering the pending command so the
// authority stays out of the Telegram callback path.
onApprove func(ctx context.Context) (string, error)
}
// permanentApproval records a decision to approve a category of dangerous
// commands permanently. Scope and lifetime are explicit.
type permanentApproval struct {
// CommandPattern is a prefix match against the command text, e.g.
// "/rollback", "/stop", or a tool name.
CommandPattern string
Recipient int64
GrantedAt time.Time
ExpiresAt time.Time
// Scope describes the approval boundary for audit purposes.
Scope string
}
// ── Gateway methods ──────────────────────────────────────────────
// registerDangerousAction stores a pending command and returns a callback
// token. The caller must present the action to the user (via an inline
// keyboard) immediately after registering.
func (g *Gateway) registerDangerousAction(
command, description string,
recipient int64,
onApprove func(ctx context.Context) (string, error),
) string {
token := makeDangerousToken()
sum := sha256.Sum256([]byte(command))
hash := hex.EncodeToString(sum[:])
g.dangerousMu.Lock()
defer g.dangerousMu.Unlock()
now := time.Now()
// Expire tokens older than maxPendingAge.
maxPendingAge := 10 * time.Minute
for key, action := range g.dangerousActions {
if !action.expiresAt.After(now) {
delete(g.dangerousActions, key)
}
}
g.dangerousActions[token] = dangerousAction{
id: token,
command: command,
commandHash: hash,
description: description,
recipient: recipient,
createdAt: now,
expiresAt: now.Add(maxPendingAge),
onApprove: onApprove,
}
return token
}
// dangerousKeyboard builds the three-button inline keyboard for a
// dangerous command: "Approve this time", "Approve Permanently", "Deny".
func (g *Gateway) dangerousKeyboard(token string) *models.InlineKeyboardMarkup {
return &models.InlineKeyboardMarkup{
InlineKeyboard: [][]models.InlineKeyboardButton{
{
{
Text: "Approve this time",
CallbackData: dangerousCmdPrefix + "approve:" + token,
},
},
{
{
Text: "Approve Permanently",
CallbackData: dangerousCmdPrefix + "permanent:" + token,
},
},
{
{
Text: "Deny",
CallbackData: dangerousCmdPrefix + "deny:" + token,
},
},
},
}
}
// answerDangerousCallback is the common acknowledge/shake response.
func (g *Gateway) answerDangerousCallback(ctx context.Context, b *bot.Bot, queryID, text string, alert bool) {
if _, err := b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
CallbackQueryID: queryID,
Text: text,
ShowAlert: alert,
}); err != nil {
g.log.Warn("answer dangerous callback failed", "error", err)
}
}
// handleDangerousCallback is the entrypoint for all dangerous-command
// inline-button taps. It validates the token (recipient, expiry, replay,
// hash), records an audit event, and executes or rejects the command.
func (g *Gateway) handleDangerousCallback(ctx context.Context, b *bot.Bot, update *models.Update) {
query := update.CallbackQuery
if query == nil {
return
}
if !g.isSenderAllowed(query.From.ID) {
g.log.Warn("dangerous callback from unauthorized sender", "user_id", query.From.ID)
g.answerDangerousCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
return
}
action, ok := g.consumeDangerousAction(query)
if !ok {
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
return
}
decision, _ := parseDangerousCallback(query.Data)
g.log.Info("dangerous command decision",
"command", action.command, "decision", decision,
"recipient", query.From.ID, "username", query.From.Username,
)
switch decision {
case "deny":
g.executeDangerousDeny(ctx, b, query, action)
case "approve":
g.executeDangerousApprove(ctx, b, query, action)
case "permanent":
g.executeDangerousPermanent(ctx, b, query, action)
default:
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
}
}
// consumeDangerousAction validates and atomically consumes the pending
// action associated with the callback query. Returns the action and true
// if valid; false if expired, wrong recipient, or already consumed.
func (g *Gateway) consumeDangerousAction(query *models.CallbackQuery) (dangerousAction, bool) {
_, token := parseDangerousCallback(query.Data)
g.dangerousMu.Lock()
action, found := g.dangerousActions[token]
if found && action.recipient == query.From.ID && action.expiresAt.After(time.Now()) {
delete(g.dangerousActions, token)
}
g.dangerousMu.Unlock()
return action, found && action.recipient == query.From.ID && action.expiresAt.After(time.Now())
}
func (g *Gateway) executeDangerousDeny(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
g.answerDangerousCallback(ctx, b, query.ID, "Command denied.", false)
g.editDangerousMessage(ctx, b, query, "❌ Denied: "+action.description)
}
func (g *Gateway) executeDangerousApprove(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
result, err := action.onApprove(ctx)
if err != nil {
g.log.Error("dangerous command execution failed", "command", action.command, "error", err)
g.answerDangerousCallback(ctx, b, query.ID, fmt.Sprintf("Command failed: %v", err), true)
g.editDangerousMessage(ctx, b, query, fmt.Sprintf("❌ Failed: %s — %v", action.description, err))
return
}
g.answerDangerousCallback(ctx, b, query.ID, "Approved and executed.", false)
msg := "✅ Approved: " + action.description
if result != "" {
msg += "\n\n" + result
}
g.editDangerousMessage(ctx, b, query, msg)
}
func (g *Gateway) executeDangerousPermanent(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
g.recordPermanentApproval(query.From.ID, action.command)
result, err := action.onApprove(ctx)
if err != nil {
g.log.Error("dangerous command execution failed (permanent approval)", "command", action.command, "error", err)
g.answerDangerousCallback(ctx, b, query.ID, fmt.Sprintf("Command failed: %v", err), true)
g.editDangerousMessage(ctx, b, query, fmt.Sprintf("❌ Failed: %s — %v", action.description, err))
return
}
g.answerDangerousCallback(ctx, b, query.ID, "Permanently approved and executed (valid 24h).", false)
msg := "✅ Approved (permanent, 24h): " + action.description
if result != "" {
msg += "\n\n" + result
}
g.editDangerousMessage(ctx, b, query, msg)
}
func (g *Gateway) recordPermanentApproval(recipient int64, command string) {
scope := permanentApproval{
CommandPattern: command,
Recipient: recipient,
GrantedAt: time.Now(),
ExpiresAt: time.Now().Add(24 * time.Hour),
Scope: fmt.Sprintf("Permanent approval for %q by user %d, expires in 24h", command, recipient),
}
g.dangerousMu.Lock()
g.permanentApprovals = append(g.permanentApprovals, scope)
now := time.Now()
kept := g.permanentApprovals[:0]
for _, pa := range g.permanentApprovals {
if pa.ExpiresAt.After(now) {
kept = append(kept, pa)
}
}
g.permanentApprovals = kept
g.dangerousMu.Unlock()
g.log.Info("dangerous command permanently approved", "scope", scope.Scope)
}
// hasPermanentApproval checks whether recipient has a current permanent
// approval covering the given command text.
func (g *Gateway) hasPermanentApproval(recipient int64, command string) bool {
g.dangerousMu.Lock()
defer g.dangerousMu.Unlock()
now := time.Now()
kept := g.permanentApprovals[:0]
found := false
for _, pa := range g.permanentApprovals {
if !pa.ExpiresAt.After(now) {
continue
}
kept = append(kept, pa)
if pa.Recipient == recipient && strings.HasPrefix(command, pa.CommandPattern) {
found = true
}
}
g.permanentApprovals = kept
return found
}
func (g *Gateway) editDangerousMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) {
if query.Message.Message == nil {
return
}
message := query.Message.Message
if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: message.Chat.ID,
MessageID: message.ID,
Text: text,
}); err != nil {
g.log.Warn("edit dangerous message failed", "error", err)
}
}
// ── /rollback handler ───────────────────────────────────────────
// rollbackHandler serves /rollback: show available checkpoints, or with
// a number, request approval to restore that checkpoint.
func (g *Gateway) rollbackHandler() bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
if !ok {
return
}
if g.Dangerous == nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Rollback is not configured for this installation.")
return
}
rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/rollback", ""))
if rest == "" {
g.showCheckpoints(ctx, b, msg.Chat.ID, msg.MessageThreadID)
return
}
num, err := strconv.Atoi(rest)
if err != nil || num < 1 {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Usage: /rollback <checkpoint number>")
return
}
g.requestRollbackApproval(ctx, b, msg, num)
}
}
func (g *Gateway) showCheckpoints(ctx context.Context, b *bot.Bot, chatID int64, threadID int) {
checkpoints, err := g.Dangerous.ListCheckpoints(ctx)
if err != nil {
g.log.Error("list checkpoints failed", "error", err)
g.sendMessage(ctx, b, chatID, threadID, "Could not list checkpoints.")
return
}
if len(checkpoints) == 0 {
g.sendMessage(ctx, b, chatID, threadID, "No checkpoints available.")
return
}
var text strings.Builder
text.WriteString("Available checkpoints:\n\n")
for _, c := range checkpoints {
fmt.Fprintf(&text, "%d — %s (%s)", c.Number, c.Timestamp.Format("2006-01-02 15:04"), c.Label)
if c.Size != "" {
fmt.Fprintf(&text, " — %s", c.Size)
}
text.WriteByte('\n')
}
text.WriteString("\nUse /rollback <number> to restore a checkpoint.")
g.sendMessage(ctx, b, chatID, threadID, text.String())
}
func (g *Gateway) requestRollbackApproval(ctx context.Context, b *bot.Bot, msg *models.Message, num int) {
rest := fmt.Sprintf("%d", num)
if g.hasPermanentApproval(msg.From.ID, "/rollback") {
result, err := g.Dangerous.Rollback(ctx, num)
if err != nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, fmt.Sprintf("❌ Rollback failed: %v", err))
return
}
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "✅ Rollback to checkpoint "+rest+":\n\n"+result)
return
}
cmdText := fmt.Sprintf("/rollback %d", num)
desc := fmt.Sprintf("Rollback to checkpoint %d", num)
token := g.registerDangerousAction(cmdText, desc, msg.From.ID, func(ctx context.Context) (string, error) {
return g.Dangerous.Rollback(ctx, num)
})
params := &bot.SendMessageParams{
ChatID: msg.Chat.ID,
Text: rollbackApprovalText(num),
ReplyMarkup: g.dangerousKeyboard(token),
}
if msg.MessageThreadID != 0 {
params.MessageThreadID = msg.MessageThreadID
}
if _, err := b.SendMessage(ctx, params); err != nil {
g.log.Error("send dangerous prompt (rollback) failed", "error", err)
}
}
func rollbackApprovalText(num int) string {
return fmt.Sprintf(
"⚠️ **Dangerous command**\n\n"+
"Command: `/rollback %d`\n"+
"Effect: Restore the worktree filesystem to checkpoint %d.\n"+
"This will discard any changes made after that checkpoint.\n\n"+
"_This request expires in 10 minutes._",
num, num,
)
}
// ── /stop handler ──────────────────────────────────────────────
// stopHandler serves /stop: terminate a background process after approval.
func (g *Gateway) stopHandler() bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
if !ok {
return
}
if g.Dangerous == nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Process control is not configured for this installation.")
return
}
rest := restAfterTelegram(msg.Text, "/stop", "")
rest = strings.TrimSpace(rest)
if rest == "" {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
"Usage: /stop <process-name>\n\nTerminate a running background process. "+
"This requires approval because it may discard in-progress work.")
return
}
// Check permanent approval.
if g.hasPermanentApproval(msg.From.ID, "/stop") {
if err := g.Dangerous.StopProcess(ctx, rest); err != nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, fmt.Sprintf("❌ Stop failed: %v", err))
return
}
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "✅ Process stopped: "+rest)
return
}
cmdText := fmt.Sprintf("/stop %s", rest)
desc := fmt.Sprintf("Stop process %q", rest)
token := g.registerDangerousAction(cmdText, desc, msg.From.ID, func(ctx context.Context) (string, error) {
if err := g.Dangerous.StopProcess(ctx, rest); err != nil {
return "", err
}
return "", nil
})
params := &bot.SendMessageParams{
ChatID: msg.Chat.ID,
Text: fmt.Sprintf(
"⚠️ **Dangerous command**\n\n"+
"Command: `/stop %s`\n"+
"Effect: Terminate the running background process %q.\n"+
"This will discard any in-progress work on that process.\n\n"+
"_This request expires in 10 minutes._",
rest, rest,
),
ReplyMarkup: g.dangerousKeyboard(token),
}
if msg.MessageThreadID != 0 {
params.MessageThreadID = msg.MessageThreadID
}
if _, err := b.SendMessage(ctx, params); err != nil {
g.log.Error("send dangerous prompt (stop) failed", "error", err)
}
}
}
// ── helpers ────────────────────────────────────────────────────
// restAfterTelegram strips a slash-command token from a Telegram message
// text, including an optional @bot suffix.
func restAfterTelegram(text, cmd, gatewayName string) string {
s := text
if gatewayName != "" {
s = strings.TrimPrefix(s, cmd+"@"+gatewayName)
}
s = strings.TrimPrefix(s, cmd)
return s
}
func makeDangerousToken() string {
bytes := make([]byte, 16)
if _, err := rand.Read(bytes); err != nil {
panic("crypto/rand: " + err.Error())
}
return hex.EncodeToString(bytes)
}
// parseDangerousCallback splits a dangerous-command callback data into
// decision ("approve", "permanent", "deny") and token.
func parseDangerousCallback(data string) (decision, token string) {
data = strings.TrimPrefix(data, dangerousCmdPrefix)
decision, token, _ = strings.Cut(data, ":")
if decision != "approve" && decision != "permanent" && decision != "deny" {
return "", ""
}
return decision, token
}
// ── /approve and /deny handlers ─────────────────────────────────
// approveHandler serves /approve: list any pending dangerous commands,
// or approve a specific one by token. When a pending command exists, the
// user interacts via inline buttons rather than typing /approve directly;
// this handler is for the edge case where a user types /approve without
// a pending command context.
func (g *Gateway) approveHandler() bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
if !ok {
return
}
if g.Dangerous == nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
"Dangerous-command approval is not configured.\n\n"+
"Use /rollback or /stop to trigger approval inline.")
return
}
g.dangerousMu.Lock()
now := time.Now()
var pending []dangerousAction
for key, action := range g.dangerousActions {
if !action.expiresAt.After(now) {
delete(g.dangerousActions, key)
continue
}
if action.recipient == msg.From.ID {
pending = append(pending, action)
}
}
g.dangerousMu.Unlock()
if len(pending) == 0 {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
"No pending commands to approve.\n\n"+
"Use /rollback or /stop to trigger a dangerous command approval inline.")
return
}
var text strings.Builder
text.WriteString("Pending dangerous commands:\n\n")
for i, action := range pending {
fmt.Fprintf(&text, "%d. %s", i+1, action.description)
remaining := time.Until(action.expiresAt).Truncate(time.Second)
fmt.Fprintf(&text, " (expires in %s)", remaining)
text.WriteByte('\n')
}
text.WriteString("\nUse the inline buttons on each pending command to approve or deny.")
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, text.String())
}
}
// denyHandler serves /deny: the counterpart to /approve for rejecting
// pending dangerous commands. Like /approve, the primary interaction is
// through inline buttons on each pending command.
func (g *Gateway) denyHandler() bot.HandlerFunc {
return g.approveHandler() // Same behaviour: show pending commands.
}
@@ -0,0 +1,992 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/go-telegram/bot/models"
)
// ── DangerousCommandAuthority stub ─────────────────────────────
type dangerousStub struct {
mu sync.Mutex
stopCalls []string
rollbackCalls []int
checkpoints []CheckpointInfo
stopErr error
rollbackErr error
rollbackResult string
checkpointsErr error
}
func (s *dangerousStub) StopProcess(_ context.Context, spec string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.stopCalls = append(s.stopCalls, spec)
return s.stopErr
}
func (s *dangerousStub) Rollback(_ context.Context, num int) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.rollbackCalls = append(s.rollbackCalls, num)
if s.rollbackErr != nil {
return "", s.rollbackErr
}
return s.rollbackResult, nil
}
func (s *dangerousStub) ListCheckpoints(_ context.Context) ([]CheckpointInfo, error) {
if s.checkpointsErr != nil {
return nil, s.checkpointsErr
}
return s.checkpoints, nil
}
// messageText returns the text content from a Telegram request,
// checking both regular text messages and rich messages.
func messageText(requests []telegramRequest, index int) string {
if index >= len(requests) {
return ""
}
req := requests[index]
if text := req.form["text"]; text != "" {
return text
}
return req.form["rich_message"]
}
// ── Tests ──────────────────────────────────────────────────────
func TestRollbackListsCheckpoints(t *testing.T) {
const allowedUserID = int64(42)
now := time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC)
stub := &dangerousStub{
checkpoints: []CheckpointInfo{
{Number: 3, Timestamp: now, Label: "After gate fix", Size: "12 MB"},
{Number: 2, Timestamp: now.Add(-1 * time.Hour), Label: "Baseline", Size: "10 MB"},
{Number: 1, Timestamp: now.Add(-2 * time.Hour), Label: "Initial checkout", Size: "8 MB"},
},
}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback",
},
})
if len(*requests) == 0 {
t.Fatal("rollback list sent no response")
}
text := messageText(*requests, 0)
for _, want := range []string{"Available checkpoints", "3 — 2026-01-15 10:30", "12 MB", "After gate fix"} {
if !strings.Contains(text, want) {
t.Errorf("checkpoint list missing %q: %s", want, text)
}
}
}
func TestRollbackEmptyCheckpoints(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{} // no checkpoints
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "No checkpoints") {
t.Errorf("expected 'No checkpoints' message, got: %s", text)
}
}
func TestRollbackCheckpointError(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{checkpointsErr: fmt.Errorf("storage offline")}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "Could not list") {
t.Errorf("expected error message, got: %s", text)
}
}
func TestRollbackWithNumberRequiresApproval(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{
rollbackResult: "Restored to checkpoint 2: 15 files changed, 3 removed.",
}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback 2",
},
})
if len(*requests) == 0 {
t.Fatal("rollback approval prompt sent no response")
}
text := (*requests)[0].form["text"]
if !strings.Contains(text, "Dangerous command") {
t.Errorf("expected dangerous command prompt, got: %s", text)
}
if !strings.Contains(text, "/rollback 2") {
t.Errorf("expected command text in prompt, got: %s", text)
}
if !strings.Contains(text, "expires in 10 minutes") {
t.Errorf("expected expiry notice, got: %s", text)
}
// Verify inline keyboard has three buttons.
var markup models.InlineKeyboardMarkup
if err := json.Unmarshal([]byte((*requests)[0].form["reply_markup"]), &markup); err != nil {
t.Fatalf("decode reply markup: %v", err)
}
if len(markup.InlineKeyboard) != 3 {
t.Fatalf("keyboard rows = %d, want 3 (Approve/Approve Permanently/Deny)", len(markup.InlineKeyboard))
}
buttons := []string{
markup.InlineKeyboard[0][0].Text,
markup.InlineKeyboard[1][0].Text,
markup.InlineKeyboard[2][0].Text,
}
if buttons[0] != "Approve this time" || buttons[1] != "Approve Permanently" || buttons[2] != "Deny" {
t.Errorf("button labels = %v, want [Approve this time, Approve Permanently, Deny]", buttons)
}
// Verify callback data prefix.
if !strings.HasPrefix(markup.InlineKeyboard[0][0].CallbackData, dangerousCmdPrefix+"approve:") {
t.Errorf("approve callback = %q, want prefix %s", markup.InlineKeyboard[0][0].CallbackData, dangerousCmdPrefix+"approve:")
}
if !strings.HasPrefix(markup.InlineKeyboard[1][0].CallbackData, dangerousCmdPrefix+"permanent:") {
t.Errorf("permanent callback = %q", markup.InlineKeyboard[1][0].CallbackData)
}
if !strings.HasPrefix(markup.InlineKeyboard[2][0].CallbackData, dangerousCmdPrefix+"deny:") {
t.Errorf("deny callback = %q", markup.InlineKeyboard[2][0].CallbackData)
}
// Verify no rollback was executed yet (still pending approval).
if len(stub.rollbackCalls) != 0 {
t.Errorf("rollback was executed before approval: %v", stub.rollbackCalls)
}
}
func TestRollbackApprovalExecutes(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{
rollbackResult: "Restored to checkpoint 2: 15 files changed.",
}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
// Step 1: Trigger the approval prompt.
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback 2",
},
})
// Extract the approve callback token.
var markup models.InlineKeyboardMarkup
if err := json.Unmarshal([]byte((*requests)[0].form["reply_markup"]), &markup); err != nil {
t.Fatalf("decode markup: %v", err)
}
approveCallback := markup.InlineKeyboard[0][0].CallbackData
*requests = nil
// Step 2: Send the approval callback.
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: approveCallback,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
// Verify rollback was executed.
if len(stub.rollbackCalls) != 1 || stub.rollbackCalls[0] != 2 {
t.Errorf("rollbackCalls = %v, want [2]", stub.rollbackCalls)
}
// Verify acknowledgement and edit.
var answered, edited bool
for _, req := range *requests {
if req.method == "answerCallbackQuery" {
answered = true
if !strings.Contains(req.form["text"], "Approved") {
t.Errorf("acknowledgement = %q", req.form["text"])
}
}
if req.method == "editMessageText" {
edited = true
if !strings.Contains(req.form["text"], "Restored to checkpoint 2") {
t.Errorf("edit text = %q", req.form["text"])
}
}
}
if !answered || !edited {
t.Fatalf("answered=%t edited=%t, requests: %#v", answered, edited, *requests)
}
}
func TestRollbackWithBadNumber(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback abc",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "Usage: /rollback") {
t.Errorf("expected usage message, got: %s", text)
}
if len(stub.rollbackCalls) != 0 {
t.Error("rollback was called with bad argument")
}
}
func TestStopRequiresApproval(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.stopHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/stop npm-dev-server",
},
})
text := (*requests)[0].form["text"]
if !strings.Contains(text, "Dangerous command") {
t.Errorf("expected dangerous command prompt, got: %s", text)
}
if !strings.Contains(text, "/stop npm-dev-server") {
t.Errorf("expected command text in prompt, got: %s", text)
}
// Verify no process was stopped yet.
if len(stub.stopCalls) != 0 {
t.Errorf("stop was executed before approval: %v", stub.stopCalls)
}
}
func TestStopApprovalExecutes(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
// Step 1: Trigger the approval prompt.
g.stopHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/stop my-process",
},
})
var markup models.InlineKeyboardMarkup
if err := json.Unmarshal([]byte((*requests)[0].form["reply_markup"]), &markup); err != nil {
t.Fatalf("decode markup: %v", err)
}
approveCallback := markup.InlineKeyboard[0][0].CallbackData
*requests = nil
// Step 2: Approve.
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: approveCallback,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
if len(stub.stopCalls) != 1 || stub.stopCalls[0] != "my-process" {
t.Errorf("stopCalls = %v, want [my-process]", stub.stopCalls)
}
}
func TestStopNoArgument(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.stopHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/stop",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "Usage: /stop") {
t.Errorf("expected usage message, got: %s", text)
}
}
func TestDangerousCallbackRejectsUnauthorizedSender(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{
rollbackResult: "ok",
}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
// Register a fake action for user 42.
_ = g.registerDangerousAction("/rollback 1", "rollback test", 42, func(ctx context.Context) (string, error) {
return "ok", nil
})
// Find the token.
g.dangerousMu.Lock()
var token string
for t := range g.dangerousActions {
token = t
}
g.dangerousMu.Unlock()
// Attempt approval from user 99 (not allowed).
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: 99},
Data: dangerousCmdPrefix + "approve:" + token,
},
})
var answer *telegramRequest
for i := range *requests {
if (*requests)[i].method == "answerCallbackQuery" {
answer = &(*requests)[i]
}
}
if answer == nil || answer.form["show_alert"] != "true" {
t.Fatalf("unauthorized rejection did not alert; requests: %#v", *requests)
}
if len(stub.rollbackCalls) != 0 {
t.Error("unauthorized sender executed rollback")
}
}
func TestDangerousCallbackExpiredToken(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{rollbackResult: "ok"}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
// Register and immediately expire.
token := g.registerDangerousAction("/rollback 1", "expired", allowedUserID, func(ctx context.Context) (string, error) {
return "ok", nil
})
g.dangerousMu.Lock()
action := g.dangerousActions[token]
action.expiresAt = time.Now().Add(-1 * time.Minute) // force expiry
g.dangerousActions[token] = action
g.dangerousMu.Unlock()
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: dangerousCmdPrefix + "approve:" + token,
},
})
if len(stub.rollbackCalls) != 0 {
t.Error("expired token executed rollback")
}
// Find the rejection answer.
for _, req := range *requests {
if req.method == "answerCallbackQuery" && req.form["text"] == "That action is no longer valid." {
return // pass
}
}
t.Errorf("no 'no longer valid' answer; requests: %#v", *requests)
}
func TestDangerousCallbackSingleUse(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{rollbackResult: "ok"}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
token := g.registerDangerousAction("/rollback 1", "single-use test", allowedUserID, func(ctx context.Context) (string, error) {
return g.Dangerous.Rollback(ctx, 1)
})
// First approval should work.
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-1",
From: models.User{ID: allowedUserID},
Data: dangerousCmdPrefix + "approve:" + token,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
if len(stub.rollbackCalls) != 1 {
t.Fatalf("first approval did not execute: calls=%d", len(stub.rollbackCalls))
}
*requests = nil
// Second approval (replay) should be rejected.
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-2",
From: models.User{ID: allowedUserID},
Data: dangerousCmdPrefix + "approve:" + token,
},
})
if len(stub.rollbackCalls) != 1 {
t.Errorf("replay executed rollback again: calls=%d", len(stub.rollbackCalls))
}
for _, req := range *requests {
if req.method == "answerCallbackQuery" && req.form["text"] == "That action is no longer valid." {
return
}
}
t.Errorf("replay was not rejected; requests: %#v", *requests)
}
func TestDangerousCallbackDeny(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{rollbackResult: "ok"}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
token := g.registerDangerousAction("/rollback 1", "deny test", allowedUserID, func(ctx context.Context) (string, error) {
return "ok", nil
})
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: dangerousCmdPrefix + "deny:" + token,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
if len(stub.rollbackCalls) != 0 {
t.Error("deny executed rollback")
}
var foundDeny bool
for _, req := range *requests {
if req.method == "answerCallbackQuery" && strings.Contains(req.form["text"], "denied") {
foundDeny = true
}
}
if !foundDeny {
t.Errorf("deny was not acknowledged; requests: %#v", *requests)
}
}
func TestDangerousCallbackExecutionFailure(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{rollbackErr: fmt.Errorf("checkpoint corrupted")}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
token := g.registerDangerousAction("/rollback 1", "failure test", allowedUserID, func(ctx context.Context) (string, error) {
return g.Dangerous.Rollback(ctx, 1)
})
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: dangerousCmdPrefix + "approve:" + token,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
var foundFail bool
for _, req := range *requests {
if req.method == "answerCallbackQuery" && strings.Contains(req.form["text"], "Command failed") {
foundFail = true
}
if req.method == "editMessageText" && strings.Contains(req.form["text"], "Failed") {
foundFail = true
}
}
if !foundFail {
t.Errorf("execution failure was not reported; requests: %#v", *requests)
}
}
func TestPermanentApprovalSkipsInlineKeyboard(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{
rollbackResult: "Restored (permanent approval).",
}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
// Grant permanent approval for rollback.
g.dangerousMu.Lock()
g.permanentApprovals = append(g.permanentApprovals, permanentApproval{
CommandPattern: "/rollback",
Recipient: allowedUserID,
GrantedAt: time.Now(),
ExpiresAt: time.Now().Add(24 * time.Hour),
Scope: "test permanent approval",
})
g.dangerousMu.Unlock()
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback 3",
},
})
// Should execute immediately without inline keyboard.
if len(stub.rollbackCalls) != 1 || stub.rollbackCalls[0] != 3 {
t.Errorf("rollbackCalls = %v, want [3]", stub.rollbackCalls)
}
text := messageText(*requests, 0)
if !strings.Contains(text, "Restored (permanent approval)") {
t.Errorf("expected immediate execution result, got: %s", text)
}
if _, ok := (*requests)[0].form["reply_markup"]; ok {
t.Error("permanent approval path rendered inline keyboard (should not)")
}
}
func TestPermanentApprovalExpired(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{rollbackResult: "ok"}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
// Grant expired permanent approval.
g.dangerousMu.Lock()
g.permanentApprovals = append(g.permanentApprovals, permanentApproval{
CommandPattern: "/rollback",
Recipient: allowedUserID,
GrantedAt: time.Now().Add(-48 * time.Hour),
ExpiresAt: time.Now().Add(-1 * time.Minute), // expired
Scope: "expired test",
})
g.dangerousMu.Unlock()
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback 2",
},
})
// Should show inline keyboard (approval required).
text := (*requests)[0].form["text"]
if !strings.Contains(text, "Dangerous command") {
t.Errorf("expected dangerous command prompt for expired permanent approval, got: %s", text)
}
if _, ok := (*requests)[0].form["reply_markup"]; !ok {
t.Error("expired permanent approval should still require inline keyboard")
}
}
func TestPermanentApprovalButtonGrantsApproval(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{
rollbackResult: "Restored after permanent approval grant.",
}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
// Step 1: Trigger approval prompt.
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback 1",
},
})
// Extract permanent approval callback.
var markup models.InlineKeyboardMarkup
if err := json.Unmarshal([]byte((*requests)[0].form["reply_markup"]), &markup); err != nil {
t.Fatalf("decode markup: %v", err)
}
permanentCallback := markup.InlineKeyboard[1][0].CallbackData
*requests = nil
// Step 2: Click Approve Permanently.
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: permanentCallback,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
// Should execute and record permanent approval.
if len(stub.rollbackCalls) != 1 || stub.rollbackCalls[0] != 1 {
t.Errorf("rollbackCalls = %v, want [1]", stub.rollbackCalls)
}
// Verify permanent approval was recorded.
g.dangerousMu.Lock()
hasPerm := false
for _, pa := range g.permanentApprovals {
if pa.CommandPattern == "/rollback 1" && pa.Recipient == allowedUserID {
hasPerm = true
if pa.ExpiresAt.Before(time.Now().Add(23 * time.Hour)) {
t.Error("permanent approval expiry too short")
}
}
}
g.dangerousMu.Unlock()
if !hasPerm {
t.Error("permanent approval was not recorded")
}
}
func TestPermanentApprovalScopedToRecipient(t *testing.T) {
const allowedUserID = int64(42)
const otherUserID = int64(99)
stub := &dangerousStub{rollbackResult: "ok"}
g := New("1:test", "", "", []int64{allowedUserID, otherUserID}, slog.Default())
g.Dangerous = stub
// Grant permanent approval for user 42.
g.dangerousMu.Lock()
g.permanentApprovals = append(g.permanentApprovals, permanentApproval{
CommandPattern: "/rollback",
Recipient: 42,
GrantedAt: time.Now(),
ExpiresAt: time.Now().Add(24 * time.Hour),
Scope: "recipient scoping test",
})
g.dangerousMu.Unlock()
b, requests := newTelegramTestBot(t)
// User 99 tries /rollback — should require approval.
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: otherUserID},
Chat: models.Chat{ID: 8, Type: models.ChatTypePrivate},
Text: "/rollback 2",
},
})
text := (*requests)[0].form["text"]
if !strings.Contains(text, "Dangerous command") {
t.Errorf("user 99 should require approval; got: %s", text)
}
}
func TestApproveHandlerShowsPendingCommands(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
// Register a pending command.
g.registerDangerousAction("/rollback 2", "Rollback to checkpoint 2", allowedUserID, func(ctx context.Context) (string, error) {
return "", nil
})
b, requests := newTelegramTestBot(t)
g.approveHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/approve",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "Pending dangerous commands") {
t.Errorf("expected pending list, got: %s", text)
}
if !strings.Contains(text, "Rollback to checkpoint 2") {
t.Errorf("expected pending command description, got: %s", text)
}
}
func TestApproveHandlerNoPendingCommands(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.approveHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/approve",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "No pending commands") {
t.Errorf("expected no pending message, got: %s", text)
}
}
func TestRollbackNotConfigured(t *testing.T) {
const allowedUserID = int64(42)
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
// Dangerous is nil.
b, requests := newTelegramTestBot(t)
g.rollbackHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/rollback 1",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "not configured") {
t.Errorf("expected not configured message, got: %s", text)
}
}
func TestStopNotConfigured(t *testing.T) {
const allowedUserID = int64(42)
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
// Dangerous is nil.
b, requests := newTelegramTestBot(t)
g.stopHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/stop process",
},
})
text := messageText(*requests, 0)
if !strings.Contains(text, "not configured") {
t.Errorf("expected not configured message, got: %s", text)
}
}
func TestDangerousCommandHelpContainsNewCommands(t *testing.T) {
const allowedUserID = int64(42)
var sentText string
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
b, requests := newTelegramTestBot(t)
g.helpHandler()(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
},
})
for _, req := range *requests {
if req.method == "sendRichMessage" {
sentText = req.form["rich_message"]
}
}
if sentText == "" {
t.Fatal("help sent no rich message")
}
for _, want := range []string{"/rollback", "/stop"} {
if !strings.Contains(sentText, want) {
t.Errorf("help text missing %q", want)
}
}
// /approve and /deny should NOT appear in help (they are hidden).
for _, hidden := range []string{"/approve\n", "/deny\n"} {
if strings.Contains(sentText, hidden) {
t.Errorf("help text contains hidden command %q", hidden)
}
}
}
func TestParseDangerousCallback(t *testing.T) {
tests := []struct {
name string
data string
decision string
token string
}{
{name: "approve", data: dangerousCmdPrefix + "approve:abc123", decision: "approve", token: "abc123"},
{name: "permanent", data: dangerousCmdPrefix + "permanent:def456", decision: "permanent", token: "def456"},
{name: "deny", data: dangerousCmdPrefix + "deny:ghi789", decision: "deny", token: "ghi789"},
{name: "wrong prefix", data: "other:approve:abc", decision: "", token: ""},
{name: "unknown decision", data: dangerousCmdPrefix + "unknown:abc", decision: "", token: ""},
{name: "empty", data: "", decision: "", token: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
decision, token := parseDangerousCallback(tt.data)
if decision != tt.decision || token != tt.token {
t.Errorf("parseDangerousCallback(%q) = (%q, %q), want (%q, %q)",
tt.data, decision, token, tt.decision, tt.token)
}
})
}
}
func TestDangerousCommandSpecDescriptions(t *testing.T) {
found := make(map[string]bool)
for _, spec := range gatewayCommandSpecs {
found[spec.Command] = true
}
for _, cmd := range []string{"rollback", "stop"} {
if !found[cmd] {
t.Errorf("/%s is missing from gatewayCommandSpecs", cmd)
}
}
for _, cmd := range []string{"approve", "deny"} {
if found[cmd] {
t.Errorf("/%s should NOT be in gatewayCommandSpecs (hidden command)", cmd)
}
}
}
func TestDangerousCallbackRejectsWrongRecipient(t *testing.T) {
const allowedUserID = int64(42)
const otherUserID = int64(43)
stub := &dangerousStub{rollbackResult: "ok"}
g := New("1:test", "", "", []int64{allowedUserID, otherUserID}, slog.Default())
g.Dangerous = stub
b, _ := newTelegramTestBot(t)
token := g.registerDangerousAction("/rollback 1", "recipient test", allowedUserID, func(ctx context.Context) (string, error) {
return "ok", nil
})
// User 43 tries to approve user 42's command.
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: otherUserID},
Data: dangerousCmdPrefix + "approve:" + token,
},
})
if len(stub.rollbackCalls) != 0 {
t.Error("wrong recipient executed rollback")
}
}
func TestMalformedDangerousCallback(t *testing.T) {
const allowedUserID = int64(42)
stub := &dangerousStub{}
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
g.Dangerous = stub
b, requests := newTelegramTestBot(t)
g.handleDangerousCallback(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: dangerousCmdPrefix + "bad-format",
},
})
for _, req := range *requests {
if req.method == "answerCallbackQuery" && req.form["text"] == "That action is no longer valid." {
return
}
}
t.Errorf("malformed callback not rejected; requests: %#v", *requests)
}
+27 -9
View File
@@ -49,6 +49,11 @@ type Gateway struct {
// deferral persistence, and installation; Telegram only presents it.
Updates UpdateService
// Dangerous is the sandbox/process authority for /rollback and /stop.
// When nil, those commands return "not configured". The composition
// root supplies this; Telegram only renders approval UX.
Dangerous DangerousCommandAuthority
// restartCh carries /restart requests from a bot handler to the
// supervisor loop in Start. Buffered so a handler never blocks.
restartCh chan restartRequest
@@ -61,6 +66,11 @@ type Gateway struct {
updateInProgress bool
updateActions map[string]updateAction
// dangerous command approval state
dangerousMu sync.Mutex
dangerousActions map[string]dangerousAction
permanentApprovals []permanentApproval
log *slog.Logger
bot *bot.Bot
webhookCancel context.CancelFunc
@@ -86,15 +96,17 @@ type ReleaseAnnouncer interface {
// processing.
func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *slog.Logger) *Gateway {
return &Gateway{
Token: token,
WebhookURL: webhookURL,
WebhookSecret: webhookSecret,
AllowedUserIDs: allowedUserIDs,
restartCh: make(chan restartRequest, 1),
modelCallbacks: make(map[string]string),
providerCallbacks: make(map[string]string),
updateActions: make(map[string]updateAction),
log: log.With("component", "gateway-telegram"),
Token: token,
WebhookURL: webhookURL,
WebhookSecret: webhookSecret,
AllowedUserIDs: allowedUserIDs,
restartCh: make(chan restartRequest, 1),
modelCallbacks: make(map[string]string),
providerCallbacks: make(map[string]string),
updateActions: make(map[string]updateAction),
dangerousActions: make(map[string]dangerousAction),
permanentApprovals: nil,
log: log.With("component", "gateway-telegram"),
}
}
@@ -182,6 +194,10 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, g.helpHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypeExact, g.restartHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/rollback", bot.MatchTypePrefix, g.rollbackHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/stop", bot.MatchTypePrefix, g.stopHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/approve", bot.MatchTypeExact, g.approveHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/deny", bot.MatchTypeExact, g.denyHandler())
// Publish the command list so Telegram renders a menu. Without this
// the commands are undiscoverable and the LLM, having no idea they
@@ -384,6 +400,8 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
if update.CallbackQuery != nil {
switch {
case strings.HasPrefix(update.CallbackQuery.Data, dangerousCmdPrefix):
g.handleDangerousCallback(ctx, b, update)
case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix):
g.handleProviderCallback(ctx, b, update, router)
case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix):
+1 -6
View File
@@ -161,12 +161,7 @@ func TestVersionReportsBothComponents(t *testing.T) {
// dangerous and should not be discoverable by casual chat users. Commands in
// this set may still be executable if typed explicitly — they just shouldn't
// appear on Telegram's discoverability surfaces.
var telegramHiddenCommands = map[string]bool{
"approve": true,
"reset": true, // alias for /new
"fork": true, // alias for /branch
"compact": true, // alias for /compress
}
var telegramHiddenCommands = map[string]bool{"approve": true, "deny": true}
func TestPublishedCommandsMatchExecutableCommandSurface(t *testing.T) {
executable := make(map[string]bool)