Skip to content

Commit 0e343d0

Browse files
committed
- fix CI
1 parent cf84cb6 commit 0e343d0

16 files changed

Lines changed: 124 additions & 83 deletions

app/__init__.py

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,16 @@
1616
from app.utils.utils import remove_str_prefix, sanitize_for_logging
1717

1818
DEBUG_LOG_FORMAT = "%(asctime)s.%(msecs)03d | %(short_logger_name)-10.15s | %(levelname)-8s | %(correlation_id)s | %(filename)s:%(lineno)d | %(message)s"
19-
LOG_FORMAT = "%(asctime)s.%(msecs)03d | %(short_logger_name)-10.15s | %(levelname)-8s | %(correlation_id)s | %(message)s"
19+
LOG_FORMAT = (
20+
"%(asctime)s.%(msecs)03d | %(short_logger_name)-10.15s | %(levelname)-8s | %(correlation_id)s | %(message)s"
21+
)
22+
2023

2124
class PackageOnlyFilter(logging.Filter):
2225
"""
2326
Logging filter that allows only log records originating from this application package.
2427
"""
28+
2529
def filter(self, record):
2630
return record.name.startswith(__name__)
2731

@@ -36,17 +40,15 @@ class LogFormatFilter(logging.Filter):
3640

3741
def filter(self, record):
3842
record.correlation_id = (
39-
getattr(g, "correlation_id", CORRELATION_ID_FALLBACK)
40-
if has_app_context()
41-
else CORRELATION_ID_FALLBACK
43+
getattr(g, "correlation_id", CORRELATION_ID_FALLBACK) if has_app_context() else CORRELATION_ID_FALLBACK
4244
)
43-
record.short_logger_name = record.name.split(".")[0] #extract main module name
45+
record.short_logger_name = record.name.split(".")[0] # extract main module name
4446
return True
4547

4648

4749
def _loader_include(loader, node):
4850
nome_file = os.path.join(os.path.dirname(loader.name), loader.construct_scalar(node))
49-
with open(nome_file, 'r', encoding='utf-8') as f:
51+
with open(nome_file, "r", encoding="utf-8") as f:
5052
return yaml.load(f, Loader=type(loader))
5153

5254

@@ -60,13 +62,12 @@ def _loader_env_var(loader, node):
6062
raw_value = loader.construct_scalar(node)
6163
new_value = os.environ.get(raw_value)
6264
if new_value is None:
63-
msg = "Cannot construct value from {node}: {value}".format(
64-
node=node, value=new_value
65-
)
65+
msg = "Cannot construct value from {node}: {value}".format(node=node, value=new_value)
6666
raise yaml.YAMLError(msg)
6767
return new_value
6868

69-
yaml.SafeLoader.add_constructor('!INCLUDE', _loader_include)
69+
70+
yaml.SafeLoader.add_constructor("!INCLUDE", _loader_include)
7071
yaml.SafeLoader.add_constructor("!ENV", _loader_env_var)
7172

7273

@@ -82,28 +83,33 @@ def setup_logging(app):
8283
fmt = logging.Formatter(LOG_FORMAT, datefmt="%Y-%m-%d %H:%M:%S")
8384

