summaryrefslogtreecommitdiff
path: root/bin/idp
blob: fc276bb51bbda6b3f134fbf6fef08de5f4f3ad4c (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
#!/usr/bin/env ruby

require "bundler/inline"

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

  gem "erb", "~> 4.0"
  gem "rack", "~> 3.0"
  gem "rackup", "~> 2.0"
  gem "saml-kit", "~> 1.0"
  gem "twirp", "~> 1.0"
  gem "webrick", "~> 1.0"
end

class User
  def initialize(attributes)
    @attributes = attributes
  end

  def name_id_for(name_id_format)
    @attributes[:email]
  end

  def assertion_attributes_for(request)
    {
      custom: 'custom attribute'
    }
  end
end

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 = "http://localhost:8282/metadata.xml"
  x.registry = OnDemandRegistry.new
  x.logger = Logger.new("/dev/stderr")
end

class IdentityProvider
  def initialize
    @storage = {}
  end

  def call(env)
    path = env['PATH_INFO']
    case env['REQUEST_METHOD']
    when 'GET'
      case path
      when '/.well-known/openid-configuration'
        return openid_metadata
      when '/.well-known/oauth-authorization-server'
        return oauth_metadata
      when '/.well-known/webfinger' # RFC-7033
        return not_found
      when "/metadata.xml"
        return saml_metadata
      when "/sessions/new"
        return saml_post_back(Rack::Request.new(env))
      when "/oauth/authorize" # RFC-6749
        return get_authorize(Rack::Request.new(env))
      else
        return not_found
      end
    when 'POST'
      case path
      when "/sessions/new"
        return saml_post_back(Rack::Request.new(env))
      when "/oauth/authorize" # RFC-6749
        return post_authorize(Rack::Request.new(env))
      when "/oauth/token" # RFC-6749
        return [200, { 'Content-Type' => "application/json" }, [JSON.pretty_generate({
          access_token: to_jwt(sub: SecureRandom.uuid, iat: Time.now.to_i),
          token_type: "Bearer",
          expires_in: 3600,
          refresh_token: SecureRandom.hex(32)
        })]]
      when "/oauth/revoke" # RFC-7009
        return not_found
      else
        return not_found
      end
    end
    not_found
  end

  private

  def to_jwt(claims)
    [
      Base64.strict_encode64(JSON.generate({alg: "RS256", typ: "JWT"})),
      Base64.strict_encode64(JSON.generate(claims)),
      Base64.strict_encode64(JSON.generate({})),
    ].join(".")
  end

  # Download IDP Metadata
  #
  # GET /metadata.xml
  def saml_metadata
    xml = Saml::Kit::Metadata.build_xml do |builder|
      builder.contact_email = 'hi@example.com'
      builder.organization_name = "Acme, Inc"
      builder.organization_url = "https://example.com"
      builder.build_identity_provider do |x|
        x.add_single_sign_on_service("http://localhost:8282/sessions/new", binding: :http_post)
        x.name_id_formats = [Saml::Kit::Namespaces::EMAIL_ADDRESS]
        x.attributes << :Username
      end
    end

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

  # GET /.well-known/oauth-authorization-server
  def oauth_metadata
    [200, { 'Content-Type' => "application/json" }, [JSON.pretty_generate({
      issuer: "http://localhost:8282/.well-known/oauth-authorization-server",
      authorization_endpoint: "http://localhost:8282/oauth/authorize",
      token_endpoint: "http://localhost:8282/oauth/token",
      jwks_uri: "", # RFC-7517
      registration_endpoint: "", # RFC-7591
      scopes_supported: ["openid", "profile", "email"],
      response_types_supported: ["code", "code id_token", "id_token", "token id_token"],
      response_modes_supported: ["query", "fragment", "form_post"],
      grant_types_supported: ["authorization_code", "implicit"], # RFC-7591
      token_endpoint_auth_methods_supported: ["client_secret_basic"], # RFC-7591
      token_endpoint_auth_signing_alg_values_supported: ["RS256"],
      service_documentation: "",
      ui_locales_supported: ["en-US"],
      op_policy_uri: "",
      op_tos_uri: "",
      revocation_endpoint: "http://localhost:8282/oauth/revoke", # RFC-7009
      revocation_endpoint_auth_methods_supported: ["client_secret_basic"],
      revocation_endpoint_auth_signing_alg_values_supported: ["RS256"],
      introspection_endpoint: "http://localhost:8282/oauth/introspect", # RFC-7662
      introspection_endpoint_auth_methods_supported: ["client_secret_basic"],
      introspection_endpoint_auth_signing_alg_values_supported: ["RS256"],
      code_challenge_methods_supported: [], # RFC-7636
    })]]
  end

  def get_authorize(request)
    template = <<~ERB
      <!doctype html>
      <html>
        <head><title></title></head>
        <body>
          <h2>Authorize?</h2>
          <form action="/oauth/authorize" method="post">
            <input type="hidden" name="client_id" value="<%= request.params['client_id'] %>" />
            <input type="hidden" name="scope" value="<%= request.params['scope'] %>" />
            <input type="hidden" name="redirect_uri" value="<%= request.params['redirect_uri'] %>" />
            <input type="hidden" name="response_mode" value="<%= request.params['response_mode'] %>" />
            <input type="hidden" name="response_type" value="<%= request.params['response_type'] %>" />
            <input type="hidden" name="state" value="<%= request.params['state'] %>" />
            <input type="hidden" name="code_challenge_method" value="<%= request.params['code_challenge_method'] %>" />
            <input type="hidden" name="code_challenge" value="<%= request.params['code_challenge'] %>" />
            <input type="submit" value="Submit" />
          </form>
        </body>
      </html>
    ERB
    html = ERB.new(template, trim_mode: '-').result(binding)
    [200, { 'Content-Type' => "text/html" }, [html]]
  end

  def post_authorize(request)
    params = request.params.slice('client_id', 'redirect_uri', 'response_type', 'response_mode', 'state', 'code_challenge_method', 'code_challenge', 'scope')
    case params['response_type']
    when 'code'
      case params['response_mode']
      when 'fragment'
        return [302, { 'Location' => "#{params['redirect_uri']}#code=#{SecureRandom.uuid}&state=#{params['state']}" }, []]
      when 'query'
        return [302, { 'Location' => "#{params['redirect_uri']}?code=#{SecureRandom.uuid}&state=#{params['state']}" }, []]
      else
        # TODO:: form post
      end

    when 'token'
      return not_found
    else
      return not_found
    end
  end

  # GET /.well-known/openid-configuration
  def openid_metadata
    [200, { 'Content-Type' => "application/json" }, [JSON.pretty_generate({
      issuer: "http://localhost:8282/.well-known/oauth-authorization-server",
      authorization_endpoint: "http://localhost:8282/oauth/authorize",
      token_endpoint: "http://localhost:8282/oauth/token",
      userinfo_endpoint: "http://localhost:8282/oidc/user/",
      jwks_uri: "", # RFC-7517
      registration_endpoint: nil,
      scopes_supported: ["openid", "profile", "email"],
      response_types_supported: ["code", "code id_token", "id_token", "token id_token"],
      response_modes_supported: ["query", "fragment", "form_post"],
      grant_types_supported: ["authorization_code", "implicit"], # RFC-7591
      acr_values_supported: [],
      subject_types_supported: ["pairwise", "public"],
      id_token_signing_alg_values_supported: ["RS256"],
      id_token_encryption_alg_values_supported: [],
      id_token_encryption_enc_values_supported: [],
      userinfo_signing_alg_values_supported: ["RS256"],
      userinfo_encryption_alg_values_supported: [],
      userinfo_encryption_enc_values_supported: [],
      request_object_signing_alg_values_supported: ["none", "RS256"],
      request_object_encryption_alg_values_supported: [],
      request_object_encryption_enc_values_supported: [],
      token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic", "client_secret_jwt", "private_key_jwt"],
      token_endpoint_auth_signing_alg_values_supported: [],
      display_values_supported: [],
      claim_types_supported: ["normal", "aggregated", "distributed"],
      claims_supported: [
        "acr",
        "auth_time",
        "email",
        "email_verified",
        "family_name",
        "given_name",
        "iss",
        "locale",
        "name",
        "nickname",
        "picture",
        "profile",
        "sub",
        "website"
      ],
      service_documentation: nil,
      claims_locales_supported: [],
      ui_locales_supported: ["en-US"],
      claims_parameter_supported: false,
      request_parameter_supported: false,
      request_uri_paramater_supported: false,
      require_request_uri_registration: false,
      op_policy_uri: "",
      op_tos_uri: "",
    })]]
  end

  def saml_post_back(request)
    params = saml_params_from(request)
    saml_request = binding_for(request).deserialize(params)
    @builder = nil
    url, saml_params = saml_request.response_for(
      User.new({ email: "example@example.com" }),
      binding: :http_post,
      relay_state: params[:RelayState]
    ) do |builder|
      builder.embed_signature = true
      @builder = builder
    end
    template = <<~ERB
      <!doctype html>
      <html>
        <head><title></title></head>
        <body>
          <h2>Recieved SAML Request</h2>
          <textarea readonly="readonly" disabled="disabled" cols=225 rows=6><%=- saml_request.to_xml(pretty: true) -%></textarea>

          <h2>Sending SAML Response (IdP -> SP)</h2>
          <textarea readonly="readonly" disabled="disabled" cols=225 rows=30><%=- @builder.build.to_xml(pretty: true) -%></textarea>
          <form action="<%= url %>" method="post">
            <%- saml_params.each do |(key, value)| -%>
              <input type="hidden" name="<%= key %>" value="<%= value %>" />
            <%- end -%>
            <input type="submit" value="Submit" />
          </form>
        </body>
      </html>
    ERB
    erb = ERB.new(template, trim_mode: '-')
    html = erb.result(binding)
    [200, { 'Content-Type' => "text/html" }, [html]]
  end

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

  def saml_params_from(request)
    if request.post?
      {
        "SAMLRequest" => request.params["SAMLRequest"],
        "RelayState" => request.params["RelayState"],
      }
    else
      query_string = request.query_string
      on = query_string.include?("&amp;") ? "&amp;" : "&"
      Hash[query_string.split(on).map { |x| x.split("=", 2) }].symbolize_keys
    end
  end

  def binding_for(request)
    location = "http://localhost:8282/sessions/new"
    if request.post?
      Saml::Kit::Bindings::HttpPost
        .new(location: location)
    else
      Saml::Kit::Bindings::HttpRedirect
        .new(location: location)
    end
  end
end

if __FILE__ == $0
  app = Rack::Builder.new do
    use Rack::Reloader
    run IdentityProvider.new
  end.to_app

  Rackup::Server.start(app: app, Port: 8282)
end