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
|
# Copyright 2022 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
import dateutil.parser
import pytest
from botocore.exceptions import (
InvalidConfigError,
SSOTokenLoadError,
TokenRetrievalError,
)
from botocore.session import Session
from botocore.tokens import SSOTokenProvider
from tests import mock
def parametrize(cases):
return pytest.mark.parametrize(
"test_case",
cases,
ids=[c["documentation"] for c in cases],
)
sso_provider_resolution_cases = [
{
"documentation": "Full valid profile",
"config": {
"profiles": {"test": {"sso_session": "admin"}},
"sso_sessions": {
"admin": {
"sso_region": "us-east-1",
"sso_start_url": "https://d-abc123.awsapps.com/start",
}
},
},
"resolves": True,
},
{
"documentation": "Non-SSO profiles are skipped",
"config": {"profiles": {"test": {"region": "us-west-2"}}},
"resolves": False,
},
{
"documentation": "Only start URL is invalid",
"config": {
"profiles": {"test": {"sso_session": "admin"}},
"sso_sessions": {
"admin": {
"sso_start_url": "https://d-abc123.awsapps.com/start"
}
},
},
"resolves": False,
"expectedException": InvalidConfigError,
},
{
"documentation": "Only sso_region is invalid",
"config": {
"profiles": {"test": {"sso_session": "admin"}},
"sso_sessions": {"admin": {"sso_region": "us-east-1"}},
},
"resolves": False,
"expectedException": InvalidConfigError,
},
{
"documentation": "Specified sso-session must exist",
"config": {
"profiles": {"test": {"sso_session": "dev"}},
"sso_sessions": {"admin": {"sso_region": "us-east-1"}},
},
"resolves": False,
"expectedException": InvalidConfigError,
},
{
"documentation": "The sso_session must be specified",
"config": {
"profiles": {"test": {"region": "us-west-2"}},
"sso_sessions": {
"admin": {
"sso_region": "us-east-1",
"sso_start_url": "https://d-abc123.awsapps.com/start",
}
},
},
"resolves": False,
},
]
def _create_mock_session(config):
mock_session = mock.Mock(spec=Session)
mock_session.get_config_variable.return_value = "test"
mock_session.full_config = config
return mock_session
@parametrize(sso_provider_resolution_cases)
def test_sso_token_provider_resolution(test_case):
mock_session = _create_mock_session(test_case["config"])
resolver = SSOTokenProvider(mock_session)
expected_exception = test_case.get("expectedException")
if expected_exception is not None:
with pytest.raises(expected_exception):
auth_token = resolver.load_token()
return
auth_token = resolver.load_token()
if test_case["resolves"]:
assert auth_token is not None
else:
assert auth_token is None
sso_provider_refresh_cases = [
{
"documentation": "Valid token with all fields",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {
"startUrl": "https://d-123.awsapps.com/start",
"region": "us-west-2",
"accessToken": "cachedtoken",
"expiresAt": "2021-12-25T21:30:00Z",
"clientId": "clientid",
"clientSecret": "YSBzZWNyZXQ=",
"registrationExpiresAt": "2022-12-25T13:30:00Z",
"refreshToken": "cachedrefreshtoken",
},
"expectedToken": {
"token": "cachedtoken",
"expiration": "2021-12-25T21:30:00Z",
},
},
{
"documentation": "Minimal valid cached token",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {
"accessToken": "cachedtoken",
"expiresAt": "2021-12-25T21:30:00Z",
},
"expectedToken": {
"token": "cachedtoken",
"expiration": "2021-12-25T21:30:00Z",
},
},
{
"documentation": "Minimal expired cached token",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {
"accessToken": "cachedtoken",
"expiresAt": "2021-12-25T13:00:00Z",
},
"expectedException": TokenRetrievalError,
},
{
"documentation": "Token missing the expiresAt field",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {"accessToken": "cachedtoken"},
"expectedException": SSOTokenLoadError,
},
{
"documentation": "Token missing the accessToken field",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {"expiresAt": "2021-12-25T13:00:00Z"},
"expectedException": SSOTokenLoadError,
},
{
"documentation": "Expired token refresh with refresh token",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {
"startUrl": "https://d-123.awsapps.com/start",
"region": "us-west-2",
"accessToken": "cachedtoken",
"expiresAt": "2021-12-25T13:00:00Z",
"clientId": "clientid",
"clientSecret": "YSBzZWNyZXQ=",
"registrationExpiresAt": "2022-12-25T13:30:00Z",
"refreshToken": "cachedrefreshtoken",
},
"refreshResponse": {
"tokenType": "Bearer",
"accessToken": "newtoken",
"expiresIn": 28800,
"refreshToken": "newrefreshtoken",
},
"expectedTokenWriteback": {
"startUrl": "https://d-123.awsapps.com/start",
"region": "us-west-2",
"accessToken": "newtoken",
"expiresAt": "2021-12-25T21:30:00Z",
"clientId": "clientid",
"clientSecret": "YSBzZWNyZXQ=",
"registrationExpiresAt": "2022-12-25T13:30:00Z",
"refreshToken": "newrefreshtoken",
},
"expectedToken": {
"token": "newtoken",
"expiration": "2021-12-25T21:30:00Z",
},
},
{
"documentation": "Expired token refresh without new refresh token",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {
"startUrl": "https://d-123.awsapps.com/start",
"region": "us-west-2",
"accessToken": "cachedtoken",
"expiresAt": "2021-12-25T13:00:00Z",
"clientId": "clientid",
"clientSecret": "YSBzZWNyZXQ=",
"registrationExpiresAt": "2022-12-25T13:30:00Z",
"refreshToken": "cachedrefreshtoken",
},
"refreshResponse": {
"tokenType": "Bearer",
"accessToken": "newtoken",
"expiresIn": 28800,
},
"expectedTokenWriteback": {
"startUrl": "https://d-123.awsapps.com/start",
"region": "us-west-2",
"accessToken": "newtoken",
"expiresAt": "2021-12-25T21:30:00Z",
"clientId": "clientid",
"clientSecret": "YSBzZWNyZXQ=",
"registrationExpiresAt": "2022-12-25T13:30:00Z",
},
"expectedToken": {
"token": "newtoken",
"expiration": "2021-12-25T21:30:00Z",
},
},
{
"documentation": "Expired token and expired client registration",
"currentTime": "2021-12-25T13:30:00Z",
"cachedToken": {
"startUrl": "https://d-123.awsapps.com/start",
"region": "us-west-2",
"accessToken": "cachedtoken",
"expiresAt": "2021-10-25T13:00:00Z",
"clientId": "clientid",
"clientSecret": "YSBzZWNyZXQ=",
"registrationExpiresAt": "2021-11-25T13:30:00Z",
"refreshToken": "cachedrefreshtoken",
},
"expectedException": TokenRetrievalError,
},
]
@parametrize(sso_provider_refresh_cases)
def test_sso_token_provider_refresh(test_case):
config = {
"profiles": {"test": {"sso_session": "admin"}},
"sso_sessions": {
"admin": {
"sso_region": "us-west-2",
"sso_start_url": "https://d-123.awsapps.com/start",
}
},
}
cache_key = "d033e22ae348aeb5660fc2140aec35850c4da997"
token_cache = {}
# Prepopulate the token cache
cached_token = test_case.pop("cachedToken", None)
if cached_token:
token_cache[cache_key] = cached_token
mock_session = _create_mock_session(config)
mock_sso_oidc = mock.Mock()
mock_session.create_client.return_value = mock_sso_oidc
refresh_response = test_case.pop("refreshResponse", None)
mock_sso_oidc.create_token.return_value = refresh_response
current_time = dateutil.parser.parse(test_case.pop("currentTime"))
def _time_fetcher():
return current_time
resolver = SSOTokenProvider(
mock_session,
token_cache,
time_fetcher=_time_fetcher,
)
auth_token = resolver.load_token()
actual_exception = None
try:
actual_token = auth_token.get_frozen_token()
except Exception as e:
actual_exception = e
expected_exception = test_case.pop("expectedException", None)
if expected_exception is not None:
assert isinstance(actual_exception, expected_exception)
elif actual_exception is not None:
raise actual_exception
expected_token = test_case.pop("expectedToken", {})
raw_token = expected_token.get("token")
if raw_token is not None:
assert actual_token.token == raw_token
raw_expiration = expected_token.get("expiration")
if raw_expiration is not None:
expected_expiration = dateutil.parser.parse(raw_expiration)
assert actual_token.expiration == expected_expiration
expected_token_write_back = test_case.pop("expectedTokenWriteback", None)
if expected_token_write_back:
mock_sso_oidc.create_token.assert_called_with(
grantType="refresh_token",
clientId=cached_token["clientId"],
clientSecret=cached_token["clientSecret"],
refreshToken=cached_token["refreshToken"],
)
raw_expiration = expected_token_write_back["expiresAt"]
# The in-memory cache doesn't serialize to JSON so expect a datetime
expected_expiration = dateutil.parser.parse(raw_expiration)
expected_token_write_back["expiresAt"] = expected_expiration
assert expected_token_write_back == token_cache[cache_key]
# Pop the documentation to ensure all test fields are handled
test_case.pop("documentation")
assert not test_case.keys(), "All fields of test case should be handled"
|