internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: StackStorm/st2

Issue:
Corner case: "st2 execution tail" fails when execution list is empty
```
$ st2 execution list
+----+------------+--------------+--------+-----------------+---------------+
| id | action.ref | context.user | status | start_timestamp | end_timestamp |
+----+------------+--------------+--------+-----------------+---------------+
+----+------------+--------------+--------+-----------------+---------------+
```
```
$ st2 --debug execution tail
2017-09-21 23:07:35,475  DEBUG - Using cached token from file "/home/vagrant/.st2/token-testu"
# -------- begin 140611505289808 request ----------
curl -X GET -H  'Connection: keep-alive' -H  'Accept-Encoding: gzip, deflate' -H  'Accept: */*' -H  'User-Agent: python-requests/2.14.2' -H  'X-Auth-Token: 46a703f653f84629b5ac15cd145e69fc' 'http://127.0.0.1:9101/v1/executions/?limit=1'
# -------- begin 140611505289808 response ----------
[]
# -------- end 140611505289808 response ------------

ERROR: 'NoneType' object has no attribute 'id'

CLI settings:
----------------
Config file path: /home/vagrant/.st2/config
Client settings:
----------------
ST2_BASE_URL: http://127.0.0.1
ST2_AUTH_URL: http://127.0.0.1:9100
ST2_API_URL: http://127.0.0.1:9101/v1
ST2_STREAM_URL: http://127.0.0.1:9102/v1
ST2_AUTH_TOKEN: 46a703f653f84629b5ac15cd145e69fc

Proxy settings:
---------------
HTTP_PROXY:
HTTPS_PROXY:

Traceback (most recent call last):
  File "/home/vagrant/git/st2/st2client/st2client/shell.py", line 327, in run
    args.func(args)
  File "/home/vagrant/git/st2/st2client/st2client/commands/resource.py", line 44, in decorate
    return func(*args, **kwargs)
  File "/home/vagrant/git/st2/st2client/st2client/commands/action.py", line 1391, in run_and_print
    execution_id = execution.id
AttributeError: 'NoneType' object has no attribute 'id'
```


Discussion:

Resolving patch:
diff --git a/st2client/st2client/commands/action.py b/st2client/st2client/commands/action.py
--- a/st2client/st2client/commands/action.py
+++ b/st2client/st2client/commands/action.py
@@ -1388,8 +1388,12 @@ def run_and_print(self, args, **kwargs):
         # Special case for id "last"
         if execution_id == 'last':
             executions = self.manager.query(limit=1)
-            execution = executions[0] if executions else None
-            execution_id = execution.id
+            if executions:
+                execution = executions[0]
+                execution_id = execution.id
+            else:
+                print('No executions found in db.')
+                return
         else:
             execution = self.manager.get_by_id(execution_id, **kwargs)
 


Test patch:
Repository: StackStorm/st2

Issue:
Action 'linux.service' fails on Centos7
When I tried to execute restart some service on the Centos7 server got the following error:
```
Traceback (most recent call last):
  File "/tmp/5a0459bc07ac686fb813a920/service.py", line 24, in <module>
    subprocess.call(cmd, shell=True)
NameError: name 'cmd' is not defined
```
After investigation the resolution has been found:
in file /opt/stackstorm/packs/linux/actions/service.py the entry

`elif re.search(distro, 'Redhat') or re.search(distro, 'Fedora'):`

fixed to 

`elif re.search(distro, 'Redhat') or re.search(distro, 'Fedora') or re.search(distro, 'CentOS Linux'):`

The issue has gone





Discussion:
Thanks for reporting it and looking on solution.

Since you have the working code change, Pull Request would be very welcome!

https://github.com/StackStorm/st2/blob/master/contrib/linux/actions/service.py


Resolving patch:
diff --git a/contrib/linux/actions/service.py b/contrib/linux/actions/service.py
--- a/contrib/linux/actions/service.py
+++ b/contrib/linux/actions/service.py
@@ -18,7 +18,8 @@
     else:
         print("Unknown service")
         sys.exit(2)
