teams_rb 2.0.3 → 2.1.0

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.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +39 -1
  3. data/docs/README.md +1 -1
  4. data/docs/essentials/README.md +1 -1
  5. data/docs/essentials/on-event.md +12 -2
  6. data/docs/essentials/sending-messages.md +7 -4
  7. data/docs/in-depth-guides/README.md +2 -0
  8. data/docs/in-depth-guides/agent-365.md +3 -1
  9. data/docs/in-depth-guides/files.md +99 -0
  10. data/docs/in-depth-guides/state.md +59 -0
  11. data/docs/in-depth-guides/streaming.md +6 -5
  12. data/docs/in-depth-guides/user-authentication.md +36 -8
  13. data/lib/teams/activity_context.rb +118 -15
  14. data/lib/teams/api/citation_appearance.rb +10 -2
  15. data/lib/teams/api/file_download_info.rb +34 -0
  16. data/lib/teams/api/message_activity.rb +37 -12
  17. data/lib/teams/api/sensitivity_usage_info.rb +38 -0
  18. data/lib/teams/app.rb +195 -153
  19. data/lib/teams/auth/jwt_validator.rb +17 -2
  20. data/lib/teams/cards/generated.rb +430 -430
  21. data/lib/teams/errors.rb +175 -4
  22. data/lib/teams/files/downloaded_file.rb +35 -0
  23. data/lib/teams/files/downloader.rb +405 -0
  24. data/lib/teams/files/files_accessor.rb +175 -0
  25. data/lib/teams/files/graph_share.rb +44 -0
  26. data/lib/teams/files/incoming_file.rb +128 -0
  27. data/lib/teams/files/inline_image.rb +88 -0
  28. data/lib/teams/files.rb +8 -0
  29. data/lib/teams/http_stream.rb +28 -28
  30. data/lib/teams/oauth/flow.rb +184 -0
  31. data/lib/teams/oauth/handlers.rb +376 -0
  32. data/lib/teams/oauth/pending_sign_ins.rb +300 -0
  33. data/lib/teams/oauth.rb +5 -0
  34. data/lib/teams/state/turn_state.rb +163 -0
  35. data/lib/teams/state/turn_state_container.rb +54 -0
  36. data/lib/teams/state/turn_state_loader.rb +143 -0
  37. data/lib/teams/state.rb +5 -0
  38. data/lib/teams/version.rb +1 -1
  39. data/lib/teams.rb +5 -0
  40. metadata +20 -1
@@ -61,13 +61,21 @@ module Teams
61
61
  body["encodingFormat"] = ADAPTIVE_CARD_CONTENT_TYPE if text && !text.empty?
62
62
  body["image"] = { "@type" => "ImageObject", "name" => icon } if icon
63
63
  body["keywords"] = keywords if keywords
64
- body["usageInfo"] = usage_info.to_h if usage_info && usage_info.respond_to?(:to_h)
65
- body["usageInfo"] = usage_info if usage_info && !usage_info.respond_to?(:to_h)
64
+ body["usageInfo"] = serialized_usage_info if usage_info
66
65
  body
67
66
  end
68
67
 
69
68
  private
70
69
 
70
+ # Accepts an Api::SensitivityUsageInfo or a hash; @type defaults to
71
+ # CreativeWork like the TypeScript, Python, and .NET SDKs.
72
+ def serialized_usage_info
73
+ info = usage_info.respond_to?(:to_h) ? usage_info.to_h : usage_info
74
+ return info unless info.is_a?(Hash)
75
+
76
+ { "@type" => "CreativeWork" }.merge(Common::Hashes.deep_stringify_keys(info).compact)
77
+ end
78
+
71
79
  def validate!
72
80
  validate_required!("name", name)
