From 973786bfd65292e892ed98643c5d6c243bc8dc2b Mon Sep 17 00:00:00 2001 From: hoang Date: Thu, 12 Nov 2026 10:57:36 +0700 Subject: [PATCH 1/2] Refactor Legacy APIs to REST APIs Promgen's legacy APIs previously inherited from the Django View class, functioning as traditional APIs. We have now refactored them to inherit from the APIView class in the rest.py file, allowing us to leverage the features of the Django REST Framework. --- promgen/rest.py | 69 +++++++++++++++++++++++++++++++++++++++++++++++- promgen/urls.py | 8 +++--- promgen/views.py | 56 --------------------------------------- 3 files changed, 72 insertions(+), 61 deletions(-) diff --git a/promgen/rest.py b/promgen/rest.py index f5b7e39fa..bd0a47c78 100644 --- a/promgen/rest.py +++ b/promgen/rest.py @@ -1,7 +1,9 @@ # Copyright (c) 2019 LINE Corporation # These sources are released under the terms of the MIT license: see LICENSE +import json from itertools import chain +from django.contrib.contenttypes.models import ContentType from django.http import HttpResponse from requests.exceptions import HTTPError from rest_framework import viewsets @@ -9,7 +11,17 @@ from rest_framework.response import Response from rest_framework.views import APIView -from promgen import filters, models, permissions, prometheus, renderers, serializers, tasks, util +from promgen import ( + filters, + models, + permissions, + prometheus, + renderers, + serializers, + signals, + tasks, + util, +) from promgen.permissions import PromgenModelPermissions @@ -219,3 +231,58 @@ def retrieve(self, request, id): hosts_data = serializers.HostSerializer(hosts, many=True).data farm_detail = {**farm_data, "hosts": hosts_data} return Response(farm_detail) + + +class ApiConfig(APIView): + def get(self, request): + return HttpResponse(prometheus.render_config(), content_type="application/json") + + def post(self, request, *args, **kwargs): + try: + body = json.loads(request.body.decode("utf-8")) + + prometheus.import_config(body, self.request.user, **kwargs) + except Exception as e: + return HttpResponse(e, status=400) + + return HttpResponse("Success", status=202) + + +class ApiQueue(APIView): + def post(self, request): + signals.trigger_write_config.send(request) + signals.trigger_write_rules.send(request) + signals.trigger_write_urls.send(request) + return HttpResponse("OK", status=202) + + +class _ExportRules(APIView): + def format(self, rules=None, name="promgen"): + content = prometheus.render_rules(rules) + response = HttpResponse(content) + response["Content-Type"] = "application/x-yaml" + response["Content-Disposition"] = "attachment; filename=%s.rule.yml" % name + return response + + +class RulesConfig(_ExportRules): + def get(self, request): + return self.format() + + +class RuleExport(_ExportRules): + def get(self, request, content_type, object_id): + ct = ContentType.objects.get( + app_label="promgen", model=content_type + ).get_object_for_this_type(pk=object_id) + rules = models.Rule.objects.filter(obj=ct) + return self.format(rules) + + +class URLConfig(APIView): + def get(self, request): + return HttpResponse(prometheus.render_urls(), content_type="application/json") + + def post(self, request): + tasks.write_urls() + return HttpResponse("OK", status=202) diff --git a/promgen/urls.py b/promgen/urls.py index 3fa87d428..89d8afa84 100644 --- a/promgen/urls.py +++ b/promgen/urls.py @@ -132,11 +132,11 @@ path("", include("django.contrib.auth.urls")), path("", include("social_django.urls", namespace="social")), # Legacy API - path("api/v1/config", csrf_exempt(views.ApiConfig.as_view())), + path("api/v1/config", csrf_exempt(rest.ApiConfig.as_view())), path("api/", include((router.urls, "api"), namespace="old-api")), - path("api/v1/rules", csrf_exempt(views.RulesConfig.as_view())), - path("api/v1/targets", csrf_exempt(views.ApiConfig.as_view()), name="config-targets"), - path("api/v1/urls", csrf_exempt(views.URLConfig.as_view()), name="config-urls"), + path("api/v1/rules", csrf_exempt(rest.RulesConfig.as_view())), + path("api/v1/targets", csrf_exempt(rest.ApiConfig.as_view()), name="config-targets"), + path("api/v1/urls", csrf_exempt(rest.URLConfig.as_view()), name="config-urls"), path("api/v1/alerts", csrf_exempt(rest.AlertReceiver.as_view()), name="alert"), path("api/v1/host/", views.HostDetail.as_view()), # Prometheus Proxy diff --git a/promgen/views.py b/promgen/views.py index 3d5f5f5bc..7cadb2efa 100644 --- a/promgen/views.py +++ b/promgen/views.py @@ -42,7 +42,6 @@ plugins, prometheus, signals, - tasks, util, ) from promgen.forms import GroupMemberForm, UserPermissionForm @@ -1367,61 +1366,6 @@ def get_check_permission_object(self): return get_object_or_404(models.Farm, id=self.kwargs["pk"]) -class ApiConfig(View): - def get(self, request): - return HttpResponse(prometheus.render_config(), content_type="application/json") - - def post(self, request, *args, **kwargs): - try: - body = json.loads(request.body.decode("utf-8")) - - prometheus.import_config(body, self.request.user, **kwargs) - except Exception as e: - return HttpResponse(e, status=400) - - return HttpResponse("Success", status=202) - - -class ApiQueue(View): - def post(self, request): - signals.trigger_write_config.send(request) - signals.trigger_write_rules.send(request) - signals.trigger_write_urls.send(request) - return HttpResponse("OK", status=202) - - -class _ExportRules(View): - def format(self, rules=None, name="promgen"): - content = prometheus.render_rules(rules) - response = HttpResponse(content) - response["Content-Type"] = "application/x-yaml" - response["Content-Disposition"] = "attachment; filename=%s.rule.yml" % name - return response - - -class RulesConfig(_ExportRules): - def get(self, request): - return self.format() - - -class RuleExport(_ExportRules): - def get(self, request, content_type, object_id): - ct = ContentType.objects.get( - app_label="promgen", model=content_type - ).get_object_for_this_type(pk=object_id) - rules = models.Rule.objects.filter(obj=ct) - return self.format(rules) - - -class URLConfig(View): - def get(self, request): - return HttpResponse(prometheus.render_urls(), content_type="application/json") - - def post(self, request): - tasks.write_urls() - return HttpResponse("OK", status=202) - - class AlertList(LoginRequiredMixin, ListView): paginate_by = 20 queryset = models.Alert.objects.order_by("-created") From 93734f988620ae4808bbcdf9f9fbdcb767b05001 Mon Sep 17 00:00:00 2001 From: hoang Date: Fri, 13 Nov 2026 12:46:04 +0700 Subject: [PATCH 2/2] Require authorization for Legacy APIs Legacy APIs are used for managing Prometheus configurations, such as retrieving all targets, URLs, or reloading configurations. These actions are critical and should not be accessible to regular users. Therefore, we have implemented new permissions and now require appropriate authorization for each API to enhance their security. --- docs/conf/prometheus.rst | 14 +++-- docs/user/api.rst | 3 ++ promgen/migrations/0055_alter_site_options.py | 22 ++++++++ promgen/models.py | 5 ++ promgen/rest.py | 27 ++++++++++ promgen/tests/test_rest.py | 52 ++++++++++++++++++- 6 files changed, 118 insertions(+), 5 deletions(-) create mode 100644 promgen/migrations/0055_alter_site_options.py diff --git a/docs/conf/prometheus.rst b/docs/conf/prometheus.rst index 07718a4ad..a05081461 100644 --- a/docs/conf/prometheus.rst +++ b/docs/conf/prometheus.rst @@ -43,15 +43,21 @@ In this case, Promgne's pull mode can be used by trigging a small script running or any other job framework. This only requires the server where Prometheus is running, to be able to access Promgen over HTTP. +.. important:: + + Create a Promgen user as a service account with the appropriate permissions, then + generate an API token to access the API endpoints. + .. code-block:: bash #!/bin/sh set -e # Download all the targets from Promgen to a temporary file - curl http://promgen/api/v1/targets --output /etc/prometheus/targets.tmp - # Optionally you could download from a specific service or project - # curl http://promgen/service/123/targets -o /etc/prometheus/targets.tmp - # curl http://promgen/project/456/targets -o /etc/prometheus/targets.tmp + # Permission required: "promgen.read_config" + curl -H "Authorization: Token $PROMGEN_TOKEN" http://promgen/api/v1/targets --output /etc/prometheus/targets.tmp + # Optionally you could download from a specific service or project if you have at least VIEWER permissions on that service or project. + # curl -H "Authorization: Token $PROMGEN_TOKEN" http://promgen/service/123/targets -o /etc/prometheus/targets.tmp + # curl -H "Authorization: Token $PROMGEN_TOKEN" http://promgen/project/456/targets -o /etc/prometheus/targets.tmp # Move our file to make it more atomic mv /etc/prometheus/targets.tmp /etc/prometheus/targets.json # Tell Prometheus to reload diff --git a/docs/user/api.rst b/docs/user/api.rst index 16dba2f44..d5f90592e 100644 --- a/docs/user/api.rst +++ b/docs/user/api.rst @@ -18,6 +18,9 @@ Prometheus nodes. See the `Prometheus API