summaryrefslogtreecommitdiff
path: root/src/saml-idp/main.rb
blob: e218afb45d4602e58a3bb3006bdfef7ca94cea4b (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
#!/usr/bin/env ruby

# Start the server by running:
#
# $ ruby -rwebrick main.rb

require "bundler/inline"
gemfile do
  source "https://rubygems.org"

  gem "rack", "~> 2.2"
  gem "saml-kit", "~> 1.3"
end
require "rack"

class Configuration
  def initialize
    @config = YAML.safe_load(IO.read("idp.yml"))
  end

  def [](key)
    @config.fetch(key.to_s)
  end
end

class User
  def name_id_for(name_id_format)
    $config[:email]
  end

  def assertion_attributes_for(request)
    {
      Username: $config[:email],
      MemberOf: $config[:email]
    }
  end
end

class OnDemandRegistry < Saml::Kit::DefaultRegistry
  REGEX = /\/sso\/saml\/samlconf-(?<uuid>[A-Za-z0-9]+)\/metadata/

  def metadata_for(entity_id)
    found = super(entity_id)
    return found if found

    uri = URI.parse(entity_id)
    if uri.host.include?("terraform.io") || uri.host.include?("ngrok.io")
      metadata = Saml::Kit::Metadata.build do |builder|
        builder.entity_id = entity_id
        builder.build_service_provider do |x|
          match = uri.path.match(REGEX)
          x.add_assertion_consumer_service("https://#{uri.host}/sso/saml/samlconf-#{match[:uuid]}/acs", binding: :http_post)
        end
      end
      register(metadata)
    else
      register_url(entity_id, verify_ssl: Rails.env.production?)
    end

    super(entity_id)
  end
end

$config = Configuration.new

Saml::Kit.configure do |x|
  x.entity_id = "https://#{$config[:host]}/metadata.xml"
  x.registry = OnDemandRegistry.new
  x.logger = Logger.new("/dev/stderr")
  x.add_key_pair($config[:cert], $config[:insecure_key], use: :signing)
end

class IdentityProvider
  def initialize
    @storage = {}
  end

  # Download IDP Metadata
  #
  # GET /metadata.xml
  # Response
  #
  # Status: 200 OK
  # {xml data}
  def metadata
    xml = Saml::Kit::Metadata.build_xml do |builder|
      builder.embed_signature = false
      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("https://#{$config[:host]}/sso", binding: :http_post)
        x.name_id_formats = [Saml::Kit::Namespaces::EMAIL_ADDRESS]
        x.attributes << :MemberOf
        x.attributes << :Username
      end
    end

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

  def post_back(request)
    location = "#{$config[:host]}/sso"
    params = saml_params_from(request)
    saml = if request.post?
      Saml::Kit::Bindings::HttpPost
        .new(location: location)
        .deserialize(params)
    else
      Saml::Kit::Bindings::HttpRedirect
        .new(location: location)
        .deserialize(params)
    end
    url, saml_params = saml.response_for(User.new, binding: :http_post, relay_state: params[:RelayState])
    template = <<~ERB
      <!doctype html>
      <html>
        <head><title></title></head>
        <body>
          <form action="<%= url %>" method="post">
            <%- saml_params.each do |(key, value)| -%>
              <input type="hidden" name="<%= key %>" value="<%= value %>" />
            <%- end -%>
          </form>
          <script>
            document.querySelector('form').submit();
          </script>
        </body>
      </html>
    ERB
    erb = ERB.new(template, nil, trim_mode: '-')
    html = erb.result(binding)
    [200, {}, [html]]
  end

  def call(env)
    path = env['PATH_INFO']
    case env['REQUEST_METHOD']
    when 'GET'
      case path
      when "/metadata.xml"
        return metadata
      when "/sso"
        return post_back(Rack::Request.new(env))
      end
    when 'POST'
      return post_back(Rack::Request.new(env))
    end
    not_found
  end

  private

  def not_found
    [404, {}, []]
  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;" : "&"
      result = Hash[query_string.split(on).map { |x| x.split("=", 2) }]
      result = result.symbolize_keys
      result
    end
  end
end

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

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