import json import re import urllib.parse from collections.abc import Callable from typing import Final import demistomock as demisto # noqa: F401 import requests import urllib3 from CommonServerPython import * # noqa: F401 from markdownify import markdownify MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB from CommonServerUserPython import * # noqa # Import AtlassianApiModule for OAuth support from AtlassianApiModule import * # type: ignore[import,assignment] # noqa: F401 # Disable insecure warnings urllib3.disable_warnings() # pylint: disable=no-member """ CONSTANTS """ DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" # ISO8601 format with UTC, default in XSOAR LOGGING_INTEGRATION_NAME = "[Atlassian Confluence Cloud]" HTTP_ERROR = { 401: "An error occurred while validating the credentials, please check the username or password.", 404: "The resource cannot be found.", 500: "The server encountered an internal error for Atlassian Confluence Cloud and was unable to complete your request.", } URL_SUFFIX = { "CONTENT_SEARCH": "/wiki/rest/api/content/search", "GROUP": "/wiki/rest/api/group", "CONTENT": "/wiki/rest/api/content", "USER": "/wiki/rest/api/search/user?cql=type=user", "SPACE": "/wiki/rest/api/space", "PRIVATE_SPACE": "/wiki/rest/api/space/_private", "EVENTS": "/wiki/rest/api/audit/", "BASE": "/wiki", "NEXT_LINK_TEMPLATE": "/rest/api/audit/?end_date={}&next=true&limit={}&start={}&startDate={}", } # Confluence Cloud REST API v2 (/wiki/api/v2) URL suffixes. URL_SUFFIX_V2 = { "PAGES": "/wiki/api/v2/pages", "BLOGPOSTS": "/wiki/api/v2/blogposts", "SPACES": "/wiki/api/v2/spaces", "FOOTER_COMMENTS": "/wiki/api/v2/footer-comments", } MESSAGES = { "REQUIRED_URL_FIELD": "Site Name can not be empty.", "NO_RECORDS_FOUND": "No {} were found for the given argument(s).", "LIMIT": "{} is an invalid value for limit. Limit must be between 0 and int32.", "START": "{} is an invalid value for start. Start must be between 0 and int32.", "INVALID_ACCESS_TYPE": "Invalid value for access type. Access type parameter must be one of 'user', 'admin', " "or 'site-admin' ", "REQUIRED_ARGUMENT": "Invalid argument value. {} is a required argument.", "INVALID_CONTENT_TYPE": "Invalid value for content type. Content type parameter can be 'page' or 'blogpost' ", "HR_DELETE_CONTENT": "Content with Id {} is deleted successfully.", "INVALID_STATUS": "Invalid value for status. Status must be one of 'current', 'draft' or 'trashed'.", "BAD_REQUEST": "Bad request: An error occurred while fetching the data.", "REQUIRED_SORT_KEY": "If 'sort_order' is specified, 'sort_key' is required.", "INVALID_STATUS_SEARCH": "Invalid value for status. Status must be one of 'current', 'any', 'archived', 'draft' " "or 'trashed'.", "INVALID_PERMISSION": "If the 'permission_account_id' or 'permission_group_name' arguments are given, " "the 'permission_operations' argument must also be given.", "INVALID_PERMISSIONS_OPERATION": "If the 'permission_operations' argument is given, " "'permission_account_id' or 'permission_group_name' argument must also be given.", "PERMISSION_FORMAT": "Please provide the permission in the valid JSON format. " "Format accepted - 'operation1:targetType1,operation2:targetType2'", "ADVANCE_PERMISSION_FORMAT": "Please provide the 'advanced_permissions' in the valid JSON format. ", "INVALID_ROLE_ASSIGNMENTS_V2": "Please provide the 'role_assignments' argument in valid JSON format.", "INVALID_SPACE_STATUS": "Invalid value for status. Status must be one of 'current' or 'archived'.", "INVALID_CONTENT_TYPE_UPDATE_CONTENT": "Invalid value for content type. Content type parameter can be 'page', " "'blogpost', 'comment' or 'attachment'.", "INVALID_BODY_REPRESENTATION": "Invalid value for body_representation. Body representation must be one of " "'editor', 'editor2' or 'storage'.", "INVALID_DELETION_TYPE": "Invalid value for deletion_type. Deletion type must be one of 'move to trash', " "'permanent delete' or 'permanent delete draft'.", "INVALID_TITLE_LENGTH": "Title cannot be longer than 255 characters.", "INVALID_SPACE_NAME_LENGTH": "Space name cannot be longer than 200 characters.", "INVALID_SPACE_KEY": "Space Key cannot be longer than 255 characters and should contain alphanumeric characters only.", "PRIVATE_SPACE_PERMISSION": "Permission can not be granted for a private space.", "MISSING_CONTENT_ID": "Argument 'content_id' is required for this command.", "INVALID_BODY_REPRESENTATION_V2": "Invalid value for body_representation. Body representation must be one of " "'storage', 'atlas_doc_format' or 'wiki'.", "INVALID_COMMENT_BODY_REPRESENTATION_V2": "Invalid value for body_representation. Body representation must be " "one of 'storage' or 'atlas_doc_format'.", "INVALID_BODY_FORMAT_V2": "Invalid value for body_format. Body format must be one of 'storage', " "'atlas_doc_format' or 'view'.", "INVALID_STATUS_CREATE_V2": "Invalid value for status. Status must be one of 'current' or 'draft'.", "INVALID_STATUS_UPDATE_V2": "Invalid value for status. Status must be one of 'current' or 'draft'.", "INVALID_PAGE_STATUS_LIST_V2": "Invalid value for status. Status must be one of 'current', 'archived', " "'deleted' or 'trashed'.", "INVALID_PAGE_STATUS_SINGLE_V2": "Invalid value for status. Status must be one of 'current', 'archived', " "'deleted', 'trashed', 'historical' or 'draft'.", "INVALID_BLOGPOST_STATUS_LIST_V2": "Invalid value for status. Status must be one of 'current', 'deleted' " "or 'trashed'.", "INVALID_BLOGPOST_STATUS_SINGLE_V2": "Invalid value for status. Status must be one of 'current', 'deleted', " "'trashed', 'historical' or 'draft'.", "INVALID_SUBTYPE_FILTER_V2": "Invalid value for subtype. Subtype must be one of 'page' or 'live'.", "MUTUALLY_EXCLUSIVE_PARENT_ROOT_LEVEL": "Arguments 'parent_id' and 'root_level' are mutually exclusive.", "MISSING_COMMENT_CONTAINER_V2": "One of the following arguments is required: 'page_id', 'blogpost_id', " "'parent_comment_id', 'attachment_id' or 'custom_content_id'.", "INVALID_SPACE_TYPE_V2": "Invalid value for type. Type must be one of 'global' or 'personal'.", "INVALID_SPACE_STATUS_V2": "Invalid value for status. Status must be one of 'current' or 'archived'.", "INVALID_DESCRIPTION_FORMAT_V2": "Invalid value for description_format. Description format must be one of " "'plain' or 'view'.", "INVALID_LIMIT_V2": "{} is an invalid value for limit. Limit must be a positive integer (greater than 0).", "HR_PAGE_CREATE": "Page with ID {} was created successfully.", "HR_PAGE_UPDATE": "Page with ID {} was updated successfully.", "HR_PAGE_DELETE": "Page with ID {} was deleted successfully.", "HR_BLOGPOST_CREATE": "Blog post with ID {} was created successfully.", "HR_BLOGPOST_UPDATE": "Blog post with ID {} was updated successfully.", "HR_BLOGPOST_DELETE": "Blog post with ID {} was deleted successfully.", "HR_FOOTER_COMMENT_CREATE": "Footer comment with ID {} was created successfully.", "HR_SPACE_CREATE_V2": "Space with ID {} was created successfully.", } OUTPUT_PREFIX = { "GROUP": "ConfluenceCloud.Group", "USER": "ConfluenceCloud.User", "CONTENT": "ConfluenceCloud.Content", "COMMENT": "ConfluenceCloud.Comment", "SPACE": "ConfluenceCloud.Space", "PAGETOKEN": "ConfluenceCloud.PageToken.Content", "EVENT": "ConfluenceCloud.Event", "PAGE": "ConfluenceCloud.Page", "BLOGPOST": "ConfluenceCloud.Blogpost", "FILE_CONTENT": "FileContent", } CONFLUENCE_URL_PATTERNS = [ # Pattern: /wiki/spaces//pages// re.compile(r"/wiki/spaces/[^/]+/pages/(\d+)"), # Pattern: /wiki/rest/api/content/<contentId> re.compile(r"/wiki/rest/api/content/(\d+)"), # Pattern: /pages/viewpage.action?pageId=<pageId> re.compile(r"pageId=(\d+)"), # Pattern: /x/<tinyId> (tiny links) - not directly resolvable to content_id ] DEFAULT_LIMIT = "50" DEFAULT_START = "0" LEGAL_ACCESS_TYPES = ["user", "site-admin", "admin"] LEGAL_CONTENT_STATUS = ["current", "trashed", "draft", "archived", "any"] LEGAL_CONTENT_TYPES = ["page", "blogpost"] LEGAL_CONTENT_TYPE_UPDATE_COMMAND = ["page", "blogpost", "comment", "attachment"] DEFAULT_EXPANDED_FIELD_CONTENT = "childTypes.all,space,version,history,ancestors,container,body" DEFAULT_EXPANDED_FIELD_SPACE = "history" LEGAL_SPACE_STATUS = ["current", "archived"] LEGAL_BODY_REPRESENTATION = ["editor", "editor2", "storage"] LEGAL_DELETION_TYPES = {"move to trash": "current", "permanent delete": "trashed", "permanent delete draft": "draft"} VENDOR = "Atlassian" PRODUCT = "Confluence" AUDIT_FETCH_PAGE_SIZE = 1000 DEFAULT_GET_EVENTS_LIMIT = "50" ONE_MINUTE_IN_MILL_SECONDS = 60000 ONE_WEEK_IN_MILL_SECONDS = 604800000 _last_run_cache = None # --- Confluence Cloud REST API v2 constants --- LEGAL_BODY_REPRESENTATION_V2 = ["storage", "atlas_doc_format", "wiki"] LEGAL_COMMENT_BODY_REPRESENTATION_V2 = ["storage", "atlas_doc_format"] LEGAL_BODY_FORMAT_V2 = ["storage", "atlas_doc_format", "view"] LEGAL_STATUS_CREATE_V2 = ["current", "draft"] LEGAL_STATUS_UPDATE_V2 = ["current", "draft"] LEGAL_PAGE_SUBTYPE_FILTER_V2 = ["page", "live"] LEGAL_PAGE_LIST_STATUS_V2 = ["current", "archived", "deleted", "trashed"] LEGAL_PAGE_SINGLE_STATUS_V2 = [*LEGAL_PAGE_LIST_STATUS_V2, "historical", "draft"] LEGAL_BLOGPOST_LIST_STATUS_V2 = ["current", "deleted", "trashed"] LEGAL_BLOGPOST_SINGLE_STATUS_V2 = [*LEGAL_BLOGPOST_LIST_STATUS_V2, "historical", "draft"] LEGAL_SPACE_TYPE_V2 = ["global", "personal"] LEGAL_SPACE_STATUS_V2 = ["current", "archived"] LEGAL_DESCRIPTION_FORMAT_V2 = ["plain", "view"] DEFAULT_LIMIT_V2 = 50 MIN_LIMIT_V2 = 1 MAX_LIMIT_V2 = 250 # Configuration shared between the page and blogpost v2 commands (they are near-identical # typed resources split from the polymorphic v1 'content' object). CONTENT_V2_CONFIG: dict[str, dict[str, Any]] = { "page": { "url_suffix": URL_SUFFIX_V2["PAGES"], "output_prefix": OUTPUT_PREFIX["PAGE"], "id_arg": "page_id", "list_status": LEGAL_PAGE_LIST_STATUS_V2, "single_status": LEGAL_PAGE_SINGLE_STATUS_V2, "list_status_message": "INVALID_PAGE_STATUS_LIST_V2", "single_status_message": "INVALID_PAGE_STATUS_SINGLE_V2", "supports_subtype_filter": True, "supports_direct_children": True, "label": "Page", }, "blogpost": { "url_suffix": URL_SUFFIX_V2["BLOGPOSTS"], "output_prefix": OUTPUT_PREFIX["BLOGPOST"], "id_arg": "blogpost_id", "list_status": LEGAL_BLOGPOST_LIST_STATUS_V2, "single_status": LEGAL_BLOGPOST_SINGLE_STATUS_V2, "list_status_message": "INVALID_BLOGPOST_STATUS_LIST_V2", "single_status_message": "INVALID_BLOGPOST_STATUS_SINGLE_V2", "supports_subtype_filter": False, "supports_direct_children": False, "label": "Blog post", }, } """ CLIENT CLASS """ class Client(BaseClient): """Client class to interact with the service API This Client implements API calls, and does not contain any XSOAR logic. Should only do requests and return data. It inherits from BaseClient defined in CommonServer Python. Most calls use _http_request() that handles proxy, SSL verification, etc. For this implementation, no special attributes defined """ def http_request(self, *args, **kwargs) -> requests.Response: """ Function to make http requests using inbuilt _http_request() method. """ kwargs["ok_codes"] = (200, 201, 204) kwargs["error_handler"] = self.exception_handler kwargs["resp_type"] = "response" return super()._http_request(*args, **kwargs) @staticmethod def exception_handler(response: requests.models.Response): """ Handle error in the response and display error message based on status code. :type response: ``requests.models.Response`` :param response: response from API. :raises: raise DemistoException based on status code of response. """ err_msg = "" if response.status_code in HTTP_ERROR: err_msg = HTTP_ERROR[response.status_code] elif response.status_code > 500: err_msg = HTTP_ERROR[500] elif response.status_code not in HTTP_ERROR: try: # Try to parse json error response error_entry = response.json() demisto.error(f"{LOGGING_INTEGRATION_NAME} {error_entry}") errors = error_entry.get("data", {}).get("errors", []) if errors: err_msg = get_error_message(errors) elif response.status_code == 400: err_msg = MESSAGES["BAD_REQUEST"] else: err_msg = error_entry.get("message", "") except ValueError: err_msg = f"{response.text}" raise DemistoException(err_msg) def search_events(self, limit: int, start_date: str = None, end_date: str = None, next_link: str = None) -> dict: return super()._http_request( method="GET", url_suffix=URL_SUFFIX["BASE"] + next_link if next_link else URL_SUFFIX["EVENTS"], params=None if next_link else {"limit": limit, "startDate": start_date, "end_date": end_date}, ) """ HELPER FUNCTIONS """ def run_fetch_mechanism(client: Client, fetch_limit: int, next_link: str, start_date: int, end_date: int): all_events: List[Dict[str, Any]] = [] started_new_query = False while len(all_events) < fetch_limit and (next_link or not started_new_query): page_size = min(AUDIT_FETCH_PAGE_SIZE, fetch_limit - len(all_events)) started_new_query = started_new_query or not next_link response = run_get_events_query(client, next_link, start_date, end_date, page_size) events = response["results"] next_link = response["_links"].get("next", None) demisto.debug(f"Fetched {len(events)} events, total_length: {len(all_events)}, next_link: {next_link}") all_events.extend(events) return all_events, started_new_query, next_link def run_get_events_query(client: Client, next_link, start_date, end_date, page_size: int) -> dict[str, Any]: if not next_link: demisto.debug(f"searching events with start date: {start_date}, end date: {end_date} and page size: {page_size}") response = client.search_events(limit=page_size, start_date=str(start_date), end_date=str(end_date)) demisto.debug(f'Found {response["size"]} events between {start_date} and {end_date}') else: demisto.debug(f"searching events with next_link: {next_link} and page size: {AUDIT_FETCH_PAGE_SIZE}") response = client.search_events(limit=page_size, next_link=next_link) demisto.debug(f'Found {response["size"]} events in the current page') return response def add_time_to_events(events: list[dict]): """ Adds the _time key to the events. Args: events: List[Dict] - list of events to add the _time key to. Returns: list: The events with the _time key. """ for event in events: create_time = arg_to_datetime(arg=event.get("creationDate")) event["_time"] = create_time.strftime(DATE_FORMAT) if create_time else None def get_error_message(errors): err_msg = "" for error in errors: if error.get("message").get("key"): err_msg += f"{error.get('message').get('key')} \n" if error.get("message").get("translation"): err_msg += f"{error.get('message').get('translation')} \n" return err_msg def strip_args(args: dict): """ Strips argument dictionary values. :type args: dict :param args: argument dictionary """ for key, value in args.items(): if isinstance(value, str): args[key] = value.strip() def validate_url(url: str): """ To Validate url parameter. :type url: str :param url: url to validate. """ if not url: raise ValueError(MESSAGES["REQUIRED_URL_FIELD"]) def remove_empty_elements_for_context(src): """ Recursively remove empty lists, empty dicts, empty string or None elements from a dictionary. :type src: ``dict`` :param src: Input dictionary. :return: Dictionary with all empty lists,empty string and empty dictionaries removed. :rtype: ``dict`` """ def empty(x): return x is None or x == "" or x == {} or x == [] if not isinstance(src, dict | list): return src elif isinstance(src, list): return [v for v in (remove_empty_elements_for_context(v) for v in src) if not empty(v)] else: return {k: v for k, v in ((k, remove_empty_elements_for_context(v)) for k, v in src.items()) if not empty(v)} def validated_required_args_for_permission(permission_account_id, permission_group_name, permission_operations): """ Raise value-error when null-values or whitespaces are provided for permission arguments. :type permission_account_id: ``str`` :param permission_account_id: Account ID :type permission_group_name: ``str`` :param permission_group_name: Name of the group :type permission_operations: ``str`` :param permission_operations: Permissions to be granted :return: None """ if (permission_account_id or permission_group_name) and not permission_operations: raise ValueError(MESSAGES["INVALID_PERMISSION"]) if permission_operations and (not permission_group_name and not permission_account_id): raise ValueError(MESSAGES["INVALID_PERMISSIONS_OPERATION"]) def prepare_permission_object(permission_account_id: str, permission_group_name: str, attr: list) -> dict: """ Prepare permission object from the user provided values :type permission_account_id: ``str`` :param permission_account_id: Account ID of the user to whom permission should be granted. :type permission_group_name: ``str`` :param permission_group_name: Group name to whom permission should be granted. :type attr: ``List`` :param attr: Operation and Target Type specified by user :rtype: ``Dict`` :return: Returns permission object """ permission_object = { "subjects": { "user": {"results": [{"accountId": permission_account_id}]}, "group": {"results": [{"name": permission_group_name}]}, }, "operation": {"operation": attr[0], "targetType": attr[1]}, "anonymousAccess": False, "unlicensedAccess": False, } return permission_object def validate_permissions(args: dict[str, Any]) -> list: """ Validates the permission argument provided by user and prepare permission object accordingly :type args: ``dict`` :param args: Input dictionary. :return: Permission object. :rtype: ``List`` """ space_permission = [] permission_account_id = args.get("permission_account_id", "") permission_group_name = args.get("permission_group_name", "") permission_operations = args.get("permission_operations", "") validated_required_args_for_permission(permission_account_id, permission_group_name, permission_operations) if permission_operations: # create a list of all the permission provided by user permissions = [permission.strip() for permission in permission_operations.split(",") if permission.strip()] # separate target_type and operation for the single permission for permission in permissions: if permission: attr = [operation.strip() for operation in permission.split(":") if operation.strip()] # if target_type or operation is missing then raise ValueError if len(attr) != 2: raise ValueError(MESSAGES["PERMISSION_FORMAT"]) permission_object = prepare_permission_object(permission_account_id, permission_group_name, attr) space_permission.append(permission_object) return space_permission def validate_list_command_args(args: dict[str, str]) -> tuple[Optional[int], Optional[int]]: """ Validate arguments for all list commands, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Parameters to send in request :rtype: ``Tuple`` """ limit = arg_to_number(args.get("limit", DEFAULT_LIMIT)) if limit < 0 or limit > 2147483647: # type:ignore raise ValueError(MESSAGES["LIMIT"].format(limit)) offset = arg_to_number(args.get("offset", DEFAULT_START)) if offset < 0 or offset > 2147483647: # type:ignore raise ValueError(MESSAGES["START"].format(offset)) return limit, offset def validate_list_group_args(args: dict[str, str]): """ Validate arguments for confluence-cloud-group-list command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. """ access_type = args.get("access_type", "").lower() if access_type and access_type not in LEGAL_ACCESS_TYPES: raise ValueError(MESSAGES["INVALID_ACCESS_TYPE"]) return access_type def prepare_group_args(args: dict[str, str]) -> dict[str, str]: """ Prepare params for list group command :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. """ limit, offset = validate_list_command_args(args) access_type = validate_list_group_args(args) return assign_params(limit=limit, start=offset, accessType=access_type) def prepare_hr_for_groups(groups: list[dict[str, Any]]) -> str: """ Prepare human-readable for list groups command. :type groups: ``List[Dict[str, Any]]`` :param groups:The group data. :rtype: ``str`` :return: Human readable. """ hr_list = [] for group in groups: hr_record = {"ID": group.get("id", ""), "Name": group.get("name", "")} hr_list.append(hr_record) return tableToMarkdown("Group(s)", hr_list, ["ID", "Name"], removeNull=True) def prepare_content_create_params(args) -> dict[str, Any]: """ Prepare json object for content create command :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Body parameters to send in request :rtype: ``Dict[str, Any]`` """ body_representation = args.get("body_representation", "") params = { "title": args["title"], "type": args["type"].lower(), "space": {"key": args.get("space_key", "")}, "status": args.get("status", "current"), "body": {body_representation: {"value": args.get("body_value", ""), "representation": body_representation}}, "ancestors": [{"id": args.get("ancestor_id", "")}], } return remove_empty_elements_for_context(params) def validate_create_content_args(args: dict[str, str], is_update: bool = False): """ Validate arguments for confluence-cloud-content-create command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type is_update: ``bool`` :param is_update: Whether command is update content or not. :return: None :rtype: ``None`` """ title = args["title"] if not title: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("title")) if len(title) > 255: raise ValueError(MESSAGES["INVALID_TITLE_LENGTH"]) content_type = args["type"].lower() if not content_type: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("type")) if not is_update and content_type not in LEGAL_CONTENT_TYPES: raise ValueError(MESSAGES["INVALID_CONTENT_TYPE"]) if is_update and content_type not in LEGAL_CONTENT_TYPE_UPDATE_COMMAND: raise ValueError(MESSAGES["INVALID_CONTENT_TYPE_UPDATE_CONTENT"]) space_key = args.get("space_key", "") if not is_update and not space_key: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("space_key")) body_value = args.get("body_value", "") body_representation = args.get("body_representation", "") if content_type == "comment": if body_value and body_representation: if body_representation not in LEGAL_BODY_REPRESENTATION: raise ValueError(MESSAGES["INVALID_BODY_REPRESENTATION"]) else: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("'body_value' and 'body_representation'")) def prepare_hr_for_content_create(content: dict[str, Any], content_type: str) -> str: """ Prepare human-readable for content create, comment create and content update command. :type content: ``Dict[str, Any]`` :param content:The content data. :type content_type: ``str`` :param content_type: Type of the content. :rtype: ``str`` :return: Human readable. """ hr_record = { "ID": content.get("id", ""), "Title": f"[{content.get('title', '')}]" f"({content.get('_links', {}).get('base', '')}{content.get('_links', {}).get('webui', '')})", "Type": content.get("type", ""), "Status": content.get("status", ""), "Space Name": content.get("space", {}).get("name", ""), "Created By": content.get("history", {}).get("createdBy", {}).get("displayName", ""), "Created At": content.get("history", {}).get("createdDate", ""), } return tableToMarkdown( f"{content_type}", hr_record, ["ID", "Title", "Type", "Status", "Space Name", "Created By", "Created At"], removeNull=True ) def prepare_hr_for_content_search(contents: list, url_prefix: str) -> str: """ Prepare human-readable for content search and content list command. :type contents: ``list`` :param contents: List of content. :type url_prefix: ``str`` :param url_prefix: Url prefix the content. :rtype: ``str`` :return: Human readable. """ hr_list = [] for content in contents: hr_record = { "ID": content.get("id", ""), "Title": f"[{content.get('title', '')}]({url_prefix}{content.get('_links', {}).get('webui', '')})", "Type": content.get("type", ""), "Status": content.get("status", ""), "Space Name": content.get("space", {}).get("name", ""), "Created By": content.get("history", {}).get("createdBy", {}).get("displayName", ""), "Created At": content.get("history", {}).get("createdDate", ""), "Version": content.get("version", {}).get("number", ""), } hr_list.append(hr_record) hr = tableToMarkdown( "Content(s)", hr_list, ["ID", "Title", "Type", "Status", "Space Name", "Created By", "Created At", "Version"], removeNull=True, ) return hr def validate_delete_content_args(args: dict[str, str]): """ Validate arguments for confluence-cloud-content-delete command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ content_id = args["content_id"] if not content_id: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("content_id")) status = args.get("deletion_type", "").lower() if status and status not in LEGAL_DELETION_TYPES: raise ValueError(MESSAGES["INVALID_DELETION_TYPE"]) def prepare_comment_create_params(args) -> dict[str, Any]: """ Prepare json object for comment create command :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Body parameters to send in request :rtype: ``Dict[str, Any]`` """ body_representation = args["body_representation"] container_type = args.get("container_type", "") params = { "type": "comment", "status": args.get("status", "current"), "container": {"id": args["container_id"], "type": container_type}, "body": {body_representation: {"value": args["body_value"], "representation": body_representation}}, "ancestors": [{"id": args.get("ancestor_id", "")}], } params = remove_empty_elements_for_context(params) params["container"]["type"] = container_type return params def validate_comment_args(args: dict[str, str]): """ Validate arguments for confluence-cloud-comment-create command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ body_value = args["body_value"] if not body_value: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("Comment body_value")) body_representation = args["body_representation"] if not body_representation: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("body_representation")) if body_representation not in LEGAL_BODY_REPRESENTATION: raise ValueError(MESSAGES["INVALID_BODY_REPRESENTATION"]) container_id = args["container_id"] if not container_id: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("container_id")) def prepare_hr_for_users(users: list[dict[str, Any]]) -> str: """ Prepare human-readable for list users command. :type users: ``List[Dict[str, Any]]`` :param users: The user data. :rtype: ``str`` :return: Human readable. """ hr_list = [] for user in users: hr_record = { "Account ID": user["user"].get("accountId", ""), "Name": user["user"].get("displayName", ""), "User Type": user["user"].get("type", ""), } hr_list.append(hr_record) return tableToMarkdown("User(s)", hr_list, ["Account ID", "Name", "User Type"], removeNull=True) def prepare_expand_argument(expand: str, default_fields: str) -> str: """ The 'expand' command argument specifies which properties should be expanded. In this integration, several of the most significant characteristics are extended by default. Other attributes that users want to expand can still be provided. This method combines the default expand fields with the expand fields specified by the user. :type expand: ``str`` :param expand: The expand argument passed by the user. :type default_fields: ``str`` :param default_fields: The default fields. :return: expand argument value to send in request :rtype: ``str`` """ default_expand_fields = default_fields.split(",") custom_expand_fields = set(expand.split(",")) expand_fields = "" for expand_field in custom_expand_fields: if expand_field.strip() not in default_expand_fields: expand_fields += f",{expand_field.strip()}" return default_fields + expand_fields def validate_query_argument(args: dict[str, str]): """ Validate query argument of content search command :param args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ query = args["query"] if not query: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("query")) def prepare_search_content_argument(args: dict[str, str]) -> dict[str, Any]: """ Prepare params for confluence-cloud-content-search command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Parameters to send in request :rtype: ``Dict[str, Any]`` """ limit, offset = validate_list_command_args(args) validate_query_argument(args) params = { "cql": args["query"], "cursor": args.get("next_page_token"), "expand": DEFAULT_EXPANDED_FIELD_CONTENT, "limit": limit, } expand = args.get("expand", "") if expand: params["expand"] = prepare_expand_argument(expand, DEFAULT_EXPANDED_FIELD_CONTENT) content_status = argToList(args.get("content_status", "")) params["cqlcontext"] = json.dumps({"contentStatuses": content_status}) return assign_params(**params) def prepare_cursor_for_content(response_json: dict[str, str]) -> str: """ Split query string parameters from a link and extract value of parameter 'cursor'. :type response_json: ``Dict[str, str]`` :param response_json: API response. :return: Next Page Token(Cursor). :rtype: ``str`` """ next_cursor = "" next_record = response_json.get("_links", {}).get("next", "") # type:ignore if next_record: next_cursor_split = next_record.split("?") parsed_next_cursor = urllib.parse.parse_qs(next_cursor_split[1]) next_cursor = parsed_next_cursor.get("cursor", [])[0] return next_cursor def validate_list_content_args(args): """ Validate arguments for confluence_cloud_content_list command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ sort_order = args.get("sort_order", "").lower() sort_key = args.get("sort_key", "") if sort_order and not sort_key: raise ValueError(MESSAGES["REQUIRED_SORT_KEY"]) content_type = args.get("type", "page").lower() if content_type not in LEGAL_CONTENT_TYPES: raise ValueError(MESSAGES["INVALID_CONTENT_TYPE"]) status = args.get("status", "").lower() if status and status not in LEGAL_CONTENT_STATUS: raise ValueError(MESSAGES["INVALID_STATUS_SEARCH"]) def prepare_list_content_argument(args: dict[str, str]) -> dict[str, Any]: """ Prepare params for confluence_cloud_content_list command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Parameters to send in request :rtype: ``Dict[str, Any]`` """ validate_list_content_args(args) limit, offset = validate_list_command_args(args) params = {"limit": limit, "start": offset, "spaceKey": args.get("space_key", ""), "type": args.get("type", "page").lower()} sort_order = args.get("sort_order", "").lower() sort_key = args.get("sort_key", "") if sort_order and sort_key: params["orderby"] = f"{sort_key} {sort_order}" elif sort_key: params["orderby"] = f"{sort_key}" content_creation_date = arg_to_datetime(args.get("creation_date")) if content_creation_date: params["postingDay"] = content_creation_date.date() # type: ignore params["status"] = args.get("status", "").lower() params["expand"] = DEFAULT_EXPANDED_FIELD_CONTENT expand = args.get("expand", "") if expand: params["expand"] = prepare_expand_argument(expand, DEFAULT_EXPANDED_FIELD_CONTENT) return assign_params(**params) def validate_create_space_args(args: dict[str, str]): """ Validate arguments for confluence-cloud-space-create command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ unique_key = args.get("unique_key") if not unique_key: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("unique_key")) if len(unique_key) > 255 or not unique_key.isalnum(): raise ValueError(MESSAGES["INVALID_SPACE_KEY"]) name = args.get("name") if not name: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("name")) if len(name) > 200: raise ValueError(MESSAGES["INVALID_SPACE_NAME_LENGTH"]) is_private_space = argToBoolean(args.get("is_private_space", False)) if is_private_space and (args.get("advanced_permissions") or args.get("permission_operations")): raise ValueError(MESSAGES["PRIVATE_SPACE_PERMISSION"]) if args.get("advanced_permissions"): try: json.loads(args["advanced_permissions"]) except (json.JSONDecodeError, json.decoder.JSONDecodeError, AttributeError): raise ValueError(MESSAGES["ADVANCE_PERMISSION_FORMAT"]) def prepare_create_space_args(args: dict[str, str]) -> tuple[dict, Union[bool, str]]: """ Prepare json object for confluence-cloud-space-create command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Parameters to send in request :rtype: ``Dict[str, Any]`` """ is_private_space = argToBoolean(args.get("is_private_space", False)) if args.get("advanced_permissions"): permissions = json.loads(args["advanced_permissions"]) else: permissions = validate_permissions(args) params = { "key": args["unique_key"], "name": args["name"], "description": {"plain": {"value": args.get("description", ""), "representation": "plain"}}, "permissions": permissions, } params = remove_empty_elements_for_context(params) return params, is_private_space def prepare_hr_for_space_create(space: dict[str, Any]) -> str: """ Prepare human-readable for create space command. :type space: ``List[Dict[str, Any]]`` :param space: The space data. :rtype: ``str`` :return: Human readable. """ hr_record = { "ID": space.get("id", ""), "Name": f"[{space.get('name', '')}]" f"({space.get('_links', {}).get('base', '')}{space.get('_links', {}).get('webui', '')})", "Type": space.get("type", ""), "Status": space.get("status", ""), } return tableToMarkdown("Space", hr_record, ["ID", "Name", "Type", "Status"], removeNull=True) def validate_status_argument(args: dict[str, str]): """ Validates the status argument of confluence-cloud-space-list command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ status = args.get("status") if status and status.lower() not in LEGAL_SPACE_STATUS: raise ValueError(MESSAGES["INVALID_SPACE_STATUS"]) def prepare_list_space_args(args: dict[str, str]) -> dict[str, Any]: """ Prepare params for confluence-cloud-space-list command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Parameters to send in request :rtype: ``Dict[str, Any]`` """ validate_status_argument(args) limit, offset = validate_list_command_args(args) params = { "limit": limit, "start": offset, "spaceKey": argToList(args.get("space_key")), "spaceId": argToList(args.get("space_id")), "type": args.get("type"), "status": args.get("status"), } favourite = args.get("favourite", "") if favourite: favourite = "true" if argToBoolean(favourite) else "false" params["favourite"] = favourite params["expand"] = DEFAULT_EXPANDED_FIELD_SPACE expand = args.get("expand", "") if expand: params["expand"] = prepare_expand_argument(expand, DEFAULT_EXPANDED_FIELD_SPACE) return assign_params(**params) def prepare_hr_for_space_list(spaces: list[dict[str, Any]], url_prefix: str) -> str: """ Prepare human-readable for list space command. :param url_prefix: :type spaces: ``List[Dict[str, Any]]`` :param spaces: The space data. :rtype: ``str`` :return: Human readable. """ hr_list = [] for space in spaces: hr_record = { "ID": space.get("id", ""), "Space Key": space.get("key", ""), "Name": f"[{space.get('name', '')}]({url_prefix}{space.get('_links', {}).get('webui', '')})", "Type": space.get("type", ""), "Status": space.get("status", ""), "Created By": space.get("history", {}).get("createdBy", {}).get("displayName", ""), "Created At": space.get("history", {}).get("createdDate", ""), } hr_list.append(hr_record) hr = tableToMarkdown( "Space(s)", hr_list, ["ID", "Space Key", "Name", "Type", "Status", "Created By", "Created At"], removeNull=True ) return hr def validate_update_content_args(args: dict[str, str]): """ Validate arguments for confluence-cloud-content-update command, raise ValueError on invalid arguments. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ validate_create_content_args(args, is_update=True) content_id = args["content_id"] if not content_id: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("content_id")) version = args["version"] if not version: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("version")) """ HELPER FUNCTIONS (REST API v2) """ def prepare_cursor_from_link_header(response: requests.Response) -> str: """ Extract the pagination cursor from a v2 API response's ``Link`` header. The Confluence REST API v2 returns pagination information in the ``Link`` HTTP response header (RFC 5988), e.g. ``<https://.../wiki/api/v2/pages?cursor=abc123>; rel="next"``. This function parses that header, isolates the URL marked with ``rel="next"`` and returns the value of the ``cursor`` query parameter. :type response: ``requests.Response`` :param response: The raw API response object. :return: Next page cursor (empty string when there is no next page). :rtype: ``str`` """ link_header = response.headers.get("Link", "") if not link_header: return "" for part in link_header.split(","): section = part.split(";") if len(section) < 2: continue rel = section[1].strip() if rel not in ('rel="next"', "rel=next"): continue url = section[0].strip().strip("<>") query = urllib.parse.urlparse(url).query cursor_values = urllib.parse.parse_qs(query).get("cursor", []) if cursor_values: return cursor_values[0] return "" def paginate_v2_results( client: "Client", url_suffix: str, params: dict[str, Any], limit: int ) -> tuple[list[dict[str, Any]], dict[str, Any]]: """ Retrieve v2 list results, automatically following the ``Link: rel="next"`` cursor until ``limit`` records are accumulated or there are no more pages. The Confluence REST API v2 caps a single page at ``MAX_LIMIT_V2`` (250) results, so this helper transparently issues additional requests to satisfy larger ``limit`` values. :type client: ``Client`` :param client: Client object used to issue the HTTP requests. :type url_suffix: ``str`` :param url_suffix: The v2 endpoint URL suffix to query. :type params: ``Dict[str, Any]`` :param params: The base query parameters (the per-request ``limit`` is managed internally). :type limit: ``int`` :param limit: The total number of records the caller wants to accumulate. :return: A tuple of (accumulated results, last page's raw JSON response). :rtype: ``Tuple[List[Dict[str, Any]], Dict[str, Any]]`` """ accumulated: list[dict[str, Any]] = [] request_params = dict(params) response_json: dict[str, Any] = {} while len(accumulated) < limit: request_params["limit"] = min(MAX_LIMIT_V2, limit - len(accumulated)) response = client.http_request(method="GET", url_suffix=url_suffix, params=request_params) response_json = response.json() page_results = response_json.get("results", []) accumulated.extend(page_results) next_cursor = prepare_cursor_from_link_header(response) if not next_cursor or not page_results: break request_params["cursor"] = next_cursor return accumulated[:limit], response_json def validate_limit_v2(args: dict[str, str]) -> Optional[int]: """ Validate and normalize the ``limit`` argument for v2 list commands. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: The validated limit or ``None`` when not provided. :rtype: ``Optional[int]`` """ limit = arg_to_number(args.get("limit"), arg_name="limit") if limit is None: return None if limit < MIN_LIMIT_V2: raise ValueError(MESSAGES["INVALID_LIMIT_V2"].format(limit)) return limit def prepare_content_body_v2(args: dict[str, str], legal_representations: list[str], message_key: str) -> dict[str, Any]: """ Build the v2 ``body`` object for page/blogpost/comment create and update requests. The v2 body format differs from v1 and is shaped as ``{"representation": "storage", "value": "<p>...</p>"}``. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type legal_representations: ``list[str]`` :param legal_representations: The allowed body representation values for the resource. :type message_key: ``str`` :param message_key: The MESSAGES key to use when the representation is invalid. :return: The v2 body object (empty dict when no body value is provided). :rtype: ``Dict[str, Any]`` """ body_value = args.get("body_value") if not body_value: return {} representation = args.get("body_representation", "storage").lower() if representation not in legal_representations: raise ValueError(f"{MESSAGES[message_key]} Received: '{representation}'.") return {"representation": representation, "value": body_value} def validate_content_create_args_v2(args: dict[str, str]) -> None: """ Validate arguments shared by page-create and blogpost-create v2 commands. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ if not args.get("space_id"): raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("space_id")) status = args.get("status", "current").lower() if status not in LEGAL_STATUS_CREATE_V2: raise ValueError(f"{MESSAGES['INVALID_STATUS_CREATE_V2']} Received: '{status}'.") representation = args.get("body_representation", "storage").lower() if representation not in LEGAL_BODY_REPRESENTATION_V2: raise ValueError(f"{MESSAGES['INVALID_BODY_REPRESENTATION_V2']} Received: '{representation}'.") def prepare_content_create_params_v2(args: dict[str, str]) -> dict[str, Any]: """ Build the request body for page-create and blogpost-create v2 commands. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: The request body object. :rtype: ``Dict[str, Any]`` """ validate_content_create_args_v2(args) body = prepare_content_body_v2(args, LEGAL_BODY_REPRESENTATION_V2, "INVALID_BODY_REPRESENTATION_V2") params = { "spaceId": args["space_id"], "status": args.get("status", "current").lower(), "title": args.get("title"), "body": body or None, } parent_id = args.get("parent_id") if parent_id: params["parentId"] = parent_id return assign_params(**params) def validate_content_update_args_v2(args: dict[str, str], config: dict[str, Any]) -> None: """ Validate arguments shared by page-update and blogpost-update v2 commands. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type config: ``Dict[str, Any]`` :param config: The resource configuration from ``CONTENT_V2_CONFIG``. :return: None """ id_arg = config["id_arg"] if not args.get(id_arg): raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format(id_arg)) if not args.get("version_number"): raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("version_number")) status = args.get("status", "current").lower() if status not in LEGAL_STATUS_UPDATE_V2: raise ValueError(f"{MESSAGES['INVALID_STATUS_UPDATE_V2']} Received: '{status}'.") representation = args.get("body_representation", "storage").lower() if representation not in LEGAL_BODY_REPRESENTATION_V2: raise ValueError(f"{MESSAGES['INVALID_BODY_REPRESENTATION_V2']} Received: '{representation}'.") def prepare_content_update_params_v2(args: dict[str, str], config: dict[str, Any]) -> dict[str, Any]: """ Build the request body for page-update and blogpost-update v2 commands. v2 update requires an explicit ``version.number`` increment supplied by the caller. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type config: ``Dict[str, Any]`` :param config: The resource configuration from ``CONTENT_V2_CONFIG``. :return: The request body object. :rtype: ``Dict[str, Any]`` """ validate_content_update_args_v2(args, config) content_id = args[config["id_arg"]] version_number = arg_to_number(args.get("version_number"), arg_name="version_number") body = prepare_content_body_v2(args, LEGAL_BODY_REPRESENTATION_V2, "INVALID_BODY_REPRESENTATION_V2") params = { "id": content_id, "status": args.get("status", "current").lower(), "title": args.get("title"), "body": body or None, "version": {"number": version_number, "message": args.get("version_message")}, } if config["label"] == "Page" and args.get("space_id"): params["spaceId"] = args["space_id"] return assign_params(**params) def validate_content_list_args_v2(args: dict[str, str], config: dict[str, Any]) -> None: """ Validate arguments for page-list and blogpost-list v2 commands. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type config: ``Dict[str, Any]`` :param config: The resource configuration from ``CONTENT_V2_CONFIG``. :return: None """ validate_limit_v2(args) status = args.get("status", "").lower() if status and status not in config["list_status"]: raise ValueError(MESSAGES[config["list_status_message"]]) if config["supports_subtype_filter"]: subtype = args.get("subtype", "").lower() if subtype and subtype not in LEGAL_PAGE_SUBTYPE_FILTER_V2: raise ValueError(MESSAGES["INVALID_SUBTYPE_FILTER_V2"]) def prepare_content_list_params_v2(args: dict[str, str], config: dict[str, Any]) -> dict[str, Any]: """ Build the query parameters for page-list and blogpost-list v2 commands. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type config: ``Dict[str, Any]`` :param config: The resource configuration from ``CONTENT_V2_CONFIG``. :return: The query parameters. :rtype: ``Dict[str, Any]`` """ validate_content_list_args_v2(args, config) # The per-page ``limit`` is managed by ``paginate_v2_results`` so that the user-supplied # ``limit`` represents the total number of records accumulated across all pages. validate_limit_v2(args) params: dict[str, Any] = { "id": argToList(args.get("id")), "space-id": argToList(args.get("space_id")), "status": argToList(args.get("status")), "title": args.get("title"), "sort": args.get("sort"), } if config["supports_subtype_filter"] and args.get("subtype"): params["subtype"] = args["subtype"].lower() return assign_params(**params) def prepare_hr_for_content_v2(content: dict[str, Any], label: str) -> str: """ Prepare human-readable output for a single v2 page/blogpost. :type content: ``Dict[str, Any]`` :param content: The page or blogpost data. :type label: ``str`` :param label: The resource label (e.g. ``Page`` or ``Blog post``). :rtype: ``str`` :return: Human readable. """ hr_record = { "ID": content.get("id", ""), "Title": content.get("title", ""), "Status": content.get("status", ""), "Space ID": content.get("spaceId", ""), "Author ID": content.get("authorId", ""), "Created At": content.get("createdAt", ""), "Version": (content.get("version") or {}).get("number", ""), } return tableToMarkdown( label, hr_record, ["ID", "Title", "Status", "Space ID", "Author ID", "Created At", "Version"], removeNull=True ) def prepare_hr_for_content_list_v2(contents: list[dict[str, Any]], label: str) -> str: """ Prepare human-readable output for a list of v2 pages/blogposts. :type contents: ``list[Dict[str, Any]]`` :param contents: The page or blogpost data. :type label: ``str`` :param label: The resource label (e.g. ``Page`` or ``Blog post``). :rtype: ``str`` :return: Human readable. """ hr_list = [] for content in contents: hr_list.append( { "ID": content.get("id", ""), "Title": content.get("title", ""), "Status": content.get("status", ""), "Space ID": content.get("spaceId", ""), "Author ID": content.get("authorId", ""), "Created At": content.get("createdAt", ""), } ) return tableToMarkdown( f"{label}(s)", hr_list, ["ID", "Title", "Status", "Space ID", "Author ID", "Created At"], removeNull=True ) def validate_comment_create_args_v2(args: dict[str, str]) -> None: """ Validate arguments for footer-comment-create v2 command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ if not args.get("body_value"): raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("body_value")) representation = args.get("body_representation", "storage").lower() if representation not in LEGAL_COMMENT_BODY_REPRESENTATION_V2: raise ValueError(MESSAGES["INVALID_COMMENT_BODY_REPRESENTATION_V2"]) container_args = ("page_id", "blogpost_id", "parent_comment_id", "attachment_id", "custom_content_id") if not any(args.get(arg) for arg in container_args): raise ValueError(MESSAGES["MISSING_COMMENT_CONTAINER_V2"]) def prepare_comment_create_params_v2(args: dict[str, str]) -> dict[str, Any]: """ Build the request body for footer-comment-create v2 command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: The request body object. :rtype: ``Dict[str, Any]`` """ validate_comment_create_args_v2(args) body = prepare_content_body_v2(args, LEGAL_COMMENT_BODY_REPRESENTATION_V2, "INVALID_COMMENT_BODY_REPRESENTATION_V2") params: dict[str, Any] = { "body": body, "pageId": args.get("page_id"), "blogPostId": args.get("blogpost_id"), "parentCommentId": args.get("parent_comment_id"), "attachmentId": args.get("attachment_id"), "customContentId": args.get("custom_content_id"), } return assign_params(**params) def prepare_hr_for_comment_v2(comment: dict[str, Any], label: str) -> str: """ Prepare human-readable output for a created v2 footer comment. :type comment: ``Dict[str, Any]`` :param comment: The comment data. :type label: ``str`` :param label: The comment label (e.g. ``Footer Comment``). :rtype: ``str`` :return: Human readable. """ hr_record = { "ID": comment.get("id", ""), "Status": comment.get("status", ""), "Page ID": comment.get("pageId", ""), "Blog Post ID": comment.get("blogPostId", ""), "Parent Comment ID": comment.get("parentCommentId", ""), "Version": (comment.get("version") or {}).get("number", ""), } return tableToMarkdown( label, hr_record, ["ID", "Status", "Page ID", "Blog Post ID", "Parent Comment ID", "Version"], removeNull=True ) def validate_space_list_args_v2(args: dict[str, str]) -> None: """ Validate arguments for space-listv2 command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ validate_limit_v2(args) space_type = args.get("type", "").lower() if space_type and space_type not in LEGAL_SPACE_TYPE_V2: raise ValueError(MESSAGES["INVALID_SPACE_TYPE_V2"]) status = args.get("status", "").lower() if status and status not in LEGAL_SPACE_STATUS_V2: raise ValueError(MESSAGES["INVALID_SPACE_STATUS_V2"]) def prepare_space_list_params_v2(args: dict[str, str]) -> dict[str, Any]: """ Build the query parameters for space-listv2 command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: The query parameters. :rtype: ``Dict[str, Any]`` """ validate_space_list_args_v2(args) # The per-page ``limit`` is managed by ``paginate_v2_results`` so that the user-supplied # ``limit`` represents the total number of records accumulated across all pages. validate_limit_v2(args) params = { "ids": argToList(args.get("ids")), "keys": argToList(args.get("keys")), "type": args.get("type"), "status": args.get("status"), "sort": args.get("sort"), } return assign_params(**params) def validate_space_create_args_v2(args: dict[str, str]) -> None: """ Validate arguments for space-createv2 command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: None """ if not args.get("name"): raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("name")) if not args.get("key"): raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("key")) description_format = args.get("description_format", "plain").lower() if description_format not in LEGAL_DESCRIPTION_FORMAT_V2: raise ValueError(MESSAGES["INVALID_DESCRIPTION_FORMAT_V2"]) def prepare_space_create_params_v2(args: dict[str, str]) -> dict[str, Any]: """ Build the request body for space-createv2 command. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: The request body object. :rtype: ``Dict[str, Any]`` """ validate_space_create_args_v2(args) params: dict[str, Any] = {"name": args["name"], "key": args["key"]} description_value = args.get("description_value") if description_value: description_format = args.get("description_format", "plain").lower() params["description"] = {description_format: {"value": description_value, "representation": description_format}} role_assignments = args.get("role_assignments") if role_assignments: try: params["roleAssignments"] = json.loads(role_assignments) except (json.JSONDecodeError, TypeError): raise ValueError(MESSAGES["INVALID_ROLE_ASSIGNMENTS_V2"]) return assign_params(**params) def prepare_hr_for_space_create_v2(space: dict[str, Any]) -> str: """ Prepare human-readable output for a created v2 space. :type space: ``Dict[str, Any]`` :param space: The space data. :rtype: ``str`` :return: Human readable. """ hr_record = { "ID": space.get("id", ""), "Key": space.get("key", ""), "Name": space.get("name", ""), "Type": space.get("type", ""), "Status": space.get("status", ""), } return tableToMarkdown("Space", hr_record, ["ID", "Key", "Name", "Type", "Status"], removeNull=True) def prepare_hr_for_space_list_v2(spaces: list[dict[str, Any]]) -> str: """ Prepare human-readable output for a list of v2 spaces. :type spaces: ``list[Dict[str, Any]]`` :param spaces: The space data. :rtype: ``str`` :return: Human readable. """ hr_list = [] for space in spaces: hr_list.append( { "ID": space.get("id", ""), "Key": space.get("key", ""), "Name": space.get("name", ""), "Type": space.get("type", ""), "Status": space.get("status", ""), } ) return tableToMarkdown("Space(s)", hr_list, ["ID", "Key", "Name", "Type", "Status"], removeNull=True) """ COMMAND FUNCTIONS """ def test_module(client: Client) -> str: """Tests API connectivity and authentication' Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :type client: ``Client`` :param client: client to use :return: 'ok' if test passed, anything else will fail the test. :rtype: ``str`` """ params: dict = {"cql": "type=page", "limit": 1} client.http_request(method="GET", url_suffix=URL_SUFFIX["CONTENT_SEARCH"], params=params) return "ok" def confluence_cloud_user_list_command(client: Client, args: dict[str, str]) -> CommandResults: """ Returns a list of users. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ limit, offset = validate_list_command_args(args) params = assign_params(limit=limit, start=offset) response = client.http_request(method="GET", url_suffix=URL_SUFFIX["USER"], params=params) response_json = response.json() total_records = response_json.get("results", []) if not total_records: return CommandResults(readable_output=MESSAGES["NO_RECORDS_FOUND"].format("user(s)")) context = [] for user in total_records: context.append(remove_empty_elements_for_context(user.get("user", {}))) readable_hr = prepare_hr_for_users(total_records) return CommandResults( outputs_prefix=OUTPUT_PREFIX["USER"], outputs_key_field="accountId", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_content_search_command(client: Client, args: dict[str, str]) -> CommandResults: """ Returns the list of content that matches a Confluence Query Language (CQL) query. The type of content can be a page, blogpost, or comment. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ params = prepare_search_content_argument(args) response = client.http_request(method="GET", url_suffix=URL_SUFFIX["CONTENT_SEARCH"], params=params) response_json = response.json() total_records = response_json.get("results", []) if not total_records: return CommandResults(readable_output=MESSAGES["NO_RECORDS_FOUND"].format("content(s)")) # Creating Context data context = remove_empty_elements_for_context(total_records) next_cursor = prepare_cursor_for_content(response_json) next_page_context = {"next_page_token": next_cursor, "name": "confluence-cloud-content-search"} next_page_context = remove_empty_elements_for_context(next_page_context) outputs = { f"{OUTPUT_PREFIX['CONTENT']}(val.id == obj.id)": context, f"{OUTPUT_PREFIX['PAGETOKEN']}(val.name == obj.name)": next_page_context, } # Creating Human Readable url_prefix = response_json.get("_links", {}).get("base", "") readable_hr = prepare_hr_for_content_search(total_records, url_prefix) if next_cursor: readable_hr += f"Run the command with argument next_page_token={next_cursor} to see the next set of contents.\n" return CommandResults(outputs=outputs, readable_output=readable_hr, raw_response=response_json) def confluence_cloud_content_update_command(client: Client, args: dict[str, str]) -> CommandResults: """ Update the existing content with new content. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ validate_update_content_args(args) content_id = args["content_id"] params = prepare_content_create_params(args) params["version"] = {"number": args["version"]} request_url = URL_SUFFIX["CONTENT"] + f"/{content_id}" response = client.http_request(method="PUT", url_suffix=request_url, json_data=params) response_json = response.json() context = remove_empty_elements_for_context(response_json) readable_hr = prepare_hr_for_content_create(response_json, "Content") return CommandResults( outputs_prefix=OUTPUT_PREFIX["CONTENT"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_content_delete_command(client: Client, args: dict[str, str]) -> CommandResults: """ This command moves a piece of content to the space's trash or purges it from the trash, depending on the content's type and status. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ validate_delete_content_args(args) content_id = args["content_id"] status = args.get("deletion_type", "").lower() params = assign_params(status=LEGAL_DELETION_TYPES.get(status)) request_url = URL_SUFFIX["CONTENT"] + f"/{content_id}" client.http_request(method="DELETE", url_suffix=request_url, params=params) return CommandResults(readable_output=MESSAGES["HR_DELETE_CONTENT"].format(content_id)) def confluence_cloud_content_list_command(client: Client, args: dict[str, str]) -> CommandResults: """ Returns the list of contents of confluence. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ params = prepare_list_content_argument(args) response = client.http_request(method="GET", url_suffix=URL_SUFFIX["CONTENT"], params=params) response_json = response.json() total_records = response_json.get("results", []) if not total_records: return CommandResults(readable_output=MESSAGES["NO_RECORDS_FOUND"].format("content(s)")) context = remove_empty_elements_for_context(total_records) url_prefix = response_json.get("_links", {}).get("base", "") readable_hr = prepare_hr_for_content_search(total_records, url_prefix) return CommandResults( outputs_prefix=OUTPUT_PREFIX["CONTENT"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_space_list_command(client: Client, args: dict[str, str]) -> CommandResults: """ Returns a list of all Confluence spaces. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ params = prepare_list_space_args(args) response = client.http_request(method="GET", url_suffix=URL_SUFFIX["SPACE"], params=params) response_json = response.json() total_records = response_json.get("results", []) if not total_records: return CommandResults(readable_output=MESSAGES["NO_RECORDS_FOUND"].format("space(s)")) context = remove_empty_elements_for_context(total_records) url_prefix = response_json.get("_links", {}).get("base", "") readable_hr = prepare_hr_for_space_list(total_records, url_prefix) return CommandResults( outputs_prefix=OUTPUT_PREFIX["SPACE"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_comment_create_command(client: Client, args: dict[str, str]) -> CommandResults: """ Creates a comment for a given content. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ validate_comment_args(args) params = prepare_comment_create_params(args) response = client.http_request(method="POST", url_suffix=URL_SUFFIX["CONTENT"], json_data=params) response_json = response.json() context = remove_empty_elements_for_context(response_json) readable_hr = prepare_hr_for_content_create(response_json, "Comment") return CommandResults( outputs_prefix=OUTPUT_PREFIX["COMMENT"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_content_create_command(client: Client, args: dict[str, str]) -> CommandResults: """ Create a page or blogpost for a specified space . :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ validate_create_content_args(args) params = prepare_content_create_params(args) response = client.http_request(method="POST", url_suffix=URL_SUFFIX["CONTENT"], json_data=params) response_json = response.json() context = remove_empty_elements_for_context(response_json) readable_hr = prepare_hr_for_content_create(response_json, "Content") return CommandResults( outputs_prefix=OUTPUT_PREFIX["CONTENT"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_space_create_command(client: Client, args: dict[str, str]) -> CommandResults: """ Creates a new space in confluence cloud. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ validate_create_space_args(args) params, is_private_space = prepare_create_space_args(args) url_suffix = URL_SUFFIX["SPACE"] if is_private_space: url_suffix = URL_SUFFIX["PRIVATE_SPACE"] if "permissions" in params: del params["permissions"] response = client.http_request(method="POST", url_suffix=url_suffix, json_data=params) response_json = response.json() # Creating the Context data context = remove_empty_elements_for_context(response_json) # Creating the Human Readable readable_hr = prepare_hr_for_space_create(response_json) return CommandResults( outputs_prefix=OUTPUT_PREFIX["SPACE"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_group_list_command(client: Client, args: dict[str, str]) -> CommandResults: """ Retrieves the list of groups. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ params = prepare_group_args(args) response = client.http_request(method="GET", url_suffix=URL_SUFFIX["GROUP"], params=params) response_json = response.json() total_records = response_json.get("results", []) if not total_records: return CommandResults(readable_output=MESSAGES["NO_RECORDS_FOUND"].format("group(s)")) context = remove_empty_elements(total_records) readable_hr = prepare_hr_for_groups(total_records) return CommandResults( outputs_prefix=OUTPUT_PREFIX["GROUP"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def fetch_events(client: Client, fetch_limit: int, last_run: Dict[str, Any]) -> tuple[List[Dict[str, Any]], Dict[str, Any]]: # constants for this run last_end_date: Final[int] = last_run.get("end_date", 0) end_date: Final[int] = int((time.time() - 5) * 1000) start_date: Final[int] = last_end_date + 1 if last_end_date else end_date - ONE_MINUTE_IN_MILL_SECONDS # updated in loop next_link = last_run.get("next_link", "") demisto.debug(f"Starting fetch_events with {last_run=} and {fetch_limit=}") all_events, started_new_query, next_link = run_fetch_mechanism(client, fetch_limit, next_link, start_date, end_date) if not all_events: demisto.debug("No events found") return [], {"next_link": None, "end_date": last_end_date} return all_events, {"next_link": next_link, "end_date": end_date if started_new_query else last_end_date} def get_events(client: Client, args: dict) -> tuple[list[dict], CommandResults]: end_date = args.get("end_date", int((time.time() - 5) * 1000)) start_date = int(args.get("start_date", end_date - ONE_MINUTE_IN_MILL_SECONDS)) fetch_limit = int(args.get("limit", DEFAULT_GET_EVENTS_LIMIT)) events, _, _ = run_fetch_mechanism(client, fetch_limit, "", start_date, end_date) return events, CommandResults( outputs=events, outputs_prefix=OUTPUT_PREFIX["EVENT"], readable_output=tableToMarkdown("Events", t=events, removeNull=True), ) def confluence_cloud_content_get_command(client: Client, args: dict[str, str]) -> CommandResults: """ Execute the confluence-cloud-content-get command. Fetches content details from Confluence Cloud by content ID. :type client: ``Client`` :param client: The client used to send HTTP requests to the Confluence Cloud API. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: ``CommandResults`` containing the content details. :rtype: ``CommandResults`` """ content_id = args.get("content_id") if not content_id: raise ValueError(MESSAGES["MISSING_CONTENT_ID"]) params = {"expand": "body.storage"} request_url = urljoin(URL_SUFFIX.get("CONTENT"), content_id) response = client.http_request(method="GET", url_suffix=request_url, params=params) response_json = response.json() context = remove_empty_elements(response_json) readable_hr = prepare_hr_for_content_create(response_json, "Content") return CommandResults( outputs_prefix=OUTPUT_PREFIX.get("CONTENT"), outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) """ COMMAND FUNCTIONS (REST API v2) """ def confluence_cloud_content_create_command_v2(client: Client, args: dict[str, str], content_type: str) -> CommandResults: """ Create a page or blogpost using the Confluence Cloud REST API v2. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type content_type: ``str`` :param content_type: Either ``page`` or ``blogpost``. :return: Standard command result. :rtype: ``CommandResults`` """ config = CONTENT_V2_CONFIG[content_type] params = prepare_content_create_params_v2(args) response = client.http_request(method="POST", url_suffix=config["url_suffix"], json_data=params) response_json = response.json() context = remove_empty_elements_for_context(response_json) readable_hr = prepare_hr_for_content_v2(response_json, config["label"]) return CommandResults( outputs_prefix=config["output_prefix"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_content_list_command_v2(client: Client, args: dict[str, str], content_type: str) -> CommandResults: """ List pages or blogposts using the Confluence Cloud REST API v2. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type content_type: ``str`` :param content_type: Either ``page`` or ``blogpost``. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ config = CONTENT_V2_CONFIG[content_type] params = prepare_content_list_params_v2(args, config) # ``limit`` is the total number of records to return across all pages. limit = validate_limit_v2(args) or DEFAULT_LIMIT_V2 total_records, response_json = paginate_v2_results(client, config["url_suffix"], params, limit) if not total_records: return CommandResults(readable_output=MESSAGES["NO_RECORDS_FOUND"].format(f"{config['label'].lower()}(s)")) context = remove_empty_elements_for_context(total_records) outputs: dict[str, Any] = {f"{config['output_prefix']}(val.id == obj.id)": context} readable_hr = prepare_hr_for_content_list_v2(total_records, config["label"]) return CommandResults(outputs=outputs, readable_output=readable_hr, raw_response=response_json) def confluence_cloud_content_update_command_v2(client: Client, args: dict[str, str], content_type: str) -> CommandResults: """ Update a page or blogpost using the Confluence Cloud REST API v2. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type content_type: ``str`` :param content_type: Either ``page`` or ``blogpost``. :return: Standard command result. :rtype: ``CommandResults`` """ config = CONTENT_V2_CONFIG[content_type] content_id = args[config["id_arg"]] params = prepare_content_update_params_v2(args, config) request_url = urljoin(config["url_suffix"], content_id) response = client.http_request(method="PUT", url_suffix=request_url, json_data=params) response_json = response.json() context = remove_empty_elements_for_context(response_json) readable_hr = prepare_hr_for_content_v2(response_json, config["label"]) return CommandResults( outputs_prefix=config["output_prefix"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_content_delete_command_v2(client: Client, args: dict[str, str], content_type: str) -> CommandResults: """ Delete a page or blogpost using the Confluence Cloud REST API v2. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :type content_type: ``str`` :param content_type: Either ``page`` or ``blogpost``. :return: Standard command result. :rtype: ``CommandResults`` """ config = CONTENT_V2_CONFIG[content_type] content_id = args.get(config["id_arg"]) if not content_id: raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format(config["id_arg"])) params = assign_params(purge=argToBoolean(args["purge"]) if args.get("purge") else None) request_url = urljoin(config["url_suffix"], content_id) client.http_request(method="DELETE", url_suffix=request_url, params=params) hr_key = "HR_PAGE_DELETE" if content_type == "page" else "HR_BLOGPOST_DELETE" return CommandResults(readable_output=MESSAGES[hr_key].format(content_id)) def confluence_cloud_page_create_command(client: Client, args: dict[str, str]) -> CommandResults: """Create a page (Confluence Cloud REST API v2).""" return confluence_cloud_content_create_command_v2(client, args, "page") def confluence_cloud_page_list_command(client: Client, args: dict[str, str]) -> CommandResults: """List pages (Confluence Cloud REST API v2).""" return confluence_cloud_content_list_command_v2(client, args, "page") def confluence_cloud_page_update_command(client: Client, args: dict[str, str]) -> CommandResults: """Update a page (Confluence Cloud REST API v2).""" return confluence_cloud_content_update_command_v2(client, args, "page") def confluence_cloud_page_delete_command(client: Client, args: dict[str, str]) -> CommandResults: """Delete a page (Confluence Cloud REST API v2).""" return confluence_cloud_content_delete_command_v2(client, args, "page") def confluence_cloud_blogpost_create_command(client: Client, args: dict[str, str]) -> CommandResults: """Create a blogpost (Confluence Cloud REST API v2).""" return confluence_cloud_content_create_command_v2(client, args, "blogpost") def confluence_cloud_blogpost_list_command(client: Client, args: dict[str, str]) -> CommandResults: """List blogposts (Confluence Cloud REST API v2).""" return confluence_cloud_content_list_command_v2(client, args, "blogpost") def confluence_cloud_blogpost_update_command(client: Client, args: dict[str, str]) -> CommandResults: """Update a blogpost (Confluence Cloud REST API v2).""" return confluence_cloud_content_update_command_v2(client, args, "blogpost") def confluence_cloud_blogpost_delete_command(client: Client, args: dict[str, str]) -> CommandResults: """Delete a blogpost (Confluence Cloud REST API v2).""" return confluence_cloud_content_delete_command_v2(client, args, "blogpost") def confluence_cloud_footer_comment_create_command(client: Client, args: dict[str, str]) -> CommandResults: """ Create a footer comment using the Confluence Cloud REST API v2. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result. :rtype: ``CommandResults`` """ params = prepare_comment_create_params_v2(args) response = client.http_request(method="POST", url_suffix=URL_SUFFIX_V2["FOOTER_COMMENTS"], json_data=params) response_json = response.json() context = remove_empty_elements_for_context(response_json) readable_hr = prepare_hr_for_comment_v2(response_json, "Footer Comment") return CommandResults( outputs_prefix=OUTPUT_PREFIX["COMMENT"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def confluence_cloud_space_list_command_v2(client: Client, args: dict[str, str]) -> CommandResults: """ List spaces using the Confluence Cloud REST API v2. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result or no records found message. :rtype: ``CommandResults`` """ params = prepare_space_list_params_v2(args) # ``limit`` is the total number of records to return across all pages. limit = validate_limit_v2(args) or DEFAULT_LIMIT_V2 total_records, response_json = paginate_v2_results(client, URL_SUFFIX_V2["SPACES"], params, limit) if not total_records: return CommandResults(readable_output=MESSAGES["NO_RECORDS_FOUND"].format("space(s)")) context = remove_empty_elements_for_context(total_records) outputs: dict[str, Any] = {f"{OUTPUT_PREFIX['SPACE']}(val.id == obj.id)": context} readable_hr = prepare_hr_for_space_list_v2(total_records) return CommandResults(outputs=outputs, readable_output=readable_hr, raw_response=response_json) def confluence_cloud_space_create_command_v2(client: Client, args: dict[str, str]) -> CommandResults: """ Create a space using the Confluence Cloud REST API v2. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. :return: Standard command result. :rtype: ``CommandResults`` """ params = prepare_space_create_params_v2(args) response = client.http_request(method="POST", url_suffix=URL_SUFFIX_V2["SPACES"], json_data=params) response_json = response.json() context = remove_empty_elements_for_context(response_json) readable_hr = prepare_hr_for_space_create_v2(response_json) return CommandResults( outputs_prefix=OUTPUT_PREFIX["SPACE"], outputs_key_field="id", outputs=context, readable_output=readable_hr, raw_response=response_json, ) def _extract_content_id_from_url(url: str) -> str: """ Extract the Confluence content ID from a Confluence page URL. Supports the following URL formats: - https://<site>.atlassian.net/wiki/spaces/<space>/pages/<pageId>/<title> - https://<site>.atlassian.net/wiki/rest/api/content/<contentId> - https://<site>.atlassian.net/wiki/pages/viewpage.action?pageId=<pageId> :type url: ``str`` :param url: The Confluence page URL. :return: The extracted content ID. :rtype: ``str`` :raises ValueError: If the content ID cannot be extracted from the URL. """ for pattern in CONFLUENCE_URL_PATTERNS: match = pattern.search(url) if match: return match.group(1) raise ValueError( f"Could not extract content ID from URL: {url}. " "Supported URL formats: " "https://<site>.atlassian.net/wiki/spaces/<space>/pages/<pageId>/<title>, " "https://<site>.atlassian.net/wiki/pages/viewpage.action?pageId=<pageId>" ) def confluence_cloud_generic_file_get_command(client: Client, args: dict[str, str]) -> CommandResults: """ Execute the get-file-content command. Fetches content from Confluence Cloud by URL and returns it in a generic unified format. :type client: ``Client`` :param client: The client used to send HTTP requests to the Confluence Cloud API. :type args: ``dict[str, str]`` :param args: The command arguments provided by the user. :return: ``CommandResults`` containing the content in a generic format. :rtype: ``CommandResults`` """ url = args.get("url", "") if not url: raise ValueError("The 'url' argument is required.") content_id = _extract_content_id_from_url(url) # Request the body in storage format (XHTML/HTML), then convert it to Markdown for readability. params = {"expand": "body.storage"} request_url = urljoin(URL_SUFFIX.get("CONTENT"), content_id) response = client.http_request(method="GET", url_suffix=request_url, params=params) response_json = response.json() title = response_json.get("title", "") html_content = response_json.get("body", {}).get("storage", {}).get("value", "") # Convert the Confluence storage-format HTML/XHTML into Markdown. body_content = markdownify(html_content).strip() if html_content else "" # Check size of the body content (limit to 5MB = 5 * 1024 * 1024 bytes). if body_content: size_bytes = len(body_content.encode("utf-8")) if size_bytes > MAX_FILE_SIZE: size_mb = size_bytes / (1024 * 1024) limit_mb = MAX_FILE_SIZE / (1024 * 1024) raise ValueError( f"The file '{title}' is {size_mb:.2f} MB, which exceeds the maximum allowed size of {limit_mb:.0f} MB." ) # The body is converted from Confluence storage-format HTML to Markdown, so the MIME type is text/markdown. generic_output = remove_empty_elements( { "Title": title, "Type": "text/markdown", "Name": title, "Content": body_content, "Url": url, "Id": response_json.get("id", ""), } ) readable_hr = tableToMarkdown( "File Content Results", generic_output, headers=["Id", "Title", "Type", "Url"], removeNull=True, ) return CommandResults( outputs_prefix=OUTPUT_PREFIX["FILE_CONTENT"], outputs=generic_output, readable_output=readable_hr, raw_response=response_json, ) def oauth_start_command(oauth_client) -> CommandResults: """Start OAuth authentication flow.""" url = oauth_client.oauth_start() return CommandResults( readable_output=( f"### Authorization Instructions\n" f"1. Click on the following link to authorize:\n{url}\n\n" f"2. After authorizing, you will be redirected to the callback URL\n" f"3. Copy the authorization code from the 'code' parameter in the URL\n" f"4. Run the command: `!confluence-cloud-oauth-complete code=<your_code>`" ) ) def oauth_complete_command(oauth_client, code: str) -> CommandResults: """Complete OAuth authentication flow.""" oauth_client.oauth_complete(code=code) return CommandResults( readable_output=( "### Successfully authenticated!\n" "The access token and refresh token have been saved.\n" "You can now use the integration to fetch events." ) ) def oauth_test_command(oauth_client) -> CommandResults: """Test OAuth authentication and verify accessible resources.""" try: access_token = oauth_client.get_access_token() # Query accessible resources to verify cloud_id and product access response = requests.get( "https://api.atlassian.com/oauth/token/accessible-resources", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"}, verify=oauth_client.verify, proxies=handle_proxy() if oauth_client.proxy else None, timeout=60, ) response.raise_for_status() resources = response.json() demisto.debug(f"{LOGGING_INTEGRATION_NAME} Accessible resources: {resources}") # Format the resources for display resource_info = [] for resource in resources: resource_info.append( f"- **{resource.get('name', 'Unknown')}** (ID: `{resource.get('id', 'N/A')}`)\n" f" URL: {resource.get('url', 'N/A')}\n" f" Scopes: {', '.join(resource.get('scopes', []))}" ) resources_display = "\n".join(resource_info) if resource_info else "No accessible resources found." return CommandResults( readable_output=(f"### ✓ Authentication successful\n\n" f"### Accessible Resources:\n{resources_display}") ) except Exception as e: raise DemistoException(f"Authentication failed: {str(e)}") def create_oauth_client(params: dict): """ Create an OAuth client for Confluence Cloud. :type params: ``dict`` :param params: The integration parameters. :return: OAuth client instance or None if not using OAuth. """ auth_method = params.get("auth_method", "Basic") if auth_method != "OAuth 2.0": return None client_creds = params.get("client_credentials", {}) client_id = client_creds.get("identifier", "") client_secret = client_creds.get("password", "") cloud_id = params.get("cloud_id", "") callback_url = params.get("callback_url", "") server_url = str(params.get("url", "")).strip().removesuffix("/") if not client_id or not client_secret: raise DemistoException("Client ID and Client Secret are required for OAuth 2.0 authentication") if not callback_url: raise DemistoException("Callback URL is required for OAuth 2.0 authentication") # Create OAuth client using AtlassianApiModule return create_atlassian_oauth_client( client_id=client_id, client_secret=client_secret, callback_url=callback_url, cloud_id=cloud_id, server_url=server_url, verify=not params.get("insecure", False), proxy=params.get("proxy", False), product="confluence", ) def create_client(params: dict, oauth_client=None) -> Client: """ Create a Client instance based on the authentication method configured. :type params: ``dict`` :param params: The integration parameters. :type oauth_client: ``Optional`` :param oauth_client: OAuth client instance for OAuth authentication. :return: Client instance configured with the appropriate authentication. :rtype: ``Client`` """ # get the service API url raw_url = params["url"].strip().removesuffix("/") verify_certificate = not params.get("insecure", False) proxy = params.get("proxy", False) validate_url(raw_url) headers: dict = {"Accept": "application/json"} # Extract the site name from the URL, handling various input formats: # "mysite", "mysite.atlassian.net", "https://mysite.atlassian.net", "https://mysite.atlassian.net/wiki/" site_name = raw_url.removeprefix("https://").removeprefix("http://").removesuffix("/") # Remove any path components (e.g., /wiki) site_name = site_name.split("/")[0] # Remove .atlassian.net suffix if present to get just the site name site_name = site_name.removesuffix(".atlassian.net").removesuffix(".atlassian.com") base_url = f"https://{site_name}.atlassian.net" # Check if OAuth authentication is configured auth_method = params.get("auth_method", "Basic") if auth_method == "OAuth 2.0" and oauth_client is not None: # OAuth 2.0 authentication demisto.debug(f"{LOGGING_INTEGRATION_NAME} Using OAuth 2.0 authentication") # Get the access token access_token = oauth_client.get_access_token() headers["Authorization"] = f"Bearer {access_token}" # Per Atlassian OAuth 2.0 (3LO) docs, the base URL for OAuth apps must use # the API gateway: https://api.atlassian.com/ex/confluence/{cloudId} # See: https://developer.atlassian.com/cloud/confluence/oauth-2-3lo-apps/#3-2-construct-the-request-url cloud_id = oauth_client.cloud_id if not cloud_id: raise DemistoException( "Cloud ID is required for OAuth 2.0 authentication. " "Confluence Cloud OAuth 2.0 (3LO) requests must use the Atlassian API gateway. " "Please configure the Cloud ID parameter in the integration instance settings." ) oauth_base_url = f"https://api.atlassian.com/ex/confluence/{cloud_id}" demisto.debug(f"{LOGGING_INTEGRATION_NAME} OAuth base_url: {oauth_base_url}") return Client( base_url=oauth_base_url, verify=verify_certificate, proxy=proxy, headers=headers, ) else: # Basic authentication (email + API token) credentials = params.get("username", {}) username = credentials.get("identifier", "").strip() if credentials.get("identifier") else "" password = credentials.get("password", "") if not username or not password: raise ValueError("Basic authentication requires Email and API Token.") demisto.debug(f"{LOGGING_INTEGRATION_NAME} Using Basic authentication") return Client( base_url=base_url, verify=verify_certificate, proxy=proxy, headers=headers, auth=(username, password), ) """ MAIN FUNCTION """ def main() -> None: # pragma: no cover """ main function, parses params and runs command functions """ params = demisto.params() command = demisto.command() args = demisto.args() demisto.debug(f"{LOGGING_INTEGRATION_NAME} Command being called is {command}") try: # Get authentication parameters auth_method = params.get("auth_method", "Basic") is_oauth = auth_method == "OAuth 2.0" # OAuth client initialization oauth_client = None if is_oauth: oauth_client = create_oauth_client(params) # Commands dictionary commands: dict[str, Callable] = { "confluence-cloud-group-list": confluence_cloud_group_list_command, "confluence-cloud-user-list": confluence_cloud_user_list_command, "confluence-cloud-content-search": confluence_cloud_content_search_command, "confluence-cloud-content-update": confluence_cloud_content_update_command, "confluence-cloud-content-delete": confluence_cloud_content_delete_command, "confluence-cloud-content-list": confluence_cloud_content_list_command, "confluence-cloud-space-list": confluence_cloud_space_list_command, "confluence-cloud-comment-create": confluence_cloud_comment_create_command, "confluence-cloud-content-create": confluence_cloud_content_create_command, "confluence-cloud-space-create": confluence_cloud_space_create_command, "confluence-cloud-content-get": confluence_cloud_content_get_command, # --- REST API v2 commands --- "confluence-cloud-page-create": confluence_cloud_page_create_command, "confluence-cloud-page-list": confluence_cloud_page_list_command, "confluence-cloud-page-update": confluence_cloud_page_update_command, "confluence-cloud-page-delete": confluence_cloud_page_delete_command, "confluence-cloud-blogpost-create": confluence_cloud_blogpost_create_command, "confluence-cloud-blogpost-list": confluence_cloud_blogpost_list_command, "confluence-cloud-blogpost-update": confluence_cloud_blogpost_update_command, "confluence-cloud-blogpost-delete": confluence_cloud_blogpost_delete_command, "confluence-cloud-footer-comment-create": confluence_cloud_footer_comment_create_command, "confluence-cloud-space-listv2": confluence_cloud_space_list_command_v2, "confluence-cloud-space-createv2": confluence_cloud_space_create_command_v2, "get-file-content": confluence_cloud_generic_file_get_command, } strip_args(args) remove_nulls_from_dictionary(args) limit = int(arg_to_number(params.get("max_events_per_fetch", 10000))) # type:ignore # Handle OAuth commands first (they don't need a client) if command == "confluence-cloud-oauth-start": if not oauth_client: raise DemistoException("OAuth commands are only available when using OAuth 2.0 authentication") return_results(oauth_start_command(oauth_client)) elif command == "confluence-cloud-oauth-complete": if not oauth_client: raise DemistoException("OAuth commands are only available when using OAuth 2.0 authentication") code = args.get("code", "") if not code: raise DemistoException("Authorization code is required") return_results(oauth_complete_command(oauth_client, code)) elif command == "confluence-cloud-oauth-test": if not oauth_client: raise DemistoException("OAuth commands are only available when using OAuth 2.0 authentication") return_results(oauth_test_command(oauth_client)) elif command == "test-module": if oauth_client: # For OAuth, test the authentication oauth_client.test_connection() demisto.results("ok") else: # For basic auth, create client and test client = create_client(params, oauth_client) return_results(test_module(client)) elif command in commands: client = create_client(params, oauth_client) return_results(commands[command](client, args)) elif command == "fetch-events": client = create_client(params, oauth_client) events, last_run_object = fetch_events(client, limit, demisto.getLastRun()) if events: add_time_to_events(events) send_events_to_xsiam(events, vendor=VENDOR, product=PRODUCT) demisto.setLastRun(last_run_object) elif command == "confluence-cloud-get-events": client = create_client(params, oauth_client) demisto.debug(f"Fetching Confluence Cloud events with the following parameters: {args}") should_push_events = argToBoolean(args.get("should_push_events", False)) events, command_results = get_events(client, args) return_results(command_results) if should_push_events: send_events_to_xsiam(events, vendor=VENDOR, product=PRODUCT) # Log exceptions and return errors except Exception as e: return_error(f"Failed to execute {demisto.command()} command.\nError:\n{e!s}") """ ENTRY POINT """ if __name__ in ("__main__", "__builtin__", "builtins"): main()