@microsoft/agents-hosting 1.6.0-beta.4.g8ab0e486bc → 1.6.0-beta.41.g36be9b7b46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/package.json +5 -9
- package/dist/src/agent-client/agentClient.js +2 -2
- package/dist/src/agent-client/agentClient.js.map +1 -1
- package/dist/src/agent-client/agentResponseHandler.js +2 -2
- package/dist/src/agent-client/agentResponseHandler.js.map +1 -1
- package/dist/src/app/agentApplication.js +27 -2
- package/dist/src/app/agentApplication.js.map +1 -1
- package/dist/src/app/auth/authorizationManager.d.ts +4 -0
- package/dist/src/app/auth/authorizationManager.js +94 -67
- package/dist/src/app/auth/authorizationManager.js.map +1 -1
- package/dist/src/app/auth/handlers/azureBotAuthorization.js +2 -2
- package/dist/src/app/auth/handlers/azureBotAuthorization.js.map +1 -1
- package/dist/src/app/proactive/createConversationOptionsBuilder.js +10 -6
- package/dist/src/app/proactive/createConversationOptionsBuilder.js.map +1 -1
- package/dist/src/app/teamsAttachmentDownloader.js +7 -1
- package/dist/src/app/teamsAttachmentDownloader.js.map +1 -1
- package/dist/src/auth/authConfiguration.d.ts +2 -143
- package/dist/src/auth/authConfiguration.js +301 -257
- package/dist/src/auth/authConfiguration.js.map +1 -1
- package/dist/src/auth/jwt-middleware.js +2 -1
- package/dist/src/auth/jwt-middleware.js.map +1 -1
- package/dist/src/auth/msalConnectionManager.js +27 -14
- package/dist/src/auth/msalConnectionManager.js.map +1 -1
- package/dist/src/auth/msalTokenProvider.d.ts +7 -0
- package/dist/src/auth/msalTokenProvider.js +156 -38
- package/dist/src/auth/msalTokenProvider.js.map +1 -1
- package/dist/src/auth/settings.d.ts +327 -0
- package/dist/src/auth/settings.js +158 -0
- package/dist/src/auth/settings.js.map +1 -0
- package/dist/src/cloudAdapter.d.ts +51 -1
- package/dist/src/cloudAdapter.js +219 -50
- package/dist/src/cloudAdapter.js.map +1 -1
- package/dist/src/connector-client/connectorClient.d.ts +2 -2
- package/dist/src/connector-client/connectorClient.js +7 -8
- package/dist/src/connector-client/connectorClient.js.map +1 -1
- package/dist/src/errorHelper.js +50 -0
- package/dist/src/errorHelper.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +6 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/oauth/userTokenClient.js +1 -1
- package/dist/src/oauth/userTokenClient.js.map +1 -1
- package/dist/src/observability/traces.d.ts +1 -1
- package/dist/src/observability/traces.js +2 -2
- package/dist/src/observability/traces.js.map +1 -1
- package/dist/src/utils/env.d.ts +50 -0
- package/dist/src/utils/env.js +113 -0
- package/dist/src/utils/env.js.map +1 -0
- package/dist/src/utils.d.ts +10 -0
- package/dist/src/utils.js +18 -0
- package/dist/src/utils.js.map +1 -0
- package/package.json +5 -9
- package/src/agent-client/agentClient.ts +2 -2
- package/src/agent-client/agentResponseHandler.ts +2 -2
- package/src/app/agentApplication.ts +28 -3
- package/src/app/auth/authorizationManager.ts +84 -41
- package/src/app/auth/handlers/azureBotAuthorization.ts +2 -2
- package/src/app/proactive/createConversationOptionsBuilder.ts +8 -4
- package/src/app/teamsAttachmentDownloader.ts +6 -1
- package/src/auth/authConfiguration.ts +317 -356
- package/src/auth/jwt-middleware.ts +1 -1
- package/src/auth/msalConnectionManager.ts +27 -10
- package/src/auth/msalTokenProvider.ts +143 -33
- package/src/auth/settings.ts +323 -0
- package/src/cloudAdapter.ts +272 -10
- package/src/connector-client/connectorClient.ts +8 -8
- package/src/errorHelper.ts +57 -0
- package/src/index.ts +4 -1
- package/src/oauth/userTokenClient.ts +1 -1
- package/src/observability/traces.ts +2 -2
- package/src/utils/env.ts +105 -0
- package/src/utils.ts +14 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
3
|
+
* Licensed under the MIT License.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { debug } from '@microsoft/agents-telemetry'
|
|
7
|
+
import type { ConnectionMapItem } from './msalConnectionManager'
|
|
8
|
+
|
|
9
|
+
const logger = debug('agents:authConfiguration')
|
|
10
|
+
|
|
11
|
+
const DEFAULT_CONNECTION = 'serviceConnection'
|
|
12
|
+
const AUTHORITY_DEFAULT = 'https://login.microsoftonline.com'
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_CONNECTION_MAP: ConnectionMapItem = { serviceUrl: '*', connection: DEFAULT_CONNECTION }
|
|
15
|
+
|
|
16
|
+
export type ConnectionKeys = keyof Omit<AuthConfiguration, 'connections' | 'connectionsMap'>
|
|
17
|
+
export type ConnectionMapKeys = keyof ConnectionMapItem
|
|
18
|
+
|
|
19
|
+
export interface LoadEnv {
|
|
20
|
+
[upperKey: string]: { key: string, value: any }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function loadEnvSettings (callback: (key: string, value: string) => void) {
|
|
24
|
+
const env: LoadEnv = {}
|
|
25
|
+
for (const [envKey, envValue] of Object.entries(process.env)) {
|
|
26
|
+
if (!envValue?.trim()) {
|
|
27
|
+
continue
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
env[envKey.toUpperCase()] = { key: envKey, value: envValue }
|
|
31
|
+
|
|
32
|
+
callback(envKey, envValue)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return env
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function applyDefaultSettings (config: AuthConfiguration) {
|
|
39
|
+
const settings = { ...config }
|
|
40
|
+
settings.authorityEndpoint ??= settings.authority ?? AUTHORITY_DEFAULT
|
|
41
|
+
settings.issuers ??= getDefaultIssuers(settings.tenantId ?? '', settings.authorityEndpoint)
|
|
42
|
+
|
|
43
|
+
// For backward compatibility
|
|
44
|
+
if (settings.federatedClientId) {
|
|
45
|
+
settings.FICClientId = settings.federatedClientId
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (settings.scopes?.length) {
|
|
49
|
+
settings.scope = settings.scopes?.[0]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (settings.authorityEndpoint) {
|
|
53
|
+
settings.authority = settings.authorityEndpoint
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (!settings.clientId && process.env.NODE_ENV?.toLowerCase() === 'production') {
|
|
57
|
+
throw new Error('ClientId required in production')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const defaultConnections = settings.connections?.size
|
|
61
|
+
? settings.connections
|
|
62
|
+
: new Map([[DEFAULT_CONNECTION, { ...settings }]])
|
|
63
|
+
const defaultConnectionsMap = settings.connectionsMap?.length
|
|
64
|
+
? settings.connectionsMap
|
|
65
|
+
: [DEFAULT_CONNECTION_MAP]
|
|
66
|
+
|
|
67
|
+
settings.connections = defaultConnections
|
|
68
|
+
settings.connectionsMap = defaultConnectionsMap
|
|
69
|
+
return settings
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* A type representing a parser settings object.
|
|
74
|
+
*/
|
|
75
|
+
type ParserSettings<K extends string> = {
|
|
76
|
+
[key in K]: (value: string) => { key?: string, value?: any } | undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Creates an environment variable parser that maps the variable keys to parsing functions.
|
|
81
|
+
* @param settings An object where each key is an environment variable name and the value is a function
|
|
82
|
+
* that takes the variable value as input and returns an object with optional `key` and `value` properties.
|
|
83
|
+
* @remarks
|
|
84
|
+
* The `key` property in the returned object can be used to rename the environment variable key,
|
|
85
|
+
* while the `value` property contains the parsed value.
|
|
86
|
+
* @returns An object with a `parse` method that takes an environment variable key and value,
|
|
87
|
+
* and returns the parsed result.
|
|
88
|
+
*/
|
|
89
|
+
export function envParser<K extends string> (settings: ParserSettings<K> & ThisType<ParserSettings<K>>) {
|
|
90
|
+
const keys = Object.keys(settings) as K[]
|
|
91
|
+
const upperKeys = keys.reduce((acc, key) => {
|
|
92
|
+
acc[key.toUpperCase()] = key
|
|
93
|
+
return acc
|
|
94
|
+
}, {} as Record<string, K>)
|
|
95
|
+
return {
|
|
96
|
+
keys,
|
|
97
|
+
/**
|
|
98
|
+
* Parses the given environment variable key and value using the provided settings.
|
|
99
|
+
* @param key The environment variable key.
|
|
100
|
+
* @param value The environment variable value.
|
|
101
|
+
* @returns The parsed result with optional renamed key and parsed value.
|
|
102
|
+
*/
|
|
103
|
+
parse (key: K, value: string) {
|
|
104
|
+
const match = upperKeys[key.toUpperCase()]
|
|
105
|
+
if (!match) {
|
|
106
|
+
return {}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const result = settings[match](value)
|
|
110
|
+
return { key: result?.key ?? match, value: result?.value }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Utility functions for environment variable parsers.
|
|
117
|
+
*/
|
|
118
|
+
export const envParserUtils = {
|
|
119
|
+
/**
|
|
120
|
+
* Bypass parser that returns the value as is.
|
|
121
|
+
* @param value The environment variable value.
|
|
122
|
+
* @returns An object with the original value.
|
|
123
|
+
*/
|
|
124
|
+
bypass: (value: string) => ({ value }),
|
|
125
|
+
/**
|
|
126
|
+
* Redirects the parsing to another parser for a specific key.
|
|
127
|
+
* @param parser The target parser to redirect to.
|
|
128
|
+
* @param key The key to use in the target parser.
|
|
129
|
+
* @returns A function that takes the environment variable value and returns the parsed result from the target parser.
|
|
130
|
+
*/
|
|
131
|
+
redirect: <Parser extends ReturnType<typeof envParser>>(parser: Parser, key: Parameters<Parser['parse']>[0]) => (value: string) => parser.parse(key, value)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Resolves the full authority URL including the tenant ID.
|
|
136
|
+
* Supports both patterns:
|
|
137
|
+
* - Tenant embedded in authority: https://login.microsoftonline.com/my-tenant
|
|
138
|
+
* - Authority + separate tenantId: https://login.microsoftonline.com + tenantId
|
|
139
|
+
* Also handles trailing slashes on authority.
|
|
140
|
+
*/
|
|
141
|
+
export function resolveAuthority (authority?: string, tenantId?: string): string {
|
|
142
|
+
const base = trimTrailingSlashes(authority ?? AUTHORITY_DEFAULT)
|
|
143
|
+
const url = new URL(base)
|
|
144
|
+
const hasPathSegment = url.pathname !== '/'
|
|
145
|
+
if (hasPathSegment) {
|
|
146
|
+
return base
|
|
147
|
+
}
|
|
148
|
+
return `${base}/${tenantId ?? 'botframework.com'}`
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function trimTrailingSlashes (value: string): string {
|
|
152
|
+
let end = value.length
|
|
153
|
+
while (end > 0 && value.charCodeAt(end - 1) === 47) {
|
|
154
|
+
end--
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return end === value.length ? value : value.slice(0, end)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function getDefaultIssuers (tenantId: string, authority: string) : string[] {
|
|
161
|
+
// Convert empty string to undefined so resolveAuthority applies its 'botframework.com' default
|
|
162
|
+
const t = tenantId || undefined
|
|
163
|
+
if (!t) {
|
|
164
|
+
logger.warn('tenantId is not configured, defaulting to botframework.com')
|
|
165
|
+
}
|
|
166
|
+
return [
|
|
167
|
+
'https://api.botframework.com',
|
|
168
|
+
`${resolveAuthority('https://sts.windows.net', t)}/`,
|
|
169
|
+
`${resolveAuthority(authority, t)}/v2.0`
|
|
170
|
+
]
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Represents the authentication configuration.
|
|
175
|
+
*/
|
|
176
|
+
export interface AuthConfiguration {
|
|
177
|
+
/**
|
|
178
|
+
* The tenant ID for the authentication configuration.
|
|
179
|
+
*/
|
|
180
|
+
tenantId?: string
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The client ID for the authentication configuration. Required in production.
|
|
184
|
+
*/
|
|
185
|
+
clientId?: string
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The client secret for the authentication configuration.
|
|
189
|
+
*/
|
|
190
|
+
clientSecret?: string
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The path to the certificate PEM file.
|
|
194
|
+
*/
|
|
195
|
+
certPemFile?: string
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The path to the certificate key file.
|
|
199
|
+
*/
|
|
200
|
+
certKeyFile?: string
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Indicates whether to send the X5C param or not (for SNI authentication).
|
|
204
|
+
*/
|
|
205
|
+
sendX5C?: boolean
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* A list of valid issuers for the authentication configuration.
|
|
209
|
+
*/
|
|
210
|
+
issuers?: string[]
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* The connection name for the authentication configuration.
|
|
214
|
+
*/
|
|
215
|
+
connectionName?: string
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* @deprecated Use federatedClientId instead.
|
|
219
|
+
*
|
|
220
|
+
* The FIC (First-Party Integration Channel) client ID.
|
|
221
|
+
*/
|
|
222
|
+
FICClientId?: string,
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* @deprecated Use authorityEndpoint instead.
|
|
226
|
+
*
|
|
227
|
+
* Entra Authentication Endpoint to use.
|
|
228
|
+
*
|
|
229
|
+
* @remarks
|
|
230
|
+
* If not populated the Entra Public Cloud endpoint is assumed.
|
|
231
|
+
* This example of Public Cloud Endpoint is https://login.microsoftonline.com
|
|
232
|
+
* see also https://learn.microsoft.com/entra/identity-platform/authentication-national-cloud
|
|
233
|
+
*/
|
|
234
|
+
authority?: string
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* @deprecated Use scopes instead.
|
|
238
|
+
*/
|
|
239
|
+
scope?: string
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* A map of connection names to their respective authentication configurations.
|
|
243
|
+
*/
|
|
244
|
+
connections?: Map<string, AuthConfiguration>
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* A list of connection map items to map service URLs to connection names.
|
|
248
|
+
*/
|
|
249
|
+
connectionsMap?: ConnectionMapItem[],
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* An optional alternative blueprint Connection name used when constructing a connector client.
|
|
253
|
+
*/
|
|
254
|
+
altBlueprintConnectionName?: string
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* @deprecated Use `authType` set to `'WorkloadIdentity'` and `federatedTokenFile` instead.
|
|
258
|
+
*
|
|
259
|
+
* The path to K8s provided token.
|
|
260
|
+
*/
|
|
261
|
+
WIDAssertionFile?: string
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The Azure region for ESTS-R regional token acquisition (e.g. 'westus', 'eastus').
|
|
265
|
+
* When set, MSAL routes token requests to the specified regional endpoint.
|
|
266
|
+
* See https://learn.microsoft.com/en-us/entra/msal/javascript/node/regional-authorities for details.
|
|
267
|
+
*/
|
|
268
|
+
azureRegion?: string
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The authentication type for the connection.
|
|
272
|
+
*/
|
|
273
|
+
authType?: AuthType | string
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The path to the federated token file used for Workload Identity authentication.
|
|
277
|
+
*/
|
|
278
|
+
federatedTokenFile?: string
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Sets the resource URL for Identity Proxy Manager (IDPM).
|
|
282
|
+
*
|
|
283
|
+
* @remarks
|
|
284
|
+
* Set this to the appropriate resource identifier when the application is running in an environment,
|
|
285
|
+
* such as a Foundry container, that exposes Managed Identity through a container-specific IMDS endpoint.
|
|
286
|
+
* This setting is only meaningful when using Identity Proxy Manager (AuthType.IdentityProxyManager) for authentication.
|
|
287
|
+
*/
|
|
288
|
+
idpmResource?: string
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Entra Authentication Endpoint to use.
|
|
292
|
+
*
|
|
293
|
+
* @remarks
|
|
294
|
+
* If not populated the Entra Public Cloud endpoint is assumed.
|
|
295
|
+
* This example of Public Cloud Endpoint is https://login.microsoftonline.com
|
|
296
|
+
* see also https://learn.microsoft.com/entra/identity-platform/authentication-national-cloud
|
|
297
|
+
*/
|
|
298
|
+
authorityEndpoint?: string
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* The federated client ID for the authentication configuration, used for workload identity federation scenarios.
|
|
302
|
+
*/
|
|
303
|
+
federatedClientId?: string
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* The scopes for the authentication configuration.
|
|
307
|
+
*/
|
|
308
|
+
scopes?: string[]
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Supported authentication types for agent connections.
|
|
313
|
+
*/
|
|
314
|
+
export enum AuthType {
|
|
315
|
+
Certificate = 'Certificate',
|
|
316
|
+
CertificateSubjectName = 'CertificateSubjectName',
|
|
317
|
+
ClientSecret = 'ClientSecret',
|
|
318
|
+
UserManagedIdentity = 'UserManagedIdentity',
|
|
319
|
+
SystemManagedIdentity = 'SystemManagedIdentity',
|
|
320
|
+
FederatedCredentials = 'FederatedCredentials',
|
|
321
|
+
WorkloadIdentity = 'WorkloadIdentity',
|
|
322
|
+
IdentityProxyManager = 'IdentityProxyManager'
|
|
323
|
+
}
|
package/src/cloudAdapter.ts
CHANGED
|
@@ -16,7 +16,7 @@ import { MsalConnectionManager } from './auth/msalConnectionManager'
|
|
|
16
16
|
import { Activity, ActivityEventNames, ActivityTypes, Channels, ConversationReference, DeliveryModes, ConversationParameters, RoleTypes, ExceptionHelper } from '@microsoft/agents-activity'
|
|
17
17
|
import { Errors } from './errorHelper'
|
|
18
18
|
import { ResourceResponse } from './connector-client/resourceResponse'
|
|
19
|
-
import
|
|
19
|
+
import { randomUUID } from 'crypto'
|
|
20
20
|
import { debug } from '@microsoft/agents-telemetry'
|
|
21
21
|
import { StatusCodes } from './statusCodes'
|
|
22
22
|
import { InvokeResponse } from './invoke/invokeResponse'
|
|
@@ -28,6 +28,7 @@ import { HeaderPropagation, HeaderPropagationCollection, HeaderPropagationDefini
|
|
|
28
28
|
import { JwtPayload } from 'jsonwebtoken'
|
|
29
29
|
import { getTokenServiceEndpoint } from './oauth/customUserTokenAPI'
|
|
30
30
|
import { Connections } from './auth/connections'
|
|
31
|
+
import { parseBooleanEnv, suggestClosest } from './utils/env'
|
|
31
32
|
import { trace } from '@microsoft/agents-telemetry'
|
|
32
33
|
import { AdapterTraceDefinitions } from './observability'
|
|
33
34
|
const logger = debug('agents:cloud-adapter')
|
|
@@ -41,22 +42,235 @@ const logger = debug('agents:cloud-adapter')
|
|
|
41
42
|
* flow between agents and users across different channels, handling activities, attachments,
|
|
42
43
|
* and conversation continuations.
|
|
43
44
|
*/
|
|
45
|
+
/**
|
|
46
|
+
* Optional configuration for {@link CloudAdapter} runtime behavior.
|
|
47
|
+
*
|
|
48
|
+
* Defaults are conservative and match the .NET SDK's `AdapterOptions` defaults.
|
|
49
|
+
*
|
|
50
|
+
* Each option can also be supplied via an environment variable using the
|
|
51
|
+
* convention `CloudAdapterOptions__<propertyName>` — for example
|
|
52
|
+
* `CloudAdapterOptions__validateServiceUrl=true`. The prefix matches the
|
|
53
|
+
* .NET SDK's `IConfiguration.GetSection("CloudAdapterOptions")` section name,
|
|
54
|
+
* so a shared environment can configure both SDKs from the same variables.
|
|
55
|
+
* Both the `CloudAdapterOptions__` prefix and the property name are matched
|
|
56
|
+
* case-insensitively, so hosts that uppercase env-var names (some PaaS
|
|
57
|
+
* platforms) still work. Values supplied directly to the constructor always
|
|
58
|
+
* win over environment variables.
|
|
59
|
+
*/
|
|
60
|
+
export interface CloudAdapterOptions {
|
|
61
|
+
/**
|
|
62
|
+
* When `true`, the default `onTurnError` handler includes `error.stack` in
|
|
63
|
+
* its log output. Defaults to `false`.
|
|
64
|
+
*
|
|
65
|
+
* Env var: `CloudAdapterOptions__emitStackTrace`.
|
|
66
|
+
*/
|
|
67
|
+
emitStackTrace?: boolean
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* When `true`, an inbound activity whose `serviceUrl` host does not match
|
|
71
|
+
* the `serviceurl` claim on the caller's identity is rejected with HTTP 400.
|
|
72
|
+
* When `false` (default for backward compatibility), the mismatch is logged
|
|
73
|
+
* as a warning but the activity is still processed.
|
|
74
|
+
*
|
|
75
|
+
* **Recommended for production.** Setting this to `true` (either directly or
|
|
76
|
+
* via `CloudAdapterOptions__validateServiceUrl=true`) defends against
|
|
77
|
+
* confused-deputy / SSRF-style attacks where an attacker with a valid token
|
|
78
|
+
* for one service URL tries to send activities targeting a different one.
|
|
79
|
+
*
|
|
80
|
+
* Env var: `CloudAdapterOptions__validateServiceUrl`.
|
|
81
|
+
*/
|
|
82
|
+
validateServiceUrl?: boolean
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const DEFAULT_CLOUD_ADAPTER_OPTIONS: Required<CloudAdapterOptions> = {
|
|
86
|
+
emitStackTrace: false,
|
|
87
|
+
validateServiceUrl: false
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Env-var prefix for {@link CloudAdapterOptions} (matches .NET config section). */
|
|
91
|
+
const CLOUD_ADAPTER_OPTIONS_ENV_PREFIX = 'CloudAdapterOptions__'
|
|
92
|
+
const CLOUD_ADAPTER_OPTIONS_ENV_PREFIX_UPPER = CLOUD_ADAPTER_OPTIONS_ENV_PREFIX.toUpperCase()
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Declarative env-var parser for {@link CloudAdapterOptions}.
|
|
96
|
+
*
|
|
97
|
+
* Shape mirrors `envParser<K>` introduced in PR #1119
|
|
98
|
+
* (`packages/agents-hosting/src/auth/settings.ts`) so this loader can be
|
|
99
|
+
* swapped for the shared utility once that lands. Each entry is a
|
|
100
|
+
* `(rawValue) => parsedValue | undefined` function. Lookups are
|
|
101
|
+
* case-insensitive via the `upperKeys` map, matching the upstream
|
|
102
|
+
* convention and accommodating hosts that uppercase env-var names.
|
|
103
|
+
*
|
|
104
|
+
* Adding a new option to `CloudAdapterOptions` only requires adding an
|
|
105
|
+
* entry here.
|
|
106
|
+
*/
|
|
107
|
+
const cloudAdapterOptionsParser = (() => {
|
|
108
|
+
const schema: {
|
|
109
|
+
[K in keyof Required<CloudAdapterOptions>]: (raw: string | undefined) => CloudAdapterOptions[K]
|
|
110
|
+
} = {
|
|
111
|
+
emitStackTrace: parseBooleanEnv,
|
|
112
|
+
validateServiceUrl: parseBooleanEnv
|
|
113
|
+
}
|
|
114
|
+
const keys = Object.keys(schema) as Array<keyof CloudAdapterOptions>
|
|
115
|
+
const upperKeys = keys.reduce<Record<string, keyof CloudAdapterOptions>>((acc, key) => {
|
|
116
|
+
acc[key.toUpperCase()] = key
|
|
117
|
+
return acc
|
|
118
|
+
}, {})
|
|
119
|
+
return {
|
|
120
|
+
schema,
|
|
121
|
+
keys,
|
|
122
|
+
/**
|
|
123
|
+
* Resolves an env-var property name (case-insensitive) to its canonical
|
|
124
|
+
* `CloudAdapterOptions` key, or `undefined` when the name is unknown.
|
|
125
|
+
*/
|
|
126
|
+
resolveKey (property: string): keyof CloudAdapterOptions | undefined {
|
|
127
|
+
return upperKeys[property.toUpperCase()]
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
})()
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Per-process dedup set for configuration warnings. Without this, every
|
|
134
|
+
* `new CloudAdapter()` re-scans `process.env` and re-emits warnings for any
|
|
135
|
+
* typo'd `CloudAdapterOptions__*` key (or unparseable value), which spams
|
|
136
|
+
* stderr in multi-adapter scenarios (tests, proactive flows, DI containers).
|
|
137
|
+
*/
|
|
138
|
+
const warnedConfigKeys = new Set<string>()
|
|
139
|
+
|
|
140
|
+
function emitConfigWarning (envKey: string, message: string): void {
|
|
141
|
+
if (warnedConfigKeys.has(envKey)) return
|
|
142
|
+
warnedConfigKeys.add(envKey)
|
|
143
|
+
// Visible by default (writes synchronously to stderr) so users see typos
|
|
144
|
+
// and bad values without having to opt in via `DEBUG=agents:cloud-adapter:*`.
|
|
145
|
+
// Hosts that want to route or suppress can intercept `console.warn` or
|
|
146
|
+
// subscribe to the `agents:cloud-adapter:warn` debug namespace below.
|
|
147
|
+
console.warn(`[agents:cloud-adapter] ${message}`)
|
|
148
|
+
logger.warn(message)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Scans `process.env` for keys with the `CloudAdapterOptions__` prefix
|
|
153
|
+
* (case-insensitive) and returns the parsed partial options. Unknown keys
|
|
154
|
+
* and values that fail to parse are warned about once per process via
|
|
155
|
+
* `console.warn` (so they are visible by default without enabling debug)
|
|
156
|
+
* and through the `agents:cloud-adapter:warn` debug channel for log
|
|
157
|
+
* aggregators. Hosts that want to route or suppress these diagnostics can
|
|
158
|
+
* intercept `console.warn` or filter the debug namespace.
|
|
159
|
+
*/
|
|
160
|
+
function loadCloudAdapterOptionsFromEnv (): CloudAdapterOptions {
|
|
161
|
+
const result: CloudAdapterOptions = {}
|
|
162
|
+
for (const [envKey, rawValue] of Object.entries(process.env)) {
|
|
163
|
+
const upper = envKey.toUpperCase()
|
|
164
|
+
if (!upper.startsWith(CLOUD_ADAPTER_OPTIONS_ENV_PREFIX_UPPER)) continue
|
|
165
|
+
const property = envKey.substring(CLOUD_ADAPTER_OPTIONS_ENV_PREFIX.length)
|
|
166
|
+
const canonical = cloudAdapterOptionsParser.resolveKey(property)
|
|
167
|
+
if (!canonical) {
|
|
168
|
+
const suggestion = suggestClosest(property, cloudAdapterOptionsParser.keys as readonly string[], 4)
|
|
169
|
+
const hint = suggestion ? ` Did you mean "${CLOUD_ADAPTER_OPTIONS_ENV_PREFIX}${suggestion}"?` : ''
|
|
170
|
+
emitConfigWarning(envKey, `Unknown CloudAdapterOptions env var: ${envKey} (ignored).${hint}`)
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
const parsed = cloudAdapterOptionsParser.schema[canonical](rawValue) as any
|
|
174
|
+
if (parsed !== undefined) {
|
|
175
|
+
(result as any)[canonical] = parsed
|
|
176
|
+
} else if (rawValue !== undefined && rawValue.trim() !== '') {
|
|
177
|
+
// Known key, recognized but unparseable value (e.g. `yes`, `on`, `enabled`).
|
|
178
|
+
// For a security-relevant flag like `validateServiceUrl`, silent
|
|
179
|
+
// fallthrough is the dangerous failure mode — surface it.
|
|
180
|
+
// Note: parseBooleanEnv treats whitespace-only as unset, so don't warn
|
|
181
|
+
// on `' '`; only warn when the user actually typed something.
|
|
182
|
+
emitConfigWarning(
|
|
183
|
+
`${envKey}=${rawValue}`,
|
|
184
|
+
`Ignored ${envKey}=${rawValue}; expected one of true/false/1/0.`
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return result
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Resolves a `CloudAdapterOptions` instance from an explicit argument or, if
|
|
193
|
+
* absent, from environment variables. Values supplied in the explicit object
|
|
194
|
+
* win over env vars.
|
|
195
|
+
*/
|
|
196
|
+
function resolveCloudAdapterOptions (options?: CloudAdapterOptions): Required<CloudAdapterOptions> {
|
|
197
|
+
const fromEnv = loadCloudAdapterOptionsFromEnv()
|
|
198
|
+
return {
|
|
199
|
+
emitStackTrace: options?.emitStackTrace ?? fromEnv.emitStackTrace ?? DEFAULT_CLOUD_ADAPTER_OPTIONS.emitStackTrace,
|
|
200
|
+
validateServiceUrl: options?.validateServiceUrl ?? fromEnv.validateServiceUrl ?? DEFAULT_CLOUD_ADAPTER_OPTIONS.validateServiceUrl
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Removes CR/LF and other control characters from an attacker-controllable
|
|
206
|
+
* string before interpolating it into a log message, to prevent log forging
|
|
207
|
+
* / log injection (OWASP A09). Truncates excessively long values.
|
|
208
|
+
*/
|
|
209
|
+
function sanitizeForLog (value: string, max = 256): string {
|
|
210
|
+
// Strip C0 (\x00-\x1f) + DEL (\x7f) + C1 (\x80-\x9f) controls plus U+2028
|
|
211
|
+
// LINE SEPARATOR / U+2029 PARAGRAPH SEPARATOR — some log viewers and
|
|
212
|
+
// terminals treat them as line breaks, which would re-open the log-
|
|
213
|
+
// injection vector that the ASCII strip closes.
|
|
214
|
+
// eslint-disable-next-line no-control-regex
|
|
215
|
+
const cleaned = value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, '?')
|
|
216
|
+
return cleaned.length > max ? cleaned.slice(0, max) + '…' : cleaned
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Truncates a JSON-serialized activity for log lines so a malformed or
|
|
221
|
+
* pathologically large inbound payload can't blow up the log pipeline.
|
|
222
|
+
*/
|
|
223
|
+
function truncateActivityForLog (activity: unknown, max = 1024): string {
|
|
224
|
+
try {
|
|
225
|
+
const json = JSON.stringify(activity)
|
|
226
|
+
if (!json) return '<unserializable>'
|
|
227
|
+
// Strip C0/DEL/C1 controls + U+2028/U+2029 from the serialized form so
|
|
228
|
+
// attacker-controlled fields (e.g. activity.text) can't forge log lines.
|
|
229
|
+
// eslint-disable-next-line no-control-regex
|
|
230
|
+
const sanitized = json.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, '?')
|
|
231
|
+
return sanitized.length > max ? `${sanitized.slice(0, max)}…(truncated)` : sanitized
|
|
232
|
+
} catch {
|
|
233
|
+
return '<unserializable>'
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
44
237
|
export class CloudAdapter extends BaseAdapter {
|
|
45
238
|
/**
|
|
46
239
|
* Client for connecting to the Azure Bot Service
|
|
47
240
|
*/
|
|
48
241
|
connectionManager: Connections
|
|
49
242
|
|
|
243
|
+
private readonly _options: Required<CloudAdapterOptions>
|
|
244
|
+
|
|
50
245
|
/**
|
|
51
246
|
* Creates an instance of CloudAdapter.
|
|
52
247
|
* @param authConfig - The authentication configuration for securing communications.
|
|
53
248
|
* @param authProvider - No longer used.
|
|
54
249
|
* @param userTokenClient - No longer used.
|
|
250
|
+
* @param options - Optional runtime behavior overrides. See {@link CloudAdapterOptions}.
|
|
55
251
|
*/
|
|
56
|
-
constructor (authConfig?: AuthConfiguration, authProvider?: AuthProvider, userTokenClient?: UserTokenClient) {
|
|
252
|
+
constructor (authConfig?: AuthConfiguration, authProvider?: AuthProvider, userTokenClient?: UserTokenClient, options?: CloudAdapterOptions) {
|
|
57
253
|
super()
|
|
58
254
|
authConfig = getAuthConfigWithDefaults(authConfig)
|
|
59
255
|
this.connectionManager = new MsalConnectionManager(undefined, undefined, authConfig)
|
|
256
|
+
this._options = resolveCloudAdapterOptions(options)
|
|
257
|
+
|
|
258
|
+
// Install a CloudAdapter-aware default `onTurnError` that honors
|
|
259
|
+
// `emitStackTrace`. The base class default only logs the message; we
|
|
260
|
+
// preserve that user-facing behavior (trace + messages) but add an
|
|
261
|
+
// optional stack trace for operators when explicitly opted in.
|
|
262
|
+
this.onTurnError = async (context: TurnContext, error: Error) => {
|
|
263
|
+
const detail = this._options.emitStackTrace && error?.stack ? error.stack : `${error}`
|
|
264
|
+
logger.error(`\n [onTurnError] unhandled error: ${detail}`)
|
|
265
|
+
await context.sendTraceActivity(
|
|
266
|
+
'OnTurnError Trace',
|
|
267
|
+
`${error}`,
|
|
268
|
+
'https://www.botframework.com/schemas/error',
|
|
269
|
+
'TurnError'
|
|
270
|
+
)
|
|
271
|
+
await context.sendActivity('The agent encountered an error or bug.')
|
|
272
|
+
await context.sendActivity('To continue to run this agent, please fix the source code.')
|
|
273
|
+
}
|
|
60
274
|
}
|
|
61
275
|
|
|
62
276
|
/**
|
|
@@ -103,7 +317,7 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
103
317
|
headers?: HeaderPropagationCollection
|
|
104
318
|
): Promise<ConnectorClient> {
|
|
105
319
|
return trace(AdapterTraceDefinitions.createConnectorClient, async ({ record }) => {
|
|
106
|
-
record({ serviceUrl, scope })
|
|
320
|
+
record({ serviceUrl, scopes: [scope] })
|
|
107
321
|
|
|
108
322
|
// get the correct token provider
|
|
109
323
|
const tokenProvider = this.connectionManager.getTokenProvider(identity, serviceUrl)
|
|
@@ -144,7 +358,7 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
144
358
|
let connectorClient
|
|
145
359
|
const tokenProvider = this.connectionManager.getTokenProviderFromActivity(identity, activity)
|
|
146
360
|
const isAgentic = activity.isAgenticRequest()
|
|
147
|
-
|
|
361
|
+
const scopes: string[] = []
|
|
148
362
|
if (isAgentic) {
|
|
149
363
|
logger.debug('Activity is from an agentic source, using special scope', activity.recipient)
|
|
150
364
|
const agenticInstanceId = activity.getAgenticInstanceId()
|
|
@@ -159,8 +373,13 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
159
373
|
headers
|
|
160
374
|
)
|
|
161
375
|
} else if (activity.recipient?.role?.toLowerCase() === RoleTypes.AgenticUser.toLowerCase() && agenticInstanceId && agenticUserId) {
|
|
162
|
-
|
|
163
|
-
|
|
376
|
+
const configuredScopes = tokenProvider.connectionSettings?.scopes
|
|
377
|
+
if (configuredScopes?.length) {
|
|
378
|
+
scopes.push(...configuredScopes)
|
|
379
|
+
} else {
|
|
380
|
+
scopes.push(tokenProvider.connectionSettings?.scope ?? ApxProductionScope)
|
|
381
|
+
}
|
|
382
|
+
const token = await tokenProvider.getAgenticUserToken(activity.getAgenticTenantId() ?? '', agenticInstanceId, agenticUserId, scopes)
|
|
164
383
|
|
|
165
384
|
connectorClient = ConnectorClient.createClientWithToken(
|
|
166
385
|
activity.serviceUrl!,
|
|
@@ -173,8 +392,8 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
173
392
|
} else {
|
|
174
393
|
// ABS tokens will not have an azp/appid so use the botframework scope.
|
|
175
394
|
// Otherwise use the appId. This will happen when communicating back to another agent.
|
|
176
|
-
|
|
177
|
-
const token = await tokenProvider.getAccessToken(
|
|
395
|
+
scopes.push(identity.azp ?? identity.appid ?? 'https://api.botframework.com')
|
|
396
|
+
const token = await tokenProvider.getAccessToken(scopes[0])
|
|
178
397
|
connectorClient = ConnectorClient.createClientWithToken(
|
|
179
398
|
activity.serviceUrl!,
|
|
180
399
|
token,
|
|
@@ -183,7 +402,7 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
183
402
|
}
|
|
184
403
|
record({
|
|
185
404
|
serviceUrl: activity.serviceUrl,
|
|
186
|
-
|
|
405
|
+
scopes,
|
|
187
406
|
activityIsAgentic: isAgentic
|
|
188
407
|
})
|
|
189
408
|
return connectorClient
|
|
@@ -388,6 +607,11 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
388
607
|
record({ activity })
|
|
389
608
|
|
|
390
609
|
if (!this.isValidChannelActivity(activity)) {
|
|
610
|
+
logger.warn(`BadRequest: invalid activity body: ${truncateActivityForLog(activity)}`)
|
|
611
|
+
return end(StatusCodes.BAD_REQUEST)
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if (!this.validateServiceUrl(request.user, activity)) {
|
|
391
615
|
return end(StatusCodes.BAD_REQUEST)
|
|
392
616
|
}
|
|
393
617
|
|
|
@@ -441,6 +665,41 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
441
665
|
return true
|
|
442
666
|
}
|
|
443
667
|
|
|
668
|
+
/**
|
|
669
|
+
* Compares the host of `activity.serviceUrl` against the `serviceurl` claim
|
|
670
|
+
* on the caller's identity. When enabled and the hosts differ (or either
|
|
671
|
+
* URL is malformed), the request is rejected with HTTP 400; when disabled,
|
|
672
|
+
* the mismatch is logged as a warning.
|
|
673
|
+
*
|
|
674
|
+
* @returns `true` if the activity should continue processing; `false` if it
|
|
675
|
+
* should be rejected with a 400.
|
|
676
|
+
*/
|
|
677
|
+
private validateServiceUrl (identity: JwtPayload | undefined, activity: Activity): boolean {
|
|
678
|
+
if (!identity) return true
|
|
679
|
+
if (!activity.serviceUrl) return true
|
|
680
|
+
|
|
681
|
+
const claimValue = identity.serviceurl
|
|
682
|
+
if (typeof claimValue !== 'string') return true
|
|
683
|
+
|
|
684
|
+
let claimHost: string | undefined
|
|
685
|
+
let activityHost: string | undefined
|
|
686
|
+
try { claimHost = new URL(claimValue).hostname.toLowerCase() } catch { /* invalid */ }
|
|
687
|
+
try { activityHost = new URL(activity.serviceUrl).hostname.toLowerCase() } catch { /* invalid */ }
|
|
688
|
+
|
|
689
|
+
if (claimHost && activityHost && claimHost === activityHost) {
|
|
690
|
+
return true
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
const safeClaim = sanitizeForLog(claimValue)
|
|
694
|
+
const safeServiceUrl = sanitizeForLog(activity.serviceUrl)
|
|
695
|
+
if (this._options.validateServiceUrl) {
|
|
696
|
+
logger.error(`Invalid service URL Claim='${safeClaim}', ServiceUrl='${safeServiceUrl}'`)
|
|
697
|
+
return false
|
|
698
|
+
}
|
|
699
|
+
logger.warn(`Invalid service URL Claim='${safeClaim}', ServiceUrl='${safeServiceUrl}'`)
|
|
700
|
+
return true
|
|
701
|
+
}
|
|
702
|
+
|
|
444
703
|
/**
|
|
445
704
|
* Updates an activity.
|
|
446
705
|
* @param context - The TurnContext for the current turn.
|
|
@@ -599,7 +858,7 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
599
858
|
activity.name = ActivityEventNames.CreateConversation
|
|
600
859
|
activity.channelId = channelId
|
|
601
860
|
activity.serviceUrl = serviceUrl
|
|
602
|
-
activity.id = createdConversationId ??
|
|
861
|
+
activity.id = createdConversationId ?? randomUUID()
|
|
603
862
|
activity.conversation = {
|
|
604
863
|
conversationType: undefined,
|
|
605
864
|
id: createdConversationId!,
|
|
@@ -609,6 +868,9 @@ export class CloudAdapter extends BaseAdapter {
|
|
|
609
868
|
}
|
|
610
869
|
activity.channelData = conversationParameters.channelData
|
|
611
870
|
activity.recipient = conversationParameters.agent
|
|
871
|
+
// For 1:1 conversations members[0] is the target user; for channel conversations
|
|
872
|
+
// (where members is absent) we fall back to the agent so from.id is always present.
|
|
873
|
+
activity.from = conversationParameters.members?.[0] ?? conversationParameters.agent
|
|
612
874
|
|
|
613
875
|
return activity
|
|
614
876
|
}
|