summaryrefslogtreecommitdiff
path: root/bin/ui
blob: 4abe43f17ba41fd48f2c34c70535c7ccbdf0b835 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env ruby

require "bundler/inline"

gemfile do
  source "https://rubygems.org"

  gem "base64", "~> 0.1"
  gem "erb", "~> 4.0"
  gem "net-hippie", "~> 1.0"
  gem "rack", "~> 3.0"
  gem "rack-session", "~> 2.0"
  gem "rackup", "~> 2.0"
  gem "saml-kit", "~> 1.0", git: "github.com:xlgmokha/saml-kit", branch: "main"
  gem "webrick", "~> 1.0"
end

$scheme = ENV.fetch("SCHEME", "http")
$port = ENV.fetch("PORT", 8283).to_i
$host = ENV.fetch("HOST", "localhost:#{$port}")
$idp_host = ENV.fetch("IDP_HOST", "localhost:8282")

Net::Hippie.logger = Logger.new($stdout, level: :debug)

class OnDemandRegistry < Saml::Kit::DefaultRegistry
  def metadata_for(entity_id)
    found = super(entity_id)
    return found if found

    register_url(entity_id, verify_ssl: false)
    super(entity_id)
  end
end

Saml::Kit.configure do |x|
  x.entity_id = "#{$scheme}://#{$host}/saml/metadata.xml"
  x.registry = OnDemandRegistry.new
  x.logger = Logger.new("/dev/stderr")
end

module OAuth
  class Client
    attr_reader :client_id, :client_secret, :http, :authz_host

    def initialize(authz_host, client_id, client_secret)
      @authz_host = authz_host
      @client_id = client_id
      @client_secret = client_secret
      @http = Net::Hippie::Client.new(headers: ::Net::Hippie::Client::DEFAULT_HEADERS.merge({
        'Authorization' => Net::Hippie.basic_auth(client_id, client_secret),
      }))
    end

    def [](key)
      server_metadata.fetch(key)
    end

    def authorize_uri(state: SecureRandom.uuid, response_type: "code", response_mode: "query", scope: "openid")
      [
        self[:authorization_endpoint],
        to_query(
          client_id: client_id,
          state: state,
          redirect_uri: redirect_uri,
          response_mode: response_mode,
          response_type: response_type,
          scope: scope,
        )
      ].join("?")
    end

    def exchange(grant_type, params = {})
      with_http do |client|
        client.post(self[:token_endpoint], body: body_for(grant_type, params))
      end
    end

    private

    def body_for(grant_type, params)
      case grant_type
      when "authorization_code"
        {
          grant_type: grant_type,
          code: params.fetch(:code),
          code_verifier: params.fetch(:code_verifier, "not_implemented"),
        }
      when "urn:ietf:params:oauth:grant-type:saml2-bearer"
        {
          grant_type: grant_type,
          assertion: params.fetch(:assertion),
        }
      else
        raise NotImplementedError.new(grant_type)
      end
    end

    def to_query(params = {})
      params.map do |(key, value)|
        [key, value].join("=")
      end.join("&")
    end

    def redirect_uri
      "#{$scheme}://#{$host}/oauth/callback"
    end

    def with_http
      http.with_retry do |client|
        yield client
      end
    end

    def server_metadata
      @server_metadata ||=
        with_http do |client|
          response = client.get("http://#{authz_host}/.well-known/oauth-authorization-server")
          JSON.parse(response.body, symbolize_names: true)
        end
    end
  end
end

module HTTPHelpers
  def current_user?(request)
    request.session[:access_token]
  end

  def not_found
    [404, { 'X-Backend-Server' => 'UI' }, []]
  end

  def redirect_to(location)
    if location.start_with?("http")
      [302, { 'Location' => location }, []]
    else
      [302, { 'Location' => "#{$scheme}://#{$host}#{location}" }, []]
    end
  end

  def with_layout(bind)
    template = <<~ERB
      <!DOCTYPE html>
      <html>
        <head>
          <title></title>
        </head>
        <body style="background-color: pink;">
          #{yield}
        </body>
      </html>
    ERB
    ERB.new(template, trim_mode: '-').result(bind)
  end
end

