mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-01 04:10:58 +08:00
Compare commits
4
Commits
sec/sandbox-mvp
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b384b0823d | ||
|
|
02b64521c6 | ||
|
|
4d8c2c74e6 | ||
|
|
fe9a0813c4 |
@@ -107,15 +107,20 @@ func (d *DB) SetChatBridgeApprovalMessage(ctx context.Context, id int64, message
|
||||
// UseChatBridgeApproval spends the nonce of a button press. It succeeds once,
|
||||
// for the chat and message the buttons were sent to, before they expire, and
|
||||
// closes the buttons in the same statement. It returns nil when the press
|
||||
// does not count: unknown nonce, another chat or message, expired, or used.
|
||||
func (d *DB) UseChatBridgeApproval(ctx context.Context, kind, chatID, messageID, nonceHash, by string) (*ChatBridgeApproval, error) {
|
||||
// does not count: unknown nonce, another chat or message, expired, used, or
|
||||
// the bridge's configuration changed (config_version) or was disabled since
|
||||
// the caller read it, so a member removed after the dispatch snapshot cannot
|
||||
// spend a button with stale access.
|
||||
func (d *DB) UseChatBridgeApproval(ctx context.Context, kind, chatID, messageID, nonceHash, by string, configVersion int64) (*ChatBridgeApproval, error) {
|
||||
var a ChatBridgeApproval
|
||||
err := d.QueryRowContext(ctx, `
|
||||
UPDATE chat_bridge_approvals SET closed_at=NOW(), closed_by=$5
|
||||
WHERE kind=$1 AND chat_id=$2 AND message_id=$3 AND message_id<>'' AND nonce_hash=$4
|
||||
AND closed_at IS NULL AND expires_at > NOW()
|
||||
RETURNING id, kind, chat_id, pending_id, message_id, message_text, expires_at`,
|
||||
kind, chatID, messageID, nonceHash, by).Scan(&a.ID, &a.Kind, &a.ChatID, &a.PendingID, &a.MessageID, &a.MessageText, &a.ExpiresAt)
|
||||
UPDATE chat_bridge_approvals a SET closed_at=NOW(), closed_by=$5
|
||||
FROM chat_bridges b
|
||||
WHERE a.kind=$1 AND b.kind=a.kind AND b.config_version=$6 AND b.enabled
|
||||
AND a.chat_id=$2 AND a.message_id=$3 AND a.message_id<>'' AND a.nonce_hash=$4
|
||||
AND a.closed_at IS NULL AND a.expires_at > NOW()
|
||||
RETURNING a.id, a.kind, a.chat_id, a.pending_id, a.message_id, a.message_text, a.expires_at`,
|
||||
kind, chatID, messageID, nonceHash, by, configVersion).Scan(&a.ID, &a.Kind, &a.ChatID, &a.PendingID, &a.MessageID, &a.MessageText, &a.ExpiresAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ func TestChatBridgeApprovalLifecycle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const kind = "t-bridge-approvals"
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) })
|
||||
if _, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false); err != nil {
|
||||
br, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := d.CreateTask("chat bridge approvals", "", nil, 0, 0)
|
||||
@@ -69,7 +70,7 @@ func TestChatBridgeApprovalLifecycle(t *testing.T) {
|
||||
t.Fatalf("still to push after create: %+v", got)
|
||||
}
|
||||
// Before the message id is known, a press cannot count.
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "", "hash-1", "u"); err != nil || a != nil {
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "", "hash-1", "u", br.ConfigVersion); err != nil || a != nil {
|
||||
t.Fatalf("press before send = %+v %v", a, err)
|
||||
}
|
||||
if err := d.SetChatBridgeApprovalMessage(ctx, id, "555"); err != nil {
|
||||
@@ -79,16 +80,16 @@ func TestChatBridgeApprovalLifecycle(t *testing.T) {
|
||||
// A press from another chat, on another message or with another nonce
|
||||
// does not count.
|
||||
for _, c := range []struct{ chat, msg, hash string }{{"200", "555", "hash-1"}, {"100", "556", "hash-1"}, {"100", "555", "hash-x"}} {
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, c.chat, c.msg, c.hash, "u"); err != nil || a != nil {
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, c.chat, c.msg, c.hash, "u", br.ConfigVersion); err != nil || a != nil {
|
||||
t.Fatalf("press %+v = %+v %v", c, a, err)
|
||||
}
|
||||
}
|
||||
// The right press counts once.
|
||||
a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7")
|
||||
a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7", br.ConfigVersion)
|
||||
if err != nil || a == nil || a.PendingID != pending || a.MessageText != "Approval needed" {
|
||||
t.Fatalf("press = %+v %v", a, err)
|
||||
}
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7"); err != nil || a != nil {
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7", br.ConfigVersion); err != nil || a != nil {
|
||||
t.Fatalf("second press = %+v %v", a, err)
|
||||
}
|
||||
// A used push is not closed again.
|
||||
@@ -106,7 +107,8 @@ func TestChatBridgeApprovalsToClose(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const kind = "t-bridge-approvals-close"
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) })
|
||||
if _, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false); err != nil {
|
||||
br, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newPending := func() int64 {
|
||||
@@ -142,7 +144,7 @@ func TestChatBridgeApprovalsToClose(t *testing.T) {
|
||||
t.Fatalf("to close = %+v %v", got, err)
|
||||
}
|
||||
// An expired nonce no longer counts.
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "mh-expired", "h-expired", "u"); err != nil || a != nil {
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "mh-expired", "h-expired", "u", br.ConfigVersion); err != nil || a != nil {
|
||||
t.Fatalf("expired press = %+v %v", a, err)
|
||||
}
|
||||
for _, a := range got {
|
||||
@@ -154,3 +156,51 @@ func TestChatBridgeApprovalsToClose(t *testing.T) {
|
||||
t.Fatalf("after close: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatBridgeApprovalStaleConfig verifies that a button press is refused
|
||||
// after the bridge configuration changed, and counts only with the current
|
||||
// config version. This is the batch-dispatch race: the poller authorized the
|
||||
// update with an older allowlist.
|
||||
func TestChatBridgeApprovalStaleConfig(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-approval-stale"
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) })
|
||||
br, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"-100"}, AllowedUsers: []string{"7"}}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := d.CreateInterceptPending(0, 0, "", "worker-1", "bash", []byte(`{}`), "ask")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE id=$1`, pending) })
|
||||
id, created, err := d.CreateChatBridgeApproval(ctx, kind, "-100", pending, "hash-stale", "text", time.Now().Add(time.Hour))
|
||||
if err != nil || !created {
|
||||
t.Fatalf("create = %v %v", created, err)
|
||||
}
|
||||
if err := d.SetChatBridgeApprovalMessage(ctx, id, "m-stale"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"-100"}, AllowedUsers: []string{}}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next.ConfigVersion == br.ConfigVersion {
|
||||
t.Fatalf("config version did not change: %d", next.ConfigVersion)
|
||||
}
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "-100", "m-stale", "hash-stale", "7", br.ConfigVersion); err != nil || a != nil {
|
||||
t.Fatalf("stale press = %+v %v", a, err)
|
||||
}
|
||||
var open bool
|
||||
if err := d.QueryRow(`SELECT closed_at IS NULL FROM chat_bridge_approvals WHERE id=$1`, id).Scan(&open); err != nil || !open {
|
||||
t.Fatalf("button after stale press: open=%v err=%v", open, err)
|
||||
}
|
||||
if a, err := d.UseChatBridgeApproval(ctx, kind, "-100", "m-stale", "hash-stale", "7", next.ConfigVersion); err != nil || a == nil {
|
||||
t.Fatalf("current press = %+v %v", a, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,8 +149,18 @@ func (s *Server) bridgeApprovalPress(ctx context.Context, req chatbridge.Request
|
||||
if !ok || s.m.interceptor == nil {
|
||||
return chatbridge.CallbackReply{Toast: "This button is not recognized."}
|
||||
}
|
||||
// The poller authorized this batch with the allowlist it read at the time.
|
||||
// Re-read the bridge before spending the button: a member removed, a chat
|
||||
// unlisted, or the bridge disabled since that snapshot must not count. The
|
||||
// consume statement below also requires this exact config_version, so a
|
||||
// save between this read and the press is refused instead of raced.
|
||||
b, err := s.m.PG().ChatBridgeByKind(ctx, req.Kind)
|
||||
if err != nil || !b.Enabled || !stillAllowed(b, req) {
|
||||
log.Printf("%s refused approval press in chat %s from user %s: bridge access changed", tag, req.ChatID, req.UserID)
|
||||
return chatbridge.CallbackReply{Toast: "This button no longer works. Decide in ARTEX."}
|
||||
}
|
||||
by := bridgeApprover(req)
|
||||
a, err := s.m.PG().UseChatBridgeApproval(ctx, req.Kind, req.ChatID, req.MessageID, approvalNonceHash(nonce), by)
|
||||
a, err := s.m.PG().UseChatBridgeApproval(ctx, req.Kind, req.ChatID, req.MessageID, approvalNonceHash(nonce), by, b.ConfigVersion)
|
||||
if err != nil {
|
||||
log.Printf("%s check approval button in chat %s: %v", tag, req.ChatID, err)
|
||||
return chatbridge.CallbackReply{Toast: "Could not check the button. Try again."}
|
||||
|
||||
@@ -155,3 +155,76 @@ func TestParseApprovalData(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatBridgeApprovalRechecksAccess covers the batch-dispatch race: the
|
||||
// poller authorized the button with the allowlist it loaded, and the sender is
|
||||
// removed before the queued press is handled. The handler must re-read the
|
||||
// bridge, refuse the press, and leave the button open for the current members.
|
||||
func TestChatBridgeApprovalRechecksAccess(t *testing.T) {
|
||||
s, task, fake := bridgeCommandServer(t)
|
||||
ctx := context.Background()
|
||||
pg := s.m.PG()
|
||||
tid, _ := strconv.ParseInt(task.ID, 10, 64)
|
||||
if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{
|
||||
Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{"bot_token":"x"}`),
|
||||
AllowedChats: []string{"-100"}, AllowedUsers: []string{"7"},
|
||||
}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pg.SetChatBridgeTask(ctx, fakeBridgeKind, "-100", "supergroup", tid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := pg.CreateInterceptPending(0, 0, task.ID, "worker-1", "bash", []byte(`{"command":"id"}`), "rule says ask")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM intercept_pending WHERE id=$1`, pending) })
|
||||
|
||||
s.chatBridgeApprovalTick(ctx, fakeBridgeKind)
|
||||
if len(fake.buttons) != 1 || fake.buttons[0].chatID != "-100" {
|
||||
t.Fatalf("pushes = %+v, want one to the group", fake.buttons)
|
||||
}
|
||||
msg := fake.buttons[0]
|
||||
allowData := msg.rows[0][0].Data
|
||||
|
||||
// The member is removed while the update is queued. The stale dispatcher
|
||||
// still reaches the handler; the handler must not spend the button.
|
||||
if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{
|
||||
Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{"bot_token":"x"}`),
|
||||
AllowedChats: []string{"-100"}, AllowedUsers: []string{},
|
||||
}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply := s.bridgeApprovalPress(ctx, chatbridge.Request{
|
||||
Kind: fakeBridgeKind, ChatID: "-100", ChatType: "supergroup", UserID: "7",
|
||||
Args: allowData, MessageID: msg.messageID,
|
||||
})
|
||||
if !strings.Contains(reply.Toast, "no longer works") {
|
||||
t.Fatalf("removed member press = %+v", reply)
|
||||
}
|
||||
if p, _ := pg.GetInterceptPending(pending); p == nil || p.Status != "pending" {
|
||||
t.Fatalf("removed member decided the request: %+v", p)
|
||||
}
|
||||
var open bool
|
||||
if err := pg.QueryRow(`SELECT closed_at IS NULL FROM chat_bridge_approvals WHERE pending_id=$1`, pending).Scan(&open); err != nil || !open {
|
||||
t.Fatalf("button after removed member press: open=%v err=%v", open, err)
|
||||
}
|
||||
|
||||
// A current member can still use the same button.
|
||||
if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{
|
||||
Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{"bot_token":"x"}`),
|
||||
AllowedChats: []string{"-100"}, AllowedUsers: []string{"7"},
|
||||
}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply = s.bridgeApprovalPress(ctx, chatbridge.Request{
|
||||
Kind: fakeBridgeKind, ChatID: "-100", ChatType: "supergroup", UserID: "7",
|
||||
Args: allowData, MessageID: msg.messageID,
|
||||
})
|
||||
if !strings.Contains(reply.Toast, "Allowed") {
|
||||
t.Fatalf("current member press = %+v", reply)
|
||||
}
|
||||
if p, _ := pg.GetInterceptPending(pending); p == nil || p.Status != "allowed" {
|
||||
t.Fatalf("current member did not decide: %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user