Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions lib/aws_advanced_ruby_driver_wrapper/utils/saml_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,30 @@ def validate_url!(url)
uri = URI.parse(url)
return if uri.is_a?(URI::HTTPS) && url.match?(HTTPS_URL_PATTERN)

raise Errors::SamlAuthError, "Invalid HTTPS URL: #{url}"
raise Errors::SamlAuthError, "Invalid HTTPS URL: #{url_for_message(url)}"
rescue URI::InvalidURIError
raise Errors::SamlAuthError, "Invalid HTTPS URL: #{url}"
raise Errors::SamlAuthError, "Invalid HTTPS URL: #{url_for_message(url)}"
end

# The URL as it may appear in an error message: without its query string, fragment, path
# parameters (";jsessionid=...") or user info. IdP URLs and the redirects an IdP sends can
# carry one-time tokens, session ids or credentials in those parts, and an error message can
# end up in application logs and telemetry. The scheme, host and path are kept so the
# message still shows which endpoint was rejected. Path segments are kept on purpose: the IdP
# flows carry their tokens in the query, never in the path.
#
# It does not parse the URL, so it also works on the malformed URLs it is mostly used for.
# User info is removed first, through the last "@" before the path, so a password containing
# a raw "?", "#" or ";" is not cut in half and left behind. The scheme and the slashes after
# it are optional and "\" is accepted for "/", so protocol-relative ("//user:pass@host"),
# backslash, single-slash and scheme-less forms are covered too. For an "@" in a query with
# no path before it, this shows the text after that "@" as the host; that only affects how
# the endpoint is shown, never what is kept secret.
#
# @param url [String]
# @return [String]
def url_for_message(url)
url.to_s.sub(%r{\A((?:[^:/?#\\]*:)?[/\\]{1,2})?[^/\\]*@}, '\1').sub(/[?#;].*/m, '')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

end

# A short, stable fingerprint of the AWS principal a SAML connection assumes,
Expand Down Expand Up @@ -125,8 +146,12 @@ def merge_cookies!(cookies, host, response)
end
end

# A malformed Location header would otherwise raise URI::InvalidURIError, whose message
# holds the whole location.
def absolute_redirect(uri, location)
URI.join(uri, location).to_s
rescue URI::InvalidURIError
raise Errors::SamlAuthError, "Invalid redirect URL: #{url_for_message(location)}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should add 'cause:nil' to avoid leaks to telemetry

end
end
end
Expand Down
167 changes: 167 additions & 0 deletions spec/unit/utils/saml_utils_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# frozen_string_literal: true

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require_relative '../../spec_helper'
require 'aws_advanced_ruby_driver_wrapper/utils/saml_utils'
require 'aws_advanced_ruby_driver_wrapper/errors'

RSpec.describe AwsAdvancedRubyDriverWrapper::Utils::SamlUtils do
subject(:utils) { described_class }

let(:saml_auth_error) { AwsAdvancedRubyDriverWrapper::Errors::SamlAuthError }

describe '.url_for_message' do
it 'drops the query string' do
expect(utils.url_for_message('https://idp.example.com/sso/saml?onetimetoken=SECRET'))
.to eq('https://idp.example.com/sso/saml')
end

it 'drops the fragment' do
expect(utils.url_for_message('https://idp.example.com/cb#access_token=SECRET')).to eq('https://idp.example.com/cb')
end

it 'drops path parameters' do
expect(utils.url_for_message('https://idp.example.com/login;jsessionid=SECRET?x=1')).to eq('https://idp.example.com/login')
end

it 'drops user info' do
expect(utils.url_for_message('https://user:SECRET@idp.example.com/adfs/ls')).to eq('https://idp.example.com/adfs/ls')
end

it 'keeps an @ that is part of the path' do
expect(utils.url_for_message('https://idp.example.com/users/jim@example.com')).to eq('https://idp.example.com/users/jim@example.com')
end

it 'keeps the scheme, host, port and path' do
expect(utils.url_for_message('http://idp.example.com:8443/adfs/ls/IdpInitiatedSignOn.aspx'))
.to eq('http://idp.example.com:8443/adfs/ls/IdpInitiatedSignOn.aspx')
end

it 'handles a URL that cannot be parsed' do
expect(utils.url_for_message('https://idp.example.com/a b?code=SECRET')).to eq('https://idp.example.com/a b')
end

it 'drops user info whose password holds a raw ?, # or ;' do
expect(utils.url_for_message('https://u:pa?ss@idp.example.com/x')).to eq('https://idp.example.com/x')
expect(utils.url_for_message('https://u:pa#ss@idp.example.com/x')).to eq('https://idp.example.com/x')
expect(utils.url_for_message('https://u:pa;ss@idp.example.com/a b')).to eq('https://idp.example.com/a b')
end

it 'drops user info through the last @ before the path' do
expect(utils.url_for_message('https://a:b@c:SECRET@idp.example.com/x')).to eq('https://idp.example.com/x')
end

it 'drops user info from a protocol-relative URL' do
expect(utils.url_for_message('//u:SECRET@idp.example.com/a b')).to eq('//idp.example.com/a b')
end

it 'drops user info from backslash, single-slash and scheme-less forms' do
expect(utils.url_for_message('https:\\\\u:SECRET@idp.example.com/x')).to eq('https:\\\\idp.example.com/x')
expect(utils.url_for_message('https:/u:SECRET@idp.example.com/x')).to eq('https:/idp.example.com/x')
expect(utils.url_for_message('u:SECRET@idp.example.com/a b')).to eq('idp.example.com/a b')
end

it 'keeps an @ in a relative path' do
expect(utils.url_for_message('/users/jim@example.com?x=1')).to eq('/users/jim@example.com')
end

it 'returns an empty string for nil' do
expect(utils.url_for_message(nil)).to eq('')
end
end

describe '.validate_url!' do
it 'accepts an https URL' do
expect { utils.validate_url!('https://idp.example.com/sso/saml?onetimetoken=abc') }.not_to raise_error
end

it 'rejects an http URL without putting its query string in the error' do
expect { utils.validate_url!('http://idp.example.com/cb?code=SECRET') }
.to raise_error(saml_auth_error, 'Invalid HTTPS URL: http://idp.example.com/cb')
end

it 'rejects a malformed URL without putting its query string in the error' do
expect { utils.validate_url!('https://idp.example.com/a b?code=SECRET') }
.to raise_error(saml_auth_error, 'Invalid HTTPS URL: https://idp.example.com/a b')
end

it 'rejects a URL with credentials without putting them in the error' do
expect { utils.validate_url!('ftp://user:SECRET@idp.example.com/x') }
.to raise_error(saml_auth_error, 'Invalid HTTPS URL: ftp://idp.example.com/x')
end
end

describe '.http_request redirects' do
def redirect_to(location)
response = Net::HTTPFound.new('1.1', '302', 'Found')
response['location'] = location
response
end

let(:http) { instance_double(Net::HTTP) }

before do
allow(Net::HTTP).to receive(:new).and_return(http)
%i[use_ssl= verify_mode= open_timeout= read_timeout=].each { |setter| allow(http).to receive(setter) }
end

it 'does not put the query string of a redirect to an http URL in the error' do
allow(http).to receive(:request).and_return(redirect_to('http://idp.example.com/cb?code=SECRET'))

expect { utils.http_request(method: :get, url: 'https://idp.example.com/start') }
.to raise_error(saml_auth_error, 'Invalid HTTPS URL: http://idp.example.com/cb')
end

it 'does not put a malformed redirect location in the error' do
allow(http).to receive(:request).and_return(redirect_to('https://idp.example.com/a b?code=SECRET'))

expect { utils.http_request(method: :get, url: 'https://idp.example.com/start') }
.to raise_error(saml_auth_error, 'Invalid redirect URL: https://idp.example.com/a b')
end

it 'does not put the user info of a malformed protocol-relative redirect in the error' do
allow(http).to receive(:request).and_return(redirect_to('//u:SECRET@idp.example.com/a b'))

expect { utils.http_request(method: :get, url: 'https://idp.example.com/start') }
.to raise_error(saml_auth_error, 'Invalid redirect URL: //idp.example.com/a b')
end

it 'still follows a valid relative redirect' do
ok = Net::HTTPOK.new('1.1', '200', 'OK')
paths = []
allow(http).to receive(:request) do |request|
paths << request.path
paths.size == 1 ? redirect_to('/next?code=ok') : ok
end

response = utils.http_request(method: :get, url: 'https://idp.example.com/start')

expect(paths).to eq(['/start', '/next?code=ok'])
expect(response).to be(ok)
end
end

describe '.absolute_redirect' do
it 'resolves a relative location against the current URL' do
expect(utils.absolute_redirect(URI('https://idp.example.com/a/b'), '../c?x=1')).to eq('https://idp.example.com/c?x=1')
end

it 'raises SamlAuthError, not URI::InvalidURIError, for a malformed location' do
expect { utils.absolute_redirect(URI('https://idp.example.com/'), 'https://idp.example.com/a b?code=SECRET') }
.to raise_error(saml_auth_error, 'Invalid redirect URL: https://idp.example.com/a b')
end
end
end