-elif re.search(distro, 'Redhat') or re.search(distro, 'Fedora'):
+elif re.search(distro, 'Redhat') or re.search(distro, 'Fedora') or \
+        re.search(distro, 'CentOS Linux'):
     cmd = "systemctl %s %s" % (args['act'], args['service'])
 
 subprocess.call(cmd, shell=True)


Test patch:
Repository: StackStorm/st2

Issue:
Incomplete help for: st2 action-alias match
```
$ st2 action-alias match --help
usage: st2 action-alias match [-t TOKEN] [--api-key API_KEY] [-j] [-y]
                              [-a ATTR [ATTR ...]] [-w WIDTH [WIDTH ...]]
                              command
st2 action-alias match: error: too few arguments
```


Discussion:

Resolving patch:
diff --git a/st2client/st2client/commands/action_alias.py b/st2client/st2client/commands/action_alias.py
--- a/st2client/st2client/commands/action_alias.py
+++ b/st2client/st2client/commands/action_alias.py
@@ -41,10 +41,10 @@ def __init__(self, description, app, subparsers, parent_parser=None):
 
         self.commands['match'] = ActionAliasMatchCommand(
             self.resource, self.app, self.subparsers,
-            add_help=False)
+            add_help=True)
         self.commands['execute'] = ActionAliasExecuteCommand(
             self.resource, self.app, self.subparsers,
-            add_help=False)
+            add_help=True)
 
 
 class ActionAliasListCommand(resource.ContentPackResourceListCommand):
