20640: Add computed permissions API.
[arvados.git] / services / api / app / models / api_client.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class ApiClient < ArvadosModel
6   include HasUuid
7   include KindAndEtag
8   include CommonApiTemplate
9   has_many :api_client_authorizations
10
11   api_accessible :user, extend: :common do |t|
12     t.add :name
13     t.add :url_prefix
14     t.add :is_trusted
15   end
16
17   def is_trusted
18     (from_trusted_url && Rails.configuration.Login.IssueTrustedTokens) || super
19   end
20
21   protected
22
23   def from_trusted_url
24     norm_url_prefix = norm(self.url_prefix)
25
26     [Rails.configuration.Services.Workbench1.ExternalURL,
27      Rails.configuration.Services.Workbench2.ExternalURL,
28      "https://controller.api.client.invalid"].each do |url|
29       if norm_url_prefix == norm(url)
30         return true
31       end
32     end
33
34     Rails.configuration.Login.TrustedClients.keys.each do |url|
35       trusted = norm(url)
36       if norm_url_prefix == trusted
37         return true
38       end
39       if trusted.host.to_s.starts_with?("*.") &&
40          norm_url_prefix.to_s.starts_with?(trusted.scheme + "://") &&
41          norm_url_prefix.to_s.ends_with?(trusted.to_s[trusted.scheme.length + 4...])
42         return true
43       end
44     end
45
46     false
47   end
48
49   def norm url
50     # normalize URL for comparison
51     url = URI(url.to_s)
52     if url.scheme == "https" && url.port == ""
53       url.port = "443"
54     elsif url.scheme == "http" && url.port == ""
55       url.port = "80"
56     end
57     url.path = "/"
58     url.query = nil
59     url.fragment = nil
60     url
61   end
62 end