VaultAPI 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Vignesh Rao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,240 @@
1
+ Metadata-Version: 2.2
2
+ Name: VaultAPI
3
+ Version: 0.1.1
4
+ Summary: Lightweight API to store/retrieve secrets to/from an encrypted Database
5
+ Author-email: Vignesh Rao <svignesh1793@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 Vignesh Rao
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/thevickypedia/VaultAPI
29
+ Project-URL: Docs, https://thevickypedia.github.io/VaultAPI
30
+ Project-URL: Source, https://github.com/thevickypedia/VaultAPI
31
+ Project-URL: Bug Tracker, https://github.com/thevickypedia/VaultAPI/issues
32
+ Project-URL: Release Notes, https://github.com/thevickypedia/VaultAPI/blob/main/release_notes.rst
33
+ Keywords: vaultapi,vault,fastapi,sqlite3,fernet
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3.10
36
+ Classifier: Programming Language :: Python :: 3.11
37
+ Classifier: Development Status :: 5 - Production/Stable
38
+ Classifier: Operating System :: MacOS :: MacOS X
39
+ Classifier: Operating System :: Microsoft :: Windows
40
+ Classifier: Operating System :: POSIX :: Linux
41
+ Requires-Python: >=3.10
42
+ Description-Content-Type: text/markdown
43
+ License-File: LICENSE
44
+ Requires-Dist: click==8.1.8
45
+ Requires-Dist: cryptography==44.0.0
46
+ Requires-Dist: fastapi==0.115.6
47
+ Requires-Dist: pydantic==2.10.5
48
+ Requires-Dist: pydantic-settings==2.7.1
49
+ Requires-Dist: python-dotenv==1.0.1
50
+ Requires-Dist: PyYAML==6.0.2
51
+ Requires-Dist: uvicorn==0.34.0
52
+ Provides-Extra: dev
53
+ Requires-Dist: sphinx==5.1.1; extra == "dev"
54
+ Requires-Dist: pre-commit; extra == "dev"
55
+ Requires-Dist: recommonmark; extra == "dev"
56
+ Requires-Dist: gitverse; extra == "dev"
57
+
58
+ # VaultAPI
59
+ Lightweight API to store/retrieve secrets to/from an encrypted Database
60
+
61
+ ![Python][label-pyversion]
62
+
63
+ **Platform Supported**
64
+
65
+ ![Platform][label-platform]
66
+ ![docker-image][image-size]
67
+
68
+ **Deployments**
69
+
70
+ [![docker][label-docker-build]][gha_docker]
71
+ [![pypi][label-actions-pypi]][gha_pypi]
72
+ [![docker_desc][label-docker-desc]][gha_docker_desc]
73
+
74
+ [![markdown][label-actions-markdown]][gha_md_valid]
75
+ [![pages][label-actions-pages]][gha_pages]
76
+
77
+ [![Pypi][label-pypi]][pypi]
78
+ [![Pypi-format][label-pypi-format]][pypi-files]
79
+ [![Pypi-status][label-pypi-status]][pypi]
80
+
81
+ ## Kick off
82
+
83
+ **Recommendations**
84
+
85
+ - Install `python` [3.10] or [3.11]
86
+ - Use a dedicated [virtual environment]
87
+
88
+ **Install VaultAPI**
89
+ ```shell
90
+ python -m pip install vaultapi
91
+ ```
92
+
93
+ **Initiate - IDE**
94
+ ```python
95
+ import vaultapi.server
96
+
97
+
98
+ if __name__ == '__main__':
99
+ vaultapi.server.start()
100
+ ```
101
+
102
+ **Initiate - CLI**
103
+ ```shell
104
+ vaultapi start
105
+ ```
106
+
107
+ > Use `vaultapi --help` for usage instructions.
108
+
109
+ ## Environment Variables
110
+
111
+ <details>
112
+ <summary><strong>Sourcing environment variables from an env file</strong></summary>
113
+
114
+ > _By default, `VaultAPI` will look for a `.env` file in the current working directory._
115
+ </details>
116
+
117
+ **Mandatory**
118
+ - **APIKEY** - API Key for authentication.
119
+ - **SECRET** - Secret access key to encode/decode the secrets in Datastore.
120
+
121
+ **Optional (with defaults)**
122
+ - **TRANSIT_KEY_LENGTH** - AES key length for transit encryption. Defaults to `32`
123
+ - **TRANSIT_TIME_BUCKET** - Interval for which the transit epoch should remain constant. Defaults to `60`
124
+ - **DATABASE** - FilePath to store the secrets' database. Defaults to `secrets.db`
125
+ - **HOST** - Hostname for the API server. Defaults to `0.0.0.0` [OR] `localhost`
126
+ - **PORT** - Port number for the API server. Defaults to `9010`
127
+ - **WORKERS** - Number of workers for the uvicorn server. Defaults to `1`
128
+ - **RATE_LIMIT** - List of dictionaries with `max_requests` and `seconds` to apply as rate limit.
129
+ Defaults to 5req/2s [AND] 10req/30s
130
+
131
+ **Optional (without defaults)**
132
+ - **LOG_CONFIG** - FilePath or dictionary of key-value pairs for log config.
133
+ - **ALLOWED_ORIGINS** - Origins that are allowed to retrieve secrets.
134
+ - **ALLOWED_IP_RANGE** - IP range that is allowed to retrieve secrets. _(eg: `10.112.8.10-210`)_
135
+
136
+ > Checkout [decryptors][decryptors] for more information about decrypting the retrieved secret from the server.
137
+
138
+ <details>
139
+ <summary>Auto generate a <code>SECRET</code> value</summary>
140
+
141
+ This value will be used to encrypt/decrypt the secrets stored in the database.
142
+
143
+ **CLI**
144
+ ```shell
145
+ vaultapi keygen
146
+ ```
147
+
148
+ **IDE**
149
+ ```python
150
+ from cryptography.fernet import Fernet
151
+ print(Fernet.generate_key())
152
+ ```
153
+ </details>
154
+
155
+ ## Coding Standards
156
+ Docstring format: [`Google`][google-docs] <br>
157
+ Styling conventions: [`PEP 8`][pep8] and [`isort`][isort]
158
+
159
+ ## [Release Notes][release-notes]
160
+ **Requirement**
161
+ ```shell
162
+ python -m pip install gitverse
163
+ ```
164
+
165
+ **Usage**
166
+ ```shell
167
+ gitverse-release reverse -f release_notes.rst -t 'Release Notes'
168
+ ```
169
+
170
+ ## Linting
171
+ `pre-commit` will ensure linting, run pytest, generate runbook & release notes, and validate hyperlinks in ALL
172
+ markdown files (including Wiki pages)
173
+
174
+ **Requirement**
175
+ ```shell
176
+ python -m pip install sphinx==5.1.1 pre-commit recommonmark
177
+ ```
178
+
179
+ **Usage**
180
+ ```shell
181
+ pre-commit run --all-files
182
+ ```
183
+
184
+ ## Pypi Package
185
+ [![pypi-module][label-pypi-package]][pypi-repo]
186
+
187
+ [https://pypi.org/project/VaultAPI/][pypi]
188
+
189
+ ## Docker Image
190
+ [![made-with-docker-doc][label-docker-doc]][docker-doc]
191
+
192
+ [https://hub.docker.com/r/thevickypedia/vaultapi][docker]
193
+
194
+ ## Runbook
195
+ [![made-with-sphinx-doc][label-sphinx-doc]][sphinx]
196
+
197
+ [https://thevickypedia.github.io/VaultAPI/][runbook]
198
+
199
+ ## License & copyright
200
+
201
+ &copy; Vignesh Rao
202
+
203
+ Licensed under the [MIT License][license]
204
+
205
+ [label-actions-markdown]: https://github.com/thevickypedia/VaultAPI/actions/workflows/markdown.yaml/badge.svg
206
+ [label-docker-build]: https://github.com/thevickypedia/VaultAPI/actions/workflows/docker-publish.yaml/badge.svg
207
+ [label-docker-desc]: https://github.com/thevickypedia/VaultAPI/actions/workflows/docker-description.yaml/badge.svg
208
+ [label-pypi-package]: https://img.shields.io/badge/Pypi%20Package-VaultAPI-blue?style=for-the-badge&logo=Python
209
+ [label-sphinx-doc]: https://img.shields.io/badge/Made%20with-Sphinx-blue?style=for-the-badge&logo=Sphinx
210
+ [label-docker-doc]: https://img.shields.io/badge/Made%20with-Docker-blue?style=for-the-badge&logo=Docker
211
+ [label-pyversion]: https://img.shields.io/badge/python-3.10%20%7C%203.11-blue
212
+ [label-platform]: https://img.shields.io/badge/Platform-Linux|macOS|Windows-1f425f.svg
213
+ [label-actions-pages]: https://github.com/thevickypedia/VaultAPI/actions/workflows/pages/pages-build-deployment/badge.svg
214
+ [label-actions-pypi]: https://github.com/thevickypedia/VaultAPI/actions/workflows/python-publish.yaml/badge.svg
215
+ [label-pypi]: https://img.shields.io/pypi/v/VaultAPI
216
+ [label-pypi-format]: https://img.shields.io/pypi/format/VaultAPI
217
+ [label-pypi-status]: https://img.shields.io/pypi/status/VaultAPI
218
+
219
+ [3.10]: https://docs.python.org/3/whatsnew/3.10.html
220
+ [3.11]: https://docs.python.org/3/whatsnew/3.11.html
221
+ [virtual environment]: https://docs.python.org/3/tutorial/venv.html
222
+ [release-notes]: https://github.com/thevickypedia/VaultAPI/blob/main/release_notes.rst
223
+ [decryptors]: https://github.com/thevickypedia/VaultAPI/blob/main/decryptors
224
+ [gha_pages]: https://github.com/thevickypedia/VaultAPI/actions/workflows/pages/pages-build-deployment
225
+ [gha_docker]: https://github.com/thevickypedia/VaultAPI/actions/workflows/docker-publish.yaml
226
+ [gha_docker_desc]: https://github.com/thevickypedia/VaultAPI/actions/workflows/docker-description.yaml
227
+ [gha_pypi]: https://github.com/thevickypedia/VaultAPI/actions/workflows/python-publish.yaml
228
+ [gha_md_valid]: https://github.com/thevickypedia/VaultAPI/actions/workflows/markdown.yaml
229
+ [google-docs]: https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings
230
+ [pep8]: https://www.python.org/dev/peps/pep-0008/
231
+ [isort]: https://pycqa.github.io/isort/
232
+ [docker]: https://hub.docker.com/r/thevickypedia/vaultapi
233
+ [docker-doc]: https://docs.docker.com/
234
+ [sphinx]: https://www.sphinx-doc.org/en/master/man/sphinx-autogen.html
235
+ [image-size]: https://img.shields.io/docker/image-size/thevickypedia/vaultapi/latest
236
+ [pypi]: https://pypi.org/project/VaultAPI
237
+ [pypi-files]: https://pypi.org/project/VaultAPI/#files
238
+ [pypi-repo]: https://packaging.python.org/tutorials/packaging-projects/
239
+ [license]: https://github.com/thevickypedia/VaultAPI/blob/main/LICENSE
240
+ [runbook]: https://thevickypedia.github.io/VaultAPI/
@@ -0,0 +1,19 @@
1
+ vaultapi/__init__.py,sha256=iONd8B1j24jfIthkiMZH-WO0C55_NfNAWDnkHjtu84U,2634
2
+ vaultapi/api.py,sha256=fm2ZG9M892GKEAbu30FYSXISKHZfPxBe0xluU2PaAxA,1744
3
+ vaultapi/auth.py,sha256=SQjByRiztCREf9mjIoGetiEMqigwfsT1HlbfitYIqQc,1799
4
+ vaultapi/database.py,sha256=B0GG1ewR3BLHDNjx8zbwzpHkCfb83cS0vRs7Be4MAf4,3815
5
+ vaultapi/exceptions.py,sha256=99R9L2vmimS68RLt5bpw1QT3C2WELHvKNRDWRDwBKi4,185
6
+ vaultapi/models.py,sha256=qnmFbCefP_OOdNmgPptg3wGusNz562ObD84WPw8nrv8,8496
7
+ vaultapi/payload.py,sha256=jOBNA9EWeSVRuvX_Y8V3E56iIdAuKonXv9rrB6fS-cE,529
8
+ vaultapi/rate_limit.py,sha256=oOcwmVmPcWYgtGr6MXrpRfr_i3iKinp_E1RjW8LlR5g,2198
9
+ vaultapi/routes.py,sha256=6X2jEw25dbleeEhB5AD9R7T80Op-7zXvuRPqW3lOLps,12991
10
+ vaultapi/server.py,sha256=-sgtEhOXdlEsWMr2aUeE4SokxSYA5_7Mpw-QAv1Vu-M,545
11
+ vaultapi/transit.py,sha256=s25NWKW_CmnV3HBJgR8C96gBzeWftwwWL09EXgPhnac,2614
12
+ vaultapi/util.py,sha256=UFeE4r68Ma8ws7loEYieEKR846gUIFeYukaUde9cBY8,2959
13
+ vaultapi/version.py,sha256=rnObPjuBcEStqSO0S6gsdS_ot8ITOQjVj_-P1LUUYpg,22
14
+ VaultAPI-0.1.1.dist-info/LICENSE,sha256=xnHdLNCLt4RW3vtnE_TfN_cjViUHyIv0m8024fS4bws,1068
15
+ VaultAPI-0.1.1.dist-info/METADATA,sha256=zVqYkfZya626QiMik8ymyZUfQ8jbfscqUmByes8RNbk,9229
16
+ VaultAPI-0.1.1.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
17
+ VaultAPI-0.1.1.dist-info/entry_points.txt,sha256=MKe6sVDEAHC3YBZoYWLMvgwupRE_QJ_iHK0umfgGOzs,50
18
+ VaultAPI-0.1.1.dist-info/top_level.txt,sha256=17jtNvOOJqazNgWn2ZTmJqfQau5jan_xF82NAJOINQg,9
19
+ VaultAPI-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vaultapi = vaultapi:commandline
@@ -0,0 +1 @@
1
+ vaultapi
vaultapi/__init__.py ADDED
@@ -0,0 +1,77 @@
1
+ import os
2
+ import sys
3
+
4
+ import click
5
+ from cryptography.fernet import Fernet
6
+
7
+ from . import version
8
+
9
+
10
+ @click.command()
11
+ @click.argument("run", required=False)
12
+ @click.argument("start", required=False)
13
+ @click.argument("keygen", required=False)
14
+ @click.option("--version", "-V", is_flag=True, help="Prints the version.")
15
+ @click.option("--help", "-H", is_flag=True, help="Prints the help section.")
16
+ @click.option(
17
+ "--env",
18
+ "-E",
19
+ type=click.Path(exists=True),
20
+ help="Environment configuration filepath.",
21
+ )
22
+ def commandline(*args, **kwargs) -> None:
23
+ """Starter function to invoke VaultAPI via CLI commands.
24
+
25
+ **Flags**
26
+ - ``--version | -V``: Prints the version.
27
+ - ``--help | -H``: Prints the help section.
28
+ - ``--env | -E``: Environment configuration filepath.
29
+ """
30
+ assert sys.argv[0].lower().endswith("vaultapi"), "Invalid commandline trigger!!"
31
+ options = {
32
+ "--version | -V": "Prints the version.",
33
+ "--help | -H": "Prints the help section.",
34
+ "--env | -E": "Environment configuration filepath.",
35
+ "start | run": "Initiates the API server.",
36
+ }
37
+ # weird way to increase spacing to keep all values monotonic
38
+ _longest_key = len(max(options.keys()))
39
+ _pretext = "\n\t* "
40
+ choices = _pretext + _pretext.join(
41
+ f"{k} {'·' * (_longest_key - len(k) + 8)}→ {v}".expandtabs()
42
+ for k, v in options.items()
43
+ )
44
+ if kwargs.get("help"):
45
+ click.echo(
46
+ f"\nUsage: vaultapi [arbitrary-command]\nOptions (and corresponding behavior):{choices}"
47
+ )
48
+ sys.exit(0)
49
+ if kwargs.get("version"):
50
+ click.secho(f"VaultAPI v{version.__version__}", fg="green")
51
+ sys.exit(0)
52
+
53
+ # Store 'env' key's value as the env var 'env_file' - with default to '.env'
54
+ os.environ["env_file"] = kwargs.get("env") or ".env"
55
+ from .server import start
56
+
57
+ trigger = (
58
+ kwargs.get("start") or kwargs.get("run") or kwargs.get("keygen") or ""
59
+ ).lower()
60
+ if trigger in ("start", "run"):
61
+ start()
62
+ sys.exit(0)
63
+ elif trigger == "keygen":
64
+ key = Fernet.generate_key()
65
+ click.secho(
66
+ "\nStore this as an env var named 'secret' or the choice of env_file\n"
67
+ "This secret will be required to decrypt the secrets retrieved from the API\n",
68
+ fg="green",
69
+ )
70
+ click.secho(key.decode() + "\n", bold=True)
71
+ sys.exit(0)
72
+ else:
73
+ click.secho(f"\n{kwargs}\nNo command provided", fg="red")
74
+ click.echo(
75
+ f"Usage: vaultapi [arbitrary-command]\nOptions (and corresponding behavior):{choices}"
76
+ )
77
+ sys.exit(1)
vaultapi/api.py ADDED
@@ -0,0 +1,53 @@
1
+ import logging
2
+ from multiprocessing.process import current_process
3
+
4
+ from fastapi import FastAPI
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+
7
+ from . import models, routes, version
8
+
9
+ VaultAPI = FastAPI(
10
+ title="VaultAPI",
11
+ description="Lightweight service to serve secrets and environment variables",
12
+ version=version.__version__,
13
+ )
14
+
15
+
16
+ def enable_cors() -> None:
17
+ """Enables CORS policy."""
18
+ origins = [
19
+ "http://localhost.com",
20
+ "https://localhost.com",
21
+ ]
22
+ for website in models.env.allowed_origins:
23
+ origins.append(f"http://{website.host}") # noqa: HttpUrlsUsage
24
+ origins.append(f"https://{website.host}")
25
+ # Log the IP info
26
+ if current_process().name in ("SpawnProcess-1", "MainProcess"):
27
+ logger = logging.getLogger("uvicorn.default")
28
+ logger.info("Setting CORS policy")
29
+ logger.info("Allowed default origins: %s", ", ".join(models.DEFAULT_ALLOWED))
30
+ if models.env.allowed_origins:
31
+ logger.info(
32
+ "Allowed origins: %s",
33
+ ", ".join(str(url) for url in models.env.allowed_origins),
34
+ )
35
+ if models.env.allowed_ip_range:
36
+ logger.info("Allowed IP range: %s", ", ".join(models.env.allowed_ip_range))
37
+ logger.debug("Overall allowed origins: %s", models.session.allowed_origins)
38
+ VaultAPI.add_middleware(
39
+ CORSMiddleware, # noqa: PyTypeChecker
40
+ allow_origins=origins,
41
+ allow_credentials=True,
42
+ allow_methods=["GET", "POST", "PUT", "DELETE"],
43
+ allow_headers=[
44
+ # Default headers
45
+ "host",
46
+ "user-agent",
47
+ "authorization",
48
+ ],
49
+ )
50
+
51
+
52
+ enable_cors()
53
+ VaultAPI.routes.extend(routes.get_all_routes())
vaultapi/auth.py ADDED
@@ -0,0 +1,51 @@
1
+ import logging
2
+ import secrets
3
+ from http import HTTPStatus
4
+
5
+ from fastapi import Request
6
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
7
+
8
+ from . import exceptions, models
9
+
10
+ LOGGER = logging.getLogger("uvicorn.default")
11
+ SECURITY = HTTPBearer()
12
+
13
+
14
+ async def validate(request: Request, apikey: HTTPAuthorizationCredentials) -> None:
15
+ """Validates the auth request using HTTPBearer.
16
+
17
+ Args:
18
+ request: Takes the authorization header token as an argument.
19
+ apikey: Basic APIKey required for all the routes.
20
+
21
+ Raises:
22
+ APIResponse:
23
+ - 401: If authorization is invalid.
24
+ - 403: If host address is forbidden.
25
+ """
26
+ if request.client.host not in models.session.allowed_origins:
27
+ LOGGER.info(
28
+ "Host: %s has been blocked since it is not added to allowed list",
29
+ request.client.host,
30
+ )
31
+ LOGGER.info(models.session.allowed_origins)
32
+ raise exceptions.APIResponse(
33
+ status_code=HTTPStatus.FORBIDDEN.real, detail=HTTPStatus.FORBIDDEN.phrase
34
+ )
35
+ if apikey.credentials.startswith("\\"):
36
+ auth = bytes(apikey.credentials, "utf-8").decode(encoding="unicode_escape")
37
+ else:
38
+ auth = apikey.credentials
39
+ if secrets.compare_digest(auth, models.env.apikey):
40
+ LOGGER.debug(
41
+ "Connection received from client-host: %s, host-header: %s, x-fwd-host: %s",
42
+ request.client.host,
43
+ request.headers.get("host"),
44
+ request.headers.get("x-forwarded-host"),
45
+ )
46
+ if user_agent := request.headers.get("user-agent"):
47
+ LOGGER.debug("User agent: %s", user_agent)
48
+ return
49
+ raise exceptions.APIResponse(
50
+ status_code=HTTPStatus.UNAUTHORIZED.real, detail=HTTPStatus.UNAUTHORIZED.phrase
51
+ )
vaultapi/database.py ADDED
@@ -0,0 +1,122 @@
1
+ from typing import List, Tuple
2
+
3
+ from . import models
4
+
5
+
6
+ def table_exists(table_name: str) -> bool:
7
+ """Function to check if a table exists in the database.
8
+
9
+ Args:
10
+ table_name: Name of the table to check.
11
+ """
12
+ with models.database.connection:
13
+ cursor = models.database.connection.cursor()
14
+ cursor.execute(
15
+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
16
+ (table_name,),
17
+ )
18
+ result = cursor.fetchone()
19
+ if result:
20
+ return True
21
+
22
+
23
+ def list_tables() -> List[str]:
24
+ """Function to list all available tables in the database."""
25
+ with models.database.connection:
26
+ cursor = models.database.connection.cursor()
27
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
28
+ tables = cursor.fetchall()
29
+ return [table[0] for table in tables]
30
+
31
+
32
+ def create_table(table_name: str, columns: List[str] | Tuple[str]) -> None:
33
+ """Creates the table with the required columns.
34
+
35
+ Args:
36
+ table_name: Name of the table that has to be created.
37
+ columns: List of columns that has to be created.
38
+ """
39
+ with models.database.connection:
40
+ cursor = models.database.connection.cursor()
41
+ # Use f-string or %s as table names cannot be parametrized
42
+ cursor.execute(
43
+ f"CREATE TABLE IF NOT EXISTS {table_name!r} ({', '.join(columns)})"
44
+ )
45
+
46
+
47
+ def get_secret(key: str, table_name: str) -> str | None:
48
+ """Function to retrieve secret from database.
49
+
50
+ Args:
51
+ key: Name of the secret to retrieve.
52
+ table_name: Name of the table where the secret is stored.
53
+
54
+ Returns:
55
+ str:
56
+ Returns the secret value.
57
+ """
58
+ with models.database.connection:
59
+ cursor = models.database.connection.cursor()
60
+ state = cursor.execute(
61
+ f'SELECT value FROM "{table_name}" WHERE key=(?)', (key,)
62
+ ).fetchone()
63
+ if state and state[0]:
64
+ return state[0]
65
+
66
+
67
+ def get_table(table_name: str) -> List[Tuple[str, str]]:
68
+ """Function to retrieve all key-value pairs from a particular table in the database.
69
+
70
+ Args:
71
+ table_name: Name of the table where the secrets are stored.
72
+
73
+ Returns:
74
+ str:
75
+ Returns the secret value.
76
+ """
77
+ with models.database.connection:
78
+ cursor = models.database.connection.cursor()
79
+ state = cursor.execute(f'SELECT * FROM "{table_name}"').fetchall()
80
+ return state
81
+
82
+
83
+ def put_secret(key: str, value: str, table_name: str) -> None:
84
+ """Function to add secret to the database.
85
+
86
+ Args:
87
+ key: Name of the secret to be stored.
88
+ value: Value of the secret to be stored
89
+ table_name: Name of the table where the secret is stored.
90
+ """
91
+ with models.database.connection:
92
+ cursor = models.database.connection.cursor()
93
+ cursor.execute(
94
+ f'INSERT INTO "{table_name}" (key, value) VALUES (?,?)',
95
+ (key, value),
96
+ )
97
+ models.database.connection.commit()
98
+
99
+
100
+ def remove_secret(key: str, table_name: str) -> None:
101
+ """Function to remove a secret from the database.
102
+
103
+ Args:
104
+ key: Name of the secret to be removed.
105
+ table_name: Name of the table where the secret is stored.
106
+ """
107
+ with models.database.connection:
108
+ cursor = models.database.connection.cursor()
109
+ cursor.execute(f'DELETE FROM "{table_name}" WHERE key=(?)', (key,))
110
+ models.database.connection.commit()
111
+
112
+
113
+ def drop_table(table_name: str) -> None:
114
+ """Function to drop a table from the database.
115
+
116
+ Args:
117
+ table_name: Name of the table to be dropped.
118
+ """
119
+ with models.database.connection:
120
+ cursor = models.database.connection.cursor()
121
+ cursor.execute(f'DROP TABLE IF EXISTS "{table_name}"')
122
+ models.database.connection.commit()
vaultapi/exceptions.py ADDED
@@ -0,0 +1,9 @@
1
+ from fastapi.exceptions import HTTPException
2
+
3
+
4
+ class APIResponse(HTTPException):
5
+ """Custom ``HTTPException`` from ``FastAPI`` to wrap an API response.
6
+
7
+ >>> APIResponse
8
+
9
+ """