Skip to content

Add OnAuthenticate to ITwilioSessionHook,ITwilioCallStatusHook#1379

Open
yileicn wants to merge 3 commits into
SciSharp:masterfrom
yileicn:master
Open

Add OnAuthenticate to ITwilioSessionHook,ITwilioCallStatusHook#1379
yileicn wants to merge 3 commits into
SciSharp:masterfrom
yileicn:master

Conversation

@yileicn

@yileicn yileicn commented Jul 16, 2026

Copy link
Copy Markdown
Member

No description provided.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Add synchronous OnAuthenticate hook for Twilio session and call status flows

✨ Enhancement ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Add synchronous Twilio hook entrypoint to establish identity before async hook execution.
• Invoke authentication hook across inbound/outbound call, status, recording, and media-stream
 paths.
• Remove unused OpenAI realtime service lookup and retire an obsolete GPT-4o realtime preview
 constant.
Diagram

graph TD
  A[Twilio Webhook] --> B["Twilio Controllers"] --> D[HookEmitter]
  A --> C["TwilioStreamMiddleware"] --> D --> E["ITwilioSessionHook"]
  D --> F["ITwilioCallStatusHook"]

  subgraph Legend
    direction LR
    _ext{{External}} ~~~ _svc([Service])
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Make OnAuthenticate async (Task)
  • ➕ Allows implementers to perform I/O (DB/API) during authentication in a first-class way
  • ➕ Consistent signature with other hooks
  • ➖ AsyncLocal/identity propagation may not survive across awaits unless identity is re-applied later
  • ➖ Changes semantics and may introduce ordering/race issues if subsequent hooks start before auth completes
2. Move identity setup into middleware/action filter
  • ➕ Centralizes authentication and avoids requiring every hook implementer to update
  • ➕ Keeps hook interfaces smaller and avoids breaking changes
  • ➖ Harder to scope per-agent hook behavior and per-event customization
  • ➖ Doesn't solve media-stream case cleanly if identity is not present in that channel without constructing equivalent request context
3. Pass explicit identity/context object to all hook methods
  • ➕ Eliminates reliance on AsyncLocal propagation across async boundaries
  • ➕ More explicit and testable context handling
  • ➖ Large, cross-cutting API change across all hook methods and call sites
  • ➖ Higher migration cost than adding a single pre-hook

Recommendation: Current approach (a synchronous OnAuthenticate invoked before any async hook work) is a pragmatic fix for AsyncLocal identity propagation issues, especially in Twilio streaming where no upstream identity exists. Keep it sync to guarantee identity is established before awaited hooks run; if future auth requires I/O, consider a two-phase design (sync identity seed + optional async enrichment) to preserve the propagation guarantees.

Files changed (9) +33 / -5

Enhancement (7) +33 / -2
TwilioInboundController.csAuthenticate synchronously before session and voicemail status hooks +6/-1

Authenticate synchronously before session and voicemail status hooks

• Emits ITwilioSessionHook.OnAuthenticate before async session hooks run. Also emits ITwilioCallStatusHook.OnAuthenticate before voicemail status handling to ensure identity is set before awaited hooks.

src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs

TwilioOutboundController.csAuthenticate synchronously before outbound voicemail status hook +3/-1

Authenticate synchronously before outbound voicemail status hook

• Emits ITwilioCallStatusHook.OnAuthenticate before invoking async voicemail-starting hooks in the machine-detected branch.

src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioOutboundController.cs

TwilioRecordController.csAuthenticate before recording-completed call status hook +1/-0

Authenticate before recording-completed call status hook

• Emits ITwilioCallStatusHook.OnAuthenticate before OnRecordingCompleted so identity-dependent state writes are available.

src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioRecordController.cs

TwilioVoiceController.csAuthenticate synchronously before session hooks and call status switch +4/-0

Authenticate synchronously before session hooks and call status switch

• Emits ITwilioSessionHook.OnAuthenticate before async session creation hooks. Emits ITwilioCallStatusHook.OnAuthenticate before processing call status events.

src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs

ITwilioCallStatusHook.csAdd OnAuthenticate to call status hook interface +1/-0

Add OnAuthenticate to call status hook interface

