{"id":13787802,"url":"https://github.com/EliuX/flask-opa","last_synced_at":"2025-05-12T02:30:33.291Z","repository":{"id":53753765,"uuid":"152926471","full_name":"EliuX/flask-opa","owner":"EliuX","description":"Flask extension for OPA","archived":false,"fork":false,"pushed_at":"2021-03-16T03:26:38.000Z","size":42,"stargazers_count":39,"open_issues_count":2,"forks_count":12,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-19T20:57:55.818Z","etag":null,"topics":["client-library","cloud","flask-extension","microservices-architecture","opa","policy","python3","security"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/EliuX.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-14T00:42:01.000Z","updated_at":"2025-03-31T16:43:03.000Z","dependencies_parsed_at":"2022-09-26T20:31:50.032Z","dependency_job_id":null,"html_url":"https://github.com/EliuX/flask-opa","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EliuX%2Fflask-opa","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EliuX%2Fflask-opa/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EliuX%2Fflask-opa/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EliuX%2Fflask-opa/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/EliuX","download_url":"https://codeload.github.com/EliuX/flask-opa/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253662528,"owners_count":21944090,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client-library","cloud","flask-extension","microservices-architecture","opa","policy","python3","security"],"created_at":"2024-08-03T21:00:31.447Z","updated_at":"2025-05-12T02:30:32.977Z","avatar_url":"https://github.com/EliuX.png","language":"Python","funding_links":[],"categories":["Language and Platform Integrations"],"sub_categories":["Python"],"readme":"Flask-OPA\n=========\n[![Build Status](https://travis-ci.com/EliuX/flask-opa.svg?branch=master)](https://travis-ci.com/EliuX/flask-opa)\n[![codecov](https://codecov.io/gh/EliuX/flask-opa/branch/master/graph/badge.svg)](https://codecov.io/gh/EliuX/flask-opa)\n[![PyPI Version](http://img.shields.io/pypi/v/Flask-OPA.svg)](https://pypi.python.org/pypi/Flask-OPA)\n\nSimple to use [Flask](http://flask.pocoo.org) extension that lets you secure your projects with\n[Open Policy Agent](https://www.openpolicyagent.org). It allows \n* HTTP API Authorization\n* Policy Enforcement Point (AOP using decorators on methods)\n\n## Quick start \n\nIts recommended for you to try out the app in the package `examples`. Thanks to the `Makefile` you can run the demo \nproject with the following command\n\n```bash\n make demo   \n```\n\n### How it works?\n\nFor a better understanding of what `make demo` does and how, you should set up `flask_opa` in your project. Follow the \nnext steps:\n\n1. Run OPA in server mode\n\n    * Check the [latest OPA release](https://github.com/open-policy-agent/opa/releases) and download it.\n    * Put the binary file in the path of your system\n    * Allow its execution with something like `chmod 755 ./opa`\n    * Run opa in server mode with the sample policies\n    \n    ```bash \n    opa run -s -w examples\n    ```\n    \n      - `-s` is to run it in server mode instead of opening the REPL\n      - `-w` is for watching the changes of the data/policy files\n\n1. Specify the configuration variables\n\n    * `OPA_URL` url accessible in your running OPA server, used to evaluate your input. It includes the path of the \n     policy, e.g. `http://localhost:8181/v1/data/examples/allow`.\n    \n    * `OPA_SECURED` boolean to specify if OPA will be enabled to your application.\n    \n    See more at the [rest api reference](https://www.openpolicyagent.org/docs/rest-api.html)\n\n1. Bind the OPA class to your Flask application\n\n    It is easy to bind the Flask-OPA library to your application. Just follow the following steps:\n\n   1. Create the OPA instance\n   \n       ```python\n       app = Flask(__name__)\n       app.config.from_pyfile('app.cfg')\n       opa = OPA(app, parse_input)\n       ```\n   \n       Let's see the parameters that we passed to the OPA class:\n       \n       - `parse_input` (Required) contains a method that returns the input data json to be evaluated by the policy, e.g.:\n   \n       ```json\n       {\n           \"input\": {\n             \"method\": \"GET\",\n             \"path\": [\"data\", \"jon\"],\n             \"user\": \"paul\"\n           }\n       }\n       ```\n       \n       - `url` (Optional) to use an specific url instead of the `OPA_URL` optionally specified in the app configuration.\n       - `allow_function` (Optional) predicate that determinate if the response from OPA allows (True) or denies (False) the request\n       \n       If you want enforce the OPA security in your application you can create the OPA instance like this:\n       \n       ```python\n       opa = OPA.secure(app, parse_input, url=\"http://localhost:8181/v1/data/package_name/allow\")\n       ```\n       \n       or\n       \n       ```python\n       opa = OPA(app, parse_input, url=\"http://localhost:8181/v1/data/package_name/allow\").secured()\n       ```\n       \n       otherwise, OPA will enforce your security only if ``OPA_SECURED`` is `True`.\n       \n       Specify the logging level to `DEBUG` if you want to get access to Flask-OPA logs of its operations using\n       \n       ```python\n       app.logger.setLevel(logging.DEBUG)\n       ```\n   \n   1. Run your Flask application.\n    \n## Policy Enforcement point\nOne of the features this module provides is [Policy Enforcement Point][PEP], which basically allows you to ensure \npolicies at any method of your application.\nFor practical purposes, lets imagine a sample method that is in charge of logging content related to some actions done by \nusers. In this case we must create a different input functions that provide useful information for certain policies that \nwill decide if a log should be sent or not to a remote server. Let's suppose that such logging method is something like:\n\n```python\ndef log_remotely(content):\n    # Imagine a code to log this remotely\n    app.logger.info(\"Logged remotely: %s\", content)\n```\n\nLet's create a [PEP][PEP] decorator using our `OPA` instance as a function (callable mode) that will intercept every \ncall to `log_remotely`. The parameters are pretty much the same as those used to secure the application. The resulting \ninstance will decorate our function of interest:\n\n```python\ndef validate_logging_input_function(*arg, **kwargs):\n   return {\n        \"input\": {\n            \"user\": request.headers.get(\"Authorization\", \"\"),\n            \"content\": arg[0]\n        }\n    }\n\nsecure_logging = app.opa(\"Logging PEP\", app.config[\"OPA_URL_LOGGING\"], validate_logging_input_function)\n\n@secure_logging\ndef log_remotely(content):\n    # Imagine a code to log content remotely\n    app.logger.info(\"Logged remotely: %s\", content)\n```\n\nAs you might have noticed, the only new thing we truly require for adding the [PEP][PEP] is a new input function. This \nfunction can provide a more versatile input than the one used by the `OPA` instance created for the whole app: in our \nexample it provides data related to the user request and data provided by the parameters of the decorated function as \nwell.\n\nRead the [examples README](examples/README.md) for more detailed information about how to run a demo.\n\n## Error handling\nAll errors related to OPA extend from `OPAException`. They will always be thrown unless the app variable \n`OPA_DENY_ON_FAIL` or `app.opa.deny_on_opa_fail` is set to `False`.\n\n### Types of `OPAException` errors\n* `AccessDeniedException`: When the `allow_function` returns `False`, indicating that a policy denies the access.\n* `OPAServerUnavailableException`: When it cannot connect to the OPA Server.\n* `OPAUnexpectedException`: When the response of the OPA server is not `OK`, i.e. the status code is not `200`.\n\n### Handling OPA Exceptions\n\nWith the `errorhandler` decorator of the Flask app, you can easily catch any of these errors, e.g.:\n\n```python\n@app.errorhandler(OPAException)\ndef handle_opa_exception(e):\n    return json.dumps({\"message\": str(e)}), 403\n```\n\nor particular ones:\n\n```python\n@app.errorhandler(OPAServerUnavailableException)\ndef handle_opa_exception_conn(e):\n    app.logger.debug(\"Issue connecting to the OPA server: %s\", e)\n    return \"Authorization cannot be enforced\", 403\n```\n\n## Makefile\n\nThe Makefile contains multiple useful actions you might need. Check them with \n\n```bash\n make help   \n```\n\n## Author\n\nEliecer Hernandez Garbey\n\n### Links\n\n- Main website: [EliuX Overflow](http://eliux.github.io)\n- Twitter: [@eliux_black](https://twitter.com/eliux_black)\n- LinkedIn: [eliecer-hernández-garbey-16172686](https://www.linkedin.com/in/eliecer-hern%C3%A1ndez-garbey-16172686/)\n- StackOverflow: [EliuX](https://stackoverflow.com/users/3233398/eliux)\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.\n\n\n[PEP]: https://tools.ietf.org/html/rfc2904#section-4.4\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FEliuX%2Fflask-opa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FEliuX%2Fflask-opa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FEliuX%2Fflask-opa/lists"}