class UI
  include ::HTTPHelpers

  attr_reader :oauth_client

  def initialize(oauth_client)
    @oauth_client = oauth_client
  end

  def call(env)
    request = Rack::Request.new(env)
    case request.request_method
    when Rack::GET
      case request.path
      when "/index.html"
        html = with_layout(binding) do
          <<~ERB
            <%- if current_user?(request) -%>
              <a href="/groups.html">Groups</a>
              <h1>Access Token</h1>
              <pre><%= request.session[:access_token] %></pre>
              <h1>ID Token</h1>
              <pre><%= request.session[:id_token] %></pre>

              <form action="/logout" method="post">
                <input type="submit" value="Logout" />
              </form>
            <%- else -%>
              <a href="/saml/new">SAML Login</a>
              <a href="/oidc/new">OIDC Login</a>
            <%- end -%>
          ERB
        end
        return [200, { 'Content-Type' => "text/html" }, [html]]
      when "/groups.html"
        if current_user?(request)
          return get_groups(request)
        else
          return redirect_to("/oidc/new")
        end
      when /\A\/groups\/\d+\/projects.html\z/
        if current_user?(request)
          return get_projects(request)
        else
          return redirect_to("/oidc/new")
        end
      when "/oauth/callback"
        return oauth_callback(Rack::Request.new(env))
      when "/oidc/new"
        return redirect_to(oauth_client.authorize_uri)
      when "/saml/metadata.xml"
        return metadata
      when "/saml/new"
        return saml_post_to_idp(Rack::Request.new(env))
      else
        return redirect_to("/index.html")
      end
    when Rack::POST
      case request.path
      when "/logout"
        request.session.delete(:access_token)
        request.session.delete(:id_token)
        request.session.delete(:refresh_token)
        return redirect_to("/")
      when "/saml/assertions"
        return saml_assertions(Rack::Request.new(env))
      else
        return not_found
      end
    end
    not_found
  end

  private

  def metadata
    xml = Saml::Kit::Metadata.build_xml do |builder|
      builder.embed_signature = false
      builder.contact_email = 'ui@example.com'
      builder.organization_name = "Acme, Inc"
      builder.organization_url = "https://example.com"
      builder.build_service_provider do |x|
        x.name_id_formats = [Saml::Kit::Namespaces::PERSISTENT]
        x.add_assertion_consumer_service("#{$scheme}://#{$host}/saml/assertions", binding: :http_post)
      end
    end

    [200, { 'Content-Type' => "application/samlmetadata+xml" }, [xml]]
  end

  def oauth_callback(request)
    response = oauth_client.exchange("authorization_code", code: request.params['code'])
    if response.code == "200"
      tokens = JSON.parse(response.body, symbolize_names: true)
      request.session[:access_token] = tokens[:access_token]
      request.session[:id_token] = tokens[:id_token]
      request.session[:refresh_token] = tokens[:access_token]

      template = <<~ERB
        <!DOCTYPE html>
        <html>
          <head><title></title></head>
          <body style="background-color: pink;">
            <pre style="display: none;"><%= response.body %></pre>
            <pre><%= JSON.pretty_generate(request.session[:access_token]) %></pre>
            <a href="/index.html">Home</a>
            <a href="/groups.html">Groups</a>
          </body>
        </html>
      ERB
      html = ERB.new(template, trim_mode: '-').result(binding)
      [200, { 'Content-Type' => "text/html" }, [html]]
    else
      [response.code, response.header, [response.body]]
    end
  end

  def get_groups(request)
    http = Net::Hippie::Client.new(headers: ::Net::Hippie::Client::DEFAULT_HEADERS.merge({
      'Authorization' => Net::Hippie.bearer_auth(request.session[:access_token])
    }))

    response = http.get("http://api.example.com:8080/groups.json")
    if response.code == "200"
      groups = JSON.parse(response.body, symbolize_names: true)
      html = with_layout(binding) do
        <<~ERB
            <a href="/index.html">Home</a>
            <a href="/groups.html">Groups</a>
            <form action="/logout" method="post">
              <input type="submit" value="Logout" />
            </form>
            <table>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Name</th>
                  <th>Organization ID</th>
                  <th>Parent ID</th>
                  <th>&nbsp;</th>
                </tr>
              </thead>
              <tbody>
              <%- groups.each do |group| -%>
                <tr>
                  <td><%= group[:id] %></td>
                  <td><%= group[:name] %></td>
                  <td><%= group[:organization_id] %></td>
                  <td><%= group[:parent_id] %></td>
                  <td><a href="/groups/<%= group[:id] %>/projects.html">Projects</a></td>
                </tr>
              <%- end -%>
              </tbody>
            </table>
        ERB
      end
      [200, { 'Content-Type' => "text/html" }, [html]]
    else
      [response.code, response.header, [response.body]]
    end
  end

  def get_projects(request)
    http = Net::Hippie::Client.new(headers: ::Net::Hippie::Client::DEFAULT_HEADERS.merge({
      'Authorization' => Net::Hippie.bearer_auth(request.session[:access_token])
    }))

    response = http.get("http://api.example.com:8080/projects.json")
    if response.code == "200"
      projects = JSON.parse(response.body, symbolize_names: true)

      html = with_layout(binding) do
        <<~ERB
          <a href="/index.html">Home</a>
          <a href="/groups.html">Groups</a>
          <form action="/logout" method="post">
            <input type="submit" value="Logout" />
          </form>
          <table>
            <thead>
              <tr>
                <th>Name</th>
                <th>Group ID</th>
              </tr>
            </thead>
            <tbody>
            <%- projects.each do |project| -%>
              <tr>
                <td><%= project[:name] %></td>
                <td><%= project[:group_id] %></td>
              </tr>
            <%- end -%>
            </tbody>
          </table>
        ERB
      end
      [200, { 'Content-Type' => "text/html" }, [html]]
    else
      [response.code, response.header, [response.body]]
    end
  end

  def saml_post_to_idp(request)
    idp = Saml::Kit.registry.metadata_for("http://#{$idp_host}/saml/metadata.xml")
    relay_state = Base64.strict_encode64(JSON.generate(redirect_to: '/dashboard'))

    @saml_builder = nil
    uri, saml_params = idp.login_request_for(binding: :http_post, relay_state: relay_state) do |builder|
      @saml_builder = builder
    end

    html = with_layout(binding) do
      <<~ERB
        <h2>Sending SAML Request (SP -> IdP)</h2>
        <textarea readonly="readonly" disabled="disabled" cols=225 rows=6><%=- @saml_builder.to_xml(pretty: true) -%></textarea>

        <form id="idp-form" action="<%= uri %>" method="post">
          <%- saml_params.each do |(key, value)| -%>
            <input type="hidden" name="<%= key %>" value="<%= value %>" />
          <%- end -%>
          <input id="submit-button" type="submit" value="Submit" />
        </form>
      ERB
    end
    [200, { 'Content-Type' => "text/html" }, [html]]
  end

  def saml_assertions(request)
    sp = Saml::Kit.registry.metadata_for("#{$scheme}://#{$host}/saml/metadata.xml")
    saml_binding = sp.assertion_consumer_service_for(binding: :http_post)
    saml_response = saml_binding.deserialize(request.params)
    raise saml_response.errors unless saml_response.valid?

    assertion = Base64.strict_encode64(saml_response.assertion.to_xml)
    response = oauth_client.exchange(
      "urn:ietf:params:oauth:grant-type:saml2-bearer",
      assertion: assertion,
    )
    if response.code == "200"
      tokens = JSON.parse(response.body, symbolize_names: true)
      request.session[:access_token] = tokens[:access_token]
      request.session[:refresh_token] = tokens[:access_token]

      html = with_layout(binding) do
        <<~ERB
        <a href="/index.html">Home</a>
        <a href="/groups.html">Groups</a>

        <h2>Received SAML Response</h2>
        <textarea readonly="readonly" disabled="disabled" cols=220 rows=40><%=- saml_response.to_xml(pretty: true) -%></textarea>
        <pre id="raw-saml-response" style="display: none;"><%= request.params["SAMLResponse"] %></pre>
        <pre id="xml-saml-assertion" style="display: none;"><%= saml_response.assertion.to_xml(pretty: true) %></pre>
        <pre id="access-token" style="display: none;"><%= JSON.pretty_generate(request.session[:access_token]) %></pre>
        ERB
      end
      [200, { 'Content-Type' => "text/html" }, [html]]
    else
      [response.code, response.header, [response.body]]
    end
  end
end

if __FILE__ == $0
  app = Rack::Builder.new do
    use Rack::CommonLogger
    use Rack::Reloader
    use Rack::Session::Cookie, { domain: $host.split(":", 2)[0], path: "/", secret: SecureRandom.hex(64) }

    run UI.new(::OAuth::Client.new($idp_host, 'client_id', 'client_secret'))
  end.to_app

  Rackup::Server.start(app: app, Port: $port)
end