├── .dockerignore
├── .github
├── dependabot.yml
└── workflows
│ └── build.yaml
├── .gitignore
├── .pre-commit-config.yaml
├── .releaserc.yml
├── .renovaterc.json
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── config-example.yml
├── powerdns_api_proxy
├── __init__.py
├── __main__.py
├── config.py
├── logging.py
├── metrics.py
├── models.py
├── pdns.py
├── proxy.py
└── utils.py
├── requirements-dev.txt
├── requirements.txt
├── setup.py
└── tests
├── __init__.py
├── fixtures
├── __init__.py
└── test_regex_parsing.yaml
├── integration
└── __init__.py
└── unit
├── __init__.py
├── config_test.py
├── proxy_test.py
└── utils_test.py
/.dockerignore:
--------------------------------------------------------------------------------
1 | .git/
2 | .venv/
3 | log
4 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "" # See documentation for possible values
9 | directory: "/" # Location of package manifests
10 | schedule:
11 | interval: "weekly"
12 |
--------------------------------------------------------------------------------
/.github/workflows/build.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | on:
3 | push:
4 | branches:
5 | - "*"
6 | tags:
7 | - "v*.*.*"
8 |
9 | jobs:
10 | test:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v4
14 | - uses: actions/setup-python@v5
15 | with:
16 | python-version: '3.11'
17 |
18 | - name: Setup
19 | run: make setup
20 |
21 | - name: Run tests
22 | run: make unit
23 | pre-commit:
24 | runs-on: ubuntu-latest
25 | steps:
26 | - uses: actions/checkout@v4
27 | - uses: actions/setup-python@v5
28 | with:
29 | python-version: '3.11'
30 |
31 | - name: Setup
32 | run: make setup
33 |
34 | - name: Run pre-commit
35 | run: make pre-commit-all
36 | env:
37 | SKIP: "no-commit-to-branch"
38 | container:
39 | runs-on: ubuntu-latest
40 | needs:
41 | - test
42 | - pre-commit
43 | steps:
44 | - name: Check out the repo
45 | uses: actions/checkout@v4
46 |
47 | - name: Extract metadata (tags, labels) for Docker
48 | id: meta
49 | uses: docker/metadata-action@v5.6.1
50 | with:
51 | # list of Docker images to use as base name for tags
52 | images: |
53 | ghcr.io/akquinet/powerdns-api-proxy
54 | # generate Docker tags based on the following events/attributes
55 | tags: |
56 | type=schedule
57 | type=ref,event=branch
58 | type=ref,event=tag
59 | type=semver,pattern={{version}}
60 | type=semver,pattern={{major}}.{{minor}}
61 | type=semver,pattern={{major}}
62 | type=sha
63 |
64 | - name: Login to GHCR
65 | if: github.event_name == 'push' && (startsWith(github.ref, 'refs/tags') || github.ref == 'refs/heads/main')
66 | uses: docker/login-action@v3
67 | with:
68 | registry: ghcr.io
69 | username: ${{ github.repository_owner }}
70 | password: ${{ secrets.GITHUB_TOKEN }}
71 |
72 | - name: Build and push master Docker image
73 | uses: docker/build-push-action@v6.14.0
74 | with:
75 | context: .
76 | push: ${{ github.event_name == 'push' && (startsWith(github.ref, 'refs/tags') || github.ref == 'refs/heads/main') }}
77 | tags: ${{ steps.meta.outputs.tags }}
78 | labels: ${{ steps.meta.outputs.labels }}
79 |
80 | semantic-release:
81 | runs-on: ubuntu-latest
82 | if: github.event_name == 'push' && github.ref == 'refs/heads/main'
83 | needs:
84 | - container
85 | steps:
86 | - name: Checkout
87 | uses: actions/checkout@v4
88 | with:
89 | persist-credentials: false
90 |
91 | - name: Generate a token
92 | id: generate_token
93 | uses: actions/create-github-app-token@v1
94 | with:
95 | app-id: ${{ secrets.CICD_APP_ID }}
96 | private-key: ${{ secrets.CICD_APP_PRIVATE_KEY }}
97 |
98 | - name: Semantic Release
99 | uses: cycjimmy/semantic-release-action@v3
100 | env:
101 | GITHUB_TOKEN: "${{ steps.generate_token.outputs.token }}"
102 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | api-test.py
2 | config.yml
3 | log
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # C extensions
11 | *.so
12 |
13 | # Distribution / packaging
14 | .Python
15 | build/
16 | develop-eggs/
17 | dist/
18 | downloads/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | wheels/
27 | share/python-wheels/
28 | *.egg-info/
29 | .installed.cfg
30 | *.egg
31 | MANIFEST
32 |
33 | # PyInstaller
34 | # Usually these files are written by a python script from a template
35 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
36 | *.manifest
37 | *.spec
38 |
39 | # Installer logs
40 | pip-log.txt
41 | pip-delete-this-directory.txt
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .nox/
47 | .coverage
48 | .coverage.*
49 | .cache
50 | nosetests.xml
51 | coverage.xml
52 | *.cover
53 | *.py,cover
54 | .hypothesis/
55 | .pytest_cache/
56 | cover/
57 |
58 | # Translations
59 | *.mo
60 | *.pot
61 |
62 | # Django stuff:
63 | *.log
64 | local_settings.py
65 | db.sqlite3
66 | db.sqlite3-journal
67 |
68 | # Flask stuff:
69 | instance/
70 | .webassets-cache
71 |
72 | # Scrapy stuff:
73 | .scrapy
74 |
75 | # Sphinx documentation
76 | docs/_build/
77 |
78 | # PyBuilder
79 | .pybuilder/
80 | target/
81 |
82 | # Jupyter Notebook
83 | .ipynb_checkpoints
84 |
85 | # IPython
86 | profile_default/
87 | ipython_config.py
88 |
89 | # pyenv
90 | # For a library or package, you might want to ignore these files since the code is
91 | # intended to run in multiple environments; otherwise, check them in:
92 | # .python-version
93 |
94 | # pipenv
95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
98 | # install all needed dependencies.
99 | #Pipfile.lock
100 |
101 | # poetry
102 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103 | # This is especially recommended for binary packages to ensure reproducibility, and is more
104 | # commonly ignored for libraries.
105 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106 | #poetry.lock
107 |
108 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
109 | __pypackages__/
110 |
111 | # Celery stuff
112 | celerybeat-schedule
113 | celerybeat.pid
114 |
115 | # SageMath parsed files
116 | *.sage.py
117 |
118 | # Environments
119 | .env
120 | .venv
121 | env/
122 | venv/
123 | ENV/
124 | env.bak/
125 | venv.bak/
126 |
127 | # Spyder project settings
128 | .spyderproject
129 | .spyproject
130 |
131 | # Rope project settings
132 | .ropeproject
133 |
134 | # mkdocs documentation
135 | /site
136 |
137 | # mypy
138 | .mypy_cache/
139 | .dmypy.json
140 | dmypy.json
141 |
142 | # Pyre type checker
143 | .pyre/
144 |
145 | # pytype static type analyzer
146 | .pytype/
147 |
148 | # Cython debug symbols
149 | cython_debug/
150 |
151 | # PyCharm
152 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
153 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
154 | # and can be added to the global gitignore or merged into this file. For a more nuclear
155 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
156 | #.idea/
157 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | repos:
3 | - repo: https://github.com/pre-commit/pre-commit-hooks
4 | rev: "v5.0.0"
5 | hooks:
6 | - id: check-yaml
7 | args:
8 | - "--allow-multiple-documents"
9 | - id: check-json
10 | - id: end-of-file-fixer
11 | - id: trailing-whitespace
12 | - id: check-added-large-files
13 | - id: check-symlinks
14 | - id: no-commit-to-branch
15 | - id: trailing-whitespace
16 | - id: debug-statements
17 | - id: requirements-txt-fixer
18 |
19 | - repo: https://github.com/astral-sh/ruff-pre-commit
20 | rev: v0.9.2
21 | hooks:
22 | - id: ruff
23 | args: [--fix, --exit-non-zero-on-fix]
24 | - id: ruff-format
25 | args: []
26 |
27 | - repo: https://github.com/asottile/pyupgrade
28 | rev: "v3.19.1"
29 | hooks:
30 | - id: pyupgrade
31 |
32 | - repo: https://github.com/pre-commit/mirrors-mypy
33 | rev: "v1.15.0"
34 | hooks:
35 | - id: mypy
36 | args:
37 | - "--ignore-missing-imports"
38 | additional_dependencies:
39 | - types-requests
40 | - types-PyYAML
41 |
42 | - repo: https://github.com/hadolint/hadolint
43 | rev: "v2.12.1-beta"
44 | hooks:
45 | - id: hadolint-docker
46 |
--------------------------------------------------------------------------------
/.releaserc.yml:
--------------------------------------------------------------------------------
1 | ---
2 | plugins:
3 | - "@semantic-release/commit-analyzer"
4 | - "@semantic-release/release-notes-generator"
5 | - "@semantic-release/github"
6 |
7 | branches:
8 | - "main"
9 |
--------------------------------------------------------------------------------
/.renovaterc.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": [
4 | "config:base",
5 | ":disableDependencyDashboard"
6 | ],
7 | "reviewers": [],
8 | "pre-commit": {
9 | "enabled": true
10 | },
11 | "pip_requirements": {
12 | "fileMatch": [
13 | "(^|/)([\\w-]*)requirements\\.(txt|pip)$",
14 | "(^|/)([\\w-]*)requirements-dev\\.(txt|pip)$"
15 | ]
16 | },
17 | "packageRules": [
18 | {
19 | "packagePatterns": [
20 | ".*"
21 | ],
22 | "semanticCommitType": "fix"
23 | },
24 | {
25 | "matchUpdateTypes": [
26 | "patch",
27 | "pin",
28 | "digest"
29 | ],
30 | "automerge": false
31 | },
32 | {
33 | "matchDatasources": [
34 | "pypi"
35 | ],
36 | "matchFiles": [
37 | "requirements-dev.txt"
38 | ],
39 | "semanticCommitType": "chore"
40 | },
41 | {
42 | "matchDatasources": [
43 | "pypi"
44 | ],
45 | "matchUpdateTypes": [
46 | "minor",
47 | "patch",
48 | "pin",
49 | "digest"
50 | ],
51 | "automerge": false
52 | },
53 | {
54 | "matchDatasources": [
55 | "pypi"
56 | ],
57 | "matchPackageNames": [
58 | "pre-commit",
59 | "flake8",
60 | "pylint",
61 | "mypy",
62 | "pytest",
63 | "pytest-cov",
64 | "black"
65 | ],
66 | "groupName": "python-dev-deps",
67 | "matchUpdateTypes": [
68 | "minor",
69 | "patch",
70 | "pin",
71 | "digest"
72 | ],
73 | "automerge": true,
74 | "semanticCommitType": "chore"
75 | },
76 | {
77 | "matchManagers": [
78 | "pre-commit"
79 | ],
80 | "matchPackageNames": [
81 | "hadolint/hadolint",
82 | "asottile/pyupgrade",
83 | "pre-commit/pre-commit-hooks",
84 | "pre-commit/mirrors-mypy",
85 | "PyCQA/flake8",
86 | "pycqa/isort"
87 | ],
88 | "automerge": true,
89 | "semanticCommitType": "chore",
90 | "groupName": "pre-commit-hooks"
91 | }
92 | ]
93 | }
94 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM docker.io/python:3.12.6-slim
2 |
3 | WORKDIR /app
4 |
5 | COPY requirements.txt /app
6 | ENV PATH=/venv/bin:$PATH
7 | RUN : \
8 | && python3 -m venv /venv \
9 | && pip --no-cache-dir install -r requirements.txt
10 |
11 | COPY . /app
12 |
13 | # Keeps Python from generating .pyc files in the container
14 | ENV PYTHONDONTWRITEBYTECODE=1
15 |
16 | # Turns off buffering for easier container logging
17 | ENV PYTHONUNBUFFERED=1
18 |
19 | # Creates a non-root user with an explicit UID and adds permission to access the /app folder
20 | RUN : \
21 | && adduser -u 1000 --disabled-password --gecos "" appuser \
22 | && chown -R appuser /app && chmod -R 0750 /app
23 | USER appuser
24 |
25 |
26 | CMD ["uvicorn", "--host", "*", "--port", "8000", "powerdns_api_proxy.proxy:app"]
27 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | PROJECT_NAME := "powerdns_api_proxy"
2 |
3 | help:
4 | @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
5 |
6 | all: setup run ## run everything
7 |
8 | test: unit pre-commit-all integration ## Run all tests
9 |
10 | setup: ## install required modules
11 | python -m pip install -U -r requirements.txt
12 | python -m pip install -U -r requirements-dev.txt
13 | pre-commit install
14 |
15 | unit: ## run unit tests
16 | python -m pytest -vvl tests/unit/ --showlocals
17 |
18 | integration: ## run integration tests
19 | python -m pytest -vvl --setup-show -vvl tests/integration/ --showlocals
20 |
21 | run: ## run project
22 | uvicorn --host 0.0.0.0 --port 8000 --reload powerdns_api_proxy.proxy:app
23 |
24 | clean: ## clean cache and temp dirs
25 | rm -rf ./.mypy_cache ./.pytest_cache
26 | rm -f .coverage
27 |
28 | build-docker: ## build docker image
29 | docker build -t $(PROJECT_NAME):test .
30 |
31 | run-docker: build-docker ## run docker image
32 | docker run --rm $(PROJECT_NAME):test
33 |
34 | pre-commit-all: ## run pre-commit on all files
35 | pre-commit run --all-files
36 |
37 | pre-commit: ## run pre-commit
38 | pre-commit run
39 |
40 | run-docker-debug: build-docker ## run debug with docker on port 8000
41 | docker run --rm -it -v "${PWD}:/app" -p 8000:8000 -e "PROXY_CONFIG_PATH=${PROXY_CONFIG_PATH}" --rm $(PROJECT_NAME):test uvicorn --host 0.0.0.0 --port 8000 --reload powerdns_api_proxy.proxy:app
42 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PowerDNS-API-Proxy
2 |
3 | ## Description
4 |
5 | The proxy can be used between a PowerDNS API and a client.
6 |
7 | There is the possibility to define multiple tokens. Each token is represented by an `environment`.
8 | A `environment` can get access to one or more zones.
9 | Within a zone, the token can be limited to one or more records.
10 |
11 | ## Usage
12 |
13 | ### Container
14 |
15 | Containers are available under [Packages](https://github.com/akquinet/powerdns-api-proxy/pkgs/container/powerdns-api-proxy).
16 |
17 | ```bash
18 | docker run -v config:/config -e PROXY_CONFIG_PATH=/config/config.yaml -e LOG_LEVEL=WARNING --name powerdns-api-proxy ghcr.io/akquinet/powerdns-api-proxy:latest
19 | ```
20 |
21 | ### Authentication
22 |
23 | The token is expected in the header `X-API-Key` as with the PowerDNS API.
24 |
25 | If the token is missing a `HTTP 401` is returned.
26 |
27 | ### RBAC
28 |
29 | If a resource is not allowed, then a `HTTP 403` comes back.
30 |
31 | An overview of the allowed resources of a token can be seen with a `GET` on `/info/allowed`.
32 |
33 | ## Configuration
34 |
35 | The configuration takes place in YAML format.
36 |
37 | ### Base
38 |
39 | The Upstream PowerDNS API must be maintained at the top level.
40 |
41 | ```yaml
42 | pdns_api_url: "https://powerdns-api.example.com"
43 | pdns_api_token: "blablub"
44 | pdns_api_verify_ssl: True
45 | environments:
46 | ...
47 |
48 | ```
49 |
50 | ### Environment
51 |
52 | An `environment` needs a name and a SHA512 token hash.
53 | The hash is then compared with the hashed value from the API client request.
54 |
55 | ```yaml
56 | ...
57 | environments:
58 | - name: "Test1"
59 | token_sha512: "1954a12ef0bf45b3a1797437509037f178af846d880115d57668a8aaa05732deedcbbd02bfa296b4f4e043b437b733fd6131933cfdc0fb50c4cf7f9f2bdaa836"
60 | zones:
61 | ...
62 | ```
63 |
64 | A token / hash pair can be created with the following commands:
65 |
66 | ```bash
67 | token=$(tr -dc A-Za-z0-9 Simply specifying the zone without any further settings allows `write` permissions within the zone.
88 | > Within a zone there are **always** `read` permissions.
89 |
90 | ##### Records
91 |
92 | Under a `zone` `records` can be defined.
93 |
94 | Thus the token has only `write` permissions on the `records` which are specified in the list.
95 |
96 | ```yaml
97 | ...
98 | environments:
99 | - name: "Test1"
100 | ...
101 | zones:
102 | - name: "example.com"
103 | records:
104 | - "test.example.com"
105 | ```
106 |
107 | ###### Regex
108 |
109 | Additionally to the `records` list a `regex_records` list can be defined.
110 | In this list regex can be to define, which records are allowed.
111 |
112 | ```yaml
113 | ...
114 | environments:
115 | - name: "Test1"
116 | ...
117 | zones:
118 | - name: "example.com"
119 | regex_records:
120 | - "_acme-challenge.service-.*.example.com"
121 | ```
122 |
123 | ##### Services
124 |
125 | Under a `zone` `services` can be defined.
126 |
127 | ###### ACME
128 |
129 | The `ACME` service allows, if only single records are specified, to create an ACME challenge for them.
130 |
131 | ```yaml
132 | ...
133 | environments:
134 | - name: "Test1"
135 | zones:
136 | - name: "example.com"
137 | records:
138 | - "test.example.com"
139 | services:
140 | acme: true
141 | ```
142 |
143 | ##### Admin
144 |
145 | Under a `zone` `admin` rights can be defined.
146 | With this it is possible to create and delete the zone.
147 |
148 | ```yaml
149 | ...
150 | environments:
151 | - name: "Test1"
152 | zones:
153 | - name: "example.com"
154 | admin: true
155 | ```
156 |
157 | ##### Subzones
158 |
159 | Under a `zone` the option `subzones: true` can be set.
160 |
161 | With this it is possible that the token also gets rights on all subzones which are under the zone.
162 |
163 | ```yaml
164 | ...
165 | environments:
166 | - name: "Test1"
167 | zones:
168 | - name: "example.com"
169 | subzones: true
170 | ```
171 |
172 | ##### Regex
173 |
174 | Under a `zone` the option `regex: true` can be set.
175 |
176 | That allows use regex in the zone name.
177 |
178 | In this example all zones which end with `.example.com` are allowed.
179 |
180 | ```YAML
181 | ...
182 | environments:
183 | - name: "Test1"
184 | zones:
185 | - name: ".*\\.example.com"
186 | regex: true
187 | ```
188 |
189 | #### Global read
190 |
191 | Global `read` permissions can be defined under an `environment`.
192 |
193 | For this the `Environment` must have the option `global_read_only: true`.
194 |
195 | This allows the token to read all zones in the PowerDNS.
196 |
197 | ```yaml
198 | ...
199 | environments:
200 | - name: "Test1"
201 | global_read_only: true
202 | ```
203 |
204 | #### Global search
205 |
206 | Global `search` rights can be defined under an `environment`.
207 |
208 | For this, the `environment` must have the `global_search: true` option.
209 |
210 | This makes it possible to use the `/search-data` endpoint.
211 |
212 |
213 | ```yaml
214 | ...
215 | environments:
216 | - name: "Test1"
217 | global_search: true
218 | ```
219 |
220 | #### Global TSIGKeys
221 |
222 | Global TSIGKeys access can be defined under an `environment`.
223 |
224 | For this the `Environment` must have the option `global_tsigkeys: true`.
225 |
226 | This allows the token to read and modify all TSIGKeys in the PowerDNS.
227 |
228 | ```yaml
229 | ...
230 | environments:
231 | - name: "Test1"
232 | global_tsigkeys: true
233 | ```
234 |
235 | ### Metrics of the proxy
236 |
237 | The proxy exposes metrics on the `/metrics` endpoint.
238 | With the `metrics_enabled` option set to `false`, the metrics can be disabled.
239 |
240 | The `metrics_require_auth` option can be used to disable the need for authentication for the `/metrics` endpoint.
241 |
242 | ```yaml
243 | ...
244 | metrics_enabled: false # default is true
245 | metrics_require_auth: false # default is true
246 | ```
247 |
248 | #### Give an environment access to the metrics
249 |
250 | When the `metrics_proxy` option is set to `true`, the environment has access to the `/metrics` endpoint of the proxy.
251 |
252 | ```yaml
253 | ...
254 | environments:
255 | - name: "Test1"
256 | metrics_proxy: true
257 | ```
258 |
259 | When `metrics_require_auth` is enabled, basic auth needs to be used.
260 |
261 | * username: name of the environment
262 | * password: token
263 |
264 | #### Metrics
265 |
266 | The [prometheus-fastapi-instrumentator](https://github.com/trallnag/prometheus-fastapi-instrumentator) is used for the default metrics.
267 |
268 | Additionally http requests per environment are counted.
269 |
270 | ### API Docs
271 |
272 | The API documentation can be viewed at `/docs`.
273 |
274 | It can be deactivated with the `api_docs_enabled` option.
275 |
276 | ```yaml
277 | api_docs_enabled: false # default is true
278 | ```
279 |
280 | ### Index
281 |
282 | The index page can be deactivated with the `index_enabled` option and customized with `index_html`.
283 |
284 | ```yaml
285 | index_enabled: false # default is true
286 | index_html: "PowerDNS API Proxy
"
287 | ```
288 |
289 | ## Development
290 |
291 | ### Install requirements
292 |
293 | ```bash
294 | virtualenv .venv && source .venv/bin/activate
295 | make setup
296 | ```
297 |
298 | ### Run tests
299 |
300 | ```bash
301 | make unit
302 | make test
303 | ```
304 |
305 | ### Start a webserver with docker
306 |
307 | On saving python files, FastAPI will reload automatically.
308 |
309 | ```bash
310 | make run-docker-debug
311 | ```
312 |
313 | ### Environment variables
314 |
315 | ```bash
316 | PROXY_CONFIG_PATH=./config.yml
317 | LOG_LEVEL=DEBUG
318 | ```
319 |
--------------------------------------------------------------------------------
/config-example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | pdns_api_url: https://powerdns-api-test.example.com
3 | pdns_api_token: ukCLNsxaOLAOcdNZ9XS
4 | pdns_api_verify_ssl: true
5 | environments:
6 | - name: example-env
7 | token_sha512: 127aab81f4caab9c00e72f26e4c5c4b20146201a1548a787494d999febf1b9422c1711932117f38d9be9efe46f78aa72d8f6a391101bedd6e200014f6738450d
8 | zones:
9 | - name: zone1.example.com
10 | - name: zone2.example.com
11 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akquinet/powerdns-api-proxy/62b0608f6acfb724310d1abd08fad021cab3ff35/powerdns_api_proxy/__init__.py
--------------------------------------------------------------------------------
/powerdns_api_proxy/__main__.py:
--------------------------------------------------------------------------------
1 | def main() -> int:
2 | print("Please start me with uvicorn :)")
3 | return 1
4 |
5 |
6 | if __name__ == "__main__":
7 | raise SystemExit(main())
8 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/config.py:
--------------------------------------------------------------------------------
1 | import hashlib
2 | import os
3 | from functools import lru_cache
4 | from pathlib import Path
5 | from typing import Annotated, Optional
6 |
7 | from fastapi import Depends, Header, HTTPException
8 | from fastapi.security import HTTPBasic, HTTPBasicCredentials
9 | from yaml import safe_load
10 |
11 | from powerdns_api_proxy.logging import logger
12 | from powerdns_api_proxy.models import (
13 | RRSET,
14 | MetricsNotAllowedException,
15 | NotAuthorizedException,
16 | ProxyConfig,
17 | ProxyConfigEnvironment,
18 | ProxyConfigZone,
19 | RRSETRequest,
20 | ZoneNotAllowedException,
21 | )
22 | from powerdns_api_proxy.utils import check_record_in_regex, check_zones_equal
23 |
24 |
25 | @lru_cache(maxsize=1)
26 | def load_config(path: Optional[Path] = None) -> ProxyConfig:
27 | logger.info("Loading config")
28 | if not path:
29 | env_path = os.getenv("PROXY_CONFIG_PATH")
30 | if not env_path:
31 | raise ValueError("Could not get proxy config path")
32 | path = Path(env_path)
33 | with open(path) as f:
34 | data = safe_load(f)
35 |
36 | config = ProxyConfig.model_validate(data)
37 | return config
38 |
39 |
40 | def token_defined(config: ProxyConfig, token: str) -> bool:
41 | sha512 = hashlib.sha512()
42 | sha512.update(token.encode())
43 | token_digest = sha512.digest().hex()
44 | for env in config.environments:
45 | if token_digest == env.token_sha512:
46 | logger.info(f'Authenticated environment "{env.name}"')
47 | return True
48 | return False
49 |
50 |
51 | def check_token_defined(config: ProxyConfig, token: str):
52 | if not token_defined(config, token):
53 | raise NotAuthorizedException()
54 |
55 |
56 | def dependency_check_token_defined(
57 | X_API_Key: str = Header(description="API Key for the proxy."),
58 | ):
59 | check_token_defined(load_config(), X_API_Key)
60 |
61 |
62 | security = HTTPBasic()
63 |
64 |
65 | def dependency_metrics_proxy_enabled(
66 | credentials: Annotated[HTTPBasicCredentials, Depends(security)] = Header(
67 | description="API Key for the proxy."
68 | ),
69 | ):
70 | username = credentials.username
71 | password = credentials.password
72 |
73 | try:
74 | environment = get_environment_for_token(load_config(), password)
75 | if not environment.name == username:
76 | raise NotAuthorizedException()
77 | if not environment.metrics_proxy:
78 | raise MetricsNotAllowedException()
79 | except ValueError:
80 | raise NotAuthorizedException()
81 |
82 |
83 | def get_environment_for_token(
84 | config: ProxyConfig, token: str
85 | ) -> ProxyConfigEnvironment:
86 | """
87 | Returns:
88 | ProxyConfigEnvironment: The environment for the given token.
89 | Raises:
90 | ValueError: If no environment is found for the given token.
91 | """
92 | sha512 = hashlib.sha512()
93 | sha512.update(token.encode())
94 | token_digest = sha512.digest().hex()
95 | for env in config.environments:
96 | if token_digest == env.token_sha512:
97 | return env
98 | raise ValueError("Could not find a environment for the given token")
99 |
100 |
101 | def get_only_pdns_zones_allowed(
102 | environment: ProxyConfigEnvironment, pdns_zones: list[dict]
103 | ) -> list[dict]:
104 | filtered = []
105 | if environment.global_read_only:
106 | return pdns_zones
107 |
108 | for zone in pdns_zones:
109 | if check_pdns_zone_allowed(environment, zone["name"]):
110 | filtered.append(zone)
111 | return filtered
112 |
113 |
114 | def check_pdns_zone_allowed(environment: ProxyConfigEnvironment, zone: str) -> bool:
115 | """Returns True if zone is allowed in the environment"""
116 | if environment.global_read_only:
117 | return True
118 |
119 | try:
120 | _ = environment.get_zone_if_allowed(zone)
121 | return True
122 | except ZoneNotAllowedException:
123 | return False
124 |
125 |
126 | def check_pdns_zone_admin(environment: ProxyConfigEnvironment, zone: str) -> bool:
127 | try:
128 | env_zone = environment.get_zone_if_allowed(zone)
129 | return env_zone.admin
130 | except ZoneNotAllowedException:
131 | pass
132 | return False
133 |
134 |
135 | def check_pdns_search_allowed(
136 | environment: ProxyConfigEnvironment, query: str, object_type: str
137 | ) -> bool:
138 | if environment.global_search:
139 | return True
140 | return False
141 |
142 |
143 | def check_rrset_allowed(zone: ProxyConfigZone, rrset: RRSET) -> bool:
144 | if zone.read_only:
145 | return False
146 |
147 | if zone.all_records:
148 | return True
149 |
150 | if not rrset["name"].rstrip(".").endswith(zone.name.rstrip(".")):
151 | logger.debug("RRSET not allowed, because zone does not match")
152 | return False
153 |
154 | for record in zone.records:
155 | if check_zones_equal(rrset["name"], record):
156 | return True
157 |
158 | for regex in zone.regex_records:
159 | if check_record_in_regex(rrset["name"], regex):
160 | return True
161 |
162 | if check_acme_record_allowed(zone, rrset):
163 | return True
164 |
165 | return False
166 |
167 |
168 | def check_acme_record_allowed(zone: ProxyConfigZone, rrset: RRSET) -> bool:
169 | if zone.all_records:
170 | logger.debug("ACME challenge allowed, because all records are allowed")
171 | return True
172 |
173 | if not zone.services.acme:
174 | logger.info("Service ACME is not activated")
175 | return False
176 |
177 | for record in zone.records:
178 | if check_zones_equal(f"_acme-challenge.{record}", rrset["name"]):
179 | logger.info(f"ACME challenge for record {record} is allowed")
180 | return True
181 |
182 | return False
183 |
184 |
185 | def check_pdns_tsigkeys_allowed(environment: ProxyConfigEnvironment) -> bool:
186 | if environment.global_tsigkeys:
187 | return True
188 | return False
189 |
190 |
191 | def ensure_rrsets_request_allowed(zone: ProxyConfigZone, request: RRSETRequest) -> bool:
192 | """Raises HTTPException if RRSET is not allowed"""
193 | if zone.read_only:
194 | logger.info("RRSET update not allowed with read only token")
195 | raise HTTPException(403, "RRSET update not allowed with read only token")
196 | for rrset in request["rrsets"]:
197 | if not check_rrset_allowed(zone, rrset):
198 | logger.info(f"RRSET {rrset['name']} not allowed in zone {zone.name}")
199 | raise HTTPException(403, f"RRSET {rrset['name']} not allowed")
200 | logger.info(f"RRSET {rrset['name']} allowed")
201 | return True
202 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/logging.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import logging.handlers
3 | from os import getenv
4 | from sys import stderr
5 |
6 | LOG_LEVEL = getenv("LOG_LEVEL") or "DEBUG"
7 |
8 | logging_format = (
9 | "%(levelname)s - %(asctime)s - %(name)s - "
10 | + "%(filename)s - %(funcName)s - %(lineno)s - %(message)s"
11 | )
12 |
13 | default_formatter = logging.Formatter(logging_format)
14 |
15 | default_stream_handler = logging.StreamHandler(stderr)
16 | default_stream_handler.setLevel(LOG_LEVEL)
17 | default_stream_handler.setFormatter(default_formatter)
18 |
19 | file_handler = logging.handlers.RotatingFileHandler(
20 | filename="log", maxBytes=1000**2 * 100, backupCount=5
21 | )
22 | file_handler.setLevel("DEBUG")
23 | file_handler.setFormatter(default_formatter)
24 |
25 | logger = logging.getLogger("powerdns_api_proxy")
26 | logger.addHandler(default_stream_handler)
27 | logger.addHandler(file_handler)
28 |
29 | logger.setLevel("DEBUG")
30 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/metrics.py:
--------------------------------------------------------------------------------
1 | from typing import Callable
2 |
3 | from prometheus_client import REGISTRY, CollectorRegistry, Counter
4 | from prometheus_fastapi_instrumentator.metrics import Info
5 |
6 | from powerdns_api_proxy.config import get_environment_for_token, load_config
7 |
8 | config = load_config()
9 |
10 |
11 | def http_requests_total_environment(
12 | metric_namespace: str = "",
13 | metric_subsystem: str = "",
14 | registry: CollectorRegistry = REGISTRY,
15 | ) -> Callable[[Info], None]:
16 | """
17 | This function is used to create a metric for the number of requests
18 | by environment, method, status and handler.
19 | """
20 | METRIC = Counter(
21 | "http_requests_environment",
22 | "Total number of requests by environment, method, status and handler.",
23 | labelnames=("environment", "method", "status", "handler"),
24 | namespace=metric_namespace,
25 | subsystem=metric_subsystem,
26 | registry=registry,
27 | )
28 |
29 | def instrumentation(info: Info) -> None:
30 | if info and "X-API-Key" in info.request.headers:
31 | try:
32 | environment = get_environment_for_token(
33 | config, info.request.headers["X-API-Key"]
34 | )
35 | except ValueError:
36 | return
37 | METRIC.labels(
38 | environment=environment.name,
39 | method=info.method,
40 | status=info.modified_status,
41 | handler=info.modified_handler,
42 | ).inc()
43 |
44 | return instrumentation
45 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/models.py:
--------------------------------------------------------------------------------
1 | from functools import lru_cache
2 | from typing import TypedDict
3 |
4 | from fastapi import HTTPException
5 | from pydantic import BaseModel, field_validator
6 |
7 | from powerdns_api_proxy.logging import logger
8 | from powerdns_api_proxy.utils import (
9 | check_subzone,
10 | check_zone_in_regex,
11 | check_zones_equal,
12 | )
13 |
14 |
15 | class ProxyConfigServices(BaseModel):
16 | acme: bool = False
17 |
18 |
19 | class ProxyConfigZone(BaseModel):
20 | """
21 | `name` is the zone name.
22 | `description` is a description of the zone.
23 | `regex` should be set to `True` if `name` is a regex.
24 | `records` is a list of record names that are allowed.
25 | `regex_records` is a list of record regexes that are allowed.
26 | `admin` enabled creating and deleting the zone.
27 | `subzones` sets the same permissions on all subzones.
28 | `all_records` will be set to `True` if no `records` are defined.
29 | `read_only` will be set to `True` if `global_read_only` is `True`.
30 | """
31 |
32 | name: str
33 | regex: bool = False
34 | description: str = ""
35 | records: list[str] = []
36 | regex_records: list[str] = []
37 | services: ProxyConfigServices = ProxyConfigServices(acme=False)
38 | admin: bool = False
39 | subzones: bool = False
40 | all_records: bool = False
41 | read_only: bool = False
42 |
43 | def __init__(self, **data):
44 | super().__init__(**data)
45 | if len(self.records) == 0 and len(self.regex_records) == 0:
46 | logger.debug(
47 | f"Setting all_records to True for zone {self.name}, because no records are defined"
48 | )
49 | self.all_records = True
50 | self.services.acme = True
51 |
52 |
53 | class ProxyConfigEnvironment(BaseModel):
54 | name: str
55 | token_sha512: str
56 | zones: list[ProxyConfigZone]
57 | global_read_only: bool = False
58 | global_search: bool = False
59 | global_tsigkeys: bool = False
60 | _zones_lookup: dict[str, ProxyConfigZone] = {}
61 | metrics_proxy: bool = False
62 |
63 | @field_validator("name")
64 | @classmethod
65 | def name_defined(cls, v):
66 | if len(v) == 0:
67 | raise ValueError("name must a non-empty string")
68 | return v
69 |
70 | @field_validator("token_sha512")
71 | @classmethod
72 | def validate_token(cls, token_sha512):
73 | if len(token_sha512) != 128:
74 | raise ValueError("A SHA512 hash must be 128 digits long")
75 | return token_sha512
76 |
77 | def __init__(self, **data):
78 | super().__init__(**data)
79 | if self.global_read_only:
80 | logger.debug(
81 | "Setting all subzones to read_only, because global_read_only is true"
82 | )
83 | for zone in self.zones:
84 | zone.read_only = True
85 |
86 | # populate zones lookup
87 | self._zones_lookup[zone.name] = zone
88 |
89 | def __hash__(self):
90 | return hash(
91 | self.name
92 | + self.token_sha512
93 | + str(self.global_read_only)
94 | + str(self.global_search)
95 | + str(self.global_tsigkeys)
96 | + str(self.zones)
97 | )
98 |
99 | @lru_cache(maxsize=10000)
100 | def get_zone_if_allowed(self, zone: str) -> ProxyConfigZone:
101 | """
102 | Returns the zone config for the given zone name
103 | Raises ZoneNotAllowedException if the zone is not allowed
104 | """
105 | if zone in self._zones_lookup:
106 | return self._zones_lookup[zone]
107 |
108 | for z in self.zones:
109 | if check_zones_equal(zone, z.name):
110 | return z
111 |
112 | if z.subzones and check_subzone(zone, z.name):
113 | logger.debug(f'"{zone}" is a subzone of "{z.name}"')
114 | return z
115 |
116 | if z.regex and check_zone_in_regex(zone, z.name):
117 | logger.debug(f'"{zone}" matches regex "{z.name}"')
118 | return z
119 |
120 | raise ZoneNotAllowedException()
121 |
122 |
123 | class ProxyConfig(BaseModel):
124 | """
125 | Configuration for the PowerDNS API Proxy.
126 |
127 | Args:
128 | pdns_api_url: The URL of the PowerDNS API.
129 | pdns_api_token: The token for the PowerDNS API.
130 | environments: A list of environments.
131 | pdns_api_verify_ssl: Verify SSL certificate of the PowerDNS API.
132 | metrics_enabled: Enable metrics.
133 | metrics_require_auth: Require authentication for metrics.
134 | api_docs_enabled: Enable API documentation.
135 | index_enabled: Enable default web page
136 | index_html: Custom html for the homepage
137 |
138 | """
139 |
140 | pdns_api_url: str
141 | pdns_api_token: str
142 | environments: list[ProxyConfigEnvironment]
143 | pdns_api_verify_ssl: bool = True
144 |
145 | metrics_enabled: bool = True
146 | metrics_require_auth: bool = True
147 |
148 | api_docs_enabled: bool = True
149 |
150 | index_enabled: bool = True
151 | index_html: str = """
152 |
153 |
154 | PowerDNS API Proxy
155 |
156 |
157 |
158 | PowerDNS API Proxy
159 | Swagger Docs
160 | The Domain Name Server (DNS) is the Achilles heel of the Web.
161 | The important thing is that it's managed responsibly.
162 |
163 |
164 |
165 | """
166 |
167 | @field_validator("pdns_api_url")
168 | @classmethod
169 | def api_url_defined(cls, v):
170 | if len(v) == 0:
171 | raise ValueError("pdns_api_url must a non-empty string")
172 | return v
173 |
174 | @field_validator("pdns_api_token")
175 | @classmethod
176 | def api_token_defined(cls, v):
177 | if len(v) == 0:
178 | raise ValueError("pdns_api_token must a non-empty string")
179 | return v
180 |
181 |
182 | class ResponseAllowed(BaseModel):
183 | zones: list[ProxyConfigZone]
184 |
185 |
186 | class ResponseZoneAllowed(BaseModel):
187 | zone: str
188 | allowed: bool
189 | config: ProxyConfigZone | None = None
190 |
191 |
192 | class ZoneNotAllowedException(HTTPException):
193 | def __init__(self):
194 | self.status_code = 403
195 | self.detail = "Zone not allowed"
196 |
197 |
198 | class ZoneAdminNotAllowedException(HTTPException):
199 | def __init__(self):
200 | self.status_code = 403
201 | self.detail = "Not Zone admin"
202 |
203 |
204 | class RecordNotAllowedException(HTTPException):
205 | def __init__(self):
206 | self.status_code = 403
207 | self.detail = "Record not allowed"
208 |
209 |
210 | class RessourceNotAllowedException(HTTPException):
211 | def __init__(self):
212 | self.status_code = 403
213 | self.detail = "Ressource not allowed"
214 |
215 |
216 | class NotAuthorizedException(HTTPException):
217 | def __init__(self):
218 | self.status_code = 401
219 | self.detail = "Unauthorized"
220 |
221 |
222 | class SearchNotAllowedException(HTTPException):
223 | def __init__(self):
224 | self.status_code = 403
225 | self.detail = "Search not allowed"
226 |
227 |
228 | class MetricsNotAllowedException(HTTPException):
229 | def __init__(self):
230 | self.status_code = 403
231 | self.detail = "Metrics not allowed"
232 |
233 |
234 | class RRSETRecord(TypedDict):
235 | content: str
236 | disabled: bool
237 |
238 |
239 | class RRSETComment(TypedDict):
240 | content: str
241 | account: str
242 | modified_at: int
243 |
244 |
245 | class RRSET(TypedDict):
246 | name: str
247 | type: str
248 | changetype: str
249 | ttl: int
250 | records: list[RRSETRecord]
251 | comments: list[RRSETComment]
252 |
253 |
254 | class RRSETRequest(TypedDict):
255 | rrsets: list[RRSET]
256 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/pdns.py:
--------------------------------------------------------------------------------
1 | import aiohttp
2 |
3 | from powerdns_api_proxy.logging import logger
4 |
5 |
6 | class PDNSConnector:
7 | def __init__(self, url: str, token: str, verify_ssl: bool = True):
8 | self.base_url = url
9 | self.token = token
10 | self.verify_ssl = verify_ssl
11 | self.headers = {
12 | "Content-Type": "application/json",
13 | "X-API-Key": self.token,
14 | }
15 |
16 | async def request(
17 | self, method: str, path: str, params: dict = {}, payload: dict = {}
18 | ):
19 | logger.info(
20 | f"Getting upstream PDNS API with method: {method}, path: {self.base_url + path}, "
21 | f"params: {params}, payload: {payload}"
22 | )
23 | async with aiohttp.ClientSession(
24 | base_url=self.base_url, headers=self.headers
25 | ) as session:
26 | async with session.request(
27 | method,
28 | url=path,
29 | params=params,
30 | json=payload,
31 | verify_ssl=self.verify_ssl,
32 | ) as req:
33 | text = await req.text()
34 | logger.debug(
35 | f'Got answer from upstream PDNS API Status: {req.status}, text: "{text}"'
36 | )
37 | return req
38 |
39 | async def get(self, path: str, params: dict = {}) -> aiohttp.ClientResponse:
40 | return await self.request("GET", path, params=params)
41 |
42 | async def post(self, path: str, payload: dict = {}) -> aiohttp.ClientResponse:
43 | return await self.request("POST", path, payload=payload)
44 |
45 | async def put(self, path: str, payload: dict = {}) -> aiohttp.ClientResponse:
46 | return await self.request("PUT", path, payload=payload)
47 |
48 | async def patch(self, path: str, payload: dict = {}) -> aiohttp.ClientResponse:
49 | return await self.request("PATCH", path, payload=payload)
50 |
51 | async def delete(self, path: str, payload: dict = {}) -> aiohttp.ClientResponse:
52 | return await self.request("DELETE", path, payload=payload)
53 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/proxy.py:
--------------------------------------------------------------------------------
1 | import os
2 | from contextlib import asynccontextmanager
3 | from http import HTTPStatus
4 | from typing import Literal
5 |
6 | import sentry_sdk
7 | from fastapi import APIRouter, Depends, FastAPI, Header, Request, Response
8 | from fastapi.responses import HTMLResponse, JSONResponse
9 | from prometheus_fastapi_instrumentator import Instrumentator, metrics
10 | from sentry_sdk.integrations.aiohttp import AioHttpIntegration
11 | from sentry_sdk.integrations.fastapi import FastApiIntegration
12 | from starlette.exceptions import HTTPException as StarletteHTTPException
13 |
14 | from powerdns_api_proxy.config import (
15 | check_pdns_search_allowed,
16 | check_pdns_tsigkeys_allowed,
17 | check_pdns_zone_admin,
18 | check_pdns_zone_allowed,
19 | dependency_check_token_defined,
20 | dependency_metrics_proxy_enabled,
21 | ensure_rrsets_request_allowed,
22 | get_environment_for_token,
23 | get_only_pdns_zones_allowed,
24 | load_config,
25 | )
26 | from powerdns_api_proxy.logging import logger
27 | from powerdns_api_proxy.metrics import http_requests_total_environment
28 | from powerdns_api_proxy.models import (
29 | ResponseAllowed,
30 | ResponseZoneAllowed,
31 | RessourceNotAllowedException,
32 | SearchNotAllowedException,
33 | ZoneAdminNotAllowedException,
34 | ZoneNotAllowedException,
35 | )
36 | from powerdns_api_proxy.pdns import PDNSConnector
37 | from powerdns_api_proxy.utils import response_json_or_text
38 |
39 | if os.getenv("SENTRY_DSN"):
40 | sentry_sdk.init(
41 | traces_sample_rate=float(os.getenv("SENTRY_TRACES_SAMPLE_RATE") or 0.1),
42 | environment=os.getenv("ENVIRONMENT") or "DEV",
43 | integrations=[FastApiIntegration(), AioHttpIntegration()],
44 | )
45 |
46 | # load config to verify it is valid
47 | config = load_config()
48 |
49 | pdns = PDNSConnector(
50 | config.pdns_api_url, config.pdns_api_token, config.pdns_api_verify_ssl
51 | )
52 |
53 |
54 | @asynccontextmanager
55 | async def _startup(app: FastAPI):
56 | yield
57 |
58 |
59 | app = FastAPI(title="PowerDNS API Proxy", version="0.1.0", lifespan=_startup)
60 |
61 | if not config.api_docs_enabled:
62 | logger.info("Disabling API docs")
63 | app = FastAPI(
64 | title=app.title,
65 | version=app.version,
66 | lifespan=_startup,
67 | docs_url=None,
68 | redoc_url=None,
69 | openapi_url=None,
70 | )
71 |
72 | if config.metrics_enabled:
73 | instrumentator = Instrumentator(
74 | should_group_status_codes=False,
75 | )
76 | logger.info("Enabling metrics")
77 | instrumentator.add(metrics.default())
78 | instrumentator.add(http_requests_total_environment())
79 | instrumentator.instrument(app)
80 |
81 | if config.metrics_require_auth:
82 | logger.info("Enabling metrics authentication")
83 | instrumentator.expose(
84 | app, dependencies=[Depends(dependency_metrics_proxy_enabled)]
85 | )
86 | else:
87 | instrumentator.expose(app)
88 | else:
89 | logger.info("Metrics are disabled")
90 |
91 |
92 | # Patching HTTPException to be compatible with PowerDNS API errors
93 | # https://doc.powerdns.com/authoritative/http-api/index.html#errors
94 | @app.exception_handler(StarletteHTTPException)
95 | async def http_exception_handler(request, exc):
96 | return JSONResponse({"error": exc.detail}, status_code=exc.status_code)
97 |
98 |
99 | router_proxy = APIRouter(
100 | prefix="/info",
101 | tags=["Information"],
102 | dependencies=[Depends(dependency_check_token_defined)],
103 | )
104 | router_health = APIRouter(
105 | prefix="/health",
106 | tags=["Information"],
107 | )
108 | router_pdns = APIRouter(
109 | prefix="/api/v1",
110 | tags=["PowerDNS Ressources"],
111 | dependencies=[Depends(dependency_check_token_defined)],
112 | )
113 |
114 |
115 | @app.head("/", include_in_schema=False)
116 | @app.get("/", response_class=HTMLResponse, include_in_schema=False)
117 | async def hello():
118 | if config.index_enabled:
119 | return config.index_html
120 | else:
121 | return HTMLResponse(status_code=404)
122 |
123 |
124 | @router_health.get("/pdns", status_code=HTTPStatus.OK)
125 | async def health_upstream_pdns_api(response: Response):
126 | """Checks connection to Upstream PowerDNS API."""
127 | logger.info("Checking upstream pdns api health")
128 | req = await pdns.get("/api/v1/servers")
129 | response.status_code = req.status
130 | data = {"details": "Upstream PowerDNS API seems to work :)"}
131 | if req.status != 200:
132 | data = {"details": "Something is wrong :(. Please help me!"}
133 | response.status_code = 500
134 | return data
135 |
136 |
137 | @router_proxy.get(
138 | "/allowed",
139 | response_model=ResponseAllowed,
140 | )
141 | async def get_allowed_ressources(X_API_Key: str = Header()):
142 | """Retrieve allowed requests for the given token."""
143 | logger.info("Checking allowed ressources for given api key")
144 | environment = get_environment_for_token(config, X_API_Key)
145 | return ResponseAllowed(zones=environment.zones)
146 |
147 |
148 | @router_proxy.get(
149 | "/zone-allowed",
150 | response_model=ResponseZoneAllowed,
151 | )
152 | async def get_zone_allowed(zone: str, X_API_Key: str = Header()):
153 | """
154 | Check if the given zone is allowed for the given token.
155 | Also returns the zone config that allows the zone.
156 | """
157 | logger.debug("Checking if zone is allowed for given api key")
158 | environment = get_environment_for_token(config, X_API_Key)
159 | if not check_pdns_zone_allowed(environment, zone):
160 | return ResponseZoneAllowed(zone=zone, allowed=False)
161 |
162 | zone_config = environment.get_zone_if_allowed(zone)
163 | return ResponseZoneAllowed(zone=zone, allowed=True, config=zone_config)
164 |
165 |
166 | @app.get("/api", dependencies=[Depends(dependency_check_token_defined)])
167 | async def api_root():
168 | """Returns the version and a info that this is a proxy."""
169 | return [
170 | {
171 | "url": "/api/v1",
172 | "version": 1,
173 | "compatibility": "PowerDNS API Proxy, PowerDNS API v1",
174 | }
175 | ]
176 |
177 |
178 | @router_pdns.get("/servers")
179 | async def get_servers(response: Response):
180 | """
181 | Retrieve a list of servers which can be used.
182 |
183 |
184 | """
185 | req = await pdns.get("/api/v1/servers")
186 | data = await req.json()
187 | response.status_code = req.status
188 | return data
189 |
190 |
191 | @router_pdns.get("/servers/{server_id}")
192 | async def get_server(response: Response, server_id: str):
193 | """
194 | Retrieve a specific server.
195 |
196 |
197 | """
198 | resp = await pdns.get(f"/api/v1/servers/{server_id}")
199 | data = await response_json_or_text(resp)
200 | response.status_code = resp.status
201 | return data
202 |
203 |
204 | @router_pdns.get(
205 | "/servers/{server_id}/configuration",
206 | )
207 | async def get_configuration(server_id: str):
208 | """
209 | Retrieve a list of configuration items for the server.
210 | Currently returns empty, as we don't want to expose the global backend configuration.
211 | """
212 | _ = server_id
213 | raise RessourceNotAllowedException()
214 |
215 |
216 | @router_pdns.get(
217 | "/servers/{server_id}/statistics",
218 | )
219 | async def get_statistics(
220 | server_id: str,
221 | ):
222 | """
223 | Retrieve a list of statistics about the server.
224 | Currently returns empty, as we don't want to expose the global backend statistics.
225 |
226 |
227 | """
228 | _ = server_id
229 | raise RessourceNotAllowedException()
230 |
231 |
232 | @router_pdns.get(
233 | "/servers/{server_id}/zones",
234 | )
235 | async def get_zones(
236 | request: Request,
237 | response: Response,
238 | server_id: str,
239 | X_API_Key: str = Header(),
240 | ):
241 | """
242 | Retrieve a list of zones that exist and belong to this account.
243 |
244 |
245 | """
246 | environment = get_environment_for_token(config, X_API_Key)
247 | resp = await pdns.get(
248 | f"/api/v1/servers/{server_id}/zones", dict(request.query_params)
249 | )
250 | response.status_code = resp.status
251 | zones = await resp.json()
252 | return get_only_pdns_zones_allowed(environment, zones)
253 |
254 |
255 | @router_pdns.post(
256 | "/servers/{server_id}/zones",
257 | )
258 | async def create_zone(
259 | request: Request, response: Response, server_id: str, X_API_Key: str = Header()
260 | ):
261 | """
262 | Create a new zone.
263 |
264 |
265 | """
266 | payload = await request.json()
267 | logger.info(f'Zone creation request data: "{payload}"')
268 | environment = get_environment_for_token(config, X_API_Key)
269 | if not check_pdns_zone_allowed(environment, payload["name"]):
270 | raise ZoneNotAllowedException()
271 | if not check_pdns_zone_admin(environment, payload["name"]):
272 | raise ZoneAdminNotAllowedException()
273 | resp = await pdns.post(f"/api/v1/servers/{server_id}/zones", payload)
274 | response.status_code = resp.status
275 | data = await response_json_or_text(resp)
276 | return data
277 |
278 |
279 | @router_pdns.get(
280 | "/servers/{server_id}/zones/{zone_id}",
281 | )
282 | async def get_zone_metadata(
283 | request: Request,
284 | response: Response,
285 | server_id: str,
286 | zone_id: str,
287 | X_API_Key: str = Header(),
288 | ):
289 | """
290 | Retrieve zone metadata.
291 |
292 |
293 | """
294 | environment = get_environment_for_token(config, X_API_Key)
295 | if not check_pdns_zone_allowed(environment, zone_id):
296 | logger.info(f"Zone {zone_id} not allowed for environment {environment.name}")
297 | raise ZoneNotAllowedException()
298 | resp = await pdns.get(
299 | f"/api/v1/servers/{server_id}/zones/{zone_id}",
300 | params=dict(request.query_params),
301 | )
302 | response.status_code = resp.status
303 | data = await response_json_or_text(resp)
304 | return data
305 |
306 |
307 | @router_pdns.put("/servers/{server_id}/zones/{zone_id}")
308 | async def update_zone_metadata(
309 | request: Request,
310 | response: Response,
311 | server_id: str,
312 | zone_id: str,
313 | X_API_Key: str = Header(),
314 | ):
315 | """
316 | Update zone metadata.
317 |
318 |
319 | """
320 | environment = get_environment_for_token(config, X_API_Key)
321 | if not check_pdns_zone_allowed(environment, zone_id):
322 | raise ZoneNotAllowedException()
323 | if not check_pdns_zone_admin(environment, zone_id):
324 | raise ZoneAdminNotAllowedException()
325 | resp = await pdns.put(
326 | f"/api/v1/servers/{server_id}/zones/{zone_id}",
327 | payload=await request.json(),
328 | )
329 | response.status_code = resp.status
330 | if response.status_code != HTTPStatus.NO_CONTENT:
331 | data = await response_json_or_text(resp)
332 | return data
333 | return Response(status_code=HTTPStatus.NO_CONTENT)
334 |
335 |
336 | @router_pdns.patch("/servers/{server_id}/zones/{zone_id}")
337 | async def update_zone_rrset(
338 | request: Request,
339 | response: Response,
340 | server_id: str,
341 | zone_id: str,
342 | X_API_Key: str = Header(),
343 | ):
344 | """
345 | Update RRSets of a zone.
346 |
347 |
348 | """
349 | logger.debug(f"Update RRSet request for {zone_id}")
350 | environment = get_environment_for_token(config, X_API_Key)
351 | if not check_pdns_zone_allowed(environment, zone_id):
352 | logger.info(f"Zone {zone_id} not allowed for environment {environment.name}")
353 | raise ZoneNotAllowedException()
354 | zone = environment.get_zone_if_allowed(zone_id)
355 | ensure_rrsets_request_allowed(zone, await request.json())
356 | resp = await pdns.patch(
357 | f"/api/v1/servers/{server_id}/zones/{zone_id}",
358 | payload=await request.json(),
359 | )
360 | response.status_code = resp.status
361 | if response.status_code != HTTPStatus.NO_CONTENT:
362 | data = await response_json_or_text(resp)
363 | return data
364 | return Response(status_code=HTTPStatus.NO_CONTENT)
365 |
366 |
367 | @router_pdns.delete("/servers/{server_id}/zones/{zone_id}")
368 | async def delete_zone(
369 | response: Response, server_id: str, zone_id: str, X_API_Key: str = Header()
370 | ):
371 | """
372 | Delete a zone immediately.
373 |
374 |
375 | """
376 | environment = get_environment_for_token(config, X_API_Key)
377 | if not check_pdns_zone_admin(environment, zone_id):
378 | raise ZoneNotAllowedException()
379 | resp = await pdns.delete(f"/api/v1/servers/{server_id}/zones/{zone_id}")
380 | response.status_code = resp.status
381 | if response.status_code != HTTPStatus.NO_CONTENT:
382 | data = await response_json_or_text(resp)
383 | return data
384 | return Response(status_code=HTTPStatus.NO_CONTENT)
385 |
386 |
387 | @router_pdns.put("/servers/{server_id}/zones/{zone_id}/notify")
388 | async def zone_notification(
389 | response: Response, server_id: str, zone_id: str, X_API_Key: str = Header()
390 | ):
391 | """
392 | Queue a zone for notification to replicas.
393 |
394 |
395 | """
396 | environment = get_environment_for_token(config, X_API_Key)
397 | if not check_pdns_zone_allowed(environment, zone_id):
398 | logger.info(f"Zone {zone_id} not allowed for environment {environment.name}")
399 | raise ZoneNotAllowedException()
400 | resp = await pdns.put(f"/api/v1/servers/{server_id}/zones/{zone_id}/notify")
401 | response.status_code = resp.status
402 | data = await response_json_or_text(resp)
403 | return data
404 |
405 |
406 | @router_pdns.get("/servers/{server_id}/search-data")
407 | async def search_data(
408 | response: Response,
409 | server_id: str,
410 | q: str,
411 | max: int | None = None,
412 | object_type: Literal["all", "zone", "record", "comment"] = "all",
413 | X_API_Key: str = Header(),
414 | ):
415 | """
416 | Search the data inside PowerDNS
417 |
418 | Search the data inside PowerDNS for search_term
419 | and return at most max_results.
420 | This includes zones, records and comments.
421 |
422 | The * character can be used in search_term as a wildcard character
423 | and the ? character can be used as a wildcard for a single character.
424 |
425 |
426 | """
427 | environment = get_environment_for_token(config, X_API_Key)
428 | if not check_pdns_search_allowed(environment, q, object_type):
429 | logger.info(
430 | f'Search "{q}" with object_type "{object_type}" is not allowed '
431 | f"for environment {environment.name}"
432 | )
433 | raise SearchNotAllowedException()
434 |
435 | search_params: dict[str, str | int] = {"q": q, "object_type": object_type}
436 | if max is not None:
437 | search_params["max"] = max
438 | resp = await pdns.get(
439 | f"/api/v1/servers/{server_id}/search-data", params=search_params
440 | )
441 | response.status_code = resp.status
442 | data = await response_json_or_text(resp)
443 | return data
444 |
445 |
446 | @router_pdns.get("/servers/{server_id}/tsigkeys")
447 | async def list_tsigkeys(response: Response, server_id: str, X_API_Key: str = Header()):
448 | """
449 | Get all TSIGKeys on the server, except the actual key.
450 |
451 |
452 | """
453 | environment = get_environment_for_token(config, X_API_Key)
454 | if not check_pdns_tsigkeys_allowed(environment):
455 | logger.info(f"TSIGKeys not allowed for environment {environment.name}")
456 | raise ZoneNotAllowedException()
457 | resp = await pdns.get(f"/api/v1/servers/{server_id}/tsigkeys")
458 | response.status_code = resp.status
459 | data = await response_json_or_text(resp)
460 | return data
461 |
462 |
463 | @router_pdns.get("/servers/{server_id}/tsigkeys/{tsigkey_id}")
464 | async def fetch_tsigkey(
465 | response: Response, server_id: str, tsigkey_id: str, X_API_Key: str = Header()
466 | ):
467 | """
468 | Get a specific TSIGKeys on the server, including the actual key.
469 |
470 |
471 | """
472 | environment = get_environment_for_token(config, X_API_Key)
473 | if not check_pdns_tsigkeys_allowed(environment):
474 | logger.info(f"TSIGKeys not allowed for environment {environment.name}")
475 | raise ZoneNotAllowedException()
476 | resp = await pdns.get(f"/api/v1/servers/{server_id}/tsigkeys/{tsigkey_id}")
477 | response.status_code = resp.status
478 | data = await response_json_or_text(resp)
479 | return data
480 |
481 |
482 | @router_pdns.post("/servers/{server_id}/tsigkeys")
483 | async def create_tsigkey(
484 | request: Request, response: Response, server_id: str, X_API_Key: str = Header()
485 | ):
486 | """
487 | Add a TSIG key.
488 |
489 | This methods add a new TSIGKey. The actual key can be generated by the server or
490 | be provided by the client.
491 |
492 |
493 | """
494 | environment = get_environment_for_token(config, X_API_Key)
495 | if not check_pdns_tsigkeys_allowed(environment):
496 | logger.info(f"TSIGKeys not allowed for environment {environment.name}")
497 | raise ZoneNotAllowedException()
498 | resp = await pdns.post(
499 | f"/api/v1/servers/{server_id}/tsigkeys", payload=await request.json()
500 | )
501 | response.status_code = resp.status
502 | data = await response_json_or_text(resp)
503 | return data
504 |
505 |
506 | @router_pdns.put("/servers/{server_id}/tsigkeys/{tsigkey_id}")
507 | async def update_tsigkey(
508 | request: Request,
509 | response: Response,
510 | server_id: str,
511 | tsigkey_id: str,
512 | X_API_Key: str = Header(),
513 | ):
514 | """
515 | The TSIGKey at tsigkey_id can be changed in multiple ways:
516 |
517 | * Changing the Name, this will remove the key with tsigkey_id after adding.
518 | * Changing the Algorithm
519 | * Changing the Key
520 |
521 | Only the relevant fields have to be provided in the request body.
522 |
523 |
524 | """
525 | environment = get_environment_for_token(config, X_API_Key)
526 | if not check_pdns_tsigkeys_allowed(environment):
527 | logger.info(f"TSIGKeys not allowed for environment {environment.name}")
528 | raise ZoneNotAllowedException()
529 | resp = await pdns.put(
530 | f"/api/v1/servers/{server_id}/tsigkeys/{tsigkey_id}",
531 | payload=await request.json(),
532 | )
533 | response.status_code = resp.status
534 | data = await response_json_or_text(resp)
535 | return data
536 |
537 |
538 | @router_pdns.delete("/servers/{server_id}/tsigkeys/{tsigkey_id}")
539 | async def delete_tsigkey(
540 | response: Response, server_id: str, tsigkey_id: str, X_API_Key: str = Header()
541 | ):
542 | """
543 | Delete the TSIGKey with tsigkey_id.
544 |
545 |
546 | """
547 | environment = get_environment_for_token(config, X_API_Key)
548 | if not check_pdns_tsigkeys_allowed(environment):
549 | logger.info(f"TSIGKeys not allowed for environment {environment.name}")
550 | raise ZoneNotAllowedException()
551 | resp = await pdns.delete(f"/api/v1/servers/{server_id}/tsigkeys/{tsigkey_id}")
552 | response.status_code = resp.status
553 | data = await response_json_or_text(resp)
554 | return data
555 |
556 |
557 | app.include_router(router_proxy)
558 | app.include_router(router_pdns)
559 | app.include_router(router_health)
560 |
--------------------------------------------------------------------------------
/powerdns_api_proxy/utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 | from json.decoder import JSONDecodeError
4 | from typing import Union
5 |
6 | from aiohttp import ClientResponse
7 |
8 |
9 | async def response_json_or_text(response: ClientResponse) -> Union[dict, str]:
10 | """Returns a `string` or a `dict` from the `ClientResponse`"""
11 | text = await response.text()
12 | try:
13 | return json.loads(text)
14 | except JSONDecodeError:
15 | return text
16 |
17 |
18 | def check_subzone(zone: str, main_zone: str) -> bool:
19 | if zone.rstrip(".").endswith(main_zone.rstrip(".")):
20 | return True
21 | return False
22 |
23 |
24 | def check_zone_in_regex(zone: str, regex: str) -> bool:
25 | """Checks if zone is in regex"""
26 | return re.match(regex, zone.rstrip(".")) is not None
27 |
28 |
29 | def check_record_in_regex(record: str, regex: str) -> bool:
30 | """Checks if record is in regex"""
31 | return re.match(regex, record.rstrip(".")) is not None
32 |
33 |
34 | def check_zones_equal(zone1: str, zone2: str) -> bool:
35 | """Checks if zones equal with or without trailing dot"""
36 | return zone1.rstrip(".") == zone2.rstrip(".")
37 |
--------------------------------------------------------------------------------
/requirements-dev.txt:
--------------------------------------------------------------------------------
1 | black==25.1.0
2 | flake8==7.2.0
3 | flake8-quotes==3.4.0
4 | mypy==1.15.0
5 | pre-commit==4.2.0
6 | pytest==8.3.5
7 | pytest-cov==6.1.1
8 | python-powerdns==2.1.0
9 | requests==2.32.3
10 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | aiohttp==3.11.13
2 | fastapi==0.115.8
3 | httpx
4 | prometheus-fastapi-instrumentator==7.0.2
5 | pyyaml==6.0.2
6 | sentry-sdk[fastapi]==2.22.0
7 | uvicorn==0.34.0
8 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from subprocess import check_output
2 |
3 | from setuptools import find_packages, setup
4 |
5 | requirements = []
6 | with open("./requirements.txt") as f:
7 | lines = f.read().splitlines()
8 | for line in lines:
9 | if not line.startswith("git+ssh"):
10 | requirements.append(line)
11 |
12 | test_requirements = []
13 | with open("./requirements-dev.txt") as f:
14 | lines = f.read().splitlines()
15 | for line in lines:
16 | if not line.startswith("git+ssh"):
17 | test_requirements.append(line)
18 |
19 | try:
20 | version = (
21 | check_output(["git", "describe", "--tags"]).rstrip().decode().replace("v", "")
22 | )
23 | except Exception as e:
24 | print(e)
25 | version = "1.0.0"
26 |
27 |
28 | setup(
29 | author="akquinet",
30 | author_email="noc@akquinet.de",
31 | python_requires=">=3.8",
32 | description="PowerDNS-API-Proxy",
33 | install_requires=requirements,
34 | include_package_data=True,
35 | keywords="powerdns_api_proxy",
36 | name="powerdns_api_proxy",
37 | packages=find_packages(include=["powerdns_api_proxy", "powerdns_api_proxy.*"]),
38 | test_suite="tests",
39 | tests_require=test_requirements,
40 | version=version,
41 | zip_safe=False,
42 | )
43 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akquinet/powerdns-api-proxy/62b0608f6acfb724310d1abd08fad021cab3ff35/tests/__init__.py
--------------------------------------------------------------------------------
/tests/fixtures/__init__.py:
--------------------------------------------------------------------------------
1 | from os import path
2 |
3 | FIXTURES_DIR = path.dirname(path.abspath(__file__))
4 |
--------------------------------------------------------------------------------
/tests/fixtures/test_regex_parsing.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | # file to test regex parsing with yaml escaping
3 | name: ".*\\.example\\.com"
4 | regex: true
5 |
--------------------------------------------------------------------------------
/tests/integration/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akquinet/powerdns-api-proxy/62b0608f6acfb724310d1abd08fad021cab3ff35/tests/integration/__init__.py
--------------------------------------------------------------------------------
/tests/unit/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akquinet/powerdns-api-proxy/62b0608f6acfb724310d1abd08fad021cab3ff35/tests/unit/__init__.py
--------------------------------------------------------------------------------
/tests/unit/config_test.py:
--------------------------------------------------------------------------------
1 | import os
2 | from copy import deepcopy
3 |
4 | import pytest
5 | from fastapi import HTTPException
6 |
7 | from powerdns_api_proxy.config import (
8 | check_acme_record_allowed,
9 | check_pdns_search_allowed,
10 | check_pdns_tsigkeys_allowed,
11 | check_pdns_zone_admin,
12 | check_pdns_zone_allowed,
13 | check_rrset_allowed,
14 | check_token_defined,
15 | ensure_rrsets_request_allowed,
16 | get_environment_for_token,
17 | get_only_pdns_zones_allowed,
18 | token_defined,
19 | )
20 | from powerdns_api_proxy.models import (
21 | RRSET,
22 | NotAuthorizedException,
23 | ProxyConfig,
24 | ProxyConfigEnvironment,
25 | ProxyConfigServices,
26 | ProxyConfigZone,
27 | RRSETRequest,
28 | ZoneNotAllowedException,
29 | )
30 |
31 | os.environ["PROXY_CONFIG_PATH"] = "./config-example.yml"
32 |
33 | dummy_proxy_zone = ProxyConfigZone(name="test.example.com.")
34 | dummy_proxy_environment_token = "lashflkashlfgkashglashglashgl"
35 | dummy_proxy_environment_token_sha512 = "127aab81f4caab9c00e72f26e4c5c4b20146201a1548a787494d999febf1b9422c1711932117f38d9be9efe46f78aa72d8f6a391101bedd6e200014f6738450d" # noqa: E501
36 | dummy_proxy_environment_token2 = "aslkghlskdhglkwhegklwhelghwleghwle"
37 | dummy_proxy_environment_token2_sha512 = "1954a12ef0bf45b3a1797437509037f178af846d880115d57668a8aaa05732deedcbbd02bfa296b4f4e043b437b733fd6131933cfdc0fb50c4cf7f9f2bdaa836" # noqa: E501
38 |
39 | dummy_proxy_environment = ProxyConfigEnvironment(
40 | name="Test 1",
41 | zones=[dummy_proxy_zone],
42 | token_sha512=dummy_proxy_environment_token_sha512,
43 | )
44 | dummy_proxy_environment2 = ProxyConfigEnvironment(
45 | name="Test 2",
46 | zones=[dummy_proxy_zone],
47 | token_sha512=dummy_proxy_environment_token2_sha512,
48 | )
49 | dummy_proxy_config = ProxyConfig(
50 | pdns_api_token="blaaa",
51 | pdns_api_url="bluub",
52 | environments=[dummy_proxy_environment, dummy_proxy_environment2],
53 | )
54 |
55 |
56 | def test_token_not_defined_in_config_raise():
57 | config = dummy_proxy_config
58 | token = "blablub"
59 | with pytest.raises(HTTPException) as err:
60 | check_token_defined(config, token)
61 | assert err.value.detail == NotAuthorizedException().detail
62 | assert err.value.status_code == NotAuthorizedException().status_code
63 |
64 |
65 | def test_token_defined_in_config():
66 | config = dummy_proxy_config
67 | token = dummy_proxy_environment_token
68 | assert token_defined(config, token)
69 |
70 |
71 | def test_get_only_pdns_zones_allowed():
72 | pdns_zones = [
73 | {"name": "test1.example.com."},
74 | {"name": "test2.example.com."},
75 | {"name": "test3.example.com."},
76 | {"name": "test4.example.com."},
77 | ]
78 |
79 | env = ProxyConfigEnvironment(
80 | name="Test Environment1",
81 | token_sha512=dummy_proxy_environment_token_sha512,
82 | zones=[
83 | ProxyConfigZone(name="test1.example.com."),
84 | ProxyConfigZone(name="test3.example.com."),
85 | ],
86 | )
87 | allowed = get_only_pdns_zones_allowed(env, pdns_zones)
88 | assert len(allowed) == len(env.zones)
89 | assert "test1.example.com." in [z.name for z in env.zones]
90 | assert "test3.example.com." in [z.name for z in env.zones]
91 |
92 |
93 | def test_get_only_pdns_zones_allowed_glboal_read_only():
94 | pdns_zones = [
95 | {"name": "test1.example.com."},
96 | {"name": "test2.example.com."},
97 | {"name": "test3.example.com."},
98 | {"name": "test4.example.com."},
99 | ]
100 |
101 | env = ProxyConfigEnvironment(
102 | name="Test Environment1",
103 | token_sha512=dummy_proxy_environment_token_sha512,
104 | zones=[],
105 | global_read_only=True,
106 | )
107 | allowed = get_only_pdns_zones_allowed(env, pdns_zones)
108 | assert len(allowed) == len(pdns_zones)
109 |
110 |
111 | def test_get_environment_for_token_found():
112 | config = dummy_proxy_config
113 | token = dummy_proxy_environment_token
114 | env = get_environment_for_token(config, token)
115 | assert env == dummy_proxy_environment
116 |
117 |
118 | def test_get_environment_for_token_not_found():
119 | config = dummy_proxy_config
120 | token = "michgibteshoffentlichnicht"
121 | with pytest.raises(ValueError):
122 | get_environment_for_token(config, token)
123 |
124 |
125 | def test_check_pdns_zone_allowed():
126 | env = dummy_proxy_environment
127 | assert check_pdns_zone_allowed(env, dummy_proxy_zone.name)
128 |
129 |
130 | def test_check_pdns_zone_allowed_false():
131 | env = dummy_proxy_environment
132 | assert not check_pdns_zone_allowed(env, "blablubTest24.example.com.")
133 |
134 |
135 | def test_check_pdns_zone_allowed_global_read_only():
136 | env = deepcopy(dummy_proxy_environment)
137 | env.global_read_only = True
138 | assert check_pdns_zone_allowed(env, "blablubTest24.example.com.") is True
139 |
140 |
141 | def test_check_pdns_zone_allowed_subzone():
142 | env = dummy_proxy_environment
143 | env.zones[0].subzones = True
144 | assert check_pdns_zone_allowed(env, "blablubTest24." + env.zones[0].name)
145 |
146 |
147 | def test_check_pdns_zone_admin():
148 | env = dummy_proxy_environment
149 | dummy_proxy_environment.zones[0].admin = True
150 | assert check_pdns_zone_admin(env, dummy_proxy_zone.name)
151 |
152 |
153 | def test_check_pdns_zone_admin_false():
154 | env = dummy_proxy_environment
155 | dummy_proxy_environment.zones[0].admin = False
156 | assert not check_pdns_zone_admin(env, dummy_proxy_zone.name)
157 |
158 |
159 | def test_check_pdns_zone_admin_false_not_found():
160 | env = dummy_proxy_environment
161 | assert not check_pdns_zone_admin(env, "blablaalball.example.com.")
162 |
163 |
164 | def test_check_pdns_zone_admin_true_subzone():
165 | env = dummy_proxy_environment
166 | dummy_proxy_environment.zones[0].admin = True
167 | env.zones[0].subzones = True
168 | assert check_pdns_zone_admin(env, "blablubTest24." + env.zones[0].name)
169 |
170 |
171 | def test_get_zone_config():
172 | env = dummy_proxy_environment
173 | zone = env.get_zone_if_allowed(dummy_proxy_zone.name)
174 | assert zone.name == dummy_proxy_zone.name
175 |
176 |
177 | def test_get_zone_config_not_allowed():
178 | env = dummy_proxy_environment
179 | with pytest.raises(HTTPException) as err:
180 | env.get_zone_if_allowed("blablub_mich_gibtsnicht.example.com.")
181 | assert err.value.detail == ZoneNotAllowedException().detail
182 | assert err.value.status_code == ZoneNotAllowedException().status_code
183 |
184 |
185 | def test_get_zone_config_subzone():
186 | env = dummy_proxy_environment
187 | dummy_proxy_environment.zones[0].subzones = True
188 | subzone = "blabluuub." + dummy_proxy_environment.zones[0].name
189 | assert env.get_zone_if_allowed(subzone)
190 |
191 |
192 | def test_get_zone_config_subzone_subzone():
193 | env = dummy_proxy_environment
194 | dummy_proxy_environment.zones[0].subzones = True
195 | subzone = "blabluuub.subzone." + dummy_proxy_environment.zones[0].name
196 | assert env.get_zone_if_allowed(subzone)
197 |
198 |
199 | def test_get_zone_config_subzone_not_allowed():
200 | env = dummy_proxy_environment
201 | subzone = "blabluuub." + dummy_proxy_environment.zones[0].name + "test."
202 | with pytest.raises(HTTPException) as err:
203 | assert env.get_zone_if_allowed(subzone)
204 | assert err.value.detail == ZoneNotAllowedException().detail
205 | assert err.value.status_code == ZoneNotAllowedException().status_code
206 |
207 |
208 | def test_get_zone_config_no_subzone():
209 | env = dummy_proxy_environment
210 | dummy_proxy_environment.zones[0].subzones = False
211 | subzone = "blabluuub." + dummy_proxy_environment.zones[0].name
212 | with pytest.raises(HTTPException) as err:
213 | assert env.get_zone_if_allowed(subzone)
214 | assert err.value.detail == ZoneNotAllowedException().detail
215 | assert err.value.status_code == ZoneNotAllowedException().status_code
216 |
217 |
218 | def test_check_pdns_zone_allowed_allowed_without_trailing_point():
219 | env = dummy_proxy_environment
220 | zone = dummy_proxy_zone.name[0 : len(dummy_proxy_zone.name) - 1] # noqa: E203
221 | print(zone)
222 | assert check_pdns_zone_allowed(env, zone)
223 |
224 |
225 | def test_check_pdns_zone_allowed_allowed_without_trailing_point_point_last_item():
226 | env = dummy_proxy_environment
227 | env.zones[0].name = "blablub.example.com+"
228 | zone = "blablub.example.com"
229 | assert not check_pdns_zone_allowed(env, zone)
230 |
231 |
232 | def test_check_rrset_allowed_all_records():
233 | zone = ProxyConfigZone(name="test-zone.example.com.")
234 | for item in [
235 | "entry1.test-zone.example.com.",
236 | "entry2.entry1.test-zone.example.com",
237 | "test-zone.example.com.",
238 | ]:
239 | rrset: RRSET = {
240 | "name": item,
241 | "type": "TXT",
242 | "changetype": "REPLACE",
243 | "ttl": 3600,
244 | "records": [],
245 | "comments": [],
246 | }
247 | assert check_rrset_allowed(zone, rrset)
248 |
249 |
250 | def test_check_rrset_allowed_single_entries():
251 | zone = ProxyConfigZone(
252 | name="test-zone.example.com.",
253 | records=[
254 | "entry1.test-zone.example.com.",
255 | "entry2.entry1.test-zone.example.com",
256 | "test-zone.example.com.",
257 | ],
258 | )
259 | for item in [
260 | "entry1.test-zone.example.com.",
261 | "entry2.entry1.test-zone.example.com",
262 | "test-zone.example.com.",
263 | ]:
264 | rrset: RRSET = {
265 | "name": item,
266 | "type": "TXT",
267 | "changetype": "REPLACE",
268 | "ttl": 3600,
269 | "records": [],
270 | "comments": [],
271 | }
272 | assert check_rrset_allowed(zone, rrset)
273 |
274 |
275 | def test_check_rrset_not_allowed_single_entries():
276 | zone = ProxyConfigZone(
277 | name="test-zone.example.com.",
278 | records=[
279 | "entry1.test-zone.example.com.",
280 | "entry2.entry1.test-zone.example.com",
281 | "test-zone.example.com.",
282 | ],
283 | )
284 | for item in [
285 | "entry100.test-zone.example.com.",
286 | "entry200.entry1.test-zone.example.com",
287 | "test-record.example.com.",
288 | ]:
289 | rrset: RRSET = {
290 | "name": item,
291 | "type": "TXT",
292 | "changetype": "REPLACE",
293 | "ttl": 3600,
294 | "records": [],
295 | "comments": [],
296 | }
297 | assert not check_rrset_allowed(zone, rrset)
298 |
299 |
300 | def test_check_rrsets_request_allowed_no_raise():
301 | zone = ProxyConfigZone(
302 | name="test-zone.example.com.",
303 | records=[
304 | "entry1.test-zone.example.com.",
305 | "entry2.entry1.test-zone.example.com",
306 | "test-zone.example.com.",
307 | ],
308 | )
309 | request: RRSETRequest = {"rrsets": []}
310 | for item in [
311 | "entry1.test-zone.example.com.",
312 | "entry2.entry1.test-zone.example.com",
313 | "test-zone.example.com.",
314 | ]:
315 | request["rrsets"].append(
316 | {
317 | "name": item,
318 | "type": "TXT",
319 | "changetype": "REPLACE",
320 | "ttl": 3600,
321 | "records": [],
322 | "comments": [],
323 | }
324 | )
325 | assert ensure_rrsets_request_allowed(zone, request)
326 |
327 |
328 | def test_check_rrsets_request_allowed_raise():
329 | zone = ProxyConfigZone(
330 | name="test-zone.example.com.",
331 | records=[
332 | "test-zone.example.com.",
333 | ],
334 | )
335 | request: RRSETRequest = {"rrsets": []}
336 | for item in [
337 | "entry1.test-zone.example.com.",
338 | "test-zone.example.com.",
339 | ]:
340 | request["rrsets"].append(
341 | {
342 | "name": item,
343 | "type": "TXT",
344 | "changetype": "REPLACE",
345 | "ttl": 3600,
346 | "records": [],
347 | "comments": [],
348 | }
349 | )
350 | with pytest.raises(HTTPException) as err:
351 | ensure_rrsets_request_allowed(zone, request)
352 | assert err.value.status_code == 403
353 | assert err.value.detail == "RRSET entry1.test-zone.example.com. not allowed"
354 |
355 |
356 | def test_check_rrsets_request_not_allowed_read_only():
357 | zone = ProxyConfigZone(
358 | name="test-zone.example.com.",
359 | read_only=True,
360 | )
361 | request: RRSETRequest = {"rrsets": []}
362 | for item in [
363 | "entry1.test-zone.example.com.",
364 | "test-zone.example.com.",
365 | ]:
366 | request["rrsets"].append(
367 | {
368 | "name": item,
369 | "type": "TXT",
370 | "changetype": "REPLACE",
371 | "ttl": 3600,
372 | "records": [],
373 | "comments": [],
374 | }
375 | )
376 | with pytest.raises(HTTPException) as err:
377 | ensure_rrsets_request_allowed(zone, request)
378 | assert err.value.status_code == 403
379 | assert err.value.detail == "RRSET update not allowed with read only token"
380 |
381 |
382 | def test_rrset_request_not_allowed_regex_empty():
383 | zone = ProxyConfigZone(
384 | name="test-zone.example.com.",
385 | regex_records=[],
386 | )
387 | request: RRSETRequest = {"rrsets": []}
388 | assert ensure_rrsets_request_allowed(zone, request)
389 |
390 |
391 | def test_rrset_request_allowed_all_regex():
392 | zone = ProxyConfigZone(
393 | name="test-zone.example.com.",
394 | regex_records=[
395 | ".*",
396 | ],
397 | )
398 | request: RRSETRequest = {"rrsets": []}
399 | for item in [
400 | "entry1.test-zone.example.com.",
401 | "entry2.entry1.test-zone.example.com",
402 | ]:
403 | request["rrsets"].append(
404 | {
405 | "name": item,
406 | "type": "TXT",
407 | "changetype": "REPLACE",
408 | "ttl": 3600,
409 | "records": [],
410 | "comments": [],
411 | }
412 | )
413 | assert ensure_rrsets_request_allowed(zone, request)
414 |
415 |
416 | def test_rrset_request_allowed_acme_regex():
417 | zone = ProxyConfigZone(
418 | name="test-zone.example.com.",
419 | regex_records=[
420 | "_acme-challenge.example.*.test-zone.example.com",
421 | ],
422 | )
423 | request: RRSETRequest = {"rrsets": []}
424 | for item in [
425 | "_acme-challenge.example-entry.test-zone.example.com.",
426 | ]:
427 | request["rrsets"].append(
428 | {
429 | "name": item,
430 | "type": "TXT",
431 | "changetype": "REPLACE",
432 | "ttl": 3600,
433 | "records": [],
434 | "comments": [],
435 | }
436 | )
437 | assert ensure_rrsets_request_allowed(zone, request)
438 |
439 |
440 | def test_rrset_request_not_allowed_false_regex():
441 | zone = ProxyConfigZone(
442 | name="test-zone.example.com.",
443 | regex_records=[
444 | "example.*.test-zone.example.com",
445 | ],
446 | )
447 | request: RRSETRequest = {"rrsets": []}
448 | for item in [
449 | "entry1.test-zone.example.com.",
450 | "entry2.entry1.test-zone.example.com",
451 | ]:
452 | request["rrsets"].append(
453 | {
454 | "name": item,
455 | "type": "TXT",
456 | "changetype": "REPLACE",
457 | "ttl": 3600,
458 | "records": [],
459 | "comments": [],
460 | }
461 | )
462 | with pytest.raises(HTTPException) as err:
463 | ensure_rrsets_request_allowed(zone, request)
464 | assert err.value.status_code == 403
465 | assert err.value.detail == "RRSET entry1.test-zone.example.com. not allowed"
466 |
467 |
468 | def test_rrset_request_not_allowed_false_zone():
469 | zone = ProxyConfigZone(
470 | name="test-zone.example.com.",
471 | regex_records=[
472 | "example.*.test-zone2.example.com",
473 | ],
474 | )
475 | request: RRSETRequest = {"rrsets": []}
476 | for item in [
477 | "example1.test-zone2.example.com.",
478 | ]:
479 | request["rrsets"].append(
480 | {
481 | "name": item,
482 | "type": "TXT",
483 | "changetype": "REPLACE",
484 | "ttl": 3600,
485 | "records": [],
486 | "comments": [],
487 | }
488 | )
489 | with pytest.raises(HTTPException) as err:
490 | ensure_rrsets_request_allowed(zone, request)
491 | assert err.value.status_code == 403
492 | assert err.value.detail == "RRSET example1.test-zone2.example.com. not allowed"
493 |
494 |
495 | def test_check_acme_record_allowed_all_records():
496 | zone = ProxyConfigZone(name="test-zone.example.com", all_records=True)
497 | rrset = RRSET(
498 | name="_acme-challenge.blabub.test-zone.example.com",
499 | type="TXT",
500 | changetype="REPLACE",
501 | ttl=3600,
502 | records=[],
503 | comments=[],
504 | )
505 | assert check_acme_record_allowed(zone, rrset)
506 |
507 |
508 | def test_check_acme_record_allowed_no_service_acme():
509 | zone = ProxyConfigZone(
510 | name="test-zone.example.com", records=["blabub.test-zone.example.com"]
511 | )
512 | rrset = RRSET(
513 | name="_acme-challenge.blabub.test-zone.example.com",
514 | type="TXT",
515 | changetype="REPLACE",
516 | ttl=3600,
517 | records=[],
518 | comments=[],
519 | )
520 | assert not check_acme_record_allowed(zone, rrset)
521 |
522 |
523 | def test_check_acme_record_allowed():
524 | zone = ProxyConfigZone(
525 | name="test-zone.example.com",
526 | records=["blabub.test-zone.example.com"],
527 | services=ProxyConfigServices(acme=True),
528 | )
529 | rrset = RRSET(
530 | name="_acme-challenge.blabub.test-zone.example.com",
531 | type="TXT",
532 | changetype="REPLACE",
533 | ttl=3600,
534 | records=[],
535 | comments=[],
536 | )
537 | assert check_acme_record_allowed(zone, rrset)
538 |
539 |
540 | def test_check_acme_record_not_allowed():
541 | zone = ProxyConfigZone(
542 | name="test-zone.example.com",
543 | records=["hallo.test-zone.example.com"],
544 | services=ProxyConfigServices(acme=True),
545 | )
546 | rrset = RRSET(
547 | name="_acme-challenge.blabub.test-zone.example.com",
548 | type="TXT",
549 | changetype="REPLACE",
550 | ttl=3600,
551 | records=[],
552 | comments=[],
553 | )
554 | assert not check_acme_record_allowed(zone, rrset)
555 |
556 |
557 | def test_check_acme_record_not_allowed_false_challenge():
558 | zone = ProxyConfigZone(
559 | name="test-zone.example.com",
560 | records=["blabub.test-zone.example.com"],
561 | services=ProxyConfigServices(acme=True),
562 | )
563 | rrset = RRSET(
564 | name="_acme.blabub.test-zone.example.com",
565 | type="TXT",
566 | changetype="REPLACE",
567 | ttl=3600,
568 | records=[],
569 | comments=[],
570 | )
571 | assert not check_acme_record_allowed(zone, rrset)
572 |
573 |
574 | def test_search_not_allowed():
575 | environment = deepcopy(dummy_proxy_environment)
576 | environment.global_search = False
577 | assert check_pdns_search_allowed(environment, "test", "all") is False
578 |
579 |
580 | def test_search_allowed_globally():
581 | environment = deepcopy(dummy_proxy_environment)
582 | environment.global_search = True
583 | assert check_pdns_search_allowed(environment, "test", "all") is True
584 |
585 |
586 | def test_tsigkeys_not_allowed():
587 | environment = deepcopy(dummy_proxy_environment)
588 | environment.global_tsigkeys = False
589 | assert check_pdns_tsigkeys_allowed(environment) is False
590 |
591 |
592 | def test_tsigkeys_allowed_globally():
593 | environment = deepcopy(dummy_proxy_environment)
594 | environment.global_tsigkeys = True
595 | assert check_pdns_tsigkeys_allowed(environment) is True
596 |
--------------------------------------------------------------------------------
/tests/unit/proxy_test.py:
--------------------------------------------------------------------------------
1 | import os
2 | from typing import Generator
3 | from unittest.mock import AsyncMock, patch
4 |
5 | import pytest
6 | from fastapi.testclient import TestClient
7 |
8 | from powerdns_api_proxy.models import (
9 | NotAuthorizedException,
10 | ProxyConfig,
11 | ProxyConfigEnvironment,
12 | ProxyConfigZone,
13 | )
14 | from powerdns_api_proxy.proxy import app
15 |
16 | client = TestClient(app)
17 |
18 |
19 | dummy_proxy_zone = ProxyConfigZone(name="test.example.com.")
20 | dummy_proxy_environment_token = "lashflkashlfgkashglashglashgl"
21 | dummy_proxy_environment_token_sha512 = "127aab81f4caab9c00e72f26e4c5c4b20146201a1548a787494d999febf1b9422c1711932117f38d9be9efe46f78aa72d8f6a391101bedd6e200014f6738450d" # noqa: E501
22 | dummy_proxy_environment_token2 = "aslkghlskdhglkwhegklwhelghwleghwle"
23 | dummy_proxy_environment_token2_sha512 = "1954a12ef0bf45b3a1797437509037f178af846d880115d57668a8aaa05732deedcbbd02bfa296b4f4e043b437b733fd6131933cfdc0fb50c4cf7f9f2bdaa836" # noqa: E501
24 |
25 | dummy_proxy_environment = ProxyConfigEnvironment(
26 | name="Test 1",
27 | zones=[dummy_proxy_zone],
28 | token_sha512=dummy_proxy_environment_token_sha512,
29 | )
30 | dummy_proxy_environment2 = ProxyConfigEnvironment(
31 | name="Test 2",
32 | zones=[dummy_proxy_zone],
33 | token_sha512=dummy_proxy_environment_token2_sha512,
34 | )
35 | dummy_proxy_config = ProxyConfig(
36 | pdns_api_token="blaaa",
37 | pdns_api_url="bluub",
38 | environments=[dummy_proxy_environment, dummy_proxy_environment2],
39 | )
40 |
41 | os.environ["PROXY_CONFIG_PATH"] = "./config-example.yml"
42 |
43 |
44 | @pytest.fixture()
45 | def fixture_patch_dummy_config() -> Generator[None, None, None]:
46 | with patch("powerdns_api_proxy.config.load_config") as load_config_patch:
47 | load_config_patch.return_value = dummy_proxy_config
48 | yield
49 |
50 |
51 | @pytest.fixture()
52 | def fixture_patch_pdns() -> Generator[AsyncMock, None, None]:
53 | with patch("powerdns_api_proxy.proxy.PDNSConnector") as pdns_patch:
54 | pdns_patch = AsyncMock()
55 | yield pdns_patch
56 |
57 |
58 | def test_api_root(fixture_patch_dummy_config):
59 | answer = client.get("/api", headers={"X-API-Key": dummy_proxy_environment_token})
60 | data = answer.json()
61 | print(data)
62 | assert answer.status_code == 200
63 | assert 1 == data[0].get("version")
64 | assert data[0].get("compatibility")
65 |
66 |
67 | def _wrong_token_request(client: TestClient, method: str, path: str):
68 | answer = client.request(method, path, headers={"X-API-Key": "alsdjlkasjdlld"})
69 | print(answer.json())
70 | assert answer.status_code == 401
71 | assert answer.json()["error"] == NotAuthorizedException().detail
72 |
73 |
74 | def _token_missing_request(client: TestClient, method: str, path: str):
75 | answer = client.request(method, path)
76 | print(answer.json())
77 | assert answer.status_code == 422
78 |
79 |
80 | get_routes = [
81 | "/info/allowed",
82 | "/info/zone-allowed",
83 | "/api",
84 | "/api/v1/servers",
85 | "/api/v1/servers/localhost",
86 | "/api/v1/servers/localhost/configuration",
87 | "/api/v1/servers/localhost/statistics",
88 | "/api/v1/servers/localhost/zones",
89 | "/api/v1/servers/localhost/zones/test.example.com.",
90 | "/api/v1/servers/localhost/search-data?q='test.example.com.'",
91 | ]
92 |
93 |
94 | @pytest.mark.parametrize("path", get_routes)
95 | def test_api_get_wrong_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
96 | _wrong_token_request(client, "GET", path)
97 |
98 |
99 | @pytest.mark.parametrize("path", get_routes)
100 | def test_api_get_missing_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
101 | _token_missing_request(client, "GET", path)
102 |
103 |
104 | post_routes = ["/api/v1/servers/localhost/zones"]
105 |
106 |
107 | @pytest.mark.parametrize("path", post_routes)
108 | def test_api_post_wrong_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
109 | _wrong_token_request(client, "POST", path)
110 |
111 |
112 | @pytest.mark.parametrize("path", post_routes)
113 | def test_api_post_missing_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
114 | _token_missing_request(client, "POST", path)
115 |
116 |
117 | put_routes = [
118 | "/api/v1/servers/localhost/zones/test-zone.example.com.",
119 | "/api/v1/servers/localhost/zones/test-zone.example.com./notify",
120 | ]
121 |
122 |
123 | @pytest.mark.parametrize("path", put_routes)
124 | def test_api_put_wrong_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
125 | _wrong_token_request(client, "PUT", path)
126 |
127 |
128 | @pytest.mark.parametrize("path", put_routes)
129 | def test_api_put_missing_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
130 | _token_missing_request(client, "PUT", path)
131 |
132 |
133 | patch_routes = ["/api/v1/servers/localhost/zones/test-zone.example.com."]
134 |
135 |
136 | @pytest.mark.parametrize("path", patch_routes)
137 | def test_api_patch_wrong_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
138 | _wrong_token_request(client, "PATCH", path)
139 |
140 |
141 | @pytest.mark.parametrize("path", patch_routes)
142 | def test_api_patch_missing_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
143 | _token_missing_request(client, "PATCH", path)
144 |
145 |
146 | delete_routes = ["/api/v1/servers/localhost/zones/test-zone.example.com."]
147 |
148 |
149 | @pytest.mark.parametrize("path", delete_routes)
150 | def test_api_delete_wrong_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
151 | _wrong_token_request(client, "DELETE", path)
152 |
153 |
154 | @pytest.mark.parametrize("path", delete_routes)
155 | def test_api_delete_missing_token(path, fixture_patch_dummy_config, fixture_patch_pdns):
156 | _token_missing_request(client, "DELETE", path)
157 |
--------------------------------------------------------------------------------
/tests/unit/utils_test.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import yaml
3 |
4 | from powerdns_api_proxy.utils import (
5 | check_subzone,
6 | check_zone_in_regex,
7 | check_zones_equal,
8 | )
9 | from tests.fixtures import FIXTURES_DIR
10 |
11 |
12 | def test_check_subzone_true():
13 | zone = "myzone.main.example.com"
14 | main = "main.example.com."
15 | assert check_subzone(zone, main)
16 |
17 |
18 | def test_check_subzone_false():
19 | zone = "myzone.test.example.com"
20 | main = "main.example.com."
21 | assert not check_subzone(zone, main)
22 |
23 |
24 | def test_zones_equal_true():
25 | zone1 = "myzone.main.example.com"
26 | zone2 = "myzone.main.example.com."
27 | assert check_zones_equal(zone1, zone2)
28 |
29 |
30 | @pytest.mark.parametrize(
31 | "zone, regex",
32 | [
33 | ("prod.customer.example.com", ".*customer.example.com"),
34 | ("prod.customer.example.com", ".*\\.customer.example.com"),
35 | ("dns.prod.customer.example.com.", ".*customer.example.com"),
36 | ("prod.customer.example.com.", r"\w+\.customer.example.com"),
37 | ("customer.example.com.", r"\w*customer.example.com"),
38 | ("prod.customer.example.com.", r"\w+\.\w+\.example.com"),
39 | ],
40 | )
41 | def test_zones_in_regex_true(zone, regex):
42 | assert check_zone_in_regex(zone, regex)
43 |
44 |
45 | @pytest.mark.parametrize(
46 | "zone, regex",
47 | [
48 | ("main.example.com.", r"\w+\.main.example.com"), # only subzone allowed
49 | ("main.example.com.", r"\w+\.main.test.com"), # false base domain
50 | (
51 | "subzone.zone.main.example.com.",
52 | r"\w+\.main.example.com",
53 | ), # missing dot for subzone
54 | ("customer.example.com.", r"main.example.com"), # only dots
55 | ],
56 | )
57 | def test_zones_in_regex_false(zone, regex):
58 | assert not check_zone_in_regex(zone, regex)
59 |
60 |
61 | def test_regex_with_parsed_yaml():
62 | with open(FIXTURES_DIR + "/test_regex_parsing.yaml") as f:
63 | parsed = yaml.safe_load(f)
64 | regex_string = parsed["name"]
65 | assert check_zone_in_regex("customer.example.com.", regex_string)
66 |
--------------------------------------------------------------------------------