73
81
  validate_required!("abstract", abstract)
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Teams
4
+ module Api
5
+ # Content type of an inbound uploaded-file attachment; its content is a
6
+ # FileDownloadInfo.
7
+ FILE_DOWNLOAD_INFO_CONTENT_TYPE = "application/vnd.microsoft.teams.file.download.info"
8
+
9
+ # The content of a file.download.info attachment, describing an uploaded
10
+ # file. Mirrors the TypeScript, Python, and .NET FileDownloadInfo.
11
+ class FileDownloadInfo < Model
12
+ # Pre-authorized, short-lived URL the file can be fetched from with a
13
+ # plain GET (no bearer token).
14
+ def download_url
15
+ read("downloadUrl", "download_url")
16
+ end
17
+
18
+ # The OneDrive/ODSP identifier for the file, when reported.
19
+ def unique_id
20
+ read("uniqueId", "unique_id")
21
+ end
22
+
23
+ # The file extension, e.g. "pdf".
24
+ def file_type
25
+ read("fileType", "file_type")
26
+ end
27
+
28
+ # Server-assigned version tag for the file's contents, when provided.
29
+ def etag
30
+ read("etag")
31
+ end
32
+ end
33
+ end
34
+ end
@@ -3,7 +3,6 @@
3
3
  module Teams
4
4
  module Api
5
5
  class MessageActivity
6
- # "extendedmarkdown" is in public preview and may be subject to change.
7
6
  TEXT_FORMATS = %w[plain markdown xml extendedmarkdown].freeze
8
7
  FEEDBACK_MODES = %w[default custom].freeze
9
8
  AI_MESSAGE_ENTITY_TYPE = "https://schema.org/Message"
@@ -108,17 +107,25 @@ module Teams
108
107
  self
109
108
  end
110
109
 
111
- # Adds a content sensitivity label. The label is carried as usageInfo on
112
- # the root schema.org/Message entity, the wire shape TypeScript, Python,
113
- # and the Teams documentation use.
114
- def add_sensitivity_label(name, description: nil, pattern: nil)
115
- usage_info = {
116
- "type" => AI_MESSAGE_ENTITY_TYPE,
117
- "@type" => "CreativeWork",
118
- "name" => name
119
- }
120
- usage_info["description"] = description if description
121
- usage_info["pattern"] = pattern if pattern
110
+ # Adds a Microsoft Purview sensitivity label (an Api::SensitivityUsageInfo,
111
+ # or a hash in its wire shape) as usageInfo on the root message entity,
112
+ # replacing any earlier label, like the TypeScript, Python, and .NET SDKs.
113
+ #
114
+ # Deprecated: passing a label name string (with optional description: and
115
+ # pattern:) writes the name-only label teams_rb used before the SDKs
116
+ # defined the Purview label contract; it carries no label id.
117
+ def add_sensitivity_label(label, description: nil, pattern: nil)
118
+ usage_info = if label.is_a?(String)
119
+ warn("add_sensitivity_label(name) is deprecated; pass a Teams::Api::SensitivityUsageInfo with the Purview label id.",
120
+ uplevel: 1, category: :deprecated)
121
+ legacy_sensitivity_usage_info(label, description, pattern)
122
+ else
123
+ unless description.nil? && pattern.nil?
124
+ raise ArgumentError, "description: and pattern: apply only to the deprecated label-name form"
125
+ end
126
+
127
+ sensitivity_usage_info(label)
128
+ end
122
129
 
123
130
  ensure_single_root_level_message_entity["usageInfo"] = usage_info
124
131
  self
@@ -157,6 +164,24 @@ module Teams
157
164
 
158
165
  private
159
166
 
167
+ def sensitivity_usage_info(label)
168
+ body = label.respond_to?(:to_h) ? label.to_h : label
169
+ raise ArgumentError, "sensitivity label must be a Teams::Api::SensitivityUsageInfo or a hash" unless body.is_a?(Hash)
170
+
171
+ { "@type" => "CreativeWork" }.merge(Common::Hashes.deep_stringify_keys(body).compact)
172
+ end
173
+
174
+ def legacy_sensitivity_usage_info(name, description, pattern)
175
+ usage_info = {
176
+ "type" => AI_MESSAGE_ENTITY_TYPE,
177
+ "@type" => "CreativeWork",
178
+ "name" => name
179
+ }
180
+ usage_info["description"] = description if description
181
+ usage_info["pattern"] = pattern if pattern
182
+ usage_info
183
+ end
184
+
160
185
  def quoted_reply_entity?(entity)
161
186
  entity_type(entity) == "quotedReply"
