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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +39 -1
- data/docs/README.md +1 -1
- data/docs/essentials/README.md +1 -1
- data/docs/essentials/on-event.md +12 -2
- data/docs/essentials/sending-messages.md +7 -4
- data/docs/in-depth-guides/README.md +2 -0
- data/docs/in-depth-guides/agent-365.md +3 -1
- data/docs/in-depth-guides/files.md +99 -0
- data/docs/in-depth-guides/state.md +59 -0
- data/docs/in-depth-guides/streaming.md +6 -5
- data/docs/in-depth-guides/user-authentication.md +36 -8
- data/lib/teams/activity_context.rb +118 -15
- data/lib/teams/api/citation_appearance.rb +10 -2
- data/lib/teams/api/file_download_info.rb +34 -0
- data/lib/teams/api/message_activity.rb +37 -12
- data/lib/teams/api/sensitivity_usage_info.rb +38 -0
- data/lib/teams/app.rb +195 -153
- data/lib/teams/auth/jwt_validator.rb +17 -2
- data/lib/teams/cards/generated.rb +430 -430
- data/lib/teams/errors.rb +175 -4
- data/lib/teams/files/downloaded_file.rb +35 -0
- data/lib/teams/files/downloader.rb +405 -0
- data/lib/teams/files/files_accessor.rb +175 -0
- data/lib/teams/files/graph_share.rb +44 -0
- data/lib/teams/files/incoming_file.rb +128 -0
- data/lib/teams/files/inline_image.rb +88 -0
- data/lib/teams/files.rb +8 -0
- data/lib/teams/http_stream.rb +28 -28
- data/lib/teams/oauth/flow.rb +184 -0
- data/lib/teams/oauth/handlers.rb +376 -0
- data/lib/teams/oauth/pending_sign_ins.rb +300 -0
- data/lib/teams/oauth.rb +5 -0
- data/lib/teams/state/turn_state.rb +163 -0
- data/lib/teams/state/turn_state_container.rb +54 -0
- data/lib/teams/state/turn_state_loader.rb +143 -0
- data/lib/teams/state.rb +5 -0
- data/lib/teams/version.rb +1 -1
- data/lib/teams.rb +5 -0
- metadata +20 -1
data/lib/teams/errors.rb
CHANGED
|
@@ -9,20 +9,191 @@ module Teams
|
|
|
9
9
|
|
|
10
10
|
class BadRequestError < Error; end
|
|
11
11
|
|
|
12
|
-
#
|
|
13
|
-
#
|
|
12
|
+
# Deprecated: Teams no longer supports stopping a stream, so the SDK never
|
|
13
|
+
# raises this. Kept so existing rescue clauses keep loading.
|
|
14
14
|
class StreamCancelledError < Error; end
|
|
15
15
|
|
|
16
16
|
# Base class for terminal streaming errors (HTTP 403) that should not be retried.
|
|
17
|
-
# https://learn.microsoft.com/en-us/microsoftteams/platform/bots/streaming-ux
|
|
17
|
+
# https://learn.microsoft.com/en-us/microsoftteams/platform/bots/streaming-ux#response-codes
|
|
18
18
|
class TerminalStreamError < Error; end
|
|
19
19
|
|
|
20
|
-
# Raised when the bot failed to complete streaming within the
|
|
20
|
+
# Raised when the bot failed to complete streaming within the ten-minute limit.
|
|
21
21
|
class StreamTimedOutError < TerminalStreamError; end
|
|
22
22
|
|
|
23
23
|
# Raised when streaming is not allowed for this user or bot.
|
|
24
24
|
class StreamNotAllowedError < TerminalStreamError; end
|
|
25
25
|
|
|
26
|
+
# Base class for the diagnosable failures on the inbound-file path, so one
|
|
27
|
+
# rescue covers them. A transport or service failure the SDK cannot
|
|
28
|
+
# attribute surfaces as a plain Teams::Error instead.
|
|
29
|
+
class FileError < Error; end
|
|
30
|
+
|
|
31
|
+
# An inbound file's short-lived download URL expired. reason is
|
|
32
|
+
# "first_fetch" (no bytes were ever fetched; the file has to be sent again)
|
|
33
|
+
# or "reread" (an earlier download through the same handle succeeded; reuse
|
|
34
|
+
# one DownloadedFile instead of re-reading the handle).
|
|
35
|
+
class FileUrlExpiredError < FileError
|
|
36
|
+
attr_reader :reason
|
|
37
|
+
|
|
38
|
+
def initialize(reason, message = nil)
|
|
39
|
+
message ||= if reason == "first_fetch"
|
|
40
|
+
"file download URL expired before any bytes were fetched. The URL is short-lived and cannot be " \
|
|
41
|
+
"renewed, so the file has to be sent again. Download on arrival rather than holding the handle."
|
|
42
|
+
else
|
|
43
|
+
"file download URL expired before a repeat read; reuse a single DownloadedFile from one " \
|
|
44
|
+
"download call instead of re-reading the handle"
|
|
45
|
+
end
|
|
46
|
+
super(message)
|
|
47
|
+
@reason = reason
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# File bytes were requested for a conversation scope whose download path
|
|
52
|
+
# is not implemented.
|
|
53
|
+
class FileScopeNotSupportedError < FileError
|
|
54
|
+
attr_reader :scope
|
|
55
|
+
|
|
56
|
+
def initialize(scope, message = nil)
|
|
57
|
+
super(message || "downloading files from '#{scope}' conversations is not supported via SDK at this time")
|
|
58
|
+
@scope = scope
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Names the identity a file read was attempted as ("app" or
|
|
63
|
+
# "agentic_user") in error messages.
|
|
64
|
+
module FileActorGuidance
|
|
65
|
+
private
|
|
66
|
+
|
|
67
|
+
def describe_actor(actor)
|
|
68
|
+
case actor
|
|
69
|
+
when "agentic_user" then "the agentic user"
|
|
70
|
+
when "app" then "the app"
|
|
71
|
+
else "the identity used"
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# No credential was available for the Graph read a file needs, detected
|
|
77
|
+
# before any request: a token could not be acquired (cause says why), or
|
|
78
|
+
# the acquired token carries no file-capable permission.
|
|
79
|
+
class FileCredentialError < FileError
|
|
80
|
+
attr_reader :actor, :cause_detail
|
|
81
|
+
|
|
82
|
+
def initialize(actor = nil, cause_detail = nil)
|
|
83
|
+
message = "cannot fetch file bytes through Graph: #{guidance(actor)}"
|
|
84
|
+
message = "#{message} (#{cause_detail})" if cause_detail
|
|
85
|
+
super(message)
|
|
86
|
+
@actor = actor
|
|
87
|
+
@cause_detail = cause_detail
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
private
|
|
91
|
+
|
|
92
|
+
def guidance(actor)
|
|
93
|
+
case actor
|
|
94
|
+
when "agentic_user"
|
|
95
|
+
"the agentic user has no usable Graph permissions. An agent identity gets Graph scopes from its " \
|
|
96
|
+
"blueprint's inheritable permissions or from a direct grant, and an administrator must consent to them. " \
|
|
97
|
+
"See https://learn.microsoft.com/entra/agent-id/concept-inheritable-permissions"
|
|
98
|
+
when "app"
|
|
99
|
+
"the app has no usable Graph credential for this file. Graph file retrieval is supported for Agentic " \
|
|
100
|
+
"Users, which read as their own identity; an app identity and/or user-delegated permissions may be " \
|
|
101
|
+
"used but are not supported via the SDK at this time"
|
|
102
|
+
else
|
|
103
|
+
"no Graph credential was available, and no identity had been selected when the attempt was made"
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# The storage service refused the Graph read. status 401 means the token
|
|
109
|
+
# was rejected; 403 means the identity lacks the grant, which also covers a
|
|
110
|
+
# file never shared with it and an item that does not exist (Graph does not
|
|
111
|
+
# tell them apart). details carries what the service said.
|
|
112
|
+
class FileAccessError < FileError
|
|
113
|
+
include FileActorGuidance
|
|
114
|
+
|
|
115
|
+
attr_reader :status, :actor, :details
|
|
116
|
+
|
|
117
|
+
def initialize(status, actor = nil, details = nil)
|
|
118
|
+
message = "cannot fetch file bytes through Graph: #{guidance(status, actor)}"
|
|
119
|
+
message = "#{message} (service said: #{details})" if details
|
|
120
|
+
super(message)
|
|
121
|
+
@status = status
|
|
122
|
+
@actor = actor
|
|
123
|
+
@details = details
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
private
|
|
127
|
+
|
|
128
|
+
def guidance(status, actor)
|
|
129
|
+
as_who = describe_actor(actor)
|
|
130
|
+
case status
|
|
131
|
+
when 401
|
|
132
|
+
"the token presented for #{as_who} was rejected. It may have expired, or been issued for the wrong " \
|
|
133
|
+
"audience or tenant"
|
|
134
|
+
when 403
|
|
135
|
+
"access was denied for #{as_who}. The required scope may not be consented, the file may never have been " \
|
|
136
|
+
"shared with that identity, or the drive item may not exist"
|
|
137
|
+
else
|
|
138
|
+
"the request for #{as_who} was refused with status #{status}"
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# The Teams service could not convert a pasted image for download (415).
|
|
144
|
+
# Some formats, such as BMP and AVIF, cannot be converted; the same image
|
|
145
|
+
# sent as a file attachment downloads normally. code is the service's error
|
|
146
|
+
# code (e.g. "TransformationFailed").
|
|
147
|
+
class InlineImageTransformationError < FileError
|
|
148
|
+
attr_reader :status, :actor, :details, :code
|
|
149
|
+
|
|
150
|
+
def initialize(status, actor = nil, details = nil, code = nil)
|
|
151
|
+
reason = code ? "status #{status}, code #{code}" : "status #{status}"
|
|
152
|
+
message = "cannot download inline image: the Teams service could not convert it for download (#{reason}). " \
|
|
153
|
+
"Some image formats, such as BMP and AVIF, cannot be converted by the Teams service, so Teams shows a " \
|
|
154
|
+
"placeholder, and they cannot be downloaded. Ask the user to send the image as a file attachment instead"
|
|
155
|
+
message = "#{message} (service said: #{details})" if details
|
|
156
|
+
super(message)
|
|
157
|
+
@status = status
|
|
158
|
+
@actor = actor
|
|
159
|
+
@details = details
|
|
160
|
+
@code = code
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# The Bot API refused the token presented for a pasted image: 401 means
|
|
165
|
+
# the token was rejected, 403 that the identity may not read the image.
|
|
166
|
+
# Inline images are read with the turn's Bot API token, not Graph.
|
|
167
|
+
class InlineImageAccessError < FileError
|
|
168
|
+
include FileActorGuidance
|
|
169
|
+
|
|
170
|
+
attr_reader :status, :actor, :details
|
|
171
|
+
|
|
172
|
+
def initialize(status, actor = nil, details = nil)
|
|
173
|
+
message = "cannot download inline image: #{guidance(status, actor)}"
|
|
174
|
+
message = "#{message} (service said: #{details})" if details
|
|
175
|
+
super(message)
|
|
176
|
+
@status = status
|
|
177
|
+
@actor = actor
|
|
178
|
+
@details = details
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
private
|
|
182
|
+
|
|
183
|
+
def guidance(status, actor)
|
|
184
|
+
as_who = describe_actor(actor)
|
|
185
|
+
case status
|
|
186
|
+
when 401
|
|
187
|
+
"the Bot API token presented for #{as_who} was rejected (status 401). " \
|
|
188
|
+
"It may have expired, or been issued for the wrong audience or tenant"
|
|
189
|
+
when 403
|
|
190
|
+
"access was denied for #{as_who} (status 403). The identity is not allowed to read the image"
|
|
191
|
+
else
|
|
192
|
+
"the Bot API token presented for #{as_who} was rejected with status #{status}"
|
|
193
|
+
end
|
|
194
|
+
end
|
|
195
|
+
end
|
|
196
|
+
|
|
26
197
|
# A failed Microsoft Graph request; code carries the Graph error code
|
|
27
198
|
# (e.g. "Authorization_RequestDenied") and body the full error payload.
|
|
28
199
|
class GraphError < Error
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Teams
|
|
4
|
+
module Files
|
|
5
|
+
# A buffered, point-in-time snapshot of a downloaded file's bytes that the
|
|
6
|
+
# caller owns. Returned by IncomingFile#download; its readers never
|
|
7
|
+
# re-download, so holding one is the way to read a file several ways.
|
|
8
|
+
class DownloadedFile
|
|
9
|
+
# bytes is a binary String; content_type is resolved from the response
|
|
10
|
+
# (never empty: falls back to application/octet-stream); source_url is
|
|
11
|
+
# where the bytes were actually fetched from.
|
|
12
|
+
attr_reader :bytes, :content_type, :filename, :source_url
|
|
13
|
+
|
|
14
|
+
def initialize(bytes:, content_type:, filename:, source_url:)
|
|
15
|
+
@bytes = bytes
|
|
16
|
+
@content_type = content_type
|
|
17
|
+
@filename = filename
|
|
18
|
+
@source_url = source_url
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# Decodes the bytes (UTF-8 by default). No content-type check; lossy:
|
|
22
|
+
# invalid bytes become U+FFFD instead of raising. Use bytes for strict or
|
|
23
|
+
# binary-safe reads.
|
|
24
|
+
def text(encoding = Encoding::UTF_8)
|
|
25
|
+
bytes.dup.force_encoding(encoding).scrub
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Writes the buffered bytes to a local path (no re-fetch).
|
|
29
|
+
def save_as(path)
|
|
30
|
+
File.binwrite(path, bytes)
|
|
31
|
+
nil
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "base64"
|
|
4
|
+
require "faraday"
|
|
5
|
+
require "json"
|
|
6
|
+
require "uri"
|
|
7
|
+
|
|
8
|
+
module Teams
|
|
9
|
+
module Files
|
|
10
|
+
# The minimal description the downloader needs to open a file's bytes.
|
|
11
|
+
FetchTarget = Struct.new(:scope, :download_url, :content_url, :content_type, :attachment_style, keyword_init: true)
|
|
12
|
+
|
|
13
|
+
# What a successful fetch resolved: where the bytes came from and their
|
|
14
|
+
# MIME type (the response's, else the file's, else octet-stream).
|
|
15
|
+
OpenedFile = Struct.new(:source_url, :content_type, keyword_init: true)
|
|
16
|
+
|
|
17
|
+
# The Graph credential for a turn's file reads: actor names the identity
|
|
18
|
+
# ("app" or "agentic_user"), token is a callable resolved only when a
|
|
19
|
+
# Graph read happens, base_url_root the Graph host root.
|
|
20
|
+
GraphCredential = Struct.new(:actor, :token, :base_url_root, keyword_init: true)
|
|
21
|
+
|
|
22
|
+
# The Bot API credential for reading pasted inline images: the turn's API
|
|
23
|
+
# token (an agentic identity reads as itself), resolved lazily, and the
|
|
24
|
+
# activity's service URL — the token is only ever sent under it.
|
|
25
|
+
BotApiCredential = Struct.new(:actor, :token, :service_url, keyword_init: true)
|
|
26
|
+
|
|
27
|
+
# Fetches inbound file bytes, keyed on the conversation scope so every
|
|
28
|
+
# scope's receive path extends this one place, like the TypeScript,
|
|
29
|
+
# Python, and .NET dispatchers.
|
|
30
|
+
#
|
|
31
|
+
# It holds a plain Faraday connection with no token middleware: a
|
|
32
|
+
# pre-authorized download URL carries its own tempauth credential, so the
|
|
33
|
+
# bot's Authorization header must never reach the storage host (Python
|
|
34
|
+
# strips it from its shared client for the same reason).
|
|
35
|
+
class Downloader
|
|
36
|
+
OCTET_STREAM = "application/octet-stream"
|
|
37
|
+
MAX_REDIRECTS = 20
|
|
38
|
+
# How much of an error body to keep for diagnostics.
|
|
39
|
+
ERROR_BODY_LIMIT = 2048
|
|
40
|
+
REDIRECT_STATUSES = [301, 302, 303, 307, 308].freeze
|
|
41
|
+
|
|
42
|
+
Response = Struct.new(:status, :headers, :reason_phrase, :error_body, keyword_init: true)
|
|
43
|
+
|
|
44
|
+
GRAPH_FILE_PERMISSION_PREFIXES = %w[files. sites.].freeze
|
|
45
|
+
|
|
46
|
+
# Whether a file that arrived with only a content URL may be read
|
|
47
|
+
# through Graph in this scope, as this actor. Shared by the accessor and
|
|
48
|
+
# the dispatcher so a file list surfaces is always one download opens.
|
|
49
|
+
# Personal is open to every actor; group chats and channels only to an
|
|
50
|
+
# agentic user, the only identity the platform delivers files to there.
|
|
51
|
+
def self.graph_route_open?(scope, actor)
|
|
52
|
+
return true if scope == "personal"
|
|
53
|
+
|
|
54
|
+
actor == "agentic_user" && %w[groupChat channel].include?(scope)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
SINGLE_DOT_SEGMENTS = %w[. %2e].freeze
|
|
58
|
+
DOUBLE_DOT_SEGMENTS = %w[.. .%2e %2e. %2e%2e].freeze
|
|
59
|
+
PERCENT_ESCAPE = /%[0-9A-Fa-f]{2}/
|
|
60
|
+
|
|
61
|
+
# Whether url is under service_url: both https, the same origin, and a
|
|
62
|
+
# path inside the service URL's path. Dot segments (including
|
|
63
|
+
# percent-encoded dots) are resolved first so a path cannot climb out;
|
|
64
|
+
# scheme and host compare case-insensitively, the path case-sensitively
|
|
65
|
+
# apart from percent-escape hex digits.
|
|
66
|
+
def self.under_service_url?(url, service_url)
|
|
67
|
+
return false if service_url.nil? || service_url.empty?
|
|
68
|
+
|
|
69
|
+
target = URI.parse(url)
|
|
70
|
+
base = URI.parse(service_url)
|
|
71
|
+
return false unless base.scheme&.downcase == "https"
|
|
72
|
+
return false unless [target.scheme&.downcase, target.host&.downcase, target.port] ==
|
|
73
|
+
[base.scheme.downcase, base.host&.downcase, base.port]
|
|
74
|
+
|
|
75
|
+
# Exactly one trailing slash, so /amer cannot match /americas.
|
|
76
|
+
base_path = normalize_percent_escapes("#{resolve_dot_segments(base.path).sub(%r{/+\z}, "")}/")
|
|
77
|
+
normalize_percent_escapes(resolve_dot_segments(target.path)).start_with?(base_path)
|
|
78
|
+
rescue URI::Error
|
|
79
|
+
false
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def self.resolve_dot_segments(path)
|
|
83
|
+
resolved = []
|
|
84
|
+
path.to_s.sub(%r{\A/+}, "").split("/", -1).each do |segment|
|
|
85
|
+
folded = segment.downcase
|
|
86
|
+
next if SINGLE_DOT_SEGMENTS.include?(folded)
|
|
87
|
+
|
|
88
|
+
if DOUBLE_DOT_SEGMENTS.include?(folded)
|
|
89
|
+
resolved.pop
|
|
90
|
+
next
|
|
91
|
+
end
|
|
92
|
+
resolved << segment
|
|
93
|
+
end
|
|
94
|
+
"/#{resolved.join("/")}"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def self.normalize_percent_escapes(path)
|
|
98
|
+
path.gsub(PERCENT_ESCAPE, &:upcase)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Faraday decodes every request URL's query and re-encodes it with the
|
|
102
|
+
# keys sorted. Pre-signed download URLs (SharePoint tempauth) are signed
|
|
103
|
+
# over the query as issued, so a reordered query is refused with 401.
|
|
104
|
+
# This encoder carries the query through untouched, the way the other
|
|
105
|
+
# SDKs' HTTP clients send these URLs. The downloader passes no params.
|
|
106
|
+
module VerbatimQueryEncoder
|
|
107
|
+
KEY = "verbatim_query"
|
|
108
|
+
|
|
109
|
+
def self.decode(query) = (query.nil? || query.empty?) ? nil : { KEY => query }
|
|
110
|
+
def self.encode(params) = params[KEY]
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def initialize(connection: nil, logger: nil)
|
|
114
|
+
@connection = connection || Faraday.new
|
|
115
|
+
@connection.options.params_encoder = VerbatimQueryEncoder
|
|
116
|
+
@logger = logger
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# Streams target's bytes to the block and returns an OpenedFile.
|
|
120
|
+
# Personal files take either route; elsewhere only the Graph route, and
|
|
121
|
+
# only where graph_route_open? allows. A download URL outside personal
|
|
122
|
+
# keeps the scope error: Graph is never substituted for a URL the
|
|
123
|
+
# platform supplied.
|
|
124
|
+
def fetch(target, prior_fetch_succeeded: false, credential: nil, bot_api_credential: nil, &on_chunk)
|
|
125
|
+
# Inline images live on the Bot API, so neither file route nor its
|
|
126
|
+
# scope restriction applies.
|
|
127
|
+
if target.attachment_style == "inlineImage"
|
|
128
|
+
return fetch_inline_image(target, credential: bot_api_credential, &on_chunk)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
if target.scope == "personal"
|
|
132
|
+
return fetch_personal(target, prior_fetch_succeeded:, credential:, &on_chunk)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
if target.download_url.nil? && target.content_url && self.class.graph_route_open?(target.scope, credential&.actor)
|
|
136
|
+
return fetch_graph(target, target.content_url, credential:, &on_chunk)
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
raise FileScopeNotSupportedError, target.scope
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
private
|
|
143
|
+
|
|
144
|
+
def fetch_personal(target, prior_fetch_succeeded:, credential:, &on_chunk)
|
|
145
|
+
url = target.download_url
|
|
146
|
+
# The agentic user case: a browsable content URL arrives instead of a
|
|
147
|
+
# download URL, so Graph is the only route to the bytes.
|
|
148
|
+
unless url
|
|
149
|
+
raise Error, "cannot download file: no download URL is available" unless target.content_url
|
|
150
|
+
|
|
151
|
+
return fetch_graph(target, target.content_url, credential:, &on_chunk)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
if credential&.actor == "agentic_user"
|
|
155
|
+
@logger&.warn(
|
|
156
|
+
"an agentic turn received a file carrying a pre-authorized download URL, which the platform did not " \
|
|
157
|
+
"previously send to agents. The SDK is using that URL, so these bytes are not attributed to the " \
|
|
158
|
+
"agentic user."
|
|
159
|
+
)
|
|
160
|
+
end
|
|
161
|
+
raise Error, "cannot download file: download URL must use https" unless url.downcase.start_with?("https://")
|
|
162
|
+
|
|
163
|
+
# Plain GET with no bearer token: the URL embeds its own credential.
|
|
164
|
+
response = get_following_https_redirects(url, {}, &on_chunk)
|
|
165
|
+
if [401, 403].include?(response.status)
|
|
166
|
+
# Terminal: the URL's own credential lapsed, and the SDK does not fall
|
|
167
|
+
# back to another identity. The file has to be sent again.
|
|
168
|
+
raise FileUrlExpiredError, (prior_fetch_succeeded ? "reread" : "first_fetch")
|
|
169
|
+
end
|
|
170
|
+
unless success?(response.status)
|
|
171
|
+
raise Error, "failed to download file: #{response.status} #{response.reason_phrase}".strip
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
opened(url, response, target)
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# Reads the bytes through Graph /shares as the credential's identity.
|
|
178
|
+
# Unlike the pre-authorized route this is an ordinary authenticated Graph
|
|
179
|
+
# call, and a missing consent is detected before the request.
|
|
180
|
+
def fetch_graph(target, sharing_url, credential:, &on_chunk)
|
|
181
|
+
actor = credential&.actor
|
|
182
|
+
token, failure = resolve_graph_token(credential)
|
|
183
|
+
raise FileCredentialError.new(actor, failure) if token.to_s.empty? || carries_no_graph_permissions?(token)
|
|
184
|
+
|
|
185
|
+
url = GraphShare.drive_item_content_url(sharing_url, credential.base_url_root || "https://graph.microsoft.com")
|
|
186
|
+
@logger&.debug("files: resolving bytes through Graph /shares as '#{actor}'")
|
|
187
|
+
|
|
188
|
+
response = get_following_https_redirects(url, { "Authorization" => "Bearer #{token}" }, &on_chunk)
|
|
189
|
+
if [401, 403].include?(response.status)
|
|
190
|
+
raise FileAccessError.new(response.status, actor, service_error(response.error_body))
|
|
191
|
+
end
|
|
192
|
+
unless success?(response.status)
|
|
193
|
+
details = service_error(response.error_body)
|
|
194
|
+
message = "failed to download file through Graph as '#{actor || "app"}': " \
|
|
195
|
+
"#{response.status} #{response.reason_phrase}".strip
|
|
196
|
+
raise Error, details ? "#{message} (#{details})" : message
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
opened(url, response, target)
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
# Reads an inline image from the Bot API with the turn's Bot API token,
|
|
203
|
+
# sent only to a URL under the activity's service URL.
|
|
204
|
+
def fetch_inline_image(target, credential:, &on_chunk)
|
|
205
|
+
url = target.content_url
|
|
206
|
+
raise Error, "cannot download inline image: no content URL is available" unless url
|
|
207
|
+
raise Error, "cannot download inline image: content URL must use https" unless url.downcase.start_with?("https://")
|
|
208
|
+
raise Error, "cannot download inline image: no Bot API token is available" unless credential
|
|
209
|
+
unless self.class.under_service_url?(url, credential.service_url)
|
|
210
|
+
raise Error, "cannot download inline image: content URL is not under the activity's service URL"
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
actor = credential.actor
|
|
214
|
+
token = credential.token ? credential.token.call.to_s.strip : ""
|
|
215
|
+
raise Error, "cannot download inline image: no Bot API token is available" if token.empty?
|
|
216
|
+
|
|
217
|
+
@logger&.debug("files: reading inline image bytes from the Bot API as '#{actor}'")
|
|
218
|
+
response = get_following_https_redirects(url, { "Authorization" => "Bearer #{token}" }, &on_chunk)
|
|
219
|
+
if response.status == 415
|
|
220
|
+
raise InlineImageTransformationError.new(
|
|
221
|
+
response.status, actor, service_error(response.error_body), service_error_code(response.error_body)
|
|
222
|
+
)
|
|
223
|
+
end
|
|
224
|
+
if [401, 403].include?(response.status)
|
|
225
|
+
raise InlineImageAccessError.new(response.status, actor, service_error(response.error_body))
|
|
226
|
+
end
|
|
227
|
+
unless success?(response.status)
|
|
228
|
+
details = service_error(response.error_body)
|
|
229
|
+
message = "failed to download inline image as '#{actor}': #{response.status} #{response.reason_phrase}".strip
|
|
230
|
+
raise Error, details ? "#{message} (#{details})" : message
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
opened(url, response, target)
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
def service_error_code(raw)
|
|
237
|
+
return nil if raw.nil? || raw.empty?
|
|
238
|
+
|
|
239
|
+
envelope = JSON.parse(raw.dup.force_encoding(Encoding::UTF_8).scrub)
|
|
240
|
+
code = envelope.dig("error", "code") if envelope.is_a?(Hash) && envelope["error"].is_a?(Hash)
|
|
241
|
+
code.is_a?(String) && !code.strip.empty? ? code.strip : nil
|
|
242
|
+
rescue JSON::ParserError
|
|
243
|
+
nil
|
|
244
|
+
end
|
|
245
|
+
|
|
246
|
+
# Resolves the token without raising: an acquisition failure degrades to
|
|
247
|
+
# "no token" with its reason, so it reports as a credential problem.
|
|
248
|
+
def resolve_graph_token(credential)
|
|
249
|
+
return [nil, nil] unless credential&.token
|
|
250
|
+
|
|
251
|
+
[credential.token.call, nil]
|
|
252
|
+
rescue StandardError => error
|
|
253
|
+
@logger&.debug("files: could not acquire a Graph token: #{error.message}")
|
|
254
|
+
[nil, error.message]
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
# A token that decodes but carries no Files.* or Sites.* permission
|
|
258
|
+
# cannot reach a drive item; Graph would answer with an ambiguous 401 or
|
|
259
|
+
# 403. Fails open on an undecodable token (the call proceeds).
|
|
260
|
+
def carries_no_graph_permissions?(token)
|
|
261
|
+
permissions = token_permissions(token)
|
|
262
|
+
return false if permissions.nil?
|
|
263
|
+
|
|
264
|
+
permissions.none? do |permission|
|
|
265
|
+
GRAPH_FILE_PERMISSION_PREFIXES.any? { |prefix| permission.downcase.start_with?(prefix) }
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
# App-only tokens list application permissions in roles; delegated and
|
|
270
|
+
# agentic-user tokens list scopes in scp. nil means undecodable.
|
|
271
|
+
def token_permissions(token)
|
|
272
|
+
payload = token.split(".")[1]
|
|
273
|
+
return nil unless payload
|
|
274
|
+
|
|
275
|
+
claims = JSON.parse(Base64.urlsafe_decode64(payload + ("=" * (-payload.length % 4))))
|
|
276
|
+
return nil unless claims.is_a?(Hash)
|
|
277
|
+
|
|
278
|
+
roles = claims["roles"].is_a?(Array) ? claims["roles"].grep(String) : []
|
|
279
|
+
scopes = claims["scp"].is_a?(String) ? claims["scp"].split : []
|
|
280
|
+
roles + scopes
|
|
281
|
+
rescue ArgumentError, JSON::ParserError, EncodingError
|
|
282
|
+
nil
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
# The readable part of a Graph error envelope ({"error": {"code",
|
|
286
|
+
# "message"}}), falling back to the raw text; a 401 from the edge can be
|
|
287
|
+
# HTML.
|
|
288
|
+
def service_error(raw)
|
|
289
|
+
return nil if raw.nil? || raw.empty?
|
|
290
|
+
|
|
291
|
+
text = raw.dup.force_encoding(Encoding::UTF_8).scrub
|
|
292
|
+
begin
|
|
293
|
+
envelope = JSON.parse(text)
|
|
294
|
+
error = envelope["error"] if envelope.is_a?(Hash)
|
|
295
|
+
if error.is_a?(Hash)
|
|
296
|
+
parts = [error["code"], error["message"]].select { |part| part && !part.to_s.empty? }.map(&:to_s)
|
|
297
|
+
return truncate(parts.join(": ")) unless parts.empty?
|
|
298
|
+
end
|
|
299
|
+
rescue JSON::ParserError
|
|
300
|
+
nil
|
|
301
|
+
end
|
|
302
|
+
truncate(text)
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def truncate(text)
|
|
306
|
+
collapsed = text.split.join(" ")
|
|
307
|
+
return nil if collapsed.empty?
|
|
308
|
+
|
|
309
|
+
collapsed.length > ERROR_BODY_LIMIT ? "#{collapsed[0, ERROR_BODY_LIMIT]}..." : collapsed
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
def opened(url, response, target)
|
|
313
|
+
OpenedFile.new(
|
|
314
|
+
source_url: url,
|
|
315
|
+
content_type: response.headers["content-type"] || target.content_type || OCTET_STREAM
|
|
316
|
+
)
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
# Storage answers with a redirect to the host holding the bytes, so
|
|
320
|
+
# redirects are followed, one hop at a time so a downgrade to plaintext
|
|
321
|
+
# can be refused. Authorization is dropped when a hop leaves the origin.
|
|
322
|
+
def get_following_https_redirects(url, headers, &on_chunk)
|
|
323
|
+
current = url
|
|
324
|
+
headers = headers.dup
|
|
325
|
+
response = perform_get(current, headers, &on_chunk)
|
|
326
|
+
MAX_REDIRECTS.times do
|
|
327
|
+
location = response.headers["location"]
|
|
328
|
+
return response unless REDIRECT_STATUSES.include?(response.status) && location
|
|
329
|
+
|
|
330
|
+
next_url = URI.join(current, location).to_s
|
|
331
|
+
next_uri = URI.parse(next_url)
|
|
332
|
+
unless next_uri.scheme&.downcase == "https"
|
|
333
|
+
raise Error, "cannot download file: a redirect destination must use https, got " \
|
|
334
|
+
"'#{next_uri.scheme}://#{next_uri.host}'. The file's bytes would cross that hop in the clear."
|
|
335
|
+
end
|
|
336
|
+
|
|
337
|
+
headers.delete("Authorization") unless same_origin?(current, next_uri)
|
|
338
|
+
current = next_url
|
|
339
|
+
response = perform_get(current, headers, &on_chunk)
|
|
340
|
+
end
|
|
341
|
+
raise Error, "cannot download file: too many redirects" if REDIRECT_STATUSES.include?(response.status)
|
|
342
|
+
|
|
343
|
+
response
|
|
344
|
+
rescue URI::Error => error
|
|
345
|
+
raise Error, "cannot download file: invalid redirect location (#{error.message})"
|
|
346
|
+
end
|
|
347
|
+
|
|
348
|
+
# One GET. Success bodies stream to the block as they arrive; any other
|
|
349
|
+
# body is kept, capped, for the error message. Adapters that do not
|
|
350
|
+
# stream (such as Faraday's test adapter) hand the whole body over once.
|
|
351
|
+
def perform_get(url, headers, &on_chunk)
|
|
352
|
+
status = nil
|
|
353
|
+
streamed = false
|
|
354
|
+
error_body = +"".b
|
|
355
|
+
|
|
356
|
+
response = @connection.get(url) do |request|
|
|
357
|
+
request.headers.update(headers)
|
|
358
|
+
request.options.on_data = proc do |chunk, _received, env|
|
|
359
|
+
status ||= env.status
|
|
360
|
+
next if chunk.empty?
|
|
361
|
+
|
|
362
|
+
if success?(status)
|
|
363
|
+
streamed = true
|
|
364
|
+
on_chunk&.call(chunk)
|
|
365
|
+
else
|
|
366
|
+
append_capped(error_body, chunk)
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
end
|
|
370
|
+
|
|
371
|
+
body = response.body
|
|
372
|
+
if body.is_a?(String) && !body.empty?
|
|
373
|
+
if success?(response.status)
|
|
374
|
+
on_chunk&.call(body) unless streamed
|
|
375
|
+
elsif error_body.empty?
|
|
376
|
+
append_capped(error_body, body)
|
|
377
|
+
end
|
|
378
|
+
end
|
|
379
|
+
|
|
380
|
+
Response.new(
|
|
381
|
+
status: response.status,
|
|
382
|
+
headers: response.headers,
|
|
383
|
+
reason_phrase: response.reason_phrase,
|
|
384
|
+
error_body:
|
|
385
|
+
)
|
|
386
|
+
rescue Faraday::Error => error
|
|
387
|
+
raise Error, "failed to download file: #{error.message}"
|
|
388
|
+
end
|
|
389
|
+
|
|
390
|
+
def append_capped(buffer, chunk)
|
|
391
|
+
remaining = ERROR_BODY_LIMIT - buffer.bytesize
|
|
392
|
+
buffer << chunk.byteslice(0, remaining).b if remaining.positive?
|
|
393
|
+
end
|
|
394
|
+
|
|
395
|
+
def success?(status)
|
|
396
|
+
status.is_a?(Integer) && status.between?(200, 299)
|
|
397
|
+
end
|
|
398
|
+
|
|
399
|
+
def same_origin?(url, other)
|
|
400
|
+
uri = URI.parse(url)
|
|
401
|
+
[uri.scheme&.downcase, uri.host&.downcase, uri.port] == [other.scheme&.downcase, other.host&.downcase, other.port]
|
|
402
|
+
end
|
|
403
|
+
end
|
|
404
|
+
end
|
|
405
|
+
end
|