• Introduces a synchronous OnAuthenticate(ConversationalVoiceRequest) method to allow identity initialization before async status hooks run.

src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioCallStatusHook.cs

ITwilioSessionHook.csAdd OnAuthenticate to session hook interface with AsyncLocal guidance +7/-0

Add OnAuthenticate to session hook interface with AsyncLocal guidance

• Adds a documented synchronous OnAuthenticate method intended to run before any awaited session hooks so AsyncLocal identity writes persist.

src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioSessionHook.cs

TwilioStreamMiddleware.csAuthenticate media-stream sessions before streaming hooks +11/-0

Authenticate media-stream sessions before streaming hooks

• Constructs a minimal ConversationalVoiceRequest (agentId, conversationId) and synchronously emits ITwilioSessionHook.OnAuthenticate before invoking streaming session hooks, addressing missing identity on the Twilio media stream channel.

src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs

Refactor (1) +0 / -2
RealTimeCompletionProvider.csRemove unused ISettingService lookup from constructor +0/-2

Remove unused ISettingService lookup from constructor

• Eliminates an unused ISettingService resolution from the provider constructor, reducing unnecessary service retrieval.

src/Plugins/BotSharp.Plugin.OpenAI/Providers/Realtime/RealTimeCompletionProvider.cs

Other (1) +0 / -1
Gpt4xModelConstants.csRemove deprecated GPT-4o mini realtime preview constant +0/-1

Remove deprecated GPT-4o mini realtime preview constant

• Deletes the GPT_4o_Mini_Realtime_Preview constant, leaving the remaining GPT-4o model identifiers intact.

src/Infrastructure/BotSharp.Abstraction/Models/Gpt4xModelConstants.cs

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. Breaking hook interface change 🐞 Bug ⚙ Maintainability
Description
ITwilioSessionHook/ITwilioCallStatusHook add a new non-default OnAuthenticate method, which is a
source-breaking API change for any external hook implementations. Because the new method is
synchronous and mandatory, any auth work needing async I/O will be forced into blocking patterns.
Code

src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioSessionHook.cs[R10-16]

+    /// <summary>
+    /// Runs synchronously before any session hook, so identity writes (AsyncLocal)
+    /// set here survive into the subsequent async hooks.
+    /// </summary>
+    /// <param name="request"></param>
+    void OnAuthenticate(ConversationalVoiceRequest request);
+
Evidence
Both Twilio hook interfaces now require an additional method with no default body, which forces all
implementers to update.

src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioSessionHook.cs[8-16]
src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioCallStatusHook.cs[7-10]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
Adding `void OnAuthenticate(...)` as a required interface member breaks compilation for all existing implementations of `ITwilioSessionHook` / `ITwilioCallStatusHook`.

### Issue Context
These are extension-point interfaces; even if this repo has no implementers, downstream projects will.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioSessionHook.cs[10-16]
- src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioCallStatusHook.cs[9-10]

### Suggested fix
- Prefer backward-compatible default interface implementations:
 - `void OnAuthenticate(ConversationalVoiceRequest request) { }`
- Or introduce a new optional interface (e.g., `ITwilioSessionAuthHook`) and have emitters call it when present.
- If you intend a hard break, bump major version and document the migration.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Auth not run for hooks 🐞 Bug ≡ Correctness
Description
OnAuthenticate is only invoked on some Twilio entrypoints, but many other endpoints still emit
ITwilioSessionHook actions without authenticating in that request, so hooks can run without the
intended AsyncLocal identity context. This contradicts the new contract comment (“before any session
hook”) and will cause inconsistent behavior across Twilio callbacks.
Code

src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[R65-67]

+        // Authenticate (synchronous, so identity writes survive into the async session hooks)
+        HookEmitter.Emit<ITwilioSessionHook>(_services, hook => hook.OnAuthenticate(request), request.AgentId);
+
Evidence
Only InitiateConversation added OnAuthenticate; other TwilioVoiceController endpoints still emit
ITwilioSessionHook hooks without authenticating, and TwilioService emits a session hook without any
auth step in that method.