162
187
  end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Teams
4
+ module Api
5
+ # A Microsoft Purview sensitivity label, identified by its label id. Teams
6
+ # resolves the label's display name and description from the id and shows
7
+ # it as a shield on the message. Used as the message-level label
8
+ # (MessageActivity#add_sensitivity_label) and as a citation's usage info.
9
+ # Mirrors the TypeScript, Python, and .NET SensitivityUsageInfo; at_id and
10
+ # at_type follow Python's names for the @id and @type wire keys.
11
+ class SensitivityUsageInfo
12
+ attr_reader :at_id, :at_type, :name, :description, :position
13
+
14
+ # name is the fallback display name when Teams cannot resolve at_id;
15
+ # position is the label's priority, used to pick the most restrictive
16
+ # label.
17
+ def initialize(at_id:, name: nil, description: nil, position: nil, at_type: "CreativeWork")
18
+ raise ArgumentError, "at_id (the Purview label id) is required" if at_id.nil?
19
+
20
+ @at_id = at_id
21
+ @at_type = at_type
22
+ @name = name
23
+ @description = description
24
+ @position = position
25
+ end
26
+
27
+ def to_h
28
+ {
29
+ "@type" => at_type,
30
+ "@id" => at_id,
31
+ "name" => name,
32
+ "description" => description,
33
+ "position" => position
34
+ }.compact
35
+ end
36
+ end
37
+ end
38
+ end
data/lib/teams/app.rb CHANGED
@@ -6,11 +6,12 @@ module Teams
6
6
  class App
7
7
  DEFAULT_MESSAGING_ENDPOINT = "/api/messages"
8
8
  DANGEROUSLY_ALLOW_UNAUTHENTICATED_REQUESTS_ENV_VAR = "DANGEROUSLY_ALLOW_UNAUTHENTICATED_REQUESTS"
9
- MAX_PROCESSED_EXCHANGE_IDS = 1000
10
9
  TRUE_ENV_VALUES = %w[1 true yes on].freeze
11
10
  FALSE_ENV_VALUES = %w[0 false no off].freeze
12
11
 
13
- attr_reader :api, :logger, :storage, :messaging_endpoint, :default_connection_name, :graph
12
+ # files_downloader and oauth_registry are plumbing for ActivityContext.
13
+ attr_reader :api, :logger, :storage, :messaging_endpoint, :default_connection_name, :graph,
14
+ :files_downloader, :oauth_registry
14
15
 
15
16
  def client_id
16
17
  @token_manager.client_id
@@ -29,11 +30,15 @@ module Teams
29
30
  dangerously_allow_unauthenticated_requests: nil,
30
31
  skip_auth: nil,
31
32
  messaging_endpoint: DEFAULT_MESSAGING_ENDPOINT,
32
- default_connection_name: "graph"
33
+ default_connection_name: "graph",
34
+ state: nil
33
35
  )
34
36
  @default_connection_name = default_connection_name
35
37
  @sign_in_handlers = []
38
+ @sign_in_failure_handlers = []
36
39
  @error_handlers = []
40
+ @oauth_registry = OAuth::FlowRegistry.new
41
+ @state_option = state
37
42
  @functions = {}
38
43
  @logger = logger
39
44
  @storage = storage
@@ -43,6 +48,7 @@ module Teams
43
48
  )
44
49
  @messaging_endpoint = normalize_messaging_endpoint(messaging_endpoint)
45
50
  @router = Router.new
51
+ @state_loader = create_state_loader(state)
46
52
 
47
53
  @token_manager = token_manager || Auth::TokenManager.from_env(client_id:, client_secret:, tenant_id:, cloud:)