8485
if settings.filename and settings.filepath:
85-
_handler = RotatingFileHandler(os.path.join(settings.filepath, settings.filename), maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8")
86+
_handler = RotatingFileHandler(
87+
os.path.join(settings.filepath, settings.filename),
88+
maxBytes=10 * 1024 * 1024,
89+
backupCount=5,
90+
encoding="utf-8",
91+
)
8692
else:
8793
_handler = logging.StreamHandler(sys.stdout)
8894

8995
_handler.setLevel(_level)
9096
_handler.setFormatter(fmt)
9197
_handler.addFilter(LogFormatFilter())
9298

93-
#configure ROOT logger
99+
# configure ROOT logger
94100
root_logger = logging.getLogger()
95101
root_logger.setLevel(_level)
96102
root_logger.handlers.clear()
97103
root_logger.addHandler(_handler)
98104

99-
app.logger.setLevel(_level) #flask
105+
app.logger.setLevel(_level) # flask
100106

101-
if not settings.libs_enabled: #disable lib logger
107+
if not settings.libs_enabled: # disable lib logger
102108
_handler.addFilter(PackageOnlyFilter())
103109
else:
104-
logging.getLogger("werkzeug") #init a lazy logger otherwise not in loggerDict
110+
logging.getLogger("werkzeug") # init a lazy logger otherwise not in loggerDict
105111
for logger_name in logging.Logger.manager.loggerDict:
106-
if logger_name.startswith(__name__): #skip app module
112+
if logger_name.startswith(__name__): # skip app module
107113
continue
108114
logging.getLogger(logger_name).setLevel(settings.libs_level)
109115

@@ -115,23 +121,21 @@ def load_config(app):
115121
raise ValueError(f"Failed to load configuration: The folder {config_path} does not exist.")
116122

117123
try:
118-
with open(os.path.join(config_path, "app_config.yaml"), 'r', encoding='utf-8') as f:
124+
with open(os.path.join(config_path, "app_config.yaml"), "r", encoding="utf-8") as f:
119125
_config = yaml.safe_load(f)
120126
config = AppConfig.model_validate(_config)
121127
app.config.update(dict(SETTINGS=config))
122128

123129
config_data = {
124-
nome: getattr(config, nome)
125-
for nome, field in config.model_fields.items()
126-
if field.annotation is dict
130+
nome: getattr(config, nome) for nome, field in config.model_fields.items() if field.annotation is dict
127131
}
128132
app.config.update(config_data)
129133
except Exception as e:
130134
raise ValueError("Failed to load configuration") from e
131135

132136

133137
def create_app():
134-
#setup app
138+
# setup app
135139
app = Flask(__name__)
136140
load_config(app)
137141
app.secret_key = app.config[APP_SETTINGS_KEY].app.secret_key

app/constants.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,32 @@
5252

5353
# EU member state ISO-3166-1 alpha-2 codes
5454
EU_COUNTRIES: set[str] = {
55-
"AT", "BE", "BG", "CZ", "CY", "DK", "DE", "EE", "ES", "FR",
56-
"FI", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL",
57-
"PL", "PT", "RO", "SK", "SI", "SE",
55+
"AT",
56+
"BE",
57+
"BG",
58+
"CZ",
59+
"CY",
60+
"DK",
61+
"DE",
62+
"EE",
63+
"ES",
64+
"FR",
65+
"FI",
66+
"GR",
67+
"HU",
68+
"IE",
69+
"IT",
70+
"LV",
71+
"LT",
72+
"LU",
73+
"MT",
74+
"NL",
75+
"PL",
76+
"PT",
77+
"RO",
78+
"SK",
79+
"SI",
80+
"SE",
5881
}
5982

6083
# Valid IdP hint identifiers
@@ -70,4 +93,3 @@
7093
JWT_PREFIX: str = "jwt"
7194
SD_JWT_PREFIX: str = "dc_sd_jwt"
7295
MSO_MDOC_PREFIX: str = "mso_mdoc"
73-

app/models/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
from app.models.config.app_config import AppConfig
22

33
__all__ = ["AppConfig"]
4-

app/models/config/app_config.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
from app.models.config.credentials_config import CredentialsConfig
66
from app.models.config.provider_config import ProviderConfig
77

8-
#TODO: validations to be implemented
8+
# TODO: validations to be implemented
9+
910

1011
class LogSetting(BaseModel):
1112
filepath: Optional[str] = None
@@ -14,6 +15,7 @@ class LogSetting(BaseModel):
1415
libs_enabled: bool
1516
libs_level: Optional[Literal["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]] = "INFO"
1617

18+
1719
class AppSettings(BaseModel):
1820
secret_key: str
1921
logging: LogSetting
@@ -23,6 +25,7 @@ class AppSettings(BaseModel):
2325
favicon_subpath: str
2426
static_folder: str
2527

28+
2629
class AppConfig(BaseModel):
2730
provider_config: ProviderConfig
2831
credentials_config: CredentialsConfig

app/models/config/credentials_config.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
from pydantic import BaseModel, Field
44

55

6-
#TODO: validations to be implemented
6+
# TODO: validations to be implemented
77
class DocumentIdentifier(BaseModel):
88
type: str
99
value: str
1010

11+
1112
class DocumentFormat(BaseModel):
1213
id: str
1314
specs: dict[str, Any] | None = Field(default_factory=dict)
@@ -20,6 +21,7 @@ class Credential(BaseModel):
2021
document_identifier: DocumentIdentifier
2122
document_format: DocumentFormat
2223

24+
2325
class CredentialsConfig(BaseModel):
2426
supported_credentials: dict[str, Credential]
2527
internal_attributes_mappings: dict[str, Any]

app/models/config/provider_config.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,23 @@
55

66

77
class ProviderConfig(BaseModel):
8-
9-
#TODO: refactoring: remove model_config and computed_field -> create plain BaseModel + validations to be implemented
10-
model_config = {"extra": "allow"} #temporary workaround
8+
# TODO: refactoring: remove model_config and computed_field -> create plain BaseModel + validations to be implemented
9+
model_config = {"extra": "allow"} # temporary workaround
1110
_config: Dict[str, Any] = PrivateAttr()
1211

13-
1412
def __init__(self, **kwargs):
1513
if not kwargs:
1614
raise Exception("Invalid provider config")
1715
super().__init__(**kwargs)
1816
self._config = kwargs
1917

20-
2118
@model_validator(mode="before")
2219
@classmethod
2320
def check_config_present(cls, data: Any) -> Any:
2421
if data is None:
2522
raise Exception("Invalid provider config")
2623
return data
2724

28-
2925
@computed_field
3026
@property
3127
def spec_version(self) -> str:

app/routes/main_routes.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
main_routes = Blueprint("main_routes", __name__)
99

10+
1011
@main_routes.app_errorhandler(404)
1112
def page_not_found(e):
1213
return render_template("404.html"), 404

app/routes/wallet_routes.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ def split_string(value, delimiter):
5656
return []
5757
return str(value).split(delimiter)
5858

59+
5960
@wallet_routes.app_template_filter("format_date")
6061
def format_date(value, fmt="%d-%m-%Y %H:%M:%S"):
6162
"""
@@ -66,6 +67,7 @@ def format_date(value, fmt="%d-%m-%Y %H:%M:%S"):
6667
Returns str(value) if unparseable, empty string if None.
6768
"""
6869
from datetime import timezone
70+
6971
if value is None:
7072
return ""
7173
try:
@@ -368,7 +370,9 @@ def credentialTypeTemplate():
368370
status_descr = "VALIDO"
369371

370372
data_row = response.get("data_row", {})
371-
internal_claims = parser_credential_format_to_internal(current_app.config[APP_SETTINGS_KEY].credentials_config, key.rsplit("_", 1)[0], claims)
373+
internal_claims = parser_credential_format_to_internal(
374+
current_app.config[APP_SETTINGS_KEY].credentials_config, key.rsplit("_", 1)[0], claims
375+
)
372376

373377
# @TODO Decprecated
374378
content_list = []
@@ -414,19 +418,15 @@ def presentation_phase():
414418
it_wallet_service = ItWalletService(session, external_discovery=True)
415419
try:
416420
params = parse_url_to_dict(qrcode_data)
417-
credentials = it_wallet_service.loginToVerifier(params.get("client_id"),params.get("request_uri"),params.get("request_uri_method"), params.get("state"))
421+
credentials = it_wallet_service.loginToVerifier(
422+
params.get("client_id"), params.get("request_uri"), params.get("request_uri_method"), params.get("state")
423+
)
418424
except Exception as e:
419425
logger.error(f"Error, message: {e}")
420426
# @Todo insert this into Util
421-
return jsonify({
422-
"success": False,
423-
"error_message": f"Exception :{e}."
424-
}), 400
425-
return jsonify({
426-
"success": True,
427-
"success_message": "Login success.",
428-
"data": credentials
429-
}), 200
427+
return jsonify({"success": False, "error_message": f"Exception :{e}."}), 400
428+
return jsonify({"success": True, "success_message": "Login success.", "data": credentials}), 200
429+
430430

431431
@wallet_routes.route("/authorization", methods=["POST"], strict_slashes=False)
432432
def authorization_phase():
@@ -441,10 +441,8 @@ def authorization_phase():
441441
except Exception as e:
442442
logger.error(f"Error, message: {e}")
443443
# @Todo insert this into Util
444-
return jsonify({
445-
"success": False,
446-
"error_message": f"Exception :{e}."
447-
}), 400
444+
return jsonify({"success": False, "error_message": f"Exception :{e}."}), 400
445+
448446

449447
def _get_template_name_for_credential_key(key: str) -> str | None:
450448
"""

app/service/itwallet_helpers.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,11 @@ def _validate_ec_iss_sub(ec_payload: dict, expected: str) -> None:
189189

190190
def _validate_ec_authority_hints(ec_payload: dict, expected_hint: Any) -> None:
191191
"""Validate EC authority_hints contains expected_hint. Raises ValueError."""
192-
logger.debug(f"Entering method: _validate_ec_authority_hints. Params [ec_payload: {ec_payload}, expected_hint: {expected_hint}]", ec_payload, expected_hint)
192+
logger.debug(
193+
f"Entering method: _validate_ec_authority_hints. Params [ec_payload: {ec_payload}, expected_hint: {expected_hint}]",
194+
ec_payload,
195+
expected_hint,
196+
)
193197
hints = ec_payload.get("authority_hints", [])
194198
if not isinstance(hints, list) or not hints or expected_hint not in hints:
195199
raise ValueError(f"EC 'authority_hints' non valido o mancante hint '{expected_hint}'")
@@ -198,7 +202,10 @@ def _validate_ec_authority_hints(ec_payload: dict, expected_hint: Any) -> None:
198202
def _validate_ec_metadata_and_jwks(ec_payload: dict, expected_metadata_types: list) -> None:
199203
"""Validate EC has required metadata types and jwks. Raises ValueError."""
200204
from app.constants import METADATA_TYPE_FEDERATION_ENTITY
201-
logger.debug(f"Entering method: _validate_ec_metadata_and_jwks. Params [ec_payload: {ec_payload}, expected_metadata_types: {expected_metadata_types}]")
205+
206+
logger.debug(
207+
f"Entering method: _validate_ec_metadata_and_jwks. Params [ec_payload: {ec_payload}, expected_metadata_types: {expected_metadata_types}]"
208+
)
202209
actual = ec_payload.get("metadata", {})
203210
missing = [t for t in expected_metadata_types if t not in actual]
204211
if missing:
@@ -216,7 +223,9 @@ def validate_ec(
216223
ec_payload: dict, expected_issuer_url: str, expected_metadata_types: list, expected_hint: Any = None
217224
) -> None:
218225
"""Validate Entity Configuration: iss/sub, authority_hints, metadata types, jwks. Raises ValueError."""
219-
logger.info(f"Entering method: validate_ec. Params [ec_payload: {ec_payload}, expected_issuer_url: {expected_issuer_url}, expected_metadata_types: {expected_metadata_types}, expected_hint: {expected_hint}]")
226+
logger.info(
227+
f"Entering method: validate_ec. Params [ec_payload: {ec_payload}, expected_issuer_url: {expected_issuer_url}, expected_metadata_types: {expected_metadata_types}, expected_hint: {expected_hint}]"
228+
)
220229
if not ec_payload:
221230
raise ValueError("Entity Configuration non specificato")
222231
_validate_ec_iss_sub(ec_payload, expected_issuer_url)

0 commit comments

Comments
 (0)