@@ -69,10 +69,8 @@ def __init__(self, resource, *args, **kwargs):
 
         self.parser.add_argument('match_text',
                                  metavar='command',
-                                 help=help)
-        self.parser.add_argument('-h', '--help',
-                                 action='store_true', dest='help',
-                                 help='Print usage for the given action.')
+                                 help=('Get the list of %s that match the command text.' %
+                                       resource.get_display_name().lower()))
         self.parser.add_argument('-a', '--attr', nargs='+',
                                  default=self.display_attributes,
                                  help=('List of attributes to include in the '
@@ -108,10 +106,8 @@ def __init__(self, resource, *args, **kwargs):
 
         self.parser.add_argument('command_text',
                                  metavar='command',
-                                 help=help)
-        self.parser.add_argument('-h', '--help',
-                                 action='store_true', dest='help',
-                                 help='Print usage for the given action.')
+                                 help=('Execute the command text by finding a matching %s.' %
+                                       resource.get_display_name().lower()))
         self.parser.add_argument('-u', '--user', type=str, default=None,
                                  help='User under which to run the action (admins only).')
 


Test patch:
Repository: StackStorm/st2

Issue:
Missing [workflow_engine] in st2.conf.sample
##### SUMMARY

https://github.com/StackStorm/st2/blob/master/conf/st2.conf.sample is missing a new section for `[workflow_engine]`

Also, shouldn't this section be named `[workflowengine]` to go along with the "style" of the other sections like `[resultstracker]` , `[garbagecollector]`, etc

##### ISSUE TYPE
 - Bug Report
 - Feature Idea

##### STACKSTORM VERSION
2.8

##### EXPECTED RESULTS
https://github.com/StackStorm/st2/blob/master/conf/st2.conf.sample contains a section for `[workflow_engine]`



Discussion:
Thanks for reporting this - will push a fix.

Resolving patch:
diff --git a/tools/config_gen.py b/tools/config_gen.py
--- a/tools/config_gen.py
+++ b/tools/config_gen.py
@@ -27,6 +27,7 @@
 CONFIGS = ['st2actions.config',
            'st2actions.notifier.config',
            'st2actions.resultstracker.config',
+           'st2actions.workflows.config',
            'st2api.config',
            'st2stream.config',
            'st2auth.config',


Test patch:
Repository: StackStorm/st2

Issue:
St2Stream service broken when using SSL with mongodb
## SUMMARY

This issue is an extension to #4832 however this time it is the st2stream service, I have looked that the code and can see the same monkey patch code hasn't been applied to the st2stream app

### STACKSTORM VERSION

Paste the output of ``st2 --version``: 3.3.0

##### OS, environment, install method

Docker compose with the split services and mongo db references commented out so that an external db can be used  https://github.com/StackStorm/st2-docker/blob/master/docker-compose.yml

All other services correctly connected to mongodb.net test instance with the exception of st2stream.

## Steps to reproduce the problem

use docker yaml at https://github.com/StackStorm/st2-docker/blob/master/docker-compose.yml, comment out mongo container and references, adjust files/st2-docker.conf to point to external DB with SSL = True enabled.
docker-compose up

## Expected Results

What did you expect to happen when running the steps above?

st2stream to operate correctly

## Actual Results

What happened? What output did you get?

2020-11-16 05:48:55,053 WARNING [-] Retry on ConnectionError - Cannot connect to database default :
maximum recursion depth exceeded



Adding monkey patch code to st2stream app resolves the issue (manually injected into container to test).

file:   st2stream/cmd/api.py
Code: 
from st2common.util.monkey_patch import monkey_patch
monkey_patch()




Discussion:
Thanks for the report!

Considering there is an example PR to fix it for other services, we'd love to accept external contributions to fix this for str2stream as well. Help wanted.
What line did you put the monkey patch in? 
Hey, I added the line just below the copyright 

https://github.com/StackStorm/st2/blob/ce31176556be506606b83f6854630f8e6c0fd5ea/st2stream/st2stream/cmd/api.py#L15

from st2common.util.monkey_patch import monkey_patch
monkey_patch()
@christopher-russell should be easy to submit a PR then. Can you do it?
No worries, I'll submit a PR

Resolving patch:
diff --git a/st2stream/st2stream/cmd/api.py b/st2stream/st2stream/cmd/api.py
--- a/st2stream/st2stream/cmd/api.py
+++ b/st2stream/st2stream/cmd/api.py
@@ -13,6 +13,9 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from st2common.util.monkey_patch import monkey_patch
+monkey_patch()
+
 import os
 import sys
 


Test patch:
Repository: StackStorm/st2

Issue:
Remove obsolete 'bin/st2-check-license'
The project ships https://github.com/StackStorm/st2/blob/master/st2common/bin/st2-check-license which is irrelevant now, considering ongoing EWC features integration in the st2 core.

The task is to find all the places: https://github.com/search?q=org%3AStackStorm+st2-check-license&type=code and remove the `st2-check-license` scripts.

This is an easy `good first issue` for someone willing to start contributing and exploring the st2 system.
Bonus points to find other obsolete, outdated, irrelevant scripts in st2 core.
Help wanted!


Discussion:

Resolving patch:
diff --git a/st2common/setup.py b/st2common/setup.py
--- a/st2common/setup.py
+++ b/st2common/setup.py
@@ -57,7 +57,6 @@
         'bin/st2-self-check',
         'bin/st2-track-result',
         'bin/st2-validate-pack-config',
-        'bin/st2-check-license',
         'bin/st2-pack-install',
         'bin/st2-pack-download',
         'bin/st2-pack-setup-virtualenv'


Test patch:
Repository: StackStorm/st2

Issue:
TODO: Remove the --python3 flag and warning in packs.install
Follow up from #5100 and [the Slack thread](https://stackstorm-community.slack.com/archives/CSBELJ78A/p1608901763314300?thread_ts=1608157605.269500&cid=CSBELJ78A) - remove the `--python3` flag to st2client entirely, including the deprecation warning.


Discussion:
I'm happy to take this on, as I think I removed it once, and then put it back as we hadn't warned about its deprecation...

Resolving patch:
diff --git a/st2client/st2client/commands/pack.py b/st2client/st2client/commands/pack.py
--- a/st2client/st2client/commands/pack.py
+++ b/st2client/st2client/commands/pack.py
@@ -19,7 +19,6 @@
 
 import six
 import editor
-import warnings
 import yaml
 
 from st2client.models import Config
@@ -255,12 +254,6 @@ def __init__(self, resource, *args, **kwargs):
             help="Name of the %s in Exchange, or a git repo URL."
             % resource.get_plural_display_name().lower(),
         )
-        self.parser.add_argument(
-            "--python3",
-            action="store_true",
-            default=False,
-            help="Use Python 3 binary for pack virtual environment.",
-        )
         self.parser.add_argument(
             "--force",
             action="store_true",
@@ -282,12 +275,6 @@ def run(self, args, **kwargs):
         if not is_structured_output:
             self._get_content_counts_for_pack(args, **kwargs)
 
-        if args.python3:
-            warnings.warn(
-                "DEPRECATION WARNING: --python3 flag is ignored and will be removed "
-                "in v3.5.0 as StackStorm now runs with python3 only"
-            )
-
         return self.manager.install(
             args.packs,
             force=args.force,


Test patch:
Repository: StackStorm/st2

Issue:
should check both 'http_proxy' and 'HTTP_PROXY' when get proxy info from environment variables
## SUMMARY

I just faced an embarrassed problem that command `st2 action list` keeps return 503. 

I tried `st2 --debug action list` and the result in line  `HTTP_PROXY`(**uppercase**) was empty. This mislead me that the proxy info was set(which is not).

I finally found that the root cause is a **lowercase** `http_proxy` env variable was set in the system.

So I think it maybe more friendly to check both 'http_proxy' and 'HTTP_PROXY' to get proxy info when using st2 command with `--debug` option.

related code:
https://github.com/StackStorm/st2/blob/5c4e5f8e93c7ed83c4aa4d196085c2912ae7b285/st2client/st2client/base.py#L404


### STACKSTORM VERSION

3.3

##### OS, environment, install method
centos 7.6, custom install

## Steps to reproduce the problem

1) set **lowercase** proxy environment variable, eg. `export http_proxy='127.0.0.1:8888'`
2) run `st2 --debug action list`

## Expected Results

proxy info should be printed

## Actual Results

proxy info did not show, value of HTTP_PROXY is empty.

Thanks!



Discussion:
Thanks @wfgydbu, that's a valid bug report and a good find.

> So I think it maybe more friendly to check both 'http_proxy' and 'HTTP_PROXY' to get proxy info when using st2 command with --debug option.

Agree :+1:  We'd welcome code contributions to improve this.
Thanks, @armab.

I will be very happy to make this contribution as my first PR for st2. 

Feel free to assign it to me.  :)
I am working on it.
is this issue still open, or @wfgydbu resolved it?


