Files
bd5adc61c8 feat(bitrix24): imbot.v2 migration, 2-way media, openline sender-tag echo, and hardening (#1236)
* refactor(bitrix24): rename "Path B" framing to maintainer-specified naming [B24:2794]

Per maintainer hard rule #10 (no generic "Path A/B" framing) from PR #1061
review. The Bitrix24 MCP auto-onboard flow is Bitrix-specific glue
("Bitrix24 OAuth -> existing mcp_user_credentials bridge"), NOT a generic
MCP architecture pattern.

Naming convention applied consistently:
- First mention per file: full "Bitrix24 OAuth -> existing
  mcp_user_credentials bridge" (matches maintainer comment verbatim).
- Subsequent mentions in same file: shortened "mcp_user_credentials bridge".
- Test/log context referencing literal endpoint /api/auto-onboard: keep
  "auto-onboard" reference (it's the actual API endpoint name).

Changes are documentation-only:
- Rename in code comments + test descriptions + plan docs.
- Clarify framing in mcp_client.go + provisioner.go doc comments to
  emphasize Bitrix-specific glue (not generic MCP infra).
- Reuse existing mcp_user_credentials table + MCPServerStore methods
  (no schema / store / abstraction change).

Files:
- cmd/gateway.go (factory registration doc)
- internal/channels/bitrix24/{channel,factory,mcp_client,provisioner}.go
- internal/channels/bitrix24/{mcp_client,provisioner}_test.go
- plan/goclaw-mcp-integration.md (21 occurrences)

Verified: go build + MCP-related tests pass (TestProvision*,
TestInitMCPProvisioner*, TestMCPClient*).

Phase 1 of Path C execution per
plans/reports/decision-log-260519-1555-bitrix24-pr-fork-decision.md.

* fix: confine outbound media paths to agent workspace [B24:2794]

Tool MEDIA:<path> output reached channel file-upload sinks (Bitrix
imbot.v2.File.upload, Telegram sendDocument, etc.) verbatim via
parseMediaResult, with no workspace-boundary check. A malicious or buggy
tool emitting MEDIA:/etc/passwd could exfiltrate arbitrary files to chat.

Extract the EvalSymlinks+Rel containment from extractMediaFromContent into
a shared confineToWorkspace helper and apply it at the parseMediaResult
sink in processToolResult. Fixing at the source/egress boundary protects
every channel at once rather than per-channel. Paths that escape the
workspace are dropped and logged (security.media_path_rejected).

Add TestConfineToWorkspace (boundary unit) and
TestParseMediaResultConfinedToWorkspace (sink regression for H2).

* feat(bitrix24): support inbound + outbound media via imbot.v2 File API [B24:2794]

Bitrix24 channel was text-only; attachments were parsed but dropped.
- Inbound: download chat files via imbot.v2.File.download (one-time URL),
  forward to the agent with MIME preserved (internal/channels/bitrix24/download.go).
- Outbound: upload agent media to the chat via imbot.v2.File.upload
  (internal/channels/bitrix24/send_media.go).
- Add BaseChannel.HandleMessageMedia to preserve MIME/filename through the bus.
- Per-channel media_max_mb cap (default 20) applies to both directions.

Tests: 92 pass (internal/channels/bitrix24 + internal/channels), go vet clean (PG + sqliteonly).

* refactor(bitrix24): migrate messaging/bot-list/unregister to imbot v2 API [B24:2794]

Move outbound REST calls to the imbot v2 family (keeps register on v1):
- imbot.message.add -> imbot.v2.Chat.Message.send (fields.message shape, live-verified)
- imbot.bot.list (+ legacy imbot.list fallback) -> imbot.v2.Bot.list; add botListRows
  to normalize the v2 {bots:[...]} envelope, legacy array, and id-keyed map forms
- imbot.unregister -> imbot.v2.Bot.unregister

Bot registration stays on v1 imbot.register: v2 imbot.v2.Bot.register changes the
event-delivery model (per-event handler URLs -> eventMode), which would require
rewriting the inbound event parser. No user-facing behavior change.

Tests: bitrix24 package green; go vet ./... clean.

* feat(bitrix24): route whisper via v1 SKIP_CONNECTOR + add v2 replyId [B24:2794]

Bot was leaking HiddenMessage (whisper) replies to the external Zalo
connector because every outbound call went through imbot.v2.Chat.Message.send,
which has no equivalent of the v1 SKIP_CONNECTOR flag. Branch the outbound
path on inbound visibility:

  whisper → imbot.message.add + SKIP_CONNECTOR=Y  (v1, send_v1.go)
  public  → imbot.v2.Chat.Message.send + fields.replyId  (v2, send_v2.go)

Pipeline:
  events.go        parse data[PARAMS][PARAMS][COMPONENT_ID]=HiddenMessage
                   into EventParams.IsHiddenMessage (form + JSON variants)
  handle.go        set bitrix_visibility on InboundMessage.Metadata
  consumer         forward visibility + message_id into OutboundMessage
  send.go          resolveSendOptions + sendChunk dispatcher +
                   shared callWithRateLimitRetry helper
  metadata_keys.go single source of truth for the keys + values

Defaults preserve pre-refactor behaviour: callers that don't populate
bitrix_visibility still go through v2 public, and replyId is omitted
unless a numeric bitrix_message_id arrives in metadata.

Tests:
  TestParseEvent_FormURLEncoded_IsHiddenMessage  (3 cases)
  TestParseEvent_JSON_IsHiddenMessage             (3 cases)
  TestResolveSendOptions                          (8 cases)
  TestSend_BranchesOnVisibility                   (4 cases)

* feat(bitrix24): openline sender-tag echo on replies [B24:2794]

Openline sender-tag echo (this change):
- Capture the connector sender tag ("[name #id]:" or "[name] #id:") from
  inbound openline group messages, strip it from the body the agent sees,
  and re-prepend the canonical "[name] #id:" form to the reply so the Open
  Channel connector routes the answer back to the right external user.
- New sender_prefix.go helper (+ test) accepts both inbound layouts and
  emits one canonical form; scoped to messages carrying the tag, so plain
  chats are unaffected.
- metadata_keys.go: MetaKeySenderPrefix; handle.go capture/strip/stash;
  gateway_consumer_normal.go forwards the key; send.go prepends it on the
  first chunk before chunking.

Bundled bitrix24 channel-core work already on this branch:
- handle.go: @mention is the sole trigger for both staff and connector
  customers; unmentioned traffic is dropped (was: drop all connector msgs).
- isGroupMessageType: treat SONET_GROUP "B" as a group.
- handle_test.go, mcp_client_test.go: cover the above.

* feat(bitrix24): accept colon-less openline sender tag, echo [name] #id [B24:2794]

The Open Channel connector dropped the trailing colon from its sender tag:
inbound now arrives as "[Name] #id <msg>" (was "[Name] #id: <msg>"). The
id-bearing patterns required the colon, so the tag fell through to the
name-only branch and the reply echoed "[Name]" — dropping the #id the
connector needs to route the answer back.

- sender_prefix.go: make the trailing ":" optional on both id layouts
  ([name #id] / [name] #id, with or without colon) and echo the canonical
  "[name] #id" (no colon) to match the connector's current format. Bare
  "[name]" (no id) still echoes "[name]" for Open Channel only.
- handle.go: gate the bare name-only layout to Open Channel (isOpenChannel)
  so ordinary group chats starting with "[x] ..." are left untouched.
- sender_prefix_test.go: cover colon/no-colon x id-inside/id-outside, the
  name-only openline case, and the non-openline no-op.

* fix: security and robustness fixes from the bitrix24 channel review [B24:2794]

- download.go: block redirect-based SSRF on inbound media. CheckRedirect
  re-validates each hop (http(s) only, reject private/loopback/link-local
  hosts, cap hops); the initial portal-domain pin is no longer bypassable
  via a 3xx to an internal service. Public-host redirects still allowed.
- handle.go: extract/echo the openline sender tag only for Open Channel
  sessions (was: any group chat), removing bogus prefixes in CRM group
  chats and narrowing the forged-tag misroute surface.
- loop_tools.go + loop_media.go: confine result.Media to the agent / team /
  tenant-allowed roots (new confineToAnyRoot) before a channel uploads it,
  so a prompt-injected out-of-workspace path (e.g. /etc/passwd) cannot
  exfiltrate, while legitimate cross-workspace media (team files, delegatee
  output) still flows.
- send_media.go: bounded outbound read via io.LimitReader replaces the
  os.Stat + os.ReadFile pair, closing the TOCTOU size-cap bypass; cap a
  single message's outbound attachments at 10 (mirrors inbound).
- register.go: paginate imbot.v2.Bot.list (limit/offset + hasNextPage,
  capped at 40 pages) so verify/lookup see bots past the first 50.
- mcp_client.go: redact access_token / refresh_token / client_secret from an
  echoed MCP error body before it is logged or returned (+ test).

* fix(security): validate resolved dial IP on Bitrix media redirects [B24:2794]

The inbound media download redirect guard only string-checked the redirect
hostname (isPrivateOrLoopback on req.URL.Hostname()), so a redirect to a public
hostname that resolves to 127.0.0.1 / 169.254.169.254 / an RFC1918 address — or a
DNS-rebinding swap between check and dial — still passed the guard and the client
would connect. Reported in PR review.

Add security.NewRedirectFollowingSafeClient: it follows redirects but validates
the RESOLVED destination IP of every hop at dial time via net.Dialer.Control,
reusing the existing blocked-CIDR list. The IP it checks is the IP actually
dialed, so both redirect-to-internal and DNS rebinding are refused, while
legitimate public CDN redirects still succeed. download.go now uses it instead of
the hostname-string guard.

Tests: deterministic dial-control table (loopback / link-local / private /
multicast / unspecified / public, v4 + v6), malformed/non-IP addr, test bypass,
loopback-dial-blocked client wiring, and redirect cap + scheme checks.

* feat(bitrix24): per-participant Zalo openline identity from 3-token sender tag [B24:2794]

Parse the connector's "[Name] #uid #msgId" sender tag so each external
customer in a shared Open Channel group gets its own contact + USER.md
instead of collapsing onto the connector proxy id. Identity minting is
gated on IS_CONNECTOR=Y to reject operator forged tags. Echo back the
msgId only ("#msgId") on replies; keep the legacy single-number and
name-only layouts unchanged. Zero DB migration.

- sender_prefix.go: parseOpenlineSenderTag() classifies 3-token / legacy / name-only
- handle.go: synthetic senderID "openlines:{instance}:{chat}:{uid}" + participant_user_id metadata, gated on FromIsConnector
- gateway_consumer_normal.go: deriveGroupUserID() routes participant -> per-person scope, group fallback otherwise
- send.go: buildAddressMention numeric-id guard so synthetic ids don't emit invalid [USER=...] BBCode
- MetaKeyMessageID kept as Bitrix MESSAGE_ID (drives v2 fields.replyId); connector msgId surfaced only via echo prefix

---------

Co-authored-by: DangTinh311 <dangtinh31193@gmail.com>
Co-authored-by: Chinh Dang <chinhdang@192.168.68.104>
2026-06-22 14:23:34 +07:00

175 lines
7.2 KiB
Go

package bitrix24
import (
"regexp"
"strings"
)
// Openline (Bitrix Open Channel) relays an external connector user's message
// into the operator chat with a sender tag at the very start of the text. The
// connector has shipped a few layouts over time; we accept them all and
// normalise the id-bearing ones to "[name] #id" and the bare one to "[name]":
//
// [Thân Công Huy #1623524631958449211]: <msg> — id inside the brackets, colon
// [Thân Công Huy #1623524631958449211] <msg> — id inside the brackets, no colon
// [Thân Công Huy] #1623524631958449211: <msg> — id after the brackets, colon
// [Thân Công Huy] #1623524631958449211 <msg> — id after the brackets, no colon
// [Thân Công Huy] <msg> — name only (no id)
//
// The trailing number is the message id (msgId) the connector uses to quote /
// route a reply back to the right external message, so it must survive into the
// echo. (Empirically it is a per-message id, not a per-user id — the same
// external person produces a different number on each message.)
// The trailing ":" is optional because the connector dropped it in its latest
// format. The bare name-only layout is far more generic, so it is only
// recognised for Open Channel sessions (see allowNameOnly).
//
// A newer connector build prepends a SECOND number — the external person's
// stable uid — ahead of the msgId: "[Name] #uid #msgId <msg>". That richer
// 3-token layout is parsed by parseOpenlineSenderTag (below), which keeps the
// uid and msgId separate so callers can scope per-participant identity. The
// single-number layouts above remain the legacy/back-compat path.
//
// Plain Bitrix24 group chats never carry these tags — they use
// "[USER=<id>]Name[/USER]" BBCode mentions, which handle.go converts to
// "@Name (ID:<id>)".
// openlineSenderPrefixPatterns match the id-bearing sender tag anchored at the
// start of the message. Group 1 = display name, group 2 = connector user id
// (digits only). The colon after the tag is optional (`:?`) — newer connector
// builds omit it.
var openlineSenderPrefixPatterns = []*regexp.Regexp{
regexp.MustCompile(`^\[(.+?)\s+#(\d+)\]:?\s*`), // [name #id]: or [name #id]
regexp.MustCompile(`^\[(.+?)\]\s+#(\d+):?\s*`), // [name] #id: or [name] #id
}
// nameOnlySenderPrefixPattern matches the shortest "[name] " tag — a display
// name in brackets followed by whitespace, with no connector id. Group 1 =
// display name. Generic on purpose, so callers gate it behind allowNameOnly to
// keep it to Open Channel sessions only.
var nameOnlySenderPrefixPattern = regexp.MustCompile(`^\[([^\]]+?)\]\s+`)
// extractOpenlineSenderPrefix detects the openline sender tag at the start of
// text. On a match it returns the canonical prefix ("[name] #id" for id-bearing
// tags, "[name]" for the name-only tag) plus the message body with the tag (and
// following whitespace) removed. On no match it returns ("", text) unchanged so
// callers can treat it as a cheap no-op.
//
// allowNameOnly enables the generic name-only "[name] " layout; pass it only
// for Open Channel sessions. The id-bearing layouts are always tried first (and
// take precedence) because their numeric id makes them unambiguous — this also
// stops the name-only pattern from clipping just "[name] " off a "[name] #id"
// tag and dropping the id.
func extractOpenlineSenderPrefix(text string, allowNameOnly bool) (prefix, rest string) {
for _, re := range openlineSenderPrefixPatterns {
m := re.FindStringSubmatch(text)
if m == nil {
continue
}
name := strings.TrimSpace(m[1])
id := m[2]
if name == "" || id == "" {
continue
}
return "[" + name + "] #" + id, text[len(m[0]):]
}
if allowNameOnly {
if m := nameOnlySenderPrefixPattern.FindStringSubmatch(text); m != nil {
if name := strings.TrimSpace(m[1]); name != "" {
return "[" + name + "]", text[len(m[0]):]
}
}
}
return "", text
}
// OpenlineSenderTagFormat classifies which connector sender-tag layout was
// found at the start of an Open Channel message.
type OpenlineSenderTagFormat int
const (
// TagFormatNone means no recognised sender tag was present.
TagFormatNone OpenlineSenderTagFormat = iota
// TagFormatNameOnly is "[Name] <msg>" — a display name with no number.
TagFormatNameOnly
// TagFormatLegacy is "[Name] #msgId <msg>" — a single number, which is the
// connector message id (NOT a user id). This is the format production
// connectors ship today.
TagFormatLegacy
// TagFormatThreeToken is "[Name] #uid #msgId <msg>" — two numbers, where the
// first is the external person's stable uid and the second is the message
// id. Only the newer connector build emits this.
TagFormatThreeToken
)
// OpenlineSenderTag is the structured result of parsing a connector sender tag.
// UID is populated only for TagFormatThreeToken; MsgID is populated for both the
// legacy and three-token layouts. Rest is the message body with the tag removed.
type OpenlineSenderTag struct {
Name string
UID string
MsgID string
Format OpenlineSenderTagFormat
Rest string
}
// threeTokenPattern matches "[Name] #uid #msgId" — two consecutive #digits
// tokens after the bracketed name. Group 1 = name, group 2 = uid, group 3 =
// msgId. The trailing ":" is optional to match the legacy patterns' tolerance.
var threeTokenPattern = regexp.MustCompile(`^\[(.+?)\]\s+#(\d+)\s+#(\d+):?\s*`)
// parseOpenlineSenderTag classifies the connector sender tag at the start of an
// Open Channel message and returns its parts separated. Precedence is
// most-specific first: three-token (uid + msgId) → id-bearing legacy (msgId
// only) → name-only → none. On no match it returns {Format: TagFormatNone,
// Rest: text} so callers can treat it as a cheap no-op.
//
// Callers must gate identity derivation on the message source (IS_CONNECTOR=Y)
// themselves — this function only parses the shape; an operator who types a
// look-alike tag would parse identically. Only call it for Open Channel
// sessions; ordinary group chats never carry these tags.
func parseOpenlineSenderTag(text string) OpenlineSenderTag {
// Three-token: "[Name] #uid #msgId" — try first so the second number isn't
// mistaken for the body by the single-number legacy patterns.
if m := threeTokenPattern.FindStringSubmatch(text); m != nil {
if name := strings.TrimSpace(m[1]); name != "" && m[2] != "" && m[3] != "" {
return OpenlineSenderTag{
Name: name,
UID: m[2],
MsgID: m[3],
Format: TagFormatThreeToken,
Rest: strings.TrimSpace(text[len(m[0]):]),
}
}
}
// Legacy id-bearing: "[Name] #msgId" or "[Name #msgId]" — one number = msgId.
for _, re := range openlineSenderPrefixPatterns {
if m := re.FindStringSubmatch(text); m != nil {
if name := strings.TrimSpace(m[1]); name != "" && m[2] != "" {
return OpenlineSenderTag{
Name: name,
MsgID: m[2],
Format: TagFormatLegacy,
Rest: strings.TrimSpace(text[len(m[0]):]),
}
}
}
}
// Name-only: "[Name] <msg>".
if m := nameOnlySenderPrefixPattern.FindStringSubmatch(text); m != nil {
if name := strings.TrimSpace(m[1]); name != "" {
return OpenlineSenderTag{
Name: name,
Format: TagFormatNameOnly,
Rest: strings.TrimSpace(text[len(m[0]):]),
}
}
}
return OpenlineSenderTag{Format: TagFormatNone, Rest: text}
}