HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.109.1.lve.el8.x86_64 #1 SMP Thu Mar 5 20:23:46 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.30
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/salt/engines/__pycache__/slack.cpython-310.pyc
o

�N�g؏�@s�dZddlZddlZddlZddlZddlZddlZddlZddlZ	ddl
Z	ddlZ	ddlZ	ddl
Z	ddlZ	ddlZ	ddlZ	ddlZ	ddlZ	ddlZ	zddlZdZWney]dZYnwe�e�ZdZdd�ZGdd	�d	�Z		
				ddd
�ZdS)ad
An engine that reads messages from Slack and can act on them

.. versionadded:: 2016.3.0

:depends: `slackclient <https://pypi.org/project/slackclient/>`_ Python module

.. important::
    This engine requires a bot user. To create a bot user, first go to the
    **Custom Integrations** page in your Slack Workspace. Copy and paste the
    following URL, and replace ``myworkspace`` with the proper value for your
    workspace:

    ``https://myworkspace.slack.com/apps/manage/custom-integrations``

    Next, click on the ``Bots`` integration and request installation. Once
    approved by an admin, you will be able to proceed with adding the bot user.
    Once the bot user has been added, you can configure it by adding an avatar,
    setting the display name, etc. You will also at this time have access to
    your API token, which will be needed to configure this engine.

    Finally, add this bot user to a channel by switching to the channel and
    using ``/invite @mybotuser``. Keep in mind that this engine will process
    messages from each channel in which the bot is a member, so it is
    recommended to narrowly define the commands which can be executed, and the
    Slack users which are allowed to run commands.


This engine has two boolean configuration parameters that toggle specific
features (both default to ``False``):

1. ``control`` - If set to ``True``, then any message which starts with the
   trigger string (which defaults to ``!`` and can be overridden by setting the
   ``trigger`` option in the engine configuration) will be interpreted as a
   Salt CLI command and the engine will attempt to run it. The permissions
   defined in the various ``groups`` will determine if the Slack user is
   allowed to run the command. The ``targets`` and ``default_target`` options
   can be used to set targets for a given command, but the engine can also read
   the following two keyword arguments:

   - ``target`` - The target expression to use for the command

   - ``tgt_type`` - The match type, can be one of ``glob``, ``list``,
     ``pcre``, ``grain``, ``grain_pcre``, ``pillar``, ``nodegroup``, ``range``,
     ``ipcidr``, or ``compound``. The default value is ``glob``.

   Here are a few examples:

   .. code-block:: text

       !test.ping target=*
       !state.apply foo target=os:CentOS tgt_type=grain
       !pkg.version mypkg target=role:database tgt_type=pillar

