Class: OpenNebula::SamlAuth

Inherits:
Object
  • Object
show all
Defined in:
lib/opennebula/saml_auth.rb

Overview

This class handles SAML authentication responses and group mapping for OpenNebula.

Instance Method Summary collapse

Constructor Details

#initialize(provider, config) ⇒ SamlAuth

Returns a new instance of SamlAuth.



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
# File 'lib/opennebula/saml_auth.rb', line 40

def initialize(provider, config)
    @options={
        :issuer             => nil,
        :idp_cert           => nil,
        :user_field         => 'NameID',
        :group_field        => 'memberOf',
        :group_required     => nil,
        :mapping_generate   => true,
        :mapping_key        => 'SAML_GROUP',
        :mapping_mode       => 'strict',
        :mapping_timeout    => 300,
        :mapping_filename   => 'saml_groups_1.yaml',
        :mapping_default    => 1,
        :group_admin_name   => 'cloud-admins'
    }.merge(provider)

    @options[:mapping_file_path] = VAR_LOCATION + @options[:mapping_filename]

    @options[:sp_entity_id] = config[:sp_entity_id]
    @options[:acs_url]      = config[:acs_url]

    if !options_ok?
        raise StandardError,
              'Identity Provider configured options are not correct.' \
              ' Please, configure a valid Identity Provider certificate.'
    end

    generate_mapping if @options[:mapping_generate]

    load_mapping
end

Instance Method Details

#generate_mappingObject



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
# File 'lib/opennebula/saml_auth.rb', line 124

def generate_mapping
    file = @options[:mapping_file_path]

    File.open(file, File::RDWR | File::CREAT) do |f|
        # Shared lock for reading the file
        f.flock(File::LOCK_SH)

        stat = f.stat
        age  = Time.now.to_i - stat.mtime.to_i

        break if age <= @options[:mapping_timeout]

        # Switch to exclusive lock for writing
        f.flock(File::LOCK_UN)
        f.flock(File::LOCK_EX)

        # Check stat again, it might have changed while we were waiting for the lock
        stat = f.stat
        age  = Time.now.to_i - stat.mtime.to_i

        break if age <= @options[:mapping_timeout]

        client     = OpenNebula::Client.new
        group_pool = OpenNebula::GroupPool.new(client)

        rc = group_pool.info

        raise StandardError, rc.message if OpenNebula.is_error?(rc)

        groups = [group_pool.get_hash['GROUP_POOL']['GROUP']].flatten
        yaml   = {}

        groups.each do |group|
            if group['TEMPLATE'] && group['TEMPLATE'][@options[:mapping_key]]
                yaml[group['TEMPLATE'][@options[:mapping_key]]] = group['ID']
            end
        end

        f.truncate(0)
        f.rewind
        f.write(yaml.to_yaml)
    ensure
        f.flock(File::LOCK_UN)
    end
end

#get_groups(idp_groups) ⇒ Object



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
# File 'lib/opennebula/saml_auth.rb', line 194

def get_groups(idp_groups)
    is_admin = false
    case @options[:mapping_mode]
    # Direct mapping of SAML group names to ONE group IDs
    when 'strict'
        valid_mappings = idp_groups.map {|group| @mapping[group] }.compact

        g_admin  = @options[:group_admin_name]
        is_admin = g_admin && idp_groups.include?(g_admin)
    # Keycloak-specific group syntax and group nesting support (e.g. /group1/subgroup1)
    when 'keycloak'
        valid_mappings = []

        idp_groups.each do |idp_group|
            group_parts = idp_group.split('/')
            group_parts.reject!(&:empty?)

            # Build all possible parent group paths
            (1..group_parts.length).each do |i|
                # Create group path with leading slash (Keycloak format)
                group_path = '/' + group_parts[0...i].join('/')

                is_admin = true if group_path == @options[:group_admin_name]

                # Check direct mapping first
                if @mapping[group_path]
                    valid_mappings << @mapping[group_path]
                elsif i == 1
                    # Try without the leading slash for single group parts
                    # E.g. in the mapping file "/group1" should be the same as "group1"
                    group_path_no_slash = group_parts[0]

                    is_admin = true if group_path_no_slash == @options[:group_admin_name]

                    if @mapping[group_path_no_slash]
                        valid_mappings << @mapping[group_path_no_slash]
                    end
                end
            end
        end

        valid_mappings.compact!
        valid_mappings.uniq!
    else
        raise StandardError,
              "Unsupported group mapping mode: #{@options[:mapping_mode]}." \
              " Supported modes are 'strict' and 'keycloak'."
    end

    # Return the default group if no mapping is found
    valid_mappings = [@options[:mapping_default].to_s] if valid_mappings.empty?

    # Handle group admin case. Group admin can NOT be a nested group
    valid_mappings = valid_mappings.map {|id| "*#{id}" } if is_admin

    return valid_mappings.join(' ')
end

#load_mappingObject



170
171
172
173
174
175
176
177
178
179
180
# File 'lib/opennebula/saml_auth.rb', line 170

def load_mapping
    file=@options[:mapping_file_path]

    @mapping = {}

    if File.exist?(file)
        @mapping = YAML.safe_load(File.read(file))
    end

    @mapping = {} unless @mapping.class == Hash
end

#options_ok?Boolean

Returns:

  • (Boolean)


72
73
74
75
76
77
78
# File 'lib/opennebula/saml_auth.rb', line 72

def options_ok?
    required_keys = [:issuer, :idp_cert, :sp_entity_id, :group_field]
    return false unless required_keys.all? {|key| @options.key?(key) }

    # Avoid XPath injection towards the assertion
    !@options[:group_field].include?("'")
end

#validate_assertion(assertion_text) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/opennebula/saml_auth.rb', line 108

def validate_assertion(assertion_text)
    saml_settings = OneLogin::RubySaml::Settings.new

    saml_settings.idp_cert = @options[:idp_cert]
    saml_settings.issuer   = @options[:issuer]

    saml_settings.sp_entity_id                   = @options[:sp_entity_id]
    saml_settings.assertion_consumer_service_url = @options[:acs_url]

    assertion = OneLogin::RubySaml::Response.new(assertion_text, :settings => saml_settings)

    return if assertion.is_valid?

    assertion.errors
end

#validate_required_group(idp_groups) ⇒ Object

Raises:

  • (StandardError)


182
183
184
185
186
187
188
189
190
191
192
# File 'lib/opennebula/saml_auth.rb', line 182

def validate_required_group(idp_groups)
    required = @options[:group_required]
    return if required.nil?

    return if idp_groups.include?(required) || idp_groups.include?("/#{required}")

    raise StandardError,
          'The user does not belong to the required group.' \
          " Groups reported by the IdP: #{idp_groups}" \
          " Configured required group: #{required} ( /#{required} if using Keycloak )"
end