src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioSessionHook.cs[10-16]
src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[114-195]
src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[205-287]
src/Plugins/BotSharp.Plugin.Twilio/Services/TwilioService.cs[303-331]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`OnAuthenticate` is not invoked before all `ITwilioSessionHook` emissions, so identity context can be missing on later Twilio callbacks (separate HTTP requests).

### Issue Context
Your new interface comment states authentication must run synchronously before any session hook so AsyncLocal identity flows into async hooks.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[65-67]

### Suggested fix
- Ensure every controller action (and service method, if callable independently) that emits `ITwilioSessionHook` first calls:
 - `HookEmitter.Emit<ITwilioSessionHook>(..., h => h.OnAuthenticate(request), request.AgentId);`
- Concretely add this at the start of at least:
 - `ReceiveCallerMessage`
 - `ReplyCallerMessage`
 - any other endpoints that call `HookEmitter.Emit<ITwilioSessionHook>`
- Consider centralizing via an action filter/base controller helper to avoid drift.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Authentication failures ignored 🐞 Bug ⛨ Security
Description
OnAuthenticate is emitted via HookEmitter.Emit(Action<T>), which catches and logs exceptions and
then continues, so authentication failures cannot stop the controller flow and the request can
proceed without identity. This is particularly risky because the method name implies a security
boundary but the execution semantics are “best-effort.”
Code

src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs[R56-58]

+        // Authenticate (synchronous, so identity writes survive into the async session hooks)
+        HookEmitter.Emit<ITwilioSessionHook>(_services, hook => hook.OnAuthenticate(request), request.AgentId);
+
Evidence
HookEmitter explicitly catches all exceptions and only logs them; the PR wires authentication into
this emitter, so failures won’t block the request.

src/Infrastructure/BotSharp.Core/Infrastructures/HookEmitter.cs[14-33]
src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs[56-63]
src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[343-383]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
Authentication is executed through `HookEmitter.Emit(...)`, which swallows hook exceptions, so an auth hook cannot abort processing.

### Issue Context
`OnAuthenticate` is intended to establish identity context; if it fails, continuing can lead to unauthenticated state mutations or incorrect authorization/auditing.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs[56-58]

### Suggested fix
- Add a dedicated fail-fast auth emission path, e.g.:
 - `HookEmitter.EmitOrThrow<T>(...)` (no try/catch), or
 - extend `HookEmitOption` with `StopOnException` / `ThrowOnException`.
- Alternatively, change the contract to return a result:
 - `bool OnAuthenticate(...)` or `AuthenticationResult OnAuthenticate(...)`
 - controllers must check result and return 401/403.
- Do not use the current best-effort emitter for security-critical auth.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. OnAuthenticate missing AgentId validation 📘 Rule violation ☼ Reliability
Description
New synchronous OnAuthenticate hook emissions use request.AgentId/agentId without validating
null/empty values at this integration boundary. This can cause unexpected exceptions in hook
resolution or incorrect identity propagation when inbound requests/WebSocket paths are malformed.
Code

src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[R84-92]

+        // No onebrain identity arrives on the Twilio media stream. Authenticate synchronously
+        // (so AsyncLocal identity writes survive) before the streaming session hooks run.
+        var request = new ConversationalVoiceRequest
+        {
+            AgentId = agentId,
+            ConversationId = conversationId
+        };
+        HookEmitter.Emit<ITwilioSessionHook>(services, hook => hook.OnAuthenticate(request), agentId);
+
Evidence
PR Compliance ID 2 requires null/empty validation at boundaries. The added code emits
OnAuthenticate using agentId/request.AgentId without checking for null/empty (e.g.,
string.IsNullOrWhiteSpace) before using them to drive hook execution and identity propagation.

src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[84-92]
src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs[56-63]
Best Practice: Learned patterns

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The newly added synchronous `HookEmitter.Emit(...OnAuthenticate...)` calls use `request.AgentId` / `agentId` without validating null/empty inputs.

## Issue Context
These calls are at API/integration boundaries (HTTP endpoints and WebSocket path-derived values). Per compliance, boundary inputs should be validated and failures handled safely.

## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[84-92]
- src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs[56-63]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Stream auth has limited data 🐞 Bug ☼ Reliability
Description
TwilioStreamMiddleware authenticates a WebSocket stream using a ConversationalVoiceRequest
containing only AgentId and ConversationId, so any auth implementation that requires call-specific
fields (e.g., CallSid) or request metadata cannot validate at this stage. This makes stream
authentication brittle and likely to diverge from the HTTP webhook authentication behavior.
Code

src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[R84-92]

+        // No onebrain identity arrives on the Twilio media stream. Authenticate synchronously
+        // (so AsyncLocal identity writes survive) before the streaming session hooks run.
+        var request = new ConversationalVoiceRequest
+        {
+            AgentId = agentId,
+            ConversationId = conversationId
+        };
+        HookEmitter.Emit<ITwilioSessionHook>(services, hook => hook.OnAuthenticate(request), agentId);
+
Evidence
The stream path constructs a request with only AgentId/ConversationId and authenticates immediately;
CallSid is only derived later when parsing the "start" event.

src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[80-97]
src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[167-192]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
Stream authentication is invoked before Twilio "start" event data is available and with a minimally populated request.

### Issue Context
The middleware later parses CallSid from the stream "start" event and stores it on the connection.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[84-92]

### Suggested fix
- Option A: defer `OnAuthenticate` until after receiving/parsing the "start" event and then populate the request with CallSid (and any other required fields) before authenticating.
- Option B: introduce a dedicated stream auth hook contract that explicitly documents what identifiers are available (agentId, conversationId) and avoid implying CallSid-based auth.
- Option C: perform two-phase auth: pre-auth by agent/conversation, then enrich/verify once CallSid arrives.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment on lines +84 to +92
// No onebrain identity arrives on the Twilio media stream. Authenticate synchronously
// (so AsyncLocal identity writes survive) before the streaming session hooks run.
var request = new ConversationalVoiceRequest
{
AgentId = agentId,
ConversationId = conversationId
};
HookEmitter.Emit<ITwilioSessionHook>(services, hook => hook.OnAuthenticate(request), agentId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

1. onauthenticate missing agentid validation 📘 Rule violation ☼ Reliability

New synchronous OnAuthenticate hook emissions use request.AgentId/agentId without validating
null/empty values at this integration boundary. This can cause unexpected exceptions in hook
resolution or incorrect identity propagation when inbound requests/WebSocket paths are malformed.
Agent Prompt
## Issue description
The newly added synchronous `HookEmitter.Emit(...OnAuthenticate...)` calls use `request.AgentId` / `agentId` without validating null/empty inputs.

## Issue Context
These calls are at API/integration boundaries (HTTP endpoints and WebSocket path-derived values). Per compliance, boundary inputs should be validated and failures handled safely.

## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[84-92]
- src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs[56-63]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +10 to +16
/// <summary>
/// Runs synchronously before any session hook, so identity writes (AsyncLocal)
/// set here survive into the subsequent async hooks.
/// </summary>
/// <param name="request"></param>
void OnAuthenticate(ConversationalVoiceRequest request);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

2. Breaking hook interface change 🐞 Bug ⚙ Maintainability

ITwilioSessionHook/ITwilioCallStatusHook add a new non-default OnAuthenticate method, which is a
source-breaking API change for any external hook implementations. Because the new method is
synchronous and mandatory, any auth work needing async I/O will be forced into blocking patterns.
Agent Prompt
### Issue description
Adding `void OnAuthenticate(...)` as a required interface member breaks compilation for all existing implementations of `ITwilioSessionHook` / `ITwilioCallStatusHook`.

### Issue Context
These are extension-point interfaces; even if this repo has no implementers, downstream projects will.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioSessionHook.cs[10-16]
- src/Plugins/BotSharp.Plugin.Twilio/Interfaces/ITwilioCallStatusHook.cs[9-10]

### Suggested fix
- Prefer backward-compatible default interface implementations:
  - `void OnAuthenticate(ConversationalVoiceRequest request) { }`
- Or introduce a new optional interface (e.g., `ITwilioSessionAuthHook`) and have emitters call it when present.
- If you intend a hard break, bump major version and document the migration.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +65 to +67
// Authenticate (synchronous, so identity writes survive into the async session hooks)
HookEmitter.Emit<ITwilioSessionHook>(_services, hook => hook.OnAuthenticate(request), request.AgentId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

3. Auth not run for hooks 🐞 Bug ≡ Correctness

OnAuthenticate is only invoked on some Twilio entrypoints, but many other endpoints still emit
ITwilioSessionHook actions without authenticating in that request, so hooks can run without the
intended AsyncLocal identity context. This contradicts the new contract comment (“before any session
hook”) and will cause inconsistent behavior across Twilio callbacks.
Agent Prompt
### Issue description
`OnAuthenticate` is not invoked before all `ITwilioSessionHook` emissions, so identity context can be missing on later Twilio callbacks (separate HTTP requests).

### Issue Context
Your new interface comment states authentication must run synchronously before any session hook so AsyncLocal identity flows into async hooks.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[65-67]

### Suggested fix
- Ensure every controller action (and service method, if callable independently) that emits `ITwilioSessionHook` first calls:
  - `HookEmitter.Emit<ITwilioSessionHook>(..., h => h.OnAuthenticate(request), request.AgentId);`
- Concretely add this at the start of at least:
  - `ReceiveCallerMessage`
  - `ReplyCallerMessage`
  - any other endpoints that call `HookEmitter.Emit<ITwilioSessionHook>`
- Consider centralizing via an action filter/base controller helper to avoid drift.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +56 to +58
// Authenticate (synchronous, so identity writes survive into the async session hooks)
HookEmitter.Emit<ITwilioSessionHook>(_services, hook => hook.OnAuthenticate(request), request.AgentId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

4. Authentication failures ignored 🐞 Bug ⛨ Security

OnAuthenticate is emitted via HookEmitter.Emit(Action<T>), which catches and logs exceptions and
then continues, so authentication failures cannot stop the controller flow and the request can
proceed without identity. This is particularly risky because the method name implies a security
boundary but the execution semantics are “best-effort.”
Agent Prompt
### Issue description
Authentication is executed through `HookEmitter.Emit(...)`, which swallows hook exceptions, so an auth hook cannot abort processing.

### Issue Context
`OnAuthenticate` is intended to establish identity context; if it fails, continuing can lead to unauthenticated state mutations or incorrect authorization/auditing.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioInboundController.cs[56-58]

### Suggested fix
- Add a dedicated fail-fast auth emission path, e.g.:
  - `HookEmitter.EmitOrThrow<T>(...)` (no try/catch), or
  - extend `HookEmitOption` with `StopOnException` / `ThrowOnException`.
- Alternatively, change the contract to return a result:
  - `bool OnAuthenticate(...)` or `AuthenticationResult OnAuthenticate(...)`
  - controllers must check result and return 401/403.
- Do not use the current best-effort emitter for security-critical auth.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +84 to +92
// No onebrain identity arrives on the Twilio media stream. Authenticate synchronously
// (so AsyncLocal identity writes survive) before the streaming session hooks run.
var request = new ConversationalVoiceRequest
{
AgentId = agentId,
ConversationId = conversationId
};
HookEmitter.Emit<ITwilioSessionHook>(services, hook => hook.OnAuthenticate(request), agentId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

5. Stream auth has limited data 🐞 Bug ☼ Reliability

TwilioStreamMiddleware authenticates a WebSocket stream using a ConversationalVoiceRequest
containing only AgentId and ConversationId, so any auth implementation that requires call-specific
fields (e.g., CallSid) or request metadata cannot validate at this stage. This makes stream
authentication brittle and likely to diverge from the HTTP webhook authentication behavior.
Agent Prompt
### Issue description
Stream authentication is invoked before Twilio "start" event data is available and with a minimally populated request.

### Issue Context
The middleware later parses CallSid from the stream "start" event and stores it on the connection.

### Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/TwilioStreamMiddleware.cs[84-92]

### Suggested fix
- Option A: defer `OnAuthenticate` until after receiving/parsing the "start" event and then populate the request with CallSid (and any other required fields) before authenticating.
- Option B: introduce a dedicated stream auth hook contract that explicitly documents what identifiers are available (agentId, conversationId) and avoid implying CallSid-based auth.
- Option C: perform two-phase auth: pre-auth by agent/conversation, then enrich/verify once CallSid arrives.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

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