2. ``fire_all`` - If set to ``True``, all messages which are not prefixed with
   the trigger string will fired as events onto Salt's ref:`event bus
   <event-system>`. The tag for these veents will be prefixed with the string
   specified by the ``tag`` config option (default: ``salt/engines/slack``).


The ``groups_pillar_name`` config option can be used to pull group
configuration from the specified pillar key.

.. note::
    In order to use ``groups_pillar_name``, the engine must be running as a
    minion running on the master, so that the ``Caller`` client can be used to
    retrieve that minions pillar data, because the master process does not have
    pillar data.


Configuration Examples
======================

.. versionchanged:: 2017.7.0
    Access control group support added

This example uses a single group called ``default``. In addition, other groups
are being loaded from pillar data. The group names do not have any
significance, it is the users and commands defined within them that are used to
determine whether the Slack user has permission to run the desired command.

.. code-block:: text

    engines:
      - slack:
          token: 'xoxb-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx'
          control: True
          fire_all: False
          groups_pillar_name: 'slack_engine:groups_pillar'
          groups:
            default:
              users:
                - '*'
              commands:
                - test.ping
                - cmd.run
                - list_jobs
                - list_commands
              aliases:
                list_jobs:
                  cmd: jobs.list_jobs
                list_commands:
                  cmd: 'pillar.get salt:engines:slack:valid_commands target=saltmaster tgt_type=list'
              default_target:
                target: saltmaster
                tgt_type: glob
              targets:
                test.ping:
                  target: '*'
                  tgt_type: glob
                cmd.run:
                  target: saltmaster
                  tgt_type: list

This example shows multiple groups applying to different users, with all users
having access to run test.ping. Keep in mind that when using ``*``, the value
must be quoted, or else PyYAML will fail to load the configuration.

.. code-block:: text

    engines:
      - slack:
          groups_pillar: slack_engine_pillar
          token: 'xoxb-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx'
          control: True
          fire_all: True
          tag: salt/engines/slack
          groups_pillar_name: 'slack_engine:groups_pillar'
          groups:
            default:
              users:
                - '*'
              commands:
                - test.ping
              aliases:
                list_jobs:
                  cmd: jobs.list_jobs
                list_commands:
                  cmd: 'pillar.get salt:engines:slack:valid_commands target=saltmaster tgt_type=list'
            gods:
              users:
                - garethgreenaway
              commands:
                - '*'

�NTF�slackcCstsdStS)N)Fz3The 'slackclient' Python module could not be loaded)�HAS_SLACKCLIENT�__virtualname__�rr�F/opt/saltstack/salt/lib/python3.10/site-packages/salt/engines/slack.py�__virtual__�src@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Z	d%d d!�Zd"d#�Zd$S)&�SlackClientcCs*tj�t�|_t�|�|_|j��|_	dS�N)
�salt�minionZMasterMinion�__opts__�
master_minion�slackclientr�scZrtm_connect�
slack_connect)�self�tokenrrr�__init__�szSlackClient.__init__cCsbtjjjd|td�}i}d|vr/|dD]}d|vr.|ds.|d||d<|d||d<q|S)z*
        Get all users from Slack
        �users��functionZapi_key�opts�messageZis_bot�id�name)r
�utilsr�queryr)rr�retr�itemrrr�get_slack_users�s�zSlackClient.get_slack_userscCsHtjjjd|ddd�d�}i}d|vr"|dD]
}|d||d<q|S)z2
        Get all channel names from Slack
        ZroomsT)Zexclude_archivedZexclude_membersrrrr)r
rrr)rrr�channelsrrrr�get_slack_channels�s�zSlackClient.get_slack_channelsc
Csvdt�t�iiid�i}|si}n|}t�d|�zt�|�|���|���}Wnty>t�d||�|�|�g}Ynw|D]q\}}t�	d||�|�
|t�t�iiid��zG||d�t|�dg���||d�t|�dg���||d�|�di��||d	�|�d	i��||d
�|�d
i��WqAt
tfy�t�d|�YqAwt�d|�|S)
z�
        get info from groups in config, and from the named pillar

        todo: add specification for the minion to use to recover pillar
        �default)r�commands�aliases�default_target�targetsz
use_groups %sz3Failed to get groups from %s: %s or from config: %sz$Trying to get %s and %s to be usefulrr#r$r%r&zHCouldn't use group %s. Check that targets is a dictionary and not a listzGot the groups: %s)�set�log�debug�	itertools�chain�_groups_from_pillar�items�AttributeError�warning�info�
setdefault�update�get�
IndexError)rZgroups_conf�groups_pillar_nameZ
ret_groupsZ
use_groupsZ
groups_genrZconfigrrr�get_config_groups�sh	�������

���zSlackClient.get_config_groupscCsT|r&tddkr&td|i�}t�d||�t�d|�t�dt|��|Si}|S)a�
        pillar_prefix is the pillar.get syntax for the pillar to be queried.
        Group name is gotten via the equivalent of using
        ``salt['pillar.get']('{}:{}'.format(pillar_prefix, group_name))``
        in a jinja template.

        returns a dictionary (unless the pillar is mis-formatted)
        XXX: instead of using Caller, make the minion to use configurable so there could be some
             restrictions placed on what pillars can be used.
        �__rolerz
pillar.getz#Got pillar groups %s from pillar %szpillar groups is %szpillar groups type is %s)r�__salt__r(r)�type)rZpillar_nameZ
pillar_groupsrrrr,'s�zSlackClient._groups_from_pillarcCsNt�d�dkrtjj�ttd�j}nd}|r|||�dStd||�dS)zn
        This replaces a function in main called 'fire'

        It fires an event into the salt bus.
        r7ZmasterZsock_dirNz
event.send)rr3r
r�eventZget_master_event�fire_masterr8)r�tag�msgr;rrr�fire;s��zSlackClient.firecCs�t�d|||�|��D]4\}}||dvrd|dvrq||dvr4||�di���vr4d|dvr4qt�d||�||fSt�d||�dS)	a�
        Break out the permissions into the following:

        Check whether a user is in any group, including whether a group has the '*' membership

        :type user: str
        :param user: The username being checked against

        :type command: str
        :param command: The command that is being invoked (e.g. test.ping)

        :type groups: dict
        :param groups: the dictionary with groups permissions structure.

        :rtype: tuple
        :returns: On a successful permitting match, returns 2-element tuple that contains
            the name of the group that successfully matched, and a dictionary containing
            the configuration of the group so it can be referenced.

            On failure it returns an empty tuple

        z!%s wants to run %s with groups %sr�*r#r$z!Slack user %s permitted to run %sz%Slack user %s denied trying to run %sr)r(r0r-r3�keys)r�userZcommand�groups�key�valrrr�can_user_runMs�zSlackClient.can_user_runc	Csttjj�|t|�d��}g}|D]&}d}t�||�}|r2|�d�|�d�|�d�}|�|�q|�|�q|S)z{
        cmdline_str is the string of the command line
        trigger_string is the trigger string, to be removed
        Nz3(?P<begin>.*)(<.*\|)(?P<url>.*)(>)(?P<remainder>.*)�begin�url�	remainder)	r
r�argsZshlex_split�len�re�match�group�append)	rZcmdline_str�trigger_string�cmdlineZcmdlistZcmditem�patternZmtchZorigtextrrr�commandline_to_listvs�zSlackClient.commandline_to_listc	Cs�|�||�}|�||d|�}t�d||�|sdd|dfS|s(dd|dfS|d|d�di���vrR|�|dd|d�dd�d�}|�|dd��n|}|�|||�}d	d
�|D�}d||fS)a#Returns a tuple of (target, cmdline,) for the response

        Raises IndexError if a user can't be looked up from all_slack_users

        Returns (False, False) if the user doesn't have permission

        These are returned together because the commandline and the targeting
        interact with the group config (specifically aliases and targeting configuration)
        so taking care of them together works out.

        The cmdline that is returned is the actual list that should be
        processed by salt, and not the alias.

        rz3slack_user_name is %s and the permitted group is %sFN�r$�cmd�cs&g|]�t�fdd�dD��r��qS)c3s�|]	}��|�VqdSr	)�
startswith)�.0�x�rrr�	<genexpr>�s�z@SlackClient.control_message_target.<locals>.<listcomp>.<genexpr>��target�tgt_type)�all)rWrrYr�
<listcomp>�s��z6SlackClient.control_message_target.<locals>.<listcomp>T)rRrEr(r)r3r@�extend�
get_target)	rZslack_user_name�text�
loaded_groupsrOrP�permitted_groupZuse_cmdliner\rrr�control_message_target�s,���
z"SlackClient.control_message_targetc
Cs�|�d�dkrtd��|�dd�p|�di��dd�}zt�d|�Wnty;}zt�d|�WYd}~nd}~wwtjj�	|�}tjj
�|�}|sPtd��|S)	zs
        Raises ValueError if a value doesn't work out, and TypeError if
        this isn't a message type
        r9rzThis is not a messagerbNz
Message is %sz5Got a message that I could not log. The reason is: %sz_text has no value)
r3�	TypeErrorr(r0�UnicodeEncodeErrorr/r
r�json�dumps�yaml�	safe_load�
ValueError)r�m_dataZ_textZueerrr�message_text�s ��zSlackClient.message_textc#s����������������fdd�}dD]}�jrnt�d�jj|�t�|�qt	d�
�j���	�j��}|D]�}z��|�}	Wnt
tfyd}
zt�d|
�d|iVWYd	}
~
q<d	}
~
ww�jjj�|d
�}||�}|	�|�rӈ�||�}
|�d�s�t�d|�d
��|�d�
|d|	��d|iVq<��|d|	|
|�\}}}t�d||�|r�||d
|d|d||d�Vq<|�d�
|d|��|Vq<|Vq<ddiVq5)a�
        slack_token = string
        trigger_string = string
        input_valid_users = set
        input_valid_commands = set

        When the trigger_string prefixes the message text, yields a dictionary
        of::

            {
                'message_data': m_data,
                'cmdline': cmdline_list, # this is a list
                'channel': channel,
                'user': m_data['user'],
                'slack_client': sc
            }

        else yields {'message_data': m_data} and the caller can handle that

        When encountering an error (e.g. invalid message), yields {}, the caller can proceed to the next message

        When the websocket being read from has given up all its messages, yields {'done': True} to
        indicate that the caller has read all of the relevant data for now, and should continue
        its own processing and check back for more data later.

        This relies on the caller sleeping between checks, otherwise this could flood
        csd|vr0d|vrd|dvrt�d�|dd}nd|vr/d|dvr/t�d�|dd}n|�d�}|�d�}|�d�rBd}n��|�}||��|�|d	�}|d
sh������������|�|d
<|ds������������|�|d<|S)z0Always try to return the user and channel anywayrArz@Message was edited, so we look for user in the original message.Zcommentz6Comment was added, so we look for user in the comment.�channel�Dzprivate chat)�message_data�user_id�	user_name�channel_namersrt)r(r)r3rV�clearr2rr!)rmrrZ
channel_idrt�data�Zall_slack_channelsZall_slack_usersrrrr�	just_data�s:�
�



�z:SlackClient.generate_triggered_messages.<locals>.just_data)��
��<z4Slack connection is invalid. Server: %s, sleeping %sz3Connection to slack is still invalid, giving up: {}Tz3Got an error from trying to get the message text %srqNrorszCThe user %s can not be looked up via slack. What has happened here?rAz;The user {} can not be looked up via slack.  Not running {}rrzGot target: %s, cmdline: %s)rqrorArsrPr\z${} is not allowed to use command {}.�done)rr!rr(r/r�server�time�sleep�UserWarning�formatZrtm_readrnrlrfr)r �findrVr6r3�error�send_messagere)rrrOrBr5rxZsleepsr=rmZmsg_textZmsg_errrorvrc�allowedr\rPrrwr�generate_triggered_messages�s����$����
�
��

��

����
�z'SlackClient.generate_triggered_messagesc	s�ddd����fdd�}||fD]1}|�|�\}}d|vrAt�d|�d|vr8t�d	|�|d|dd�S|ddd�Sq||fD]}||d
�}t�d|�|�d�r]|SqF�S)a�
        When we are permitted to run a command on a target, look to see
        what the default targeting is for that group, and for that specific
        command (if provided).

        It's possible for None or False to be the result of either, which means
        that it's expected that the caller provide a specific target.

        If no configured target is provided, the command line will be parsed
        for target=foo and tgt_type=bar

        Test for this::

            h = {'aliases': {}, 'commands': {'cmd.run', 'pillar.get'},
                'default_target': {'target': '*', 'tgt_type': 'glob'},
                'targets': {'pillar.get': {'target': 'you_momma', 'tgt_type': 'list'}},
                'users': {'dmangot', 'jmickle', 'pcn'}}
            f = {'aliases': {}, 'commands': {'cmd.run', 'pillar.get'},
                 'default_target': {}, 'targets': {},'users': {'dmangot', 'jmickle', 'pcn'}}

            g = {'aliases': {}, 'commands': {'cmd.run', 'pillar.get'},
                 'default_target': {'target': '*', 'tgt_type': 'glob'},
                 'targets': {}, 'users': {'dmangot', 'jmickle', 'pcn'}}

        Run each of them through ``get_configured_target(('foo', f), 'pillar.get')`` and confirm a valid target

        r?�globr[csZ�\}}|�d�}|s
�}|�d�r|d�|�r|d|}|�d�s+t�d||�|S)z_
            Validate cmd against the group to return the target, or a null target
            r%r&r\z7Group %s is not configured to have a target for cmd %s.)r3r(r))rTrZgroup_configr\�Znull_targetrdrr�check_cmd_against_group�s


�z7SlackClient.get_target.<locals>.check_cmd_against_groupr\ztarget is in kwargs %s.r]ztgt_type is in kwargs %s.rzthis cmdline has target %s.)�parse_args_and_kwargsr(r)r3)	rrdrPZ
alias_cmdliner�Zthis_cl�_�kwargs�checkedrr�rrals$
�
�zSlackClient.get_targetc
Ks�z,z
|tt|���d�}Wn
ttfyd}Ynwtjjdd�|��D�|t	d�WSt
yL}zddl}t�
d|�|��WYd}~dSd}~ww)	z5
        Print out YAML using the block mode
        �outNcSsi|]	\}}||d�qS)�returnr)rWrX�yrrr�
<dictcomp>�sz2SlackClient.format_return_text.<locals>.<dictcomp>)r�rrz1Exception encountered when trying to serialize %sz5Got an error trying to serialze/clean up the response)�next�iterr3�
StopIterationr.r
�outputZ
string_formatr-r�	Exception�pprintr(�	exceptionZpformat)rrvrr�Z	outputter�excr�rrr�format_return_text�s(�����zSlackClient.format_return_textcCsZg}i}t|�dkr)|dd�D]}d|vr#|�dd�\}}|||<q|�|�q||fS)zU
        cmdline: list

        returns tuple of: args (list), kwargs (dict)
        rSN�=)rJ�splitrN)rrPrIr�rrC�valuerrrr��s
z!SlackClient.parse_args_and_kwargsc	Cs�tj�t�}t�d�}|st�d�}i}|D]1}|jj|�d�|�rG|�d|g�}|�di�}|�di�}tjj	�
tjj	�|��|d�||<q|S)aV
        Given a list of job_ids, return a dictionary of those job_ids that have
        completed and their results.

        Query the salt event bus via the jobs runner. jobs.list_job will show
        a job in progress, jobs.lookup_jid will return a job that has
        completed.

        returns a dictionary of job id: result
        Z
ext_job_cacheZmaster_job_cachez.get_jidz
jobs.list_jobZResultZFunction)rvr)r
�runner�RunnerClientrr3r
Z	returnersrTrrh�loadsri)	rZoutstanding_jidsr��source�results�jidZ
job_resultZ
jid_resultZjid_functionrrr�get_jobs_from_runner�s


��z SlackClient.get_jobs_from_runnerrSc	Cspi}	t�d|�t�|�d}|D]�}t�d|���|dkr't�d�nl|s3|d7}t�d�q|�d	�r?t�d
�nT|r]t�d|�t�d||�|�d
�	||d�d��|�|r�t
|�dkr�|�d�r�|jjj
�|d�}	|�|�}
t�d|
�|||
<|	�d�	|d|
��|d7}qt��}|�|���}t�dt
|�t��|�|D]�}
||
d}
||
d}|
�r6t�d|
�||
}|jjj
�|d�}	|�|
|�}d�	|d|d|
|d�}|	�|�t��}tj�|��d�}d|�d�}|jjd|	j||d�}t�d |�tjj�tjj�|��}d!|v�r3|d!d"u�r3|d�d#�	|d$��||
=q�q)%z�
        Pull any pending messages from the message_generator, sending each
        one to either the event bus, the command_async or both, depending on
        the values of fire_all and command
        TzSleeping for interval of %srz$Got a message from the generator: %srzz6Breaking in getting messages because count is exceededrSzSkipping an empty message.r}zmsg is donez&Firing message to the bus with tag: %sz%s %sz{}/{}rqr9rProzSubmitted a job and got jid: %sz%@{}'s job is submitted as salt jid {}rsz&Getting %s jobs status took %s secondsrvrzret to send back is %sz-@{}'s job `{}` (id: {}) (target: {}) returnedr\z%Y%m%d%H%M%S%fz
salt-results-z.yamlzfiles.upload)r �filename�contentz Got back %s via the slack client�okFz	Error: {}r�)r(Ztracerr�r@r/r3r)r>r�rJrr~r r��run_command_asyncr�r�r��datetime�
fromtimestamp�strftimeZapi_callrr
rrjrkrhri)r�message_generator�fire_allr<�control�intervalZoutstanding�countr=ror�Z
start_timeZ
job_status�resultrZthis_jobZreturn_textZ
return_prefix�ts�str��rZresprrr�run_commands_from_slack_async�s�	
�



���
�
���
����z)SlackClient.run_commands_from_slack_asynccCs2t�d�ttj�t�j�}|dd}|�|d�\}}d|vr,|j	t
�|d�d�|dd}|dd}t�d|�||vr]tj�t�}t�d	|�|�
|||d
��}	|	d}
|
St�d||�t�d
|||||�tj���}|jt|�|||t|�d�}
Wd�n1s�wYt�d|
�|
S)a�
        :type message_generator: generator of dict
        :param message_generator: Generates messages from slack that should be run

        :type fire_all: bool
        :param fire_all: Whether to also fire messages to the event bus

        :type tag: str
        :param tag: The tag to send to use to send to the event bus

        :type interval: int
        :param interval: time to wait between ending a loop and beginning the next

        z#Going to run a command asynchronousrPr�pillar)r�r\r]ztarget_type is: %sz(Command %s will run via runner_functions)�arg�kwargr�z5Command %s will run via local.cmd_async, targeting %szRunning %s, %s, %s, %s, %s)r�r�r]Nzret from local.cmd_async is %s)r(r)�sortedr
r�ZRunnerrZ	functionsr�r2�astZliteral_evalr�Zasynchronous�clientZLocalClientZ	cmd_async�strr0)rr=Zrunner_functionsrTrIr�r\r]r�Zjob_id_dictZjob_id�localrrrr�Ys<
����zSlackClient.run_command_asyncN)rS)�__name__�
__module__�__qualname__rrr!r6r,r>rErRrernr�rar�r�r�r�r�rrrrr�s(F)6@!
�_r�!�salt/engines/slackc	Cs�tjj�dd�|r|�d�st�d�t�d�t	d��zt
|d�}|�||||�}|�||||�WdSt
yCt
t�����w)	zF
    Listen to slack events and forward them to salt, new version
    ZArgonz�This 'slack' engine will be deprecated and will be replace by the slack_bolt engine. This new engine will use the new Bolt library from Slack and requires a Slack app and a Slack bot account.Zxoxb�z%Slack bot token not found, bailing...z%Slack Engine bot token not configured)rN)r
rZversionsZ
warn_untilrVrr�r(r�r�rr�r�r��	traceback�
format_exc)	rr�ZtriggerrBr5r�r<r�r�rrr�start�s"
�


��r�)Fr�NNFr�)�__doc__r�r�r*�loggingrKrr�Zsalt.clientr
Zsalt.loaderZsalt.minionZsalt.outputZsalt.runnerZsalt.utils.argsZsalt.utils.eventZsalt.utils.httpZsalt.utils.jsonZsalt.utils.slackZsalt.utils.yamlrr�ImportError�	getLoggerr�r(rrrr�rrrr�<module>sT�
_