microsoft_base.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # Copyright (C) 2012-2025 Zammad Foundation, https://zammad-foundation.org/
  2. class ExternalCredential::MicrosoftBase < ExternalCredential::Base::ChannelXoauth2
  3. def self.provider_name
  4. name.demodulize.underscore
  5. end
  6. def self.error_missing_app_configuration
  7. raise NotImplementedError
  8. end
  9. def self.authorize_scope
  10. raise NotImplementedError
  11. end
  12. def self.channel_options_inbound(user_data)
  13. raise NotImplementedError
  14. end
  15. def self.channel_options_outbound(user_data)
  16. raise NotImplementedError
  17. end
  18. def self.channel_migration_possible?
  19. false
  20. end
  21. def self.app_verify(params)
  22. request_account_to_link(params, false)
  23. params
  24. end
  25. def self.request_account_to_link(credentials = {}, app_required = true)
  26. external_credential = ExternalCredential.find_by(name: provider_name)
  27. raise Exceptions::UnprocessableEntity, error_missing_app_configuration if !external_credential && app_required
  28. if external_credential
  29. if credentials[:client_id].blank?
  30. credentials[:client_id] = external_credential.credentials['client_id']
  31. end
  32. if credentials[:client_secret].blank?
  33. credentials[:client_secret] = external_credential.credentials['client_secret']
  34. end
  35. # client_tenant may be empty. Set only if key is nonexistant at all
  36. if !credentials.key? :client_tenant
  37. credentials[:client_tenant] = external_credential.credentials['client_tenant']
  38. end
  39. end
  40. raise Exceptions::UnprocessableEntity, __("The required parameter 'client_id' is missing.") if credentials[:client_id].blank?
  41. raise Exceptions::UnprocessableEntity, __("The required parameter 'client_secret' is missing.") if credentials[:client_secret].blank?
  42. authorize_url = generate_authorize_url(credentials)
  43. {
  44. authorize_url: authorize_url,
  45. }
  46. end
  47. def self.link_account(_request_token, params)
  48. # return to admin interface if admin Consent is in process and user clicks on "Back to app"
  49. return "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#channels/#{provider_name}/error/AADSTS65004" if params[:error_description].present? && params[:error_description].include?('AADSTS65004')
  50. external_credential = ExternalCredential.find_by(name: provider_name)
  51. raise Exceptions::UnprocessableEntity, error_missing_app_configuration if !external_credential
  52. raise Exceptions::UnprocessableEntity, __("The required parameter 'code' is missing.") if !params[:code]
  53. response = authorize_tokens(external_credential.credentials, params[:code])
  54. %w[refresh_token access_token expires_in scope token_type id_token].each do |key|
  55. raise Exceptions::UnprocessableEntity, "No #{key} for authorization request found!" if response[key.to_sym].blank?
  56. end
  57. user_data = user_info(response[:id_token])
  58. raise Exceptions::UnprocessableEntity, __("The user's 'preferred_username' could not be extracted from 'id_token'.") if user_data[:preferred_username].blank?
  59. account_data = {}
  60. # Restore shared mailbox information from session and clean it up.
  61. if params[:shared_mailbox].present?
  62. account_data[:shared_mailbox] = params[:shared_mailbox]
  63. end
  64. channel_options = {
  65. inbound: channel_options_inbound(user_data, account_data),
  66. outbound: channel_options_outbound(user_data),
  67. auth: response.merge(
  68. provider: provider_name,
  69. type: 'XOAUTH2',
  70. client_id: external_credential.credentials[:client_id],
  71. client_secret: external_credential.credentials[:client_secret],
  72. client_tenant: external_credential.credentials[:client_tenant],
  73. ),
  74. }
  75. if params[:channel_id]
  76. existing_channel = Channel.where(area: channel_area).find(params[:channel_id])
  77. # Check if current user of the channel is matching the user from the token.
  78. # Allow mismatch in case of a shared mailbox, since multiple users may be able access the same mailbox.
  79. # In this case, inbound probe should verify if everything still works as expected.
  80. token_user = user_data[:preferred_username]&.downcase
  81. inbound_user = channel_user(existing_channel, :inbound)&.downcase
  82. outbound_user = channel_user(existing_channel, :outbound)&.downcase
  83. shared_mailbox = channel_shared_mailbox(existing_channel)
  84. if ((inbound_user.present? && inbound_user != token_user) || (outbound_user.present? && outbound_user != token_user)) && shared_mailbox.blank?
  85. return "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#channels/#{provider_name}/error/user_mismatch/channel/#{existing_channel.id}"
  86. end
  87. channel_options[:inbound][:options][:shared_mailbox] = shared_mailbox if shared_mailbox.present?
  88. channel_options[:inbound][:options][:folder] = existing_channel.options[:inbound][:options][:folder]
  89. channel_options[:inbound][:options][:keep_on_server] = existing_channel.options[:inbound][:options][:keep_on_server]
  90. existing_channel.update!(
  91. options: channel_options,
  92. )
  93. existing_channel.refresh_xoauth2!
  94. return existing_channel
  95. end
  96. if channel_migration_possible?
  97. migration_channel = find_migration_channel(user_data)
  98. return execute_channel_migration(migrate_channel, channel_options) if migration_channel
  99. end
  100. email_address = {
  101. name: "#{Setting.get('product_name')} Support",
  102. email: account_data[:shared_mailbox] || user_data[:preferred_username],
  103. }
  104. existing_email_address = EmailAddress.where(email: email_address[:email])
  105. # Check if a bound address with the same email already exists.
  106. if existing_email_address.where.not(channel: nil).exists?
  107. return "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#channels/#{provider_name}/error/duplicate_email_address/param/#{CGI.escapeURIComponent(email_address[:email])}"
  108. end
  109. # create channel
  110. channel = Channel.create!(
  111. area: channel_area,
  112. group_id: Group.first.id,
  113. options: channel_options,
  114. active: false,
  115. created_by_id: 1,
  116. updated_by_id: 1,
  117. )
  118. # Assign an email address to the channel by either creating a new or repurposing an existing one.
  119. if existing_email_address.exists?
  120. existing_email_address.update!(
  121. channel_id: channel.id,
  122. name: email_address[:name],
  123. email: email_address[:email],
  124. active: true,
  125. created_by_id: 1,
  126. updated_by_id: 1,
  127. )
  128. else
  129. EmailAddress.create_or_update(
  130. channel_id: channel.id,
  131. name: email_address[:name],
  132. email: email_address[:email],
  133. active: true,
  134. created_by_id: 1,
  135. updated_by_id: 1,
  136. )
  137. end
  138. channel
  139. end
  140. def self.generate_authorize_url(credentials, scope = authorize_scope)
  141. # TODO: should we add recoomended "state" parameter here for security reasons?
  142. params = {
  143. 'client_id' => credentials[:client_id],
  144. 'redirect_uri' => ExternalCredential.callback_url(provider_name),
  145. 'scope' => scope,
  146. 'response_type' => 'code',
  147. 'access_type' => 'offline',
  148. 'prompt' => credentials[:prompt] || 'login',
  149. }
  150. tenant = credentials[:client_tenant].presence || 'common'
  151. uri = URI::HTTPS.build(
  152. host: 'login.microsoftonline.com',
  153. path: "/#{tenant}/oauth2/v2.0/authorize",
  154. query: params.to_query
  155. )
  156. uri.to_s
  157. end
  158. def self.authorize_tokens(credentials, authorization_code)
  159. uri = authorize_tokens_uri(credentials[:client_tenant])
  160. params = authorize_tokens_params(credentials, authorization_code)
  161. response = UserAgent.post(uri.to_s, params)
  162. if response.code != 200 && response.body.blank?
  163. Rails.logger.error "Request failed! (code: #{response.code})"
  164. raise "Request failed! (code: #{response.code})"
  165. end
  166. result = JSON.parse(response.body)
  167. if result['error'] && response.code != 200
  168. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  169. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  170. end
  171. result[:created_at] = Time.zone.now
  172. result.symbolize_keys
  173. end
  174. def self.authorize_tokens_params(credentials, authorization_code)
  175. {
  176. client_secret: credentials[:client_secret],
  177. code: authorization_code,
  178. grant_type: 'authorization_code',
  179. client_id: credentials[:client_id],
  180. redirect_uri: ExternalCredential.callback_url(provider_name),
  181. }
  182. end
  183. def self.authorize_tokens_uri(tenant)
  184. URI::HTTPS.build(
  185. host: 'login.microsoftonline.com',
  186. path: "/#{tenant.presence || 'common'}/oauth2/v2.0/token",
  187. )
  188. end
  189. def self.refresh_token(token)
  190. return token if token[:created_at] >= 50.minutes.ago
  191. params = refresh_token_params(token)
  192. uri = refresh_token_uri(token)
  193. response = UserAgent.post(uri.to_s, params)
  194. if response.code != 200 && response.body.blank?
  195. Rails.logger.error "Request failed! (code: #{response.code})"
  196. raise "Request failed! (code: #{response.code})"
  197. end
  198. result = JSON.parse(response.body)
  199. if result['error'] && response.code != 200
  200. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  201. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  202. end
  203. token.merge(result.symbolize_keys).merge(
  204. created_at: Time.zone.now,
  205. )
  206. end
  207. def self.refresh_token_params(credentials)
  208. {
  209. client_id: credentials[:client_id],
  210. client_secret: credentials[:client_secret],
  211. refresh_token: credentials[:refresh_token],
  212. grant_type: 'refresh_token',
  213. }
  214. end
  215. def self.refresh_token_uri(credentials)
  216. tenant = credentials[:client_tenant].presence || 'common'
  217. URI::HTTPS.build(
  218. host: 'login.microsoftonline.com',
  219. path: "/#{tenant}/oauth2/v2.0/token",
  220. )
  221. end
  222. def self.channel_user(channel, key)
  223. channel.options.dig(key.to_sym, :options, :user)
  224. end
  225. def self.channel_shared_mailbox(channel)
  226. channel.options.dig(:inbound, :options, :shared_mailbox)
  227. end
  228. def self.user_info(id_token)
  229. split = id_token.split('.')[1]
  230. return if split.blank?
  231. JSON.parse(Base64.decode64(split)).symbolize_keys
  232. end
  233. end