Skip to content

Commit

Permalink
[MicrosoftApiModule] Auth code reconfigurations (demisto#29035)
Browse files Browse the repository at this point in the history
* Auth code reconfigurations

* Update RN

* Reduced use of get_integration_context()

* Add docs to the unit test

* Add docs to the function

* Bump pack from version MicrosoftGraphTeams to 1.0.11.

---------

Co-authored-by: Content Bot <bot@demisto.com>
  • Loading branch information
2 people authored and xsoar-bot committed Oct 5, 2023
1 parent 50b406e commit 42e0c19
Show file tree
Hide file tree
Showing 68 changed files with 331 additions and 37 deletions.
34 changes: 32 additions & 2 deletions Packs/ApiModules/Scripts/MicrosoftApiModule/MicrosoftApiModule.py
Expand Up @@ -735,6 +735,8 @@ def __init__(self, tenant_id: str = '',
self.resources = resources if resources else []
self.resource_to_access_token: dict[str, str] = {}

self.auth_code_reconfigured = False

# for Azure Managed Identities purpose
self.managed_identities_client_id = managed_identities_client_id
self.managed_identities_resource_uri = managed_identities_resource_uri
Expand Down Expand Up @@ -867,7 +869,11 @@ def get_access_token(self, resource: str = '', scope: str | None = None) -> str:

valid_until = integration_context.get(valid_until_keyword)

if access_token and valid_until and self.epoch_seconds() < valid_until:
self.auth_code_reconfigured = self.is_auth_code_reconfigured(integration_context.get('auth_code', ''))
if self.auth_code_reconfigured:
demisto.debug("Auth code reconfigured, saving new auth code to integration context")
integration_context['auth_code'] = self.auth_code
elif access_token and valid_until and self.epoch_seconds() < valid_until:
return access_token

if self.auth_type == OPROXY_AUTH_TYPE:
Expand Down Expand Up @@ -904,6 +910,7 @@ def get_access_token(self, resource: str = '', scope: str | None = None) -> str:
integration_context.update(self.resource_to_access_token)

set_integration_context(integration_context)
demisto.debug('Set integration context successfully.')

if self.multi_resource:
return self.resource_to_access_token[resource]
Expand Down Expand Up @@ -1100,7 +1107,7 @@ def _get_self_deployed_token_auth_code(
data['scope'] = scope

refresh_token = refresh_token or self._get_refresh_token_from_auth_code_param()
if refresh_token:
if refresh_token and not self.auth_code_reconfigured:
data['grant_type'] = REFRESH_TOKEN
data['refresh_token'] = refresh_token
else:
Expand Down Expand Up @@ -1386,6 +1393,29 @@ def start_auth(self, complete_command: str) -> str:
and enter the code **{user_code}** to authenticate.
2. Run the **{complete_command}** command in the War Room."""

def is_auth_code_reconfigured(self, auth_code) -> bool:
"""
Checks if the auth_code is reconfigured by comparing to the self.auth_code from the instance params.
Args:
auth_code: The auth_code form the integration context.
Returns:
bool: True if the auth_code is reconfigured, otherwise False.
"""
# Case of oproxy
if self.auth_type == OPROXY_AUTH_TYPE:
return False
# Case of the next times or after reconfigured the auth_code
if auth_code and self.auth_code:
is_reconfigured = auth_code != self.auth_code
demisto.debug(f'Auth code is reconfigured: {is_reconfigured}')
return is_reconfigured
# Case of the first time or after deleting the auth_code
elif auth_code or self.auth_code:
demisto.debug('Auth code is only in ' + ('integration_context' if auth_code else 'params'))
return True
else:
return False


class NotFoundError(Exception):
"""Exception raised for 404 - Not Found errors.
Expand Down
Expand Up @@ -18,6 +18,8 @@
CLIENT_ID = 'dummy_client'
CLIENT_SECRET = 'dummy_secret'
APP_URL = 'https://login.microsoftonline.com/dummy_tenant/oauth2/v2.0/token'
AUTH_CODE = 'dummy_auth_code'
REDIRECT_URI = 'https://localhost/myapp'
SCOPE = 'https://graph.microsoft.com/.default'
RESOURCE = 'https://defender.windows.com/shtak'
RESOURCES = ['https://resource1.com', 'https://resource2.com']
Expand Down Expand Up @@ -62,15 +64,17 @@ def oproxy_client_refresh():
)


def self_deployed_client():
def self_deployed_client(grant_type=CLIENT_CREDENTIALS):
tenant_id = TENANT
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
base_url = BASE_URL
auth_code = AUTH_CODE if grant_type == AUTHORIZATION_CODE else ''
resource = RESOURCE
ok_codes = OK_CODES

return MicrosoftClient(self_deployed=True, tenant_id=tenant_id, auth_id=client_id, enc_key=client_secret,
grant_type=grant_type, auth_code=auth_code,
resource=resource, base_url=base_url, verify=True, proxy=False, ok_codes=ok_codes)


Expand Down Expand Up @@ -717,11 +721,57 @@ def test_generate_login_url():
"""
from MicrosoftApiModule import generate_login_url

client = self_deployed_client()
client = self_deployed_client(grant_type=AUTHORIZATION_CODE)

result = generate_login_url(client)

expected_url = f'[login URL](https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/authorize?' \
f'response_type=code&scope=offline_access%20https://graph.microsoft.com/.default' \
f'&client_id={CLIENT_ID}&redirect_uri=https://localhost/myapp)'
assert expected_url in result.readable_output, "Login URL is incorrect"


def test_get_access_token_auth_code_reconfigured(mocker, requests_mock):
"""
Given:
- The auth code was reconfigured
When:
- Calling function get_access_token
Then:
- Ensure the access token is as expected in the body of the request and in the integration context
"""
context = {'auth_code': AUTH_CODE, 'access_token': TOKEN,
'valid_until': 3605, 'current_refresh_token': REFRESH_TOKEN}

mocker.patch.object(demisto, 'getIntegrationContext', return_value=context)
mocker.patch.object(demisto, 'setIntegrationContext')

tenant_id = TENANT
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
base_url = BASE_URL
new_auth_code = 'reconfigured_auth_code'
resource = None
ok_codes = OK_CODES
grant_type = AUTHORIZATION_CODE

client = MicrosoftClient(self_deployed=True, tenant_id=tenant_id, auth_id=client_id, enc_key=client_secret,
grant_type=grant_type, auth_code=new_auth_code,
resource=resource, base_url=base_url, verify=True, proxy=False, ok_codes=ok_codes)

requests_mock.post(
APP_URL,
json={'access_token': TOKEN, 'expires_in': '3600'})

body = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': AUTHORIZATION_CODE,
'code': new_auth_code,
}

assert client.get_access_token()
req_body = requests_mock._adapter.last_request._request.body
assert urllib.parse.urlencode(body) == req_body
assert demisto.getIntegrationContext().get('auth_code') == new_auth_code
6 changes: 6 additions & 0 deletions Packs/AzureActiveDirectory/ReleaseNotes/1_3_16.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Active Directory Identity Protection (Deprecated)

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureActiveDirectory/pack_metadata.json
Expand Up @@ -3,7 +3,7 @@
"description": "Deprecated. Use Microsoft Graph Identity and Access instead.",
"support": "xsoar",
"hidden": true,
"currentVersion": "1.3.15",
"currentVersion": "1.3.16",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureCompute/ReleaseNotes/1_2_13.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Compute v2

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureCompute/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Compute",
"description": "Create and Manage Azure Virtual Machines",
"support": "xsoar",
"currentVersion": "1.2.12",
"currentVersion": "1.2.13",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureDataExplorer/ReleaseNotes/1_2_25.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Data Explorer

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureDataExplorer/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Data Explorer",
"description": "Use Azure Data Explorer integration to collect and analyze data inside clusters of Azure Data Explorer and manage search queries.",
"support": "xsoar",
"currentVersion": "1.2.24",
"currentVersion": "1.2.25",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureDevOps/ReleaseNotes/1_2_17.md
@@ -0,0 +1,6 @@

#### Integrations

##### AzureDevOps

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureDevOps/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "AzureDevOps",
"description": "Create and manage Git repositories in Azure DevOps Services.",
"support": "xsoar",
"currentVersion": "1.2.16",
"currentVersion": "1.2.17",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureFirewall/ReleaseNotes/1_1_25.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Firewall

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureFirewall/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Firewall",
"description": "Azure Firewall is a cloud-native and intelligent network firewall security service that provides breed threat protection for cloud workloads running in Azure.It's a fully stateful, firewall as a service with built-in high availability and unrestricted cloud scalability.",
"support": "xsoar",
"currentVersion": "1.1.24",
"currentVersion": "1.1.25",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureKeyVault/ReleaseNotes/1_1_26.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Key Vault

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureKeyVault/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Key Vault",
"description": "Use Key Vault to safeguard and manage cryptographic keys and secrets used by cloud applications and services.",
"support": "xsoar",
"currentVersion": "1.1.25",
"currentVersion": "1.1.26",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureKubernetesServices/ReleaseNotes/1_1_18.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Kubernetes Services

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureKubernetesServices/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Kubernetes Services",
"description": "Deploy and manage containerized applications with a fully managed Kubernetes service.",
"support": "xsoar",
"currentVersion": "1.1.17",
"currentVersion": "1.1.18",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureLogAnalytics/ReleaseNotes/1_1_16.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Log Analytics

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureLogAnalytics/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Log Analytics",
"description": "Log Analytics is a service that helps you collect and analyze data generated by resources in your cloud and on-premises environments.",
"support": "xsoar",
"currentVersion": "1.1.15",
"currentVersion": "1.1.16",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureNetworkSecurityGroups/ReleaseNotes/1_2_18.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Network Security Groups

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureNetworkSecurityGroups/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Network Security Groups",
"description": "Azure Network Security Groups are used to filter network traffic to and from Azure resources in an Azure virtual network",
"support": "xsoar",
"currentVersion": "1.2.17",
"currentVersion": "1.2.18",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureRiskyUsers/ReleaseNotes/1_1_16.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Risky Users

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureRiskyUsers/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Risky Users",
"description": "Azure Risky Users provides access to all at-risk users and risk detections in Azure AD environment.",
"support": "xsoar",
"currentVersion": "1.1.15",
"currentVersion": "1.1.16",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureSQLManagement/ReleaseNotes/1_1_27.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure SQL Management

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureSQLManagement/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure SQL Management",
"description": "Microsoft Azure SQL Database is a managed cloud database provided as part of Microsoft Azure",
"support": "xsoar",
"currentVersion": "1.1.26",
"currentVersion": "1.1.27",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
10 changes: 10 additions & 0 deletions Packs/AzureSecurityCenter/ReleaseNotes/2_0_8.md
@@ -0,0 +1,10 @@

#### Integrations

##### Microsoft Defender for Cloud

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.

##### Microsoft Defender for Cloud Event Collector

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureSecurityCenter/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Microsoft Defender for Cloud",
"description": "Unified security management and advanced threat protection across hybrid cloud workloads.",
"support": "xsoar",
"currentVersion": "2.0.7",
"currentVersion": "2.0.8",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureSentinel/ReleaseNotes/1_5_18.md
@@ -0,0 +1,6 @@

#### Integrations

##### Microsoft Sentinel

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureSentinel/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Microsoft Sentinel",
"description": "Microsoft Sentinel is a cloud-native security information and event manager (SIEM) platform that uses built-in AI to help analyze large volumes of data across an enterprise.",
"support": "xsoar",
"currentVersion": "1.5.17",
"currentVersion": "1.5.18",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureStorage/ReleaseNotes/1_2_18.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Storage Management

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureStorage/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure Storage Management",
"description": "Deploy and manage storage accounts and blob service properties.",
"support": "xsoar",
"currentVersion": "1.2.17",
"currentVersion": "1.2.18",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
6 changes: 6 additions & 0 deletions Packs/AzureWAF/ReleaseNotes/1_1_16.md
@@ -0,0 +1,6 @@

#### Integrations

##### Azure Web Application Firewall

Fixed an issue where changes made to the *Authorization code* parameter were not being reflected in the integration code, resulting in the continued use of the first parameter.
2 changes: 1 addition & 1 deletion Packs/AzureWAF/pack_metadata.json
Expand Up @@ -2,7 +2,7 @@
"name": "Azure WAF",
"description": "Azure Web Application Firewall is used to detect web related attacks targeting your web servers hosted in azure and allow quick respond to threats",
"support": "xsoar",
"currentVersion": "1.1.15",
"currentVersion": "1.1.16",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down

0 comments on commit 42e0c19

Please sign in to comment.