def test_input_validation_invalid_token(self): ''' input validation: invalid token ''' with self.assertRaises(ValueError) as ctx: xssec.create_security_context('invalid', uaa_configs.VALID['uaa']) self.assertEqual( 'Failed to decode provided token', str(ctx.exception))
def test_invalid_signature_end_user_token(self): ''' Test invalid signature end-user token ''' with self.assertRaises(RuntimeError) as ctx: xssec.create_security_context( jwt_tokens.INVALID_SIGNATURE_END_USER_TOKEN, uaa_configs.VALID['uaa']) self.assertTrue( 'Error in offline validation of access token:' in str(ctx.exception))
def test_token_with_ext_cxt_invalid_validation_key(self): ''' valid user token with "ext_cxt" property, invalid validation key ''' with self.assertRaises(RuntimeError) as ctx: xssec.create_security_context( jwt_tokens.TOKEN_NEW_FORMAT, uaa_configs.INVALID['uaa_verificationkey_invalid']) self.assertTrue( 'Error in offline validation of access token:' in str(ctx.exception))
def test_expired_end_user_token(self): ''' Test expired end-user token ''' with self.assertRaises(RuntimeError) as ctx: xssec.create_security_context( sign(jwt_payloads.USER_TOKEN_EXPIRED), uaa_configs.VALID['uaa']) self.assertTrue('Error in offline validation of access token:' in str( ctx.exception) and 'expired' in str(ctx.exception))
def _check_token_in_foreign_mode_error(self, cid, idz, uaa_config_name): environ['SAP_JWT_TRUST_ACL'] = json.dumps([{ 'clientid': cid, 'identityzone': idz }]) with self.assertRaises(RuntimeError) as ctx: xssec.create_security_context( jwt_tokens.CORRECT_END_USER_TOKEN_NO_ATTR, uaa_configs.VALID[uaa_config_name]) self.assertTrue(str(ctx.exception).startswith( 'No match found in JWT trust ACL (SAP_JWT_TRUST_ACL)'))
def test_invalid_jku_in_token_header(self): uaa_config = uaa_configs.VALID['uaa'] header = get_unverified_header(jwt_tokens.CORRECT_END_USER_TOKEN) header['jku'] = 'http://ana.ondemandh.com\\\\\\\\\\\\\\\\@' + uaa_config['uaadomain'] token_parts = jwt_tokens.CORRECT_END_USER_TOKEN.split(".") token_parts[0] = base64url_encode(json.dumps(header).encode('utf-8')).decode() token = '.'.join(token_parts) with self.assertRaises(RuntimeError) as e: xssec.create_security_context(token, uaa_config) self.assertEqual("JKU of token is not trusted", str(e.exception),)
def test_invalid_signature_end_user_token(self): ''' Test invalid signature end-user token ''' token_parts = sign(jwt_payloads.USER_TOKEN).split('.') token_parts[2] = 'aW52YWxpZAo' invalid_token = '.'.join(token_parts) with self.assertRaises(RuntimeError) as ctx: xssec.create_security_context(invalid_token, uaa_configs.VALID['uaa']) self.assertTrue('Error in offline validation of access token:' in str( ctx.exception))
def test_not_trusted_jku(self): with self.assertRaises(RuntimeError) as e: xssec.create_security_context( sign(jwt_payloads.USER_TOKEN), uaa_configs.VALID['uaa_no_verification_key_other_domain']) self.assertEqual( "JKU of token is not trusted", str(e.exception), )
def test_valid_client_credentials_broker_plan_token_with_wrong_trustedclientidsuffix(self): ''' valid client credentials broker plan token with wrong trustedclientidsuffix ''' with self.assertRaises(RuntimeError) as ctx: xssec.create_security_context( jwt_tokens.CORRECT_CLIENT_CREDENTIALS_BROKER_PLAN_TOKEN, uaa_configs.INVALID['uaa_broker_plan_wrong_suffix']) self.assertEqual( 'Missmatch of client id and/or identityzone id. No JWT trust ACL (SAP_JWT_TRUST_ACL) specified in environment. ' 'Client id of the access token: "sb-xssectestclone!b4|sb-xssectest!b4", identity zone of the access token: ' '"test-idz", OAuth client id: "sb-xssectest!t4", application identity zone: "test-idz".' , str(ctx.exception))
def test_invalid_application_plan_with_trustedclientidsuffix(self): ''' invalid application plan with SAP_JWT_TRUST_ACL ''' environ['SAP_JWT_TRUST_ACL'] = json.dumps([{ 'clientid': 'wrong-tenant', 'identityzone': 'api' }]) with self.assertRaises(RuntimeError) as ctx: xssec.create_security_context( sign(jwt_payloads.INVALID_TRUSTED_APPLICATION_PLAN_TOKEN), uaa_configs.INVALID['uaa_broker_plan_wrong_suffix']) self.assertTrue( str(ctx.exception).startswith( 'No match found in JWT trust ACL (SAP_JWT_TRUST_ACL)'))
def test_invalid_jku_in_token_header(self): uaa_config = uaa_configs.VALID['uaa'] token = sign(jwt_payloads.USER_TOKEN, headers={ "jku": 'http://ana.ondemandh.com\\\\\\\\\\\\\\\\@' + uaa_config['uaadomain'], "kid": "key-id-0" }) with self.assertRaises(RuntimeError) as e: xssec.create_security_context(token, uaa_config) self.assertEqual( "JKU of token is not trusted", str(e.exception), )
def test_message(message): print("test_message: " + str(message)) # https://github.com/SAP/cloud-pysec/wiki Docs uaa_service = env.get_service(label='xsuaa').credentials access_token = request.headers.get('authorization')[7:] #print("access_token: " + str(access_token)) security_context = xssec.create_security_context(access_token, uaa_service) print("security_context: " + str(security_context)) isAuthorized = security_context.check_scope('openid') if isAuthorized: print("Authorized") print('get_logon_name: ' + security_context.get_logon_name()) print('get_given_name: ' + security_context.get_given_name()) print('get_family_name: ' + security_context.get_family_name()) print('get_email: ' + security_context.get_email()) print('get_origin: ' + security_context.get_origin()) print('get_subdomain: ' + security_context.get_subdomain()) print('get_subaccount_id: ' + security_context.get_subaccount_id()) else: print("Unauthorized") session['receive_count'] = session.get('receive_count', 0) + 1 emit('my_response', { 'data': message['data'], 'count': session['receive_count'] })
def auth_check(): output = 'Python Authorized DB Validated Request. \n' output += '\n' output += 'Receiving module should check that it came from our approuter and verify or abort if otherwise.\n' output += '\n' svcs_json = str(os.getenv("VCAP_SERVICES", 0)) svcs = json.loads(svcs_json) uaa_service = env.get_service(label='xsuaa').credentials access_token = request.headers.get('authorization')[7:] security_context = xssec.create_security_context(access_token, uaa_service) isAuthorized = security_context.check_scope('openid') if not isAuthorized: abort(403) output += 'get_logon_name: ' + security_context.get_logon_name() + '\n' # output += 'get_given_name: ' + security_context.get_given_name() + '\n' # output += 'get_family_name: ' + security_context.get_family_name() + '\n' output += 'get_email: ' + security_context.get_email() + '\n' output += 'get_subdomain: ' + security_context.get_subdomain() + '\n' # output += 'get_clientid: ' + security_context.get_clientid() + '\n' output += 'get_identity_zone: ' + security_context.get_identity_zone( ) + '\n' output += 'get_grant_type: ' + security_context.get_grant_type() + '\n' return output
def test_valid_end_user_token_no_attr(self): ''' Test valid end-user token no attributes ''' sec_context = xssec.create_security_context( jwt_tokens.CORRECT_END_USER_TOKEN_NO_ATTR, uaa_configs.VALID['uaa']) self._check_user_token(sec_context) self.assertFalse(sec_context.has_attributes()) self.assertIsNone(sec_context.get_clone_service_instance_id())
def domath(): logger = logging.getLogger('route.logger') logger.info('Someone accessed us') average = 0 jokecount = 0 if 'authorization' not in request.headers: abort(403) access_token = request.headers.get('authorization')[7:] security_context = xssec.create_security_context(access_token, uaa_service) isAuthorized = security_context.check_scope('$XSAPPNAME.access') if not isAuthorized: abort(403) logger.info('Authorization successful') conn = dbapi.connect(address=hana.credentials['host'], port=int(hana.credentials['port']), user=hana.credentials['user'], password=hana.credentials['password'],CURRENTSCHEMA=hana.credentials['schema']) cursor = conn.cursor() try: cursor.execute("SELECT REVIEW FROM DB_JOKES") result = [i[0] for i in cursor.fetchall()] average = round(s.mean(result),1) jokecount = len(result) cursor.close() conn.close() return jsonify(reviews=average,resultcount=jokecount) except: logger.error('DB read error') return jsonify(reviews=0,resultcount=0)
def test_valid_xsa_token_with_newlines(self): ''' valid client credentials token (with attributes) ''' sec_context = xssec.create_security_context( jwt_tokens.TOKEN_XSA_FORMAT, uaa_configs.VALID['uaa_xsa_with_newlines']) self.assertEqual( sec_context.get_logon_name(), 'ADMIN')
def test_get_token_with_invalid_parameters(self): ''' valid user token with "ext_cxt" property ''' sec_context = xssec.create_security_context( jwt_tokens.TOKEN_NEW_FORMAT, uaa_configs.VALID['uaa_new_token_structure']) self._check_hdb_token(sec_context) self.assertIsNone(sec_context.get_token('invalid', xssec.constants.JOBSCHEDULER)) self.assertIsNone(sec_context.get_token(xssec.constants.SYSTEM, 'invalid'))
def test_valid_client_credentials_token_no_attributes(self): ''' valid client credentials token (no attributes) ''' sec_context = xssec.create_security_context( jwt_tokens.CORRECT_CLIENT_CREDENTIALS_TOKEN_NO_ATTR, uaa_configs.VALID['uaa_cc']) self._check_client_credentials_token(sec_context) self.assertIsNone( sec_context.get_additional_auth_attribute('external_group'))
def test_valid_end_user_token_with_ext_attr(self): ''' Test valid end-user token (given_name/family_name in ext_attr) ''' sec_context = xssec.create_security_context( jwt_tokens.CORRECT_END_USER_TOKEN_NAMES_IN_EXT_ATTR, uaa_configs.VALID['uaa']) self.assertEqual( sec_context.get_given_name(), 'NodetestFirstNameExtAttr') self.assertEqual( sec_context.get_family_name(), 'NodetestLastNameExtAttr')
def test_req_client_for_user_401_error(self): sec_context = xssec.create_security_context( sign(jwt_payloads.USER_TOKEN_SCOPE_UAA_USER), uaa_configs.VALID['uaa']) expected_message = \ 'Bearer token invalid, requesting client does'\ ' not have grant_type=user_token or no scopes were granted.' self._request_token_for_client_error( sec_context, flask_url + '/401', expected_message)
def test_token_with_ext_cxt(self): ''' valid user token with "ext_cxt" property ''' sec_context = xssec.create_security_context( jwt_tokens.TOKEN_NEW_FORMAT, uaa_configs.VALID['uaa_new_token_structure']) self._check_hdb_token(sec_context) jobsheduler_token = sec_context.get_token( xssec.constants.SYSTEM, xssec.constants.JOBSCHEDULER) self.assertEqual(jobsheduler_token, jwt_tokens.TOKEN_NEW_FORMAT) self.assertNotEqual(sec_context.get_hdb_token(), jobsheduler_token)
def test_valid_client_credentials_token_attributes(self): ''' valid client credentials token (with attributes) ''' sec_context = xssec.create_security_context( jwt_tokens.CORRECT_CLIENT_CREDENTIALS_TOKEN, uaa_configs.VALID['uaa_cc']) self._check_client_credentials_token(sec_context) self.assertEqual( sec_context.get_additional_auth_attribute('external_group'), 'domaingroup1') self.assertEqual( sec_context.get_clone_service_instance_id(), 'abcd1234')
def validatejwt(encodedJwtToken): """JWT offline validation""" xs_security = getattr(g, '_sap_xssec', None) if xs_security is None: xs_security = xssec.create_security_context(encodedJwtToken, g._uaaCredentials) if xs_security.get_grant_type is None: return False g._sap_xssec = xs_security return True
def test_request_token_for_client_missing_uaa_user_scope(self): ''' Test valid end-user token no attributes. request_token_for_client failure, scope uaa.user missing ''' sec_context = xssec.create_security_context( sign(jwt_payloads.USER_TOKEN_NO_ATTR), uaa_configs.VALID['uaa']) self._request_token_for_client_error( sec_context, flask_url + '/500', 'JWT token does not include scope "uaa.user"')
def test_req_client_for_user(self): sec_context = xssec.create_security_context( sign(jwt_payloads.USER_TOKEN_SCOPE_UAA_USER), uaa_configs.VALID['uaa']) service_credentials = { 'clientid': 'clientid', 'clientsecret': 'clientsecret', 'url': flask_url + '/correct' } token = sec_context.request_token_for_client(service_credentials, None) self.assertEqual(token, 'access_token')
def test_valid_end_user_token_in_foreign_mode_idz(self): ''' valid end-user token in foreign mode (idz - correct SAP_JWT_TRUST_ACL) ''' environ['SAP_JWT_TRUST_ACL'] = '[{"clientid":"sb-xssectest","identityzone":"test-idz"}]' sec_context = xssec.create_security_context( jwt_tokens.CORRECT_END_USER_TOKEN, uaa_configs.VALID['uaa_foreign_idz']) self.assertTrue(sec_context.is_in_foreign_mode()) self.assertEqual( sec_context.get_additional_auth_attribute('external_group'), 'domaingroup1') self.assertIsNone(sec_context.get_additional_auth_attribute('hugo')) self.assertIsNone(sec_context.get_hdb_token()) self.assertIsNotNone(sec_context.get_app_token())
def test_valid_end_user_token_with_attr(self): ''' Test valid end-user token with attributes ''' sec_context = xssec.create_security_context( jwt_tokens.CORRECT_END_USER_TOKEN, uaa_configs.VALID['uaa']) self._check_user_token(sec_context) self.assertTrue(sec_context.has_attributes()) self.assertEqual(sec_context.get_attribute('country'), ['USA']) self.assertEqual( sec_context.get_clone_service_instance_id(), 'abcd1234') self.assertEqual( sec_context.get_additional_auth_attribute('external_group'), 'domaingroup1')
def checkAuth(header): if 'authorization' not in request.headers: return False access_token = header.get('authorization')[7:] security_context = xssec.create_security_context(access_token, uaa_service) isAuthorized = security_context.check_scope( 'openid') or security_context.check_scope('uaa.resource') if not isAuthorized: return False return True
def test_valid_application_plan_with_trustedclientidsuffix(self): ''' valid application plan with shared tenant mode, defined via SAP_JWT_TRUST_ACL ''' environ['SAP_JWT_TRUST_ACL'] = json.dumps([{ 'clientid': '*', 'identityzone': '*' }]) sec_context = xssec.create_security_context( jwt_tokens.INVALID_TRUSTED_APPLICATION_PLAN_TOKEN, uaa_configs.INVALID['uaa_broker_plan_wrong_suffix']) self.assertEqual('sb-tenant-test!t13',sec_context.get_clientid()) self.assertEqual('api', sec_context.get_identity_zone()) self.assertEqual('api', sec_context.get_zone_id())
def test_valid_end_user_saml_bearer_token(self): ''' valid end-user saml bearer token ''' sec_context = xssec.create_security_context( jwt_tokens.CORRECT_END_USER_SAML_BEARER_TOKEN, uaa_configs.VALID['uaa_bearer']) self.assertTrue(sec_context.check_scope('openid')) self._check_user_info(sec_context) self._check_hdb_token(sec_context) self.assertEqual(sec_context.get_grant_type(), xssec.constants.GRANTTYPE_SAML2BEARER) self.assertEqual(sec_context.get_identity_zone(), 'test-idz') self.assertEqual(sec_context.get_zone_id(), 'test-idz') self.assertEqual(sec_context.get_subaccount_id(), 'test-idz') self.assertIsNone(sec_context.get_subdomain()) self.assertFalse(sec_context.is_in_foreign_mode())