Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Integration][Jira] Added support for oauth2 for live events #1429

Merged
merged 3 commits into from
Feb 24, 2025

Conversation

matan84
Copy link
Member

@matan84 matan84 commented Feb 24, 2025

User description

Description

What - Added support for live events using OAuth2 bearer token for authentication

Why - Enabling oauth flow for creating integrations including live events

How - Adding a new flow for creating webhooks using the REST API v3 of Jira for creating dynamic webhooks

Type of change

Please leave one option from the following and delete the rest:

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • New Integration (non-breaking change which adds a new integration)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Non-breaking change (fix of existing functionality that will not change current behavior)
  • Documentation (added/updated documentation)

All tests should be run against the port production environment(using a testing org).

Core testing checklist

  • Integration able to create all default resources from scratch
  • Resync finishes successfully
  • Resync able to create entities
  • Resync able to update entities
  • Resync able to detect and delete entities
  • Scheduled resync able to abort existing resync and start a new one
  • Tested with at least 2 integrations from scratch
  • Tested with Kafka and Polling event listeners
  • Tested deletion of entities that don't pass the selector

Integration testing checklist

  • Integration able to create all default resources from scratch
  • Resync able to create entities
  • Resync able to update entities
  • Resync able to detect and delete entities
  • Resync finishes successfully
  • If new resource kind is added or updated in the integration, add example raw data, mapping and expected result to the examples folder in the integration directory.
  • If resource kind is updated, run the integration with the example data and check if the expected result is achieved
  • If new resource kind is added or updated, validate that live-events for that resource are working as expected
  • Docs PR link here

Preflight checklist

  • Handled rate limiting
  • Handled pagination
  • Implemented the code in async
  • Support Multi account

Screenshots

Include screenshots from your environment showing how the resources of the integration will look.

API Documentation

Provide links to the API documentation used for this integration.


PR Type

Enhancement, Tests


Description

  • Added OAuth2 support for Jira live events using webhooks.

  • Refactored webhook creation logic for OAuth and non-OAuth hosts.

  • Updated tests to validate new webhook creation flow.

  • Incremented version and updated changelog for release.


Changes walkthrough 📝

Relevant files
Enhancement
client.py
Add OAuth2 webhook creation and refactor logic                     

