From 322fa06ff0931a769efbc090127ef4817866b26f Mon Sep 17 00:00:00 2001 From: Adeel Ahmad <adeel.ahmad@geant.org> Date: Tue, 18 Mar 2025 16:27:15 +0000 Subject: [PATCH] Add route based authorisation for services --- inventory_provider/__init__.py | 21 +++++++++++++++++++-- inventory_provider/auth.py | 3 ++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/inventory_provider/__init__.py b/inventory_provider/__init__.py index 590610d..41575ba 100644 --- a/inventory_provider/__init__.py +++ b/inventory_provider/__init__.py @@ -3,7 +3,7 @@ automatically invoked app factory """ import logging import os -from flask import Flask +from flask import g, Flask, request, jsonify from flask_cors import CORS from inventory_provider import environment @@ -54,7 +54,24 @@ def create_app(setup_logging=True): @auth.login_required def secure_before_request(): """Enforces authentication for all routes""" - pass + client = g.get("auth_service") + + if not client: + # This allows clients to access any resource without providing an API key + # TODO: Only for testing, should be removed in Production + return + # return jsonify({"error": "Unauthorized"}), 403 + + CLIENT_PERMISSIONS = { + "serviceA": ["msr"], + "serviceB": ["testing"], + } + + allowed_routes = CLIENT_PERMISSIONS.get(client, []) + route = request.path.strip("/").split("/")[0] + + if route not in allowed_routes: + return jsonify({"error": "Forbidden"}), 403 # IMS based routes diff --git a/inventory_provider/auth.py b/inventory_provider/auth.py index 1f99503..466073e 100644 --- a/inventory_provider/auth.py +++ b/inventory_provider/auth.py @@ -1,4 +1,4 @@ -from flask import Blueprint, current_app +from flask import Blueprint, current_app, g from flask_httpauth import HTTPTokenAuth auth = HTTPTokenAuth(scheme="ApiKey") @@ -12,6 +12,7 @@ def verify_api_key(api_key): for service, details in config['api-keys'].items(): if details.get('api-key') == api_key: + g.auth_service = service return service return None -- GitLab