48
54
  @api = api || Api::Client.new(
@@ -62,11 +68,16 @@ module Teams
62
68
  # clouds), like the TypeScript SDK; the app-identity client requests
63
69
  # app-only tokens through the client-credentials flow.
64
70
  graph_root = cloud.graph_scope.to_s[%r{\Ahttps?://[^/]+}]
71
+ @graph_base_url_root = graph_root
65
72
  @graph = Graph::Client.new(
66
73
  token: -> { @token_manager.token_for(cloud.graph_scope, @token_manager.credentials&.tenant_id || cloud.login_tenant) },
67
74
  base_url_root: graph_root
68
75
  )
69
76
 
77
+ # One plain connection for inbound file downloads, shared across turns.
78
+ @files_downloader = Files::Downloader.new(logger:)
79
+
80
+ @oauth_handlers = OAuth::Handlers.new(self)
70
81
  register_default_oauth_handlers
71
82
  warn_missing_credentials
72
83
  end
@@ -120,7 +131,7 @@ module Teams
120
131
  # exchange, signin/verifyState after interactive OAuth card sign-in,
121
132
  # signin/failure when the Teams client reports a failed SSO attempt.
122
133
  # Default handlers registered at construction complete these flows and
123
- # fire on_sign_in / on_error; handlers registered here run after them.
134
+ # fire on_oauth_sign_in / on_error; handlers registered here run after them.
124
135
  def on_signin_token_exchange(&block)
125
136
  @router.on_signin_token_exchange(&block)
126
137
  self
@@ -156,13 +167,21 @@ module Teams
156
167
  self
157
168
  end
158
169
 
170
+ # App-level OAuth events use the on_oauth_ prefix, which keeps them apart
171
+ # from the on_signin_* invoke routes on this object.
172
+
159
173
  # Called with (ctx, token_response) whenever a sign-in completes through
160
174
  # the default token-exchange or verify-state handlers.
161
- def on_sign_in(&block)
175
+ def on_oauth_sign_in(&block)
162
176
  @sign_in_handlers << block
163
177
  self
164
178
  end
165
179
 
180
+ def on_sign_in(&block)
181
+ warn("App#on_sign_in is deprecated; use App#on_oauth_sign_in.", uplevel: 1, category: :deprecated)
182
+ on_oauth_sign_in(&block)
183
+ end
184
+
166
185
  # Called with (error, activity) when a default OAuth handler hits an
167
186
  # unexpected failure or the Teams client reports a sign-in failure.
168
187
  def on_error(&block)
@@ -170,10 +189,64 @@ module Teams
170
189
  self
171
190
  end
172
191
 
192
+ # Called with an OAuth::SignInFailureEvent when the Teams client reports
193
+ # a failed sign-in (the signin/failure invoke). Terminal Token Service
194
+ # errors reach only the flows' own on_sign_in_failure handlers.
195
+ def on_oauth_sign_in_failure(&block)
196
+ @sign_in_failure_handlers << block
197
+ self
198
+ end
199
+
200
+ # Registers a named OAuth connection and returns its OAuth::Flow, like
201
+ # the Python SDK's add_oauth_flow. Connection names are case-insensitive
202
+ # and must be unique. Registering a flow turns on per-turn state when the
203
+ # state: option was left unset, because connection-less callbacks need
204
+ # somewhere to record which connection a sign-in started on; pass
205
+ # state: false to opt out (pending sign-ins then use a bounded
206
+ # process-local cache).
207
+ def add_oauth_flow(connection_name, oauth_card_text: OAuth::DEFAULT_OAUTH_CARD_TEXT,
208
+ sign_in_button_text: OAuth::DEFAULT_SIGN_IN_BUTTON_TEXT)
209
+ flow = @oauth_registry.add(
210
+ OAuth::Flow.new(connection_name, oauth_card_text:, sign_in_button_text:, logger:)
211
+ )
212
+ # Only after the registry accepted it, so a rejected duplicate cannot
213
+ # switch state on.
214
+ if @state_option.nil? && @state_loader.nil?
215
+ @state_loader = create_state_loader(true)
216
+ logger&.debug(
217
+ "Enabled per-turn state because an OAuth flow was registered and no state option was set. " \
218
+ "Pass state: false to opt out, or state: true / StateOptions to choose the storage."
219
+ )
220
+ end
221
+ flow
222
+ end
223
+
224
+ # The registered flow for a connection (case-insensitive); raises when
225
+ # none is registered.
226
+ def get_oauth_flow(connection_name)
227
+ flow = @oauth_registry[connection_name]
228
+ return flow if flow
229
+
230
+ registered = @oauth_registry.names.join(", ")
231
+ registered = "<none>" if registered.empty?
232
+ raise ArgumentError,
233
+ "No OAuth flow registered for connection '#{connection_name}'. Registered connections: #{registered}."
234
+ end
235
+
173
236
  def emit_sign_in(context, token_response)
174
237
  @sign_in_handlers.each { |handler| handler.call(context, token_response) }
175
238
  end
176
239
 
240
+ def emit_sign_in_failure(event)
241
+ @sign_in_failure_handlers.each { |handler| handler.call(event) }
242
+ end
243
+
244
+ # Process-local pending sign-ins, used when per-turn state is off.
245
+ # Plumbing for ActivityContext#sign_in.
246
+ def oauth_pending_cache
247
+ @oauth_handlers.pending_cache
248
+ end
249
+
177
250
  def emit_error(error, activity: nil)
178
251
  @error_handlers.each { |handler| handler.call(error, activity) }
179
252
  end
@@ -293,17 +366,24 @@ module Teams
293
366
  activity:,
294
367
  conversation_reference:,
295
368
  api: turn_api,
296
- stream: HttpStream.new(app: self, conversation_reference:, api: turn_api)
369
+ stream: HttpStream.new(app: self, conversation_reference:, api: turn_api),
370
+ files_credential: files_credential(activity, agentic_identity),
371
+ files_bot_api_credential: files_bot_api_credential(activity, agentic_identity, turn_api),
372
+ state: load_turn_state(activity)
297
373
  )
298
- result = run_handlers(context)
299
- context.stream.close
374
+ processing_completed = false
375
+ begin
376
+ result = run_handlers(context)
377
+ context.stream.close
378
+ processing_completed = true
379
+ ensure
380
+ persist_turn_state(context, processing_completed)
381
+ end
300
382
 
301
383
  return result if result.is_a?(Response)
302
384
 
303
385
  body = activity.invoke? ? invoke_response_body(result) : nil
304
386
  Response.new(status: 200, body:)
305
- rescue StreamCancelledError
306
- Response.new(status: 200)
307
387
  end
308
388
 
309
389
  # Builds an Api::AgenticIdentity for proactive agentic operations: the
@@ -362,17 +442,15 @@ module Teams
362
442
  def send_activity(conversation_reference, activity_or_text, api: self.api)
363
443
  activity = activity_for_reference(conversation_reference, activity_or_text)
364
444
  targeted = targeted_activity?(activity)
365
-
366
- if targeted && conversation_reference.conversation.conversation_type == "personal"
367
- raise ArgumentError, "Targeted messages are not supported in 1:1 (personal) chats."
368
- end
369
-
370
445
  id = activity_id(activity)
371
446
  conversation_id = conversation_reference.conversation_id
372
447
  service_url = conversation_reference.service_url
373
448
 
374
449
  response = if id && targeted
375
- api.conversations.update_targeted_activity(conversation_id, id, activity, service_url:)
450
+ # The recipient of an existing targeted message cannot change: it only
451
+ # selects the targeted endpoint and is dropped from the payload, like
452
+ # the TypeScript and Python SDKs. The returned activity keeps it.
453
+ api.conversations.update_targeted_activity(conversation_id, id, activity.except("recipient"), service_url:)
376
454
  elsif id
377
455
  api.conversations.update_activity(conversation_id, id, activity, service_url:)
378
456
  elsif targeted
@@ -455,151 +533,115 @@ module Teams
455
533
  value.to_s.empty? ? nil : value
456
534
  end
457
535
 
458
- # Default OAuth handlers, mirroring the TypeScript/Python OauthHandlers:
459
- # registered first on the signin routes, they complete the flows, fire
460
- # the sign-in/error events, and chain to user handlers via next. Their
461
- # return value is the invoke response; 412 tells the Teams client to
462
- # fall back to the interactive card flow.
536
+ # Default OAuth handlers (OAuth::Handlers), registered first on the signin
537
+ # routes so they complete the flows and chain to user handlers via next.
463
538
  def register_default_oauth_handlers
464
- app = self
465
-
466
- # Each Teams client (desktop, web, mobile) that renders the OAuth card
467
- # attempts its own silent exchange, so one sign-in can produce several
468
- # signin/tokenExchange invokes sharing the same value id. Only the first
469
- # runs the exchange and fires sign-in; a duplicate of a completed
470
- # exchange answers 200 without re-emitting or chaining, and a duplicate
471
- # arriving while the first is in flight waits and returns its result.
472
- # Failed exchanges are not marked, so each attempt gets its own 412.
473
- exchange_mutex = Mutex.new
474
- processed_exchange_ids = []
475
- exchange_locks = {}
476
-
477
- perform_token_exchange = lambda do |ctx, nxt|
478
- value = ctx.activity.value
479
- begin
480
- if value.raw["connectionName"] != app.default_connection_name
481
- app.logger&.warn(
482
- "Sign-in token exchange invoked with connection name #{value.raw["connectionName"].inspect}, " \
483
- "but the default connection name is #{app.default_connection_name.inspect}. " \
484
- "Token verification will likely fail."
485
- )
486
- end
487
-
488
- begin
489
- token = ctx.api.users.exchange_token(
490
- user_id: ctx.activity.from.id,
491
- connection_name: value.raw["connectionName"],
492
- channel_id: ctx.activity.channel_id,
493
- exchange_request: { "token" => value.raw["token"] }
494
- )
495
- app.emit_sign_in(ctx, token)
496
- nil
497
- rescue HttpError => error
498
- unless [404, 400, 412].include?(error.status)
499
- app.logger&.error("Error exchanging token: #{error.message}")
500
- app.emit_error(error, activity: ctx.activity)
501
- next Response.new(status: error.status || 500)
502
- end
503
-
504
- Response.new(
505
- status: 412,
506
- body: {
507
- "id" => value.raw["id"],
508
- "connectionName" => value.raw["connectionName"],
509
- "failureDetail" => error.message
510
- }
511
- )
512
- end
513
- ensure
514
- nxt.call
515
- end
539
+ handlers = @oauth_handlers
540
+ @router.on_signin_token_exchange { |ctx, nxt| handlers.token_exchange(ctx, nxt) }
541
+ @router.on_signin_verify_state { |ctx, nxt| handlers.verify_state(ctx, nxt) }
542
+ @router.on_signin_failure { |ctx, nxt| handlers.failure(ctx, nxt) }
543
+ end
544
+
545
+ # Resolves the state: option like the Python SDK: nil/false disables
546
+ # state, true enables it on the app's storage, State::StateOptions
547
+ # configures the storage and key prefix.
548
+ def create_state_loader(state)
549
+ return nil unless state
550
+
551
+ options = state == true ? State::StateOptions.new : state
552
+ unless options.is_a?(State::StateOptions)
553
+ raise ArgumentError, "state: must be true, false, nil, or a Teams::State::StateOptions"
516
554
  end
517
555
 
518
- @router.on_signin_token_exchange do |ctx, nxt|
519
- exchange_id = ctx.activity.value.raw["id"]
520
- next perform_token_exchange.call(ctx, nxt) unless exchange_id
521
-
522
- lock = nil
523
- duplicate = exchange_mutex.synchronize do
524
- if processed_exchange_ids.include?(exchange_id)
525
- true
526
- else
527
- lock = (exchange_locks[exchange_id] ||= { mutex: Mutex.new, settled: false, result: nil })
528
- false
529
- end
530
- end
531
- next Response.new(status: 200) if duplicate
532
-
533
- outcome = lock[:mutex].synchronize do
534
- if lock[:settled]
535
- lock[:result]
536
- else
537
- result = perform_token_exchange.call(ctx, nxt)
538
- if result.nil?
539
- exchange_mutex.synchronize do
540
- processed_exchange_ids << exchange_id
541
- processed_exchange_ids.shift while processed_exchange_ids.length > MAX_PROCESSED_EXCHANGE_IDS
542
- end
543
- lock[:result] = Response.new(status: 200)
544
- else
545
- lock[:result] = result
546
- end
547
- lock[:settled] = true
548
- result
549
- end
550
- end
551
- exchange_mutex.synchronize { exchange_locks.delete(exchange_id) }
552
- outcome
556
+ storage = options.storage || @storage
557
+ if storage.is_a?(Storage::MemoryStore)
558
+ @logger&.warn(
559
+ "State is enabled with in-memory storage (MemoryStore): per-turn state is lost on restart " \
560
+ "and is not shared across instances."
561
+ )
553
562
  end
563
+ State::TurnStateLoader.new(storage:, key_prefix: options.key_prefix, logger: @logger)
564
+ end
554
565
 
555
- @router.on_signin_verify_state do |ctx, nxt|
556
- begin
557
- state = ctx.activity.value.raw["state"]
558
- if state.to_s.empty?
559
- app.logger&.warn("Auth state not present on signin/verifyState invoke")
560
- next Response.new(status: 404)
561
- end
562
-
563
- begin
564
- token = ctx.api.users.get_token(
565
- user_id: ctx.activity.from.id,
566
- connection_name: app.default_connection_name,
567
- channel_id: ctx.activity.channel_id,
568
- code: state
569
- )
570
- app.emit_sign_in(ctx, token)
571
- nil
572
- rescue HttpError => error
573
- app.logger&.error("Error verifying sign-in state: #{error.message}")
574
- unless [404, 400, 412].include?(error.status)
575
- app.emit_error(error, activity: ctx.activity)
576
- next Response.new(status: error.status || 500)
577
- end
578
-
579
- Response.new(status: 412)
580
- end
581
- ensure
582
- nxt.call
583
- end
566
+ # Loads the conversation scope and the user scope (keyed by the
567
+ # activity's from identity) when state is enabled; nil otherwise.
568
+ def load_turn_state(activity)
569
+ return nil unless @state_loader
570
+
571
+ conversation_id = activity.conversation&.id
572
+ return nil if conversation_id.to_s.empty?
573
+
574
+ user_id = activity.from&.id
575
+ @state_loader.load(conversation_id, user_id.to_s.empty? ? nil : user_id)
576
+ end
577
+
578
+ # Saves dirty scopes and seals the state at the end of the turn, also
579
+ # when a handler raised. A save failure is reported through on_error and
580
+ # re-raised only when the turn itself succeeded, so it never masks the
581
+ # handler's error.
582
+ def persist_turn_state(context, processing_completed)
583
+ container = context.state
584
+ return unless @state_loader && container
585
+
586
+ begin
587
+ container.save
588
+ ensure
589
+ container.seal
590
+ end
591
+ rescue StandardError => error
592
+ begin
593
+ emit_error(error, activity: context.activity)
594
+ rescue StandardError => handler_error
595
+ logger&.error("Error handler failed while reporting a state persistence failure: #{handler_error.message}")
584
596
  end
597
+ raise if processing_completed
598
+ end
585
599
 
586
- @router.on_signin_failure do |ctx, nxt|
587
- begin
588
- value = ctx.activity.value
589
- app.logger&.warn(
590
- "Sign-in failed: #{value.raw["code"]} - #{value.raw["message"]}. " \
591
- "If the code is 'resourcematchfailed', verify the Entra app registration's " \
592
- "Application ID URI matches the OAuth connection's Token Exchange URL."
593
- )
594
- app.emit_error(
595
- Error.new("Sign-in failure: #{value.raw["code"]} - #{value.raw["message"]}"),
596
- activity: ctx.activity
597
- )
598
- nil
599
- ensure
600
- nxt.call
601
- end
600
+ # The Graph credential for the turn's file reads, resolved only when a
601
+ # Graph read happens. An agentic user reads as itself, never the app: an
602
+ # app-only token sees what the app may read tenant-wide, a different set
603
+ # from what was shared with the agent, like the other SDKs.
604
+ def files_credential(activity, agentic_identity)
605
+ tenant_id = activity.conversation&.tenant_id || activity.channel_data&.tenant&.id
606
+ token = if agentic_identity
607
+ -> { agentic_graph_token(agentic_identity, tenant_id) }
608
+ else
609
+ -> { @token_manager.token_for(@cloud.graph_scope, tenant_id || @token_manager.credentials&.tenant_id || @cloud.login_tenant) }
602
610
  end
611
+
612
+ Files::GraphCredential.new(
613
+ actor: agentic_identity ? "agentic_user" : "app",
614
+ token:,
615
+ base_url_root: @graph_base_url_root
616
+ )
617
+ end
618
+
619
+ # Inline images are read with the turn's Bot API token (the agentic
620
+ # identity's when the turn is scoped to one), resolved only on download
621
+ # and sent only under the activity's service URL.
622
+ def files_bot_api_credential(activity, agentic_identity, turn_api)
623
+ Files::BotApiCredential.new(
624
+ actor: agentic_identity ? "agentic_user" : "app",
625
+ service_url: activity.service_url,
626
+ token: lambda do
627
+ token = turn_api.http.token
628
+ token.respond_to?(:call) ? token.call : token
629
+ end
630
+ )
631
+ end
632
+
633
+ # The identity's own tenant wins, then the tenant the activity arrived
634
+ # from; TokenManager raises when neither is known rather than acquiring
635
+ # in the wrong directory.
636
+ def agentic_graph_token(identity, tenant_id)
637
+ return nil if identity.agentic_app_id.to_s.empty? || identity.agentic_user_id.to_s.empty?
638
+
639
+ @token_manager.agentic_user_token(
640
+ @cloud.graph_scope,
641
+ agentic_app_id: identity.agentic_app_id,
642
+ agentic_user_id: identity.agentic_user_id,
643
+ tenant_id: identity.tenant_id || tenant_id
644
+ )
603
645
  end
604
646
 
605
647
  # Resolves the auth-bypass setting like the Python SDK: the explicit
@@ -6,6 +6,9 @@ module Teams
6
6
  module Auth
7
7
  class JwtValidator
8
8
  ENTRA_V1_ISSUER_PREFIX = "https://sts.windows.net/"
9
+ # App id of the Agent 365 platform, the only client app allowed to
10
+ # request the Entra tokens that authenticate agentic inbound activities.
11
+ AGENT_365_PLATFORM_APP_ID = "5a807f24-c9de-44ee-a3a7-329e88a00ffc"
9
12
  JWKS_CACHE_TTL = 10 * 60
10
13
  JWKS_CACHE_MAX_ENTRIES = 5
11
14
  # Endpoints are bounded so random tenant ids in unverified inbound
@@ -103,17 +106,29 @@ module Teams
103
106
 
104
107
  issuers = ["#{@cloud.login_endpoint}/#{tenant_id}/v2.0", "#{ENTRA_V1_ISSUER_PREFIX}#{tenant_id}/"]
105
108
  # Cheap claim checks run first so junk inbound tokens cannot trigger
106
- # JWKS fetches for arbitrary tenants; decode! re-verifies both after
107
- # the signature.
109
+ # JWKS fetches for arbitrary tenants; decode! re-verifies issuer and
110
+ # audience after the signature, which also covers the caller app.
108
111
  raise AuthenticationError, "JWT issuer is invalid" unless issuers.include?(claims["iss"])
109
112
  raise AuthenticationError, "JWT audience is invalid" if (Array(claims["aud"]) & valid_audiences).empty?
110
113
 
114
+ validate_entra_caller_app!(claims)
115
+
111
116
  uri = entra_tenant_jwks_uri(tenant_id)
112
117
  decode!(token, issuers: issuers) do |header, _decoded|
113
118
  signing_key(uri, header["kid"])
114
119
  end
115
120
  end
116
121
 
122
+ # Entra v2 tokens name the requesting client app in azp, v1 tokens in
123
+ # appid. appid is consulted only when azp is absent, so a present but
124
+ # wrong azp is rejected. Matches the TypeScript, Python, and .NET SDKs.
125
+ def validate_entra_caller_app!(claims)
126
+ caller_app_id = claims.key?("azp") ? claims["azp"] : claims["appid"]
127
+ return if caller_app_id.is_a?(String) && caller_app_id.casecmp?(AGENT_365_PLATFORM_APP_ID)
128
+
129
+ raise AuthenticationError, "Entra inbound token caller app is not allowed: #{caller_app_id.inspect}"
130
+ end
131
+
117
132
  # Inbound tokens may be audienced as the bare app id, api://{appId},
118
133
  # or api://botid-{appId}; all three SDKs accept all three forms.
119
134
  def valid_audiences