Resolving patch:
diff --git a/st2client/st2client/base.py b/st2client/st2client/base.py
--- a/st2client/st2client/base.py
+++ b/st2client/st2client/base.py
@@ -447,6 +447,12 @@ def _print_client_settings(self, args):
         print("")
         print("Proxy settings:")
         print("---------------")
-        print("HTTP_PROXY: %s" % (os.environ.get("HTTP_PROXY", "")))
-        print("HTTPS_PROXY: %s" % (os.environ.get("HTTPS_PROXY", "")))
+        print(
+            "HTTP_PROXY: %s"
+            % (os.environ.get("http_proxy", os.environ.get("HTTP_PROXY", "")))
+        )
+        print(
+            "HTTPS_PROXY: %s"
+            % (os.environ.get("http_proxy", os.environ.get("HTTPS_PROXY", "")))
+        )
         print("")


Test patch:
Repository: StackStorm/st2

Issue:
Trigger name collision workaround
This addresses the jinja trigger name collision noted in issue #4641


Discussion:

Resolving patch:
diff --git a/contrib/core/actions/inject_trigger.py b/contrib/core/actions/inject_trigger.py
--- a/contrib/core/actions/inject_trigger.py
+++ b/contrib/core/actions/inject_trigger.py
@@ -21,7 +21,7 @@
 
 
 class InjectTriggerAction(Action):
-    def run(self, trigger, payload=None, trace_tag=None):
+    def run(self, trigger=None, trigger_name=None, payload=None, trace_tag=None):
         payload = payload or {}
 
         datastore_service = self.action_service.datastore_service