integrations/jira/jira/client.py

  • Added OAuth2-specific webhook creation logic.
  • Introduced is_oauth_host method to determine host type.
  • Refactored webhook creation into separate methods for OAuth and
    non-OAuth.
  • Updated request authentication handling for OAuth hosts.
  • +51/-10 
    main.py
    Update webhook setup to use new method                                     

    integrations/jira/main.py

    • Updated to use the new create_webhooks method.
    +1/-1     
    Tests
    test_client.py
    Update tests for new webhook creation logic                           

    integrations/jira/tests/test_client.py

  • Updated tests to use create_webhooks instead of create_events_webhook.
  • Verified OAuth and non-OAuth webhook creation flows.
  • +2/-2     
    Documentation
    CHANGELOG.md
    Update changelog for OAuth live events support                     

    integrations/jira/CHANGELOG.md

  • Documented addition of OAuth live events support.
  • Added version 0.3.2 release notes.
  • +9/-0     
    Configuration changes
    pyproject.toml
    Bump version to 0.3.2                                                                       

    integrations/jira/pyproject.toml

    • Incremented version to 0.3.2.
    +1/-1     

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • @matan84 matan84 requested a review from a team as a code owner February 24, 2025 14:44
    Copy link
    Contributor

    Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account here.

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Webhook Validation

    The webhook creation for OAuth2 doesn't validate the response status code or handle potential errors when creating the webhook. Consider adding error handling and response validation.

    async def _create_events_webhook_oauth(self, app_host: str) -> None:
        webhook_target_app_host = f"{app_host}/integration/webhook"
        webhooks = (await self._send_api_request("GET", url=self.webhooks_url))[
            "values"
        ]
    
        if webhooks:
            logger.info("Ocean real time reporting webhook already exists")
            return
    
        # We search a random project to get data from all projects
        random_project = str(uuid.uuid4())
    
        body = {
            "url": webhook_target_app_host,
            "webhooks": [
                {
                    "jqlFilter": f"project not in ({random_project})",
                    "events": OAUTH2_WEBHOOK_EVENTS,
                }
            ],
        }
    
        await self._send_api_request("POST", self.webhooks_url, json=body)
        logger.info("Ocean real time reporting webhook created")
    Hardcoded Filter

    The JQL filter uses a random UUID to exclude a non-existent project. Consider using a more robust approach or documenting why this specific implementation was chosen.

    "jqlFilter": f"project not in ({random_project})",

    Copy link
    Contributor

    qodo-merge-pro bot commented Feb 24, 2025

    Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account here.

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Security
    Validate webhook URL parameter

    Validate the app_host URL parameter to ensure it's a valid URL before using it
    in webhook creation to prevent potential security issues.

    integrations/jira/jira/client.py [210-214]

     async def create_webhooks(self, app_host: str) -> None:
    +    if not app_host or not app_host.startswith(('http://', 'https://')):
    +        raise ValueError("Invalid app_host URL provided")
         if self.is_oauth_host():
             await self._create_events_webhook_oauth(app_host)
         else:
             await self._create_events_webhook(app_host)
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    __

    Why: Input validation for URLs is crucial for security. The suggestion adds important checks to prevent potential security vulnerabilities from malformed or malicious URLs before they're used in API calls.

    Medium
    Possible issue
    Add error handling for webhooks

    Add error handling for webhook creation to handle potential API failures
    gracefully and ensure the application doesn't crash if webhook registration
    fails.

    integrations/jira/jira/client.py [184-208]

     async def _create_events_webhook_oauth(self, app_host: str) -> None:
         webhook_target_app_host = f"{app_host}/integration/webhook"
    -    webhooks = (await self._send_api_request("GET", url=self.webhooks_url))[
    -        "values"
    -    ]
    +    try:
    +        webhooks = (await self._send_api_request("GET", url=self.webhooks_url))[
    +            "values"
    +        ]
     
    -    if webhooks:
    -        logger.info("Ocean real time reporting webhook already exists")
    -        return
    +        if webhooks:
    +            logger.info("Ocean real time reporting webhook already exists")
    +            return
     
    -    # We search a random project to get data from all projects
    -    random_project = str(uuid.uuid4())
    +        # We search a random project to get data from all projects
    +        random_project = str(uuid.uuid4())
     
    -    body = {
    -        "url": webhook_target_app_host,
    -        "webhooks": [
    -            {
    -                "jqlFilter": f"project not in ({random_project})",
    -                "events": OAUTH2_WEBHOOK_EVENTS,
    -            }
    -        ],
    -    }
    +        body = {
    +            "url": webhook_target_app_host,
    +            "webhooks": [
    +                {
    +                    "jqlFilter": f"project not in ({random_project})",
    +                    "events": OAUTH2_WEBHOOK_EVENTS,
    +                }
    +            ],
    +        }
     
    -    await self._send_api_request("POST", self.webhooks_url, json=body)
    -    logger.info("Ocean real time reporting webhook created")
    +        await self._send_api_request("POST", self.webhooks_url, json=body)
    +        logger.info("Ocean real time reporting webhook created")
    +    except Exception as e:
    +        logger.error(f"Failed to create webhook: {str(e)}")
    +        raise
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    __

    Why: Adding error handling with logging for webhook creation is important for production reliability and debugging. The suggestion properly wraps the webhook creation logic in a try-except block while maintaining the original functionality.

    Medium
    • Update

    Copy link

    This pull request is automatically being deployed by Amplify Hosting (learn more).

    Access this pull request here: https://pr-1429.d1ftd8v2gowp8w.amplifyapp.com

    @matan84 matan84 merged commit ace9a32 into main Feb 24, 2025
    19 checks passed
    @matan84 matan84 deleted the fixed-jira-live-events-for-oauth branch February 24, 2025 15:05
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants