Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

disable default jwks for production deployments #2414

Merged
merged 4 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -352,3 +352,5 @@ secrets.sh

# Redis
*.rdb

jwks.b64.txt
13 changes: 13 additions & 0 deletions care/utils/jwks/generate_jwk.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import base64
import json
from pathlib import Path

from authlib.jose import JsonWebKey

Expand All @@ -11,3 +12,15 @@
keys = {"keys": [key]}
keys_json = json.dumps(keys)
return base64.b64encode(keys_json.encode()).decode()


def get_jwks_from_file(base_path: Path):
file_path = base_path / "jwks.b64.txt"
try:
with open(file_path, "r") as file:

Check failure on line 20 in care/utils/jwks/generate_jwk.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (UP015)

care/utils/jwks/generate_jwk.py:20:14: UP015 Unnecessary open mode parameters

Check failure on line 20 in care/utils/jwks/generate_jwk.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (PTH123)

care/utils/jwks/generate_jwk.py:20:14: PTH123 `open()` should be replaced by `Path.open()`
return file.read()
except FileNotFoundError:
jwks = generate_encoded_jwks()
with open(file_path, "w") as file:

Check failure on line 24 in care/utils/jwks/generate_jwk.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (PTH123)

care/utils/jwks/generate_jwk.py:24:14: PTH123 `open()` should be replaced by `Path.open()`
file.write(jwks)
return jwks
9 changes: 0 additions & 9 deletions config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@
Base settings to build other settings files upon.
"""

import base64
import json
from datetime import datetime, timedelta
from pathlib import Path

import environ
from authlib.jose import JsonWebKey
from django.utils.translation import gettext_lazy as _
from healthy_django.healthcheck.celery_queue_length import (
DjangoCeleryQueueLengthHealthCheck,
Expand All @@ -17,7 +14,6 @@
from healthy_django.healthcheck.django_database import DjangoDatabaseHealthCheck

from care.utils.csp import config as csp_config
from care.utils.jwks.generate_jwk import generate_encoded_jwks
from plug_config import manager

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
Expand Down Expand Up @@ -280,7 +276,7 @@
CSRF_TRUSTED_ORIGINS = env.json("CSRF_TRUSTED_ORIGINS", default=[])

# https://github.com/adamchainz/django-cors-headers#cors_allowed_origin_regexes-sequencestr--patternstr
# CORS_URLS_REGEX = r"^/api/.*$"

Check failure on line 279 in config/settings/base.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ERA001)

config/settings/base.py:279:1: ERA001 Found commented-out code

# EMAIL
# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -308,9 +304,9 @@
# https://docs.djangoproject.com/en/dev/ref/settings/#server-email
# SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL) # noqa F405
# https://docs.djangoproject.com/en/dev/ref/settings/#admins
# ADMINS = [("""👪""", "admin@ohc.network")]

Check failure on line 307 in config/settings/base.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ERA001)

config/settings/base.py:307:1: ERA001 Found commented-out code
# https://docs.djangoproject.com/en/dev/ref/settings/#managers
# MANAGERS = ADMINS

Check failure on line 309 in config/settings/base.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ERA001)

config/settings/base.py:309:1: ERA001 Found commented-out code

# Django Admin URL.
ADMIN_URL = env("DJANGO_ADMIN_URL", default="admin")
Expand Down Expand Up @@ -381,7 +377,7 @@
"TITLE": "Care API",
"DESCRIPTION": "Documentation of API endpoints of Care ",
"VERSION": "1.0.0",
# "SERVE_PERMISSIONS": ["rest_framework.permissions.IsAdminUser"],

Check failure on line 380 in config/settings/base.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ERA001)

config/settings/base.py:380:5: ERA001 Found commented-out code
}

# Simple JWT (JWT Authentication)
Expand Down Expand Up @@ -415,10 +411,10 @@
# https://docs.celeryq.dev/en/latest/userguide/configuration.html#std:setting-result_serializer
CELERY_RESULT_SERIALIZER = "json"
# https://docs.celeryq.dev/en/latest/userguide/configuration.html#task-time-limit
# TODO: set to whatever value is adequate in your circumstances

Check failure on line 414 in config/settings/base.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (TD002)

config/settings/base.py:414:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`

Check failure on line 414 in config/settings/base.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (TD003)

config/settings/base.py:414:3: TD003 Missing issue link on the line following this TODO
CELERY_TASK_TIME_LIMIT = 1800 * 5
# https://docs.celeryq.dev/en/latest/userguide/configuration.html#task-soft-time-limit
# TODO: set to whatever value is adequate in your circumstances

Check failure on line 417 in config/settings/base.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (TD002)

config/settings/base.py:417:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`
CELERY_TASK_SOFT_TIME_LIMIT = 1800

# Maintenance Mode
Expand Down Expand Up @@ -630,11 +626,6 @@
CURRENT_DOMAIN = env("CURRENT_DOMAIN", default="localhost:8000")
BACKEND_DOMAIN = env("BACKEND_DOMAIN", default="localhost:9000")

# open id connect
JWKS = JsonWebKey.import_key_set(
json.loads(base64.b64decode(env("JWKS_BASE64", default=generate_encoded_jwks())))
)

APP_VERSION = env("APP_VERSION", default="unknown")

# ABDM
Expand Down
6 changes: 6 additions & 0 deletions config/settings/deployment.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import base64
import json
import logging

import sentry_sdk
from authlib.jose import JsonWebKey
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger
Expand Down Expand Up @@ -118,3 +121,6 @@
SNS_ACCESS_KEY = env("SNS_ACCESS_KEY")
SNS_SECRET_KEY = env("SNS_SECRET_KEY")
SNS_REGION = "ap-south-1"

# open id connect
JWKS = JsonWebKey.import_key_set(json.loads(base64.b64decode(env("JWKS_BASE64"))))
29 changes: 25 additions & 4 deletions config/settings/local.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
import base64
import json

from authlib.jose import JsonWebKey

from care.utils.jwks.generate_jwk import get_jwks_from_file

from .base import * # noqa
from .base import BASE_DIR, INSTALLED_APPS, MIDDLEWARE, env

# https://github.com/adamchainz/django-cors-headers#cors_allow_all_origins-bool
CORS_ORIGIN_ALLOW_ALL = True

# WhiteNoise
# ------------------------------------------------------------------------------
# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development
INSTALLED_APPS = ["whitenoise.runserver_nostatic"] + INSTALLED_APPS # noqa F405
INSTALLED_APPS = ["whitenoise.runserver_nostatic"] + INSTALLED_APPS

# django-silk
# ------------------------------------------------------------------------------
# https://github.com/jazzband/django-silk#requirements
INSTALLED_APPS += ["silk"] # F405
MIDDLEWARE += ["silk.middleware.SilkyMiddleware"] # noqa F405
INSTALLED_APPS += ["silk"]
MIDDLEWARE += ["silk.middleware.SilkyMiddleware"]
# https://github.com/jazzband/django-silk#profiling
SILKY_PYTHON_PROFILER = True

# django-extensions
# ------------------------------------------------------------------------------
# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration
INSTALLED_APPS += ["django_extensions"] # F405
INSTALLED_APPS += ["django_extensions"]


# Celery
Expand All @@ -33,3 +42,15 @@
RUNSERVER_PLUS_PRINT_SQL_TRUNCATE = 100000

DISABLE_RATELIMIT = True

# open id connect
JWKS = JsonWebKey.import_key_set(
json.loads(
base64.b64decode(
env(
"JWKS_BASE64",
default=get_jwks_from_file(BASE_DIR),
)
)
)
)
26 changes: 21 additions & 5 deletions config/settings/test.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
"""
With these settings, tests run faster.
"""
import base64
import json

from authlib.jose import JsonWebKey

from care.utils.jwks.generate_jwk import get_jwks_from_file

from .base import * # noqa
from .base import env
from .base import BASE_DIR, TEMPLATES, env

# GENERAL
# ------------------------------------------------------------------------------
Expand All @@ -17,7 +20,7 @@

# TEMPLATES
# ------------------------------------------------------------------------------
TEMPLATES[-1]["OPTIONS"]["loaders"] = [ # type: ignore[index] # noqa F405
TEMPLATES[-1]["OPTIONS"]["loaders"] = [ # type: ignore[index]
(
"django.template.loaders.cached.Loader",
[
Expand Down Expand Up @@ -74,3 +77,16 @@
}

CELERY_TASK_ALWAYS_EAGER = True


# open id connect
JWKS = JsonWebKey.import_key_set(
json.loads(
base64.b64decode(
env(
"JWKS_BASE64",
default=get_jwks_from_file(BASE_DIR),
)
)
)
)