@@ -32,6 +32,18 @@ def run(self, trigger, payload=None, trace_tag=None):
         # results in a TriggerInstanceDB database object creation or not. The object is created
         # inside rulesengine service and could fail due to the user providing an invalid trigger
         # reference or similar.
+
+        # Raise an error if both trigger and trigger_name are specified
+        if trigger and trigger_name:
+            raise ValueError(
+                "Parameters `trigger` and `trigger_name` are mutually exclusive."
+            )
+
+        # Raise an error if neither trigger nor trigger_name are specified
+        if not trigger and not trigger_name:
+            raise ValueError("You must include the `trigger_name` parameter.")
+
+        trigger = trigger if trigger else trigger_name
         self.logger.debug(
             'Injecting trigger "%s" with payload="%s"' % (trigger, str(payload))
         )


Test patch:
Repository: StackStorm/st2

Issue:
St2 auth logs leak sensitive information
## SUMMARY

St2 writes http requests with unsanitised username/password pair to `st2.auth.log` when log level set to ``DEBUG``.

### STACKSTORM VERSION

``st2 3.8.0, on Python 3.6.9``

##### OS, environment, install method
```
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.6 LTS
Release:        18.04
Codename:       bionic
```

**Install method:** manual (https://docs.stackstorm.com/install/u18.html)

## Steps to reproduce the problem

1. Configure ``st2.conf`` auth section using LDAP backend
```
[auth]
host = 127.0.0.1
port = 9100
use_ssl = False
debug = True
enable = True
logging = /etc/st2/logging.auth.conf

mode = standalone
backend = ldap
backend_kwargs = { "bind_dn": "cn=st2,dc=example,dc=net", "bind_password": "xxxx", "base_ou": "dc=example,dc=com", "group_dns": ["cn=stackstorm users", "cn=stackstorm admins"], "host": "localhost", "port": 389, "use_ssl": false }
```

2. Login via st2 cli
```st2 auth st2admin -t```

3. Review log entries in ``st2.auth.log``

Logged http request contains Authorization header with username/password.
```
2023-05-13 09:52:17,208 140432424245856 DEBUG router [-] Received call with WebOb: POST /tokens HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Authorization: Basic c3QyYWRtaW46TGVha2VkUGFzc3dvcmQK
Connection: keep-alive
Content-Length: 2
Content-Type: application/json
Host: 127.0.0.1:9100
User-Agent: python-requests/2.25.1
X-Request-Id: 52ad53f1-9942-4b31-95c6-cb12e442f77a

{}
```
``Authorization`` is plain text base64 encoded: ``base64 -d <<<c3QyYWRtaW46TGVha2VkUGFzc3dvcmQK
st2admin:LeakedPassword``

## Expected Results

In order of preference:
1. remove/obfuscate the ``Authorization` header
2. don't log the request, just the call url.

## Actual Results

Authentication secrets leaked in plain text through logs.


Discussion:

Resolving patch:
diff --git a/st2common/st2common/router.py b/st2common/st2common/router.py
--- a/st2common/st2common/router.py
+++ b/st2common/st2common/router.py
@@ -328,7 +328,12 @@ def __call__(self, req):
 
         At the time of writing, the only property being utilized by middleware was `x-log-result`.
         """
-        LOG.debug("Received call with WebOb: %s", req)
+        LOG.debug("Received call with WebOb: %s %s", req.method, req.url)
+        # if a more detailed log is required:
+        # loggable_req = req.copy()
+        # loggable_req.headers.pop('Authorization', None)
+        # loggable_req.headers.pop('X-Request-Id', None)
+        # LOG.debug("Received call with WebOb: %s", loggable_req)
         endpoint, path_vars = self.match(req)
         LOG.debug("Parsed endpoint: %s", endpoint)
         LOG.debug("Parsed path_vars: %s", path_vars)


Test patch:
Repository: Miserlou/Zappa

Issue:
Add 'Rollback' Capability
It'd be nice if we could do something like

```
python manage.py rollback dev 
```

to return the previously deployed function, or

```
python manage.py rollback dev
```

to rollback 5 versions, etc.



Discussion:
:+1: on this idea. 

Also I think you mean: 

> python manage.py rollback dev 5 

to rollback 5 versions of dev 

Ah, yes.

Hey @graemeglass - how would you feel about trying to implement this?   

@Miserlou Happy to give it a try. Will attempt to carve out some time near the end of this week.

Great! Looking forward to it.


Resolving patch:
diff --git a/zappa/zappa.py b/zappa/zappa.py
--- a/zappa/zappa.py
+++ b/zappa/zappa.py
@@ -7,6 +7,7 @@
 import os
 import time
 import zipfile
+import requests
 
 from boto.s3.connection import S3Connection
 from boto.s3.key import Key
@@ -430,6 +431,37 @@ def invoke_lambda_function(self, function_name, payload, invocation_type='Event'
         )
 
         return response
+
+    def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True):
+        """
+        Rollback the lambda function code 'versions_back' number of revisions.
+
+        Returns the Function ARN.
+
+        """
+        boto_session = self.get_boto_session()
+        client = boto_session.client('lambda')
+
+        response = client.list_versions_by_function(FunctionName=function_name)
+        #Take into account $LATEST
+        if len(response['Versions']) < versions_back + 1:
+            print("We do not have {} revisions. Aborting".format(str(versions_back)))
+            return False
+
+        revisions = [int(revision['Version']) for revision in response['Versions'] if revision['Version'] != '$LATEST']
+        revisions.sort(reverse=True)
+
+        response = client.get_function(FunctionName='function:{}:{}'.format(function_name, revisions[versions_back]))
+        response = requests.get(response['Code']['Location'])
+
+        if response.status_code != 200:
+            print("Failed to get version {} of {} code".format(versions_back, function_name))
+            return False
+
+        response = client.update_function_code(FunctionName=function_name, ZipFile=response.content, Publish=publish)
+
+        return response['FunctionArn']
+
     ##
     # API Gateway
     ##
@@ -657,6 +689,7 @@ def get_api_url(self, stage_name):
                 return endpoint_url
 
         return ''
+
     ##
     # IAM
     ##


Test patch:
Repository: Miserlou/Zappa

Issue:
Unable to locate credentials
When I run at latest master:
`zappa update staging`

I get this error:

```
Updating assume role policy on ZappaLambdaExecution IAM Role.
Unable to locate credentials
```

I do have custom `"profile_name": "myprofile"` at the zappa_settings.json file

Looks like the bug is here that it doesn't use the existing session:
https://github.com/Miserlou/Zappa/blob/master/zappa/zappa.py#L851

Do you think changing to this will work?
`client = self.boto_session.client('iam')`



Discussion:

Resolving patch:
diff --git a/zappa/zappa.py b/zappa/zappa.py
--- a/zappa/zappa.py
+++ b/zappa/zappa.py
@@ -848,7 +848,7 @@ def create_iam_roles(self):
         if role.assume_role_policy_document != assume_policy_obj and \
                 set(role.assume_role_policy_document['Statement'][0]['Principal']['Service']) != set(assume_policy_obj['Statement'][0]['Principal']['Service']):
             print("Updating assume role policy on " + self.role_name + " IAM Role.")
-            client = boto3.client('iam') # Is there a way to do this with the IAM session?
+            client = self.boto_session.client('iam')
             client.update_assume_role_policy(
                 RoleName=self.role_name,
                 PolicyDocument=assume_policy_s


Test patch:
Repository: Miserlou/Zappa

Issue:
Cannot set custom headers
Zappa does not let me specify custom headers which should be returned in the response.



Discussion:

Resolving patch:
diff --git a/zappa/cli.py b/zappa/cli.py
--- a/zappa/cli.py
+++ b/zappa/cli.py
@@ -39,6 +39,7 @@
     'exclude',
     'http_methods',
     'integration_response_codes',
+    'method_header_types',
     'method_response_codes',
     'parameter_depth',
     'role_name',


Test patch: