Skip to content

feat(park): Pocket agent park CallApp + audit fixes - #316

Open
bobme2025 wants to merge 14 commits into
restsend:mainfrom
bobme2025:feature/park_app_support
Open

bobme2025 wants to merge 14 commits into
restsend:mainfrom
bobme2025:feature/park_app_support

Conversation

@bobme2025

Copy link
Copy Markdown

PR Title

feat(park): Pocket agent park CallApp + audit fixes

PR Body (paste into the description)

Pocket agent park CallApp + 代码审计修复

A call routed to park:<context>?key=&agent=&progress=&progress2=&record=&max= is not answered: the app sends 183 Session Progress with looping early-media ringback to hold the caller, and registers itself in a process-wide PARK_REGISTRY. A daemon drives the two-stage exit via RWI call.unpark (stage:"leg" dials the agent leg; agent-leg 200 auto-bridges the caller; cancel:true hangs up). RWI also exposes park.list and call.park.info.

路由到 park:<context>?... 的通话不被接听:app 发 183 Session Progress + 循环 early-media 彩铃保持主叫,并注册到进程级 PARK_REGISTRY。daemon 通过 RWI call.unpark 驱动两段式退出(stage:"leg" 拨端腿;端腿 200 自动桥接主叫;cancel:true 挂断)。RWI 另提供 park.list / call.park.info。

Feature / 功能

  • New ParkApp (src/call/app/park.rs) — 183 early-media hold, ParkKey 3-level resolution (target key= → key_header → X-cid), per-agent ringback, two-stage unpark state machine.
  • RWI events park_entered / park_exited / park_agent_leg; commands call.unpark / park.list / call.park.info (processor-level, resolved against the registry).
  • Per-agent ringback console API (upload/serve/delete/list) with SSRF + traversal guards.
  • HTTP router application action (app / app_params / auto_answer); always-forwarding + blind-transfer park: targets.
  • [park] config; ringback sound files (hold-music zh/en, pocket-park, pocket-park2).

Audit fixes / 审计修复

A multi-dimension, adversarially-verified review (see PARK_AUDIT.md) found and fixed:

  • M1 — record= target param was parsed but never used; now feeds the bridge recording decision (resolve_record).
  • M2 — registry cleanup by key could delete another call's entry on key collision; now cleans by session_id.
  • M3 — app-loop early Err skipped on_exit, leaking the registry entry; added a Drop safety net + best-effort start_recording.
  • L1–L5 — park_exited real context/key; removed dead pending_bridge; progress2 accepts http(s) like progress; max=0 = unlimited; CcCall lookup honors called.
  • R1 — ringback upload SSRF: async SSRF guard (DNS-resolving) + no-redirect HTTP client.
  • R2 — park_exited was never emitted (in_park_context() always false at AppExited); now gated on the persistent park_identity with exactly-once take_park_identity().
  • R3 — always-forwarding + transfer paths started the park app with auto_answer=true (answered the caller instead of 183 hold); now false.
  • R5 — removed redundant/stale record_override; resolve_record simplified to two tiers.

Tests / 测试

16 park unit tests green (X-cid parsing, registry, unpark payload, recording precedence, Drop cleanup, park_identity exactly-once, CcCall filter, ringback source validation).

Deferred / 待办

  • R4 — RWI per-command scope authorization (pre-existing RWI model; tracked as a follow-up).
  • R6/R7/R8 (low) — ringback not restored on ring-timeout; registry capacity TOCTOU; X-cid path traversal into the ringback path.

wangfeng added 13 commits November 26, 2026 00:54
…wer)

- HttpRouteAction 增加 Application 变体;HttpResponsePayload 增加 app、app_params、auto_answer
- Application 与 Forward 共用呼叫级组装(媒体/录音/头/超时),只跳过 targets
- app 缺失或为空直接 500 PARSE_FAILED,不静默回落(避免什么都没 park、主叫一直振铃)
- auto_answer 缺省 false:park 自己回 183 放等待音
- 为 CCM 呼入按被叫号动态路由到 park 提供 schema 表达力(静态 dialplan 只能固定 key)
… unpark

Implements the park design doc (Pocket坐席park-实施方案) on the 0.5.2-rc
baseline, CCS/CCM untouched:

