Skip to content

Commit f32164e

Browse files
feat: enhance gRPC integration safety and update dependencies
1 parent 1c052ca commit f32164e

5 files changed

Lines changed: 656 additions & 448 deletions

File tree

archipy/helpers/utils/keycloak_utils.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,15 @@
44
from contextvars import ContextVar
55
from typing import Any
66

7-
import grpc
7+
try:
8+
import grpc
9+
from grpc import ServicerContext
10+
from grpc.aio import ServicerContext as AsyncServicerContext
11+
12+
except ImportError:
13+
ServicerContext = None
14+
AsyncServicerContext = None
15+
816
from fastapi import Depends, Request, Security
917
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
1018
from pydantic import BaseModel
@@ -284,7 +292,7 @@ async def dependency(
284292
return dependency
285293

286294
@staticmethod
287-
def _extract_token_from_metadata(context: grpc.aio.ServicerContext) -> str | None:
295+
def _extract_token_from_metadata(context: ServicerContext) -> str | None:
288296
"""Extract Bearer token from gRPC metadata."""
289297
metadata = dict(context.invocation_metadata())
290298

@@ -335,7 +343,7 @@ def grpc_auth(
335343

336344
def decorator(func: Callable) -> Callable:
337345
@functools.wraps(func)
338-
def wrapper(self: object, request: object, context: grpc.ServicerContext) -> object:
346+
def wrapper(self: object, request: object, context: ServicerContext) -> object:
339347
try:
340348
# 1. Extract and validate token
341349
token_str = cls._extract_token_from_metadata(context)
@@ -428,7 +436,8 @@ def wrapper(self: object, request: object, context: grpc.ServicerContext) -> obj
428436
if isinstance(e, BaseError):
429437
e.abort_grpc_sync(context)
430438
raise InternalError(
431-
lang=lang, additional_data={"original_error": str(e), "error_type": type(e).__name__}
439+
lang=lang,
440+
additional_data={"original_error": str(e), "error_type": type(e).__name__},
432441
) from e
433442

434443
finally:
@@ -472,7 +481,7 @@ def async_grpc_auth(
472481

473482
def decorator(func: Callable) -> Callable:
474483
@functools.wraps(func)
475-
async def wrapper(self: object, request: object, context: grpc.aio.ServicerContext) -> object:
484+
async def wrapper(self: object, request: object, context: AsyncServicerContext) -> object:
476485
try:
477486
# 1. Extract and validate token
478487
token_str = cls._extract_token_from_metadata(context)
@@ -565,7 +574,8 @@ async def wrapper(self: object, request: object, context: grpc.aio.ServicerConte
565574
if isinstance(e, BaseError):
566575
await e.abort_grpc_async(context)
567576
await InternalError(
568-
lang=lang, additional_data={"original_error": str(e), "error_type": type(e).__name__}
577+
lang=lang,
578+
additional_data={"original_error": str(e), "error_type": type(e).__name__},
569579
).abort_grpc_async(context)
570580

571581
finally:

archipy/models/errors/base_error.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ class BaseError(Exception):
4141
"""
4242

4343
http_status_code: ClassVar[int] = 500
44-
grpc_status_code: ClassVar[grpc.StatusCode] = grpc.StatusCode.INTERNAL if grpc else 13
44+
grpc_status_code: ClassVar[int] = grpc.StatusCode.INTERNAL if grpc else 13
4545

4646
def __init__(
4747
self,
@@ -178,11 +178,11 @@ def message_fa(self) -> str:
178178
"""
179179
return self.error_detail.message_fa
180180

181-
def _get_grpc_status_code(self) -> grpc.StatusCode | int:
181+
def _get_grpc_status_code(self) -> int:
182182
"""Gets the proper gRPC status code for this error.
183183
184184
Returns:
185-
grpc.StatusCode | int: The gRPC status code enum value or integer code.
185+
int: The gRPC status code enum value or integer code.
186186
"""
187187
if not GRPC_AVAILABLE:
188188
return 13 # INTERNAL

docs/changelog.md

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,39 @@
22

33
All notable changes to ArchiPy are documented in this changelog, organized by version.
44

5+
## [3.4.4] - 2025-07-17
6+
7+
### Improvements
8+
9+
#### gRPC Integration Improvements
10+
11+
- **Import Safety** - Added robust gRPC import handling with try/except blocks to prevent import errors when gRPC is not
12+
available
13+
- **Type Safety** - Enhanced type annotations for gRPC context handling with improved error type definitions
14+
- **Error Handling** - Improved gRPC error handling with better type safety and context management
15+
16+
#### Dependency Updates
17+
18+
- **Kafka** - Updated confluent-kafka to version 2.11.0+ for improved stability and performance
19+
- **Keycloak** - Updated python-keycloak to version 5.7.0+ for enhanced security and features
20+
- **Sentry** - Updated sentry-sdk to version 2.33.0+ for better error tracking capabilities
21+
- **MyPy** - Updated MyPy to version 1.17.0+ for improved type checking and Python 3.13 support
22+
523
## [3.4.3] - 2025-07-17
624

725
### Improvements
826

927
#### Keycloak Security Enhancements
28+
1029
- **Admin Mode Control** - Implemented `IS_ADMIN_MODE_ENABLED` configuration flag to control Keycloak admin operations
11-
- **Enhanced Security** - Added granular control over admin capabilities allowing authentication-only mode without admin privileges
12-
- **Principle of Least Privilege** - Updated both synchronous and asynchronous Keycloak adapters to respect admin mode configuration
30+
- **Enhanced Security** - Added granular control over admin capabilities allowing authentication-only mode without admin
31+
privileges
32+
- **Principle of Least Privilege** - Updated both synchronous and asynchronous Keycloak adapters to respect admin mode
33+
configuration
1334
- **Test Coverage** - Updated BDD test steps to properly handle admin mode configuration for comprehensive testing
1435

1536
### Security
37+
1638
- **Reduced Attack Surface** - Admin operations can now be disabled while maintaining authentication capabilities
1739
- **Environment Isolation** - Different environments can have different admin capabilities based on configuration
1840
- **Audit Trail** - Clear separation between authentication and administrative operations for better security monitoring
@@ -21,7 +43,8 @@ All notable changes to ArchiPy are documented in this changelog, organized by ve
2143

2244
### Bug Fixes
2345

24-
- **Import Error Resolution** - Fixed critical import errors that were preventing proper module initialization and functionality
46+
- **Import Error Resolution** - Fixed critical import errors that were preventing proper module initialization and
47+
functionality
2548

2649
## [3.4.1] - 2025-07-07
2750

@@ -34,27 +57,42 @@ All notable changes to ArchiPy are documented in this changelog, organized by ve
3457
### New Features
3558

3659
#### gRPC Integration Enhancements
37-
- **Async gRPC Server Interceptors** - Added comprehensive async gRPC server interceptors with enhanced tracing capabilities and metric collection for better observability
38-
- **Enhanced Authentication Context** - Implemented advanced authentication context management with gRPC decorators for seamless integration
39-
- **Improved Error Handling** - Enhanced gRPC error handling and context management with better type annotations and error propagation
60+
61+
- **Async gRPC Server Interceptors** - Added comprehensive async gRPC server interceptors with enhanced tracing
62+
capabilities and metric collection for better observability
63+
- **Enhanced Authentication Context** - Implemented advanced authentication context management with gRPC decorators for
64+
seamless integration
65+
- **Improved Error Handling** - Enhanced gRPC error handling and context management with better type annotations and
66+
error propagation
4067

4168
#### Keycloak gRPC Authentication
42-
- **gRPC Authentication Enhancement** - Added token extraction and role validation capabilities for gRPC services with Keycloak integration
43-
- **Composite Role Management** - Implemented composite role management methods in both KeycloakAdapter and AsyncKeycloakAdapter for advanced authorization scenarios
44-
- **Streamlined Role Checks** - Enhanced role checking and error handling in KeycloakAdapter for better performance and reliability
69+
70+
- **gRPC Authentication Enhancement** - Added token extraction and role validation capabilities for gRPC services with
71+
Keycloak integration
72+
- **Composite Role Management** - Implemented composite role management methods in both KeycloakAdapter and
73+
AsyncKeycloakAdapter for advanced authorization scenarios
74+
- **Streamlined Role Checks** - Enhanced role checking and error handling in KeycloakAdapter for better performance and
75+
reliability
4576

4677
### Improvements
4778

4879
#### Error Handling & Type Safety
49-
- **Enhanced Type Annotations** - Updated type annotations in BaseError class for improved gRPC context handling and better type safety
50-
- **Refined Interceptors** - Improved gRPC server interceptors with better error handling and method name context support
80+
81+
- **Enhanced Type Annotations** - Updated type annotations in BaseError class for improved gRPC context handling and
82+
better type safety
83+
- **Refined Interceptors** - Improved gRPC server interceptors with better error handling and method name context
84+
support
5185

5286
#### Code Quality & Performance
53-
- **DateTime Optimization** - Refactored BaseUtils and UpdatableMixin to use naive local datetime for improved performance and consistency
87+
88+
- **DateTime Optimization** - Refactored BaseUtils and UpdatableMixin to use naive local datetime for improved
89+
performance and consistency
5490
- **Library Updates** - Updated dependencies and libraries for better compatibility and security
5591

5692
### Community Contributions
57-
- **Collaborative Development** - Merged contributions from @Mohammadreza-kh94 for Keycloak gRPC authentication enhancements
93+
94+
- **Collaborative Development** - Merged contributions from @Mohammadreza-kh94 for Keycloak gRPC authentication
95+
enhancements
5896
- **Code Refactoring** - Integrated improvements from @heysaeid for datetime handling optimizations
5997

6098
## [v3.3.1] - 2025-06-12

0 commit comments

Comments
 (0)