├── .editorconfig ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── captainwebhook ├── __init__.py └── captainwebhook.py ├── circle.yml ├── docs └── index.md ├── mkdocs.yml ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py └── test_captainwebhook.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = false 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [Makefile] 18 | indent_style = tab 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | htmlcov 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | 38 | # Complexity 39 | output/*.html 40 | output/*/index.html 41 | 42 | # Sphinx 43 | docs/_build 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "3.4" 7 | - "3.3" 8 | - "2.7" 9 | - "pypy" 10 | 11 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 12 | install: pip install -r requirements.txt 13 | 14 | # command to run tests, e.g. python setup.py test 15 | script: python setup.py test 16 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Stavros Korokithakis 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/skorokithakis/captainwebhook/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | Captain Webhook could always use more documentation, whether as part of the 40 | official Captain Webhook docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/skorokithakis/captainwebhook/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `captainwebhook` for local development. 59 | 60 | 1. Fork the `captainwebhook` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/captainwebhook.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv captainwebhook 68 | $ cd captainwebhook/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: 78 | 79 | $ flake8 captainwebhook tests 80 | $ python setup.py test 81 | $ tox 82 | 83 | To get flake8 and tox, just pip install them into your virtualenv. 84 | 85 | 6. Commit your changes and push your branch to GitHub:: 86 | 87 | $ git add . 88 | $ git commit -m "Your detailed description of your changes." 89 | $ git push origin name-of-your-bugfix-or-feature 90 | 91 | 7. Submit a pull request through the GitHub website. 92 | 93 | Pull Request Guidelines 94 | ----------------------- 95 | 96 | Before you submit a pull request, check that it meets these guidelines: 97 | 98 | 1. The pull request should include tests. 99 | 2. If the pull request adds functionality, the docs should be updated. Put 100 | your new functionality into a function with a docstring, and add the 101 | feature to the list in README.rst. 102 | 3. The pull request should work for Python 2.7, 3.3, and 3.4, and for PyPy. Check 103 | https://travis-ci.org/skorokithakis/captainwebhook/pull_requests 104 | and make sure that the tests pass for all supported Python versions. 105 | 106 | Tips 107 | ---- 108 | 109 | To run a subset of tests:: 110 | 111 | $ python -m unittest tests.test_captainwebhook 112 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.1.0 (2015-02-11) 7 | --------------------- 8 | 9 | * First release on PyPI. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Stavros Korokithakis 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | * Neither the name of Captain Webhook nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | 7 | recursive-include tests * 8 | recursive-exclude * __pycache__ 9 | recursive-exclude * *.py[co] 10 | 11 | recursive-include docs *.rst conf.py Makefile make.bat 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs clean 2 | 3 | help: 4 | @echo "clean - remove all build, test, coverage and Python artifacts" 5 | @echo "clean-build - remove build artifacts" 6 | @echo "clean-pyc - remove Python file artifacts" 7 | @echo "clean-test - remove test and coverage artifacts" 8 | @echo "lint - check style with flake8" 9 | @echo "test - run tests quickly with the default Python" 10 | @echo "test-all - run tests on every Python version with tox" 11 | @echo "coverage - check code coverage quickly with the default Python" 12 | @echo "docs - generate Sphinx HTML documentation, including API docs" 13 | @echo "release - package and upload a release" 14 | @echo "dist - package" 15 | @echo "install - install the package to the active Python's site-packages" 16 | 17 | clean: clean-build clean-pyc clean-test 18 | 19 | clean-build: 20 | rm -fr build/ 21 | rm -fr dist/ 22 | rm -fr .eggs/ 23 | find . -name '*.egg-info' -exec rm -fr {} + 24 | find . -name '*.egg' -exec rm -f {} + 25 | 26 | clean-pyc: 27 | find . -name '*.pyc' -exec rm -f {} + 28 | find . -name '*.pyo' -exec rm -f {} + 29 | find . -name '*~' -exec rm -f {} + 30 | find . -name '__pycache__' -exec rm -fr {} + 31 | 32 | clean-test: 33 | rm -fr .tox/ 34 | rm -f .coverage 35 | rm -fr htmlcov/ 36 | 37 | lint: 38 | flake8 captainwebhook tests 39 | 40 | test: 41 | python setup.py test 42 | 43 | test-all: 44 | tox 45 | 46 | coverage: 47 | coverage run --source captainwebhook setup.py test 48 | coverage report -m 49 | coverage html 50 | open htmlcov/index.html 51 | 52 | docs: 53 | rm -f docs/captainwebhook.rst 54 | rm -f docs/modules.rst 55 | sphinx-apidoc -o docs/ captainwebhook 56 | $(MAKE) -C docs clean 57 | $(MAKE) -C docs html 58 | open docs/_build/html/index.html 59 | 60 | release: clean 61 | python setup.py sdist upload 62 | python setup.py bdist_wheel upload 63 | 64 | dist: clean 65 | python setup.py sdist 66 | python setup.py bdist_wheel 67 | ls -l dist 68 | 69 | install: clean 70 | python setup.py install 71 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | Captain Webhook 3 | =============================== 4 | 5 | .. image:: https://travis-ci.org/skorokithakis/captainwebhook.png?branch=master 6 | :target: https://travis-ci.org/skorokithakis/captainwebhook 7 | 8 | .. image:: https://img.shields.io/pypi/v/captainwebhook.svg 9 | :target: https://pypi.python.org/pypi/captainwebhook 10 | 11 | 12 | Captain Webhook runs your scripts when it receives a webhook. 13 | 14 | * Free software: BSD license 15 | * Documentation: https://captain-webhook.readthedocs.org. 16 | 17 | Features 18 | -------- 19 | 20 | * Runs an HTTP server and executes a given command when a pre-selected URL is requested. 21 | * Nothing else. 22 | -------------------------------------------------------------------------------- /captainwebhook/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Stavros Korokithakis' 4 | __email__ = 'hi@stavros.io' 5 | __version__ = '0.2.0' 6 | -------------------------------------------------------------------------------- /captainwebhook/captainwebhook.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import argparse 3 | try: 4 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 5 | except ImportError: 6 | from http.server import BaseHTTPRequestHandler, HTTPServer 7 | 8 | try: 9 | from urlparse import urlparse, parse_qsl 10 | except ImportError: 11 | from urllib.parse import urlparse, parse_qsl 12 | import subprocess 13 | import sys 14 | import threading 15 | 16 | 17 | URL_PREFIX = "/webhook/" 18 | 19 | 20 | def get_handler(args): 21 | key = URL_PREFIX + args.key 22 | if not key.endswith("/"): 23 | key += "/" 24 | 25 | class CommandHandler(BaseHTTPRequestHandler): 26 | exec_in_progress = False 27 | 28 | def _constant_time_compare(self, val1, val2): 29 | """ 30 | Mitigate timing attacks on the URL. 31 | """ 32 | if len(val1) != len(val2): 33 | return False 34 | 35 | result = 0 36 | for x, y in zip(val1, val2): 37 | result |= ord(x) ^ ord(y) 38 | return result == 0 39 | 40 | def _exec(self, parameters): 41 | CommandHandler.exec_in_progress = True 42 | if args.template: 43 | try: 44 | subprocess.call(args.command.format(**parameters), shell=True) 45 | except KeyError: 46 | print("Could not execute command, required parameters not passed.") 47 | else: 48 | subprocess.call(args.command, shell=True) 49 | CommandHandler.exec_in_progress = False 50 | 51 | def do_GET(self): 52 | url = urlparse(self.path) 53 | path = url.path 54 | parameters = dict(parse_qsl(url.query)) 55 | 56 | if not path.endswith("/"): 57 | self.path += "/" 58 | 59 | if self._constant_time_compare(path, key): 60 | self.send_response(200) 61 | self.send_header('Content-type', 'application/json') 62 | self.end_headers() 63 | 64 | if CommandHandler.exec_in_progress: 65 | self.wfile.write(b'{"status": "Another command is already in progress."}') 66 | else: 67 | self.wfile.write(b'{"status": "ok"}') 68 | t = threading.Thread(target=self._exec, args=[parameters]) 69 | t.daemon = True 70 | t.start() 71 | else: 72 | self.send_response(404) 73 | self.send_header('Content-type', 'text/html') 74 | self.end_headers() 75 | self.wfile.write("Page not found.") 76 | 77 | return 78 | do_POST = do_GET 79 | return CommandHandler 80 | 81 | 82 | def main(): 83 | parser = argparse.ArgumentParser(description='Run a command when a webhook is triggered.') 84 | parser.add_argument('command', help='the command to run when the URL is requested') 85 | parser.add_argument('-k', '--key', default="changeme", help='the secret key that will trigger the command') 86 | parser.add_argument('-t', '--template', action="store_true", help='whether to use template formatting based on the query string parameters') 87 | parser.add_argument('-p', '--port', type=int, default=48743, help='the port to listen on') 88 | parser.add_argument('-i', '--interface', default="0.0.0.0", help='the interface to listen on') 89 | 90 | args = parser.parse_args() 91 | 92 | try: 93 | server = HTTPServer((args.interface, args.port), get_handler(args)) 94 | except: 95 | print("Could not start server, invalid interface or port specified.") 96 | sys.exit(1) 97 | 98 | print("Starting server...\nTrigger URL: http://%s:%s%s%s/\nCommand: %s" % (args.interface, args.port, URL_PREFIX, args.key, args.command)) 99 | try: 100 | server.serve_forever() 101 | except: 102 | server.socket.close() 103 | 104 | if __name__ == "__main__": 105 | main() 106 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | machine: 2 | python: 3 | version: 2.7.8 4 | 5 | dependencies: 6 | pre: 7 | - ln -s ~/.pyenv/versions/3.3.2/bin/python3.3 ~/bin 8 | - ln -s ~/.pyenv/versions/3.4.1/bin/python3.4 ~/bin 9 | - ln -s ~/.pyenv/versions/pypy-2.4.0/bin/pypy ~/bin 10 | override: 11 | - pip install tox 12 | 13 | test: 14 | override: 15 | - env PATH="$HOME/bin:$PATH" tox 16 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Captain Webhook 2 | 3 | Captain Webhook is a very simple Python script that will run an HTTP server and trigger commands whenever a secret URL 4 | is requested. It is mainly used for deployments, for example triggering ansible-pull whenever a commit is pushed to 5 | GitHub. 6 | 7 | ## Installing 8 | 9 | You can install Captain Webhook using `pip`: 10 | 11 | ``` 12 | pip install captainwebhook 13 | ``` 14 | 15 | You can also get the latest source at the canonical location of Captain Webhook, its GitHub repository: 16 | 17 | [https://github.com/skorokithakis/captainwebhook](https://github.com/skorokithakis/captainwebhook) 18 | 19 | 20 | ## How to use 21 | 22 | Using Captain Webhook is very simple. Just launch it with the command you want to run: 23 | 24 | ``` 25 | cptwebhook "echo hello!" 26 | ``` 27 | 28 | And visit the URL in your browser: 29 | 30 | [http://localhost:48743/webhook/changeme/](http://localhost:48743/webhook/changeme/) 31 | 32 | The command you specified will be run. 33 | 34 | 35 | ## "Advanced" options 36 | 37 | Captain Webhook supports some super-advanced functionality that is detailed 38 | below. 39 | 40 | ### Password protection 41 | 42 | Obviously, the URL above isn't very secure, since anyone could trigger the command then. To make things a bit more 43 | obscure, and thus secure, Captain Webhook allows you to specify a key: 44 | 45 | ``` 46 | cptwebhook -k ichoKie5IeGhiexa "echo hello!" 47 | ``` 48 | 49 | The URL now becomes: 50 | 51 | [http://localhost:48743/webhook/ichoKie5IeGhiexa/](http://localhost:48743/webhook/ichoKie5IeGhiexa/) 52 | 53 | ### Command templates 54 | 55 | Your command doesn't have to be static! Captain Webhook can accept template 56 | variables in the command string and populate them with whatever comes in the 57 | query string of the request by passing the `--template` flag. For example: 58 | 59 | ``` 60 | cptwebhook -t "echo Hello, {name}!" 61 | ``` 62 | 63 | Try the URL: 64 | 65 | [http://localhost:48743/webhook/changeme/?name=world](http://localhost:48743/webhook/changeme/?name=world) 66 | 67 | will execute "echo Hello, world!". Isn't that the best thing ever? 68 | 69 | ### Miscellanea 70 | 71 | Other options include the interface and port the server will listen on. You can see more details with: 72 | 73 | ``` 74 | cptwebhook -h 75 | ``` 76 | 77 | 78 | ## Miscellaneous 79 | 80 | Captain Webhook will always return a 200 (some services don't like other return codes), and will always return JSON. 81 | A command will never be triggered again while the first one is running, Captain Webhook will just ignore any subsequent 82 | invocations until the first one is finished. 83 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: Captain Webhook documentation 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | wheel==0.23.0 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | try: 6 | from setuptools import setup 7 | except ImportError: 8 | from distutils.core import setup 9 | 10 | from captainwebhook import __version__ 11 | 12 | 13 | with open('README.rst') as readme_file: 14 | readme = readme_file.read() 15 | 16 | with open('HISTORY.rst') as history_file: 17 | history = history_file.read().replace('.. :changelog:', '') 18 | 19 | requirements = [ 20 | # TODO: put package requirements here 21 | ] 22 | 23 | test_requirements = [ 24 | # TODO: put package test requirements here 25 | ] 26 | 27 | setup( 28 | name='captainwebhook', 29 | version=__version__, 30 | description="Captain Webhook runs your scripts when it receives a webhook.", 31 | long_description=readme + '\n\n' + history, 32 | author="Stavros Korokithakis", 33 | author_email='hi@stavros.io', 34 | url='https://github.com/skorokithakis/captainwebhook', 35 | packages=[ 36 | 'captainwebhook', 37 | ], 38 | package_dir={'captainwebhook': 39 | 'captainwebhook'}, 40 | include_package_data=True, 41 | install_requires=requirements, 42 | license="BSD", 43 | zip_safe=False, 44 | entry_points={ 45 | 'console_scripts': ['cptwebhook=captainwebhook.captainwebhook:main'], 46 | }, 47 | keywords='captainwebhook', 48 | classifiers=[ 49 | 'Development Status :: 2 - Pre-Alpha', 50 | 'Intended Audience :: Developers', 51 | 'License :: OSI Approved :: BSD License', 52 | 'Natural Language :: English', 53 | "Programming Language :: Python :: 2", 54 | 'Programming Language :: Python :: 2.7', 55 | 'Programming Language :: Python :: 3', 56 | 'Programming Language :: Python :: 3.3', 57 | 'Programming Language :: Python :: 3.4', 58 | ], 59 | test_suite='tests', 60 | tests_require=test_requirements 61 | ) 62 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /tests/test_captainwebhook.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | test_captainwebhook 6 | ---------------------------------- 7 | 8 | Tests for `captainwebhook` module. 9 | """ 10 | 11 | import unittest 12 | from collections import namedtuple 13 | 14 | from captainwebhook.captainwebhook import get_handler, BaseHTTPRequestHandler 15 | 16 | 17 | class TestCaptainwebhook(unittest.TestCase): 18 | 19 | def test_something(self): 20 | args = namedtuple("Args", ["key", "command"])("some key", "some command") 21 | PullHandler = get_handler(args) 22 | self.assertTrue(issubclass(PullHandler, BaseHTTPRequestHandler)) 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude=env/*,*/migrations/*,venv/* 3 | ignore=F403,E128,E126,E123,E121,E265,E501,N802,N803,N806 4 | 5 | [tox] 6 | envlist = py27, py33, py34, pypy 7 | 8 | [testenv] 9 | setenv = 10 | PYTHONPATH = {toxinidir}:{toxinidir}/captainwebhook 11 | commands = python setup.py test 12 | deps = 13 | -r{toxinidir}/requirements.txt 14 | --------------------------------------------------------------------------------