- ParkApp (src/call/app/park.rs): 183 Session Progress + looping ringback
  holds the caller; no park-side timeout — convergence via caller BYE /
  CCM BYE / daemon cancel / agent answer. Three-level correlation key
  (target key= → key_header → X-cid parse) with explicit degradation;
  three-level ringback (progress= → agents/{ext}/ringback.wav → tone);
  capacity gate rejects busy at max instead of queueing.
- ParkRegistry (process-wide): register/update/resolve/list for the RWI
  layer; latest-wins upsert warns on key collision.
- CallCommand::Unpark + ParkStage (leg/bridge/one-shot), delivered to the
  running park app as AppEvent::Custom("park.unpark").
- CallController::ring_with_early_media thin wrapper (Ring{EarlyMedia}).
- park: target end-to-end: TransferEndpoint::Park, TransferTarget::Park,
  always-forwarding arm, builtin app factory "park" arm, DialplanFlow
  Application path unchanged (shared).
- RWI: call.unpark / park.list / call.park.info processor-level commands
  resolved against the park registry; ParkList/ParkInfo results.
- HTTP router: new `application` action (app + app_params + auto_answer)
  so the per-call park target reaches the app factory without dialplan
  changes — the daemon's router returns the park target directly.
- [park] config section (key_header/max/default_tone/sounds_dir/
  ring_timeout_secs).

X-cid parse uses split_once (call_id numeric and first); the doc's
rsplit_once suggestion measured wrong for called segments containing '-'.
R1c of the park design doc: agent ringback import reusing the queue
console validation chain — SSRF guard (is_url_ssrf_safe), wav/mp3
whitelist on the URL basename, size-capped download (30s timeout,
max_audio_download_bytes), payload validation (content-type + magic
header). Files land at {sounds_dir}/agents/{ext}/ringback.wav with a
digits-only ext constraint; serve/delete/list endpoints keep the
canonical-path traversal guard. Mounted on the console api router.

The park app's three-level ringback resolution picks these up
automatically (progress= → agents/{ext}/ringback.wav → default tone).
Daemon-facing event stream for the park flow (design doc §1a/§3.4a/§4):

- park_entered: emitted on park entry with the resolved correlation key,
  context, caller/called and ringback — the daemon's parked-call mapping
  (always emitted, not the doc's optional webhook).
- park_agent_leg: dialing / leg_ready / failed / ring_timeout transitions
  of the two-stage unpark agent leg.
- park_exited: emitted by the session on AppExited while in park context;
  reason derived from the recorded hangup reason (caller_hangup /
  cancelled / transferred / ended).
Covers the call.unpark session resolution order (call_id → key → x_cid →
cc_call_id+called) against the real process-wide park registry, including
the malformed-cc_call_id and no-match degradation paths.
Add a second ringback segment to the park app: `progress2=` (config and
inline param) is switched in when the agent leg starts ringing, so the
caller hears a different tone once the agent is actually being alerted.
Only the early-media audio is swapped; the existing 183 is kept. If the
agent leg fails and the app falls back to Parked, the caller's ringback
is restored to the first segment.

Also parse progress2 from both the per-target params and the query
string, tolerating tone:// and on-disk paths the same way progress does.
代码审计(PARK_AUDIT.md)发现并修复三个中severity 正确性问题:

- M1: park: 目标的 record= 参数此前被解析但从未使用,record=0 不生效。
  bridge 录音判定改为 record.or(record_override).or(Some(params.record))
  .unwrap_or(true),并抽成纯函数 resolve_record 便于单测。
- M2: registry 清理此前按 key 删除,key 冲突(同 X-cid 重拨)时 on_exit
  会误删其他会话的条目。ParkApp 新增 session_id 字段,on_exit 改用
  remove_by_session 按会话精确清理。
- M3: app 事件循环在 on_enter/on_external_event 提前 Err 时跳过 on_exit,
  导致 registry 条目泄漏。新增 impl Drop for ParkApp 作为幂等兜底;
  start_recording 改为 best-effort(失败仅 warn,不再 ? 中断已桥接通话)。

同时定稿端腿 200 自动桥接(pocket 端不再上报 answer,避免等 daemon
bridge 造成主叫挂在第二段彩铃的死锁),并给"无 answer SDP 时 200 不发送"
的静默失败补上 warn 日志。

新增 4 个单测:resolve_record_precedence、drop_removes_own_registry_entry、
drop_does_not_remove_other_call_with_same_key、drop_is_idempotent_after_on_exit_cleanup。
12 个 park 单测全绿。
- L1: ParkExited 事件此前硬编码 context="pocket"/key="",非 pocket 上下文对账
  破裂。park app 在 on_enter 通过 SessionExtensions::set_park_identity 发布真实
  context/key,session 在 AppExited 处理里读取(缺失回退默认)。
- L2: 删除端腿 200 自动桥接定稿后变为只写不读的死字段 pending_bridge,
  并去掉 dial_agent_leg 只为它服务的 stage 参数。
- L3: progress2 此前只放行 tone:// 和已存在本地文件,http(s) URL 被静默丢弃。
  新增 is_usable_ringback_source 与 progress 对齐,不可用值打 warn。
- L4: max=0(target 或 config)此前恒 486 拒绝,现视为"不限"回退默认 2000。
- L5: ParkLookup::CcCall 此前忽略 called,现按 called 做二次过滤(空则宽松)。

新增 3 个单测:usable_ringback_source_kinds、cc_call_lookup_filters_by_called、
park_identity_roundtrip。15 个 park 单测全绿。
R2: park_exited 事件从不发出。AppExited 处理用 in_park_context() 作 gate,
但 app-runtime 先发 AppExited 前已清空 running 槽,gate 恒 false,导致
park_exited 在所有退出路径被跳过(上一轮 L1 的 park_identity 读取是死代码)。
改为用持久的 park_identity 作 gate,并新增消费式 take_park_identity() 保证
park_exited 恰好发一次(parked 通话随后转到其他 app 时不重复发)。
in_park_context() 仍用于 4 个运行期信号发射点,未改动。

R3: always-forwarding 与 blind-transfer 路径以 auto_answer=true 启动 park app,
主叫被 200 接听+静音,而非 183 early-media 保持(仅 HTTP 路径正确)。
start_park_app 改用 ensure_app_running_with(..., false, ...);call.rs
always-forwarding park 臂第三元组改 false。

新增单测 take_park_identity_is_exactly_once。16 个 park 单测全绿。
R1: 彩铃上传 SSRF。守卫改用 is_url_ssrf_safe_async(解析 DNS 并拒绝内网
IP,堵住域名指向内网/DNS-rebinding 绕过);ConsoleState 新增
http_client_no_redirect(Policy::none())+ getter,上传抓取改用它,
302 到内网地址不再被跟随(默认客户端最多跟随 10 次重定向)。参照
ivr_exec_hook.rs 的既有模式。

R5: 删除 record_override 字段。它与 unpark record 同源(显式桥接路径冗余),
且在端腿 200 自动桥接路径上是来自先前 leg-dial unpark 的陈旧值,导致录音
结果错(target record=1 却因 leg-dial 的 record=false 跳过录音)。
resolve_record 简化为两层:unpark record → target record= → 默认 true。
更新 resolve_record_precedence 单测。

16 个 park 单测全绿。
@bobme2025

Copy link
Copy Markdown
Author

ParkApp give more flex controlability## Pocket agent park CallApp + 代码审计修复
A call routed to park:<context>?key=&agent=&progress=&progress2=&record=&max= is not answered: the app sends 183 Session Progress with looping early-media ringback to hold the caller, and registers itself in a process-wide PARK_REGISTRY. A daemon drives the two-stage exit via RWI call.unpark (stage:"leg" dials the agent leg; agent-leg 200 auto-bridges the caller; cancel:true hangs up). RWI also exposes park.list and call.park.info.

Primary use case: call center platform cmdcallout to mobile Pocket Agent agent

  1. Call center issues cmdcallout; RustPBX routes the incoming call to park: target.
  2. ParkApp does NOT send 200 OK. It replies 183 Session Progress + looping early-media hold audio to keep the caller media alive, registers the call into process-wide PARK_REGISTRY, emits park_entered.
  3. Wait until mobile Pocket Agent finishes SIP registration and becomes ready.
  4. Platform/CTI triggers unpark via RWI call.unpark with stage:"leg": PBX originates the agent leg to mobile SIP endpoint.
  5. Once mobile agent answers (200 OK), media bridge is automatically set up between caller and agent; event park_agent_leg fires.
  6. cancel:true variant: tear down parked call directly without originating agent leg. On call end/cancel, park_exited is emitted and registry entry cleaned up.

Additional capabilities:

  • max= limits concurrent parked calls in this park context; max=0 means unlimited.
  • record= controls bridge recording after agent answer.
  • RWI park.list / call.park.info allow CTI to inspect parked call inventory.
  • Reusable for consult transfer / blind transfer intermediate hold scenarios.

路由到 park:<context>?... 的通话不被接听:app 发 183 Session Progress + 循环 early-media 彩铃保持主叫,并注册到进程级 PARK_REGISTRY。daemon 通过 RWI call.unpark 驱动两段式出驻留流程(stage:"leg" 拨端腿;端腿 200 自动桥接主叫;cancel:true 挂断)。RWI 另提供 park.list / call.park.info。

🎯 使用场景:呼叫中心平台转移动端坐席(cmdcallout)

本模块核心支撑呼叫中心平台 cmdcallout 转移动端 Pocket Agent 坐席流程:

  1. 呼叫中心平台下发 cmdcallout 调度指令,RustPBX 把来电路由到 park: 目标;
  2. ParkApp 不回复 200 OK,向主叫返回 183 Session Progress + 循环早期媒体保持音,维持主叫媒体链路不释放,同时将该呼叫注册进进程级 PARK_REGISTRY,抛出 park_entered 事件;
  3. 等待移动端坐席 Pocket Agent 完成 SIP 注册、就绪;
  4. 平台/CTI 通过 RWI call.unpark(stage:"leg")触发出驻留:PBX 发起坐席腿呼叫(移动端 SIP 分机);
  5. 移动端坐席应答(200 OK)后,系统自动桥接主叫与坐席媒体,通话建立;抛出 park_agent_leg;
  6. 支持 cancel:true 模式:直接挂断驻留呼叫,不拉起坐席腿;呼叫结束/取消时触发 park_exited,注册表自动清理。

配套能力:

  • 支持 max= 控制该 park 槽位最大并发驻留数量,max=0 不限;
  • record= 参数控制桥接接通后是否开启录音;
  • 支持查询 park.list / call.park.info,CTI 侧可实时查看当前驻留呼叫清单;
  • 同时兼容咨询转接、盲转场景下的中间态驻留,统一复用这套 ParkApp。

时序示意

sequenceDiagram
    participant Caller as Caller
    participant PBX as RustPBX<br/>ParkApp
    participant Daemon
    participant CTI as CTI/呼叫中心平台
    participant Agent as Pocket Agent<br/>移动端坐席

    Caller->>PBX: INVITE
    PBX->>PBX: 路由至 park:<context>
    PBX-->>Caller: 183 Session Progress + early-media 保持音
    PBX->>PBX: 写入 PARK_REGISTRY
    PBX->>CTI: event park_entered

    Note over PBX,Agent: 等待 Pocket Agent SIP 注册就绪

    CTI->>Daemon: RWI call.unpark(stage:"leg")
    Daemon->>PBX: 发起坐席腿 INVITE
    PBX->>Agent: INVITE
    Agent-->>PBX: 200 OK
    PBX->>PBX: 自动桥接主叫与坐席媒体
    PBX->>CTI: event park_agent_leg

    Note over Caller,Agent: 通话进行中

    alt 主动取消驻留
        CTI->>Daemon: RWI call.unpark(cancel:true)
        PBX-->>Caller: 释放呼叫
    else 通话正常结束
        Agent/Caller->>PBX: BYE
    end
    PBX->>CTI: event park_exited
    PBX->>PBX: 清理 PARK_REGISTRY 条目
Loading

R6: on_timeout(振铃超时)回到 Parked 时不恢复第一段彩铃,主叫会停在
progress2("坐席正在振铃")音。现镜像 park_agent_failed,超时后切回第一段。

R7: ParkRegistry::register 容量检查是非原子 check-then-act(TOCTOU),并发
注册时 max 上限不被强制。新增 register_lock(parking_lot::Mutex),容量检查
+ insert 全程持锁,cap 原子强制。

R8: 经攻击者可控 X-cid 到 resolve_ringback 文件路径的路径遍历。新增
sanitize_agent_ext(只保留字母数字/下划线,剥离 / 与 ..),resolve_ringback
构造路径前消毒 called;只消毒文件路径,registry/事件的 called 值不变。

新增单测 sanitize_agent_ext_strips_path_separators。17 个 park 单测全绿。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant