name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
open-banking-gateway_Xs2aLogResolver_m0_rdh
// executions+context public void m0(String message, DelegateExecution execution) { log.info(message, mapper.mapFromExecutionToXs2aExecutionLog(execution)); }
3.26
open-banking-gateway_Xs2aLogResolver_log_rdh
// responses public void log(String message, Response<T> response) { ResponseLog<T> responseLog = new ResponseLog<>(); responseLog.setStatusCode(response.getStatusCode()); responseLog.setHeaders(response.getHeaders()); responseLog.setBody(response.getBody()); if (log.isDebugEnabled()) {log.debug(message, responseLog); } else { log.info(message, responseLog.getNotSensitiveData()); } }
3.26
open-banking-gateway_Xs2aConsentInfo_isDecoupledScaFinalizedByPSU_rdh
/** * Is decoupled SCA was finalised by PSU with mobile or other type of device */ public boolean isDecoupledScaFinalizedByPSU(Xs2aContext ctx) { return ctx.isDecoupledScaFinished(); }
3.26
open-banking-gateway_Xs2aConsentInfo_isPasswordPresent_rdh
/** * Is the PSU password present in the context. */ public boolean isPasswordPresent(Xs2aContext ctx) { return (null != ctx.getPsuPassword()) && (!isOauthEmbeddedPreStepDone(ctx)); }
3.26
open-banking-gateway_Xs2aConsentInfo_isWrongPassword_rdh
/** * Was the PSU password that was sent to ASPSP wrong. */ public boolean isWrongPassword(Xs2aContext ctx) { return (null != ctx.getWrongAuthCredentials()) && ctx.getWrongAuthCredentials(); }
3.26
open-banking-gateway_Xs2aConsentInfo_hasWrongCredentials_rdh
/** * Generic wrong credentials indicator. */ public boolean hasWrongCredentials(Xs2aContext ctx) { return (null != ctx.getWrongAuthCredentials()) && ctx.getWrongAuthCredentials(); }
3.26
open-banking-gateway_Xs2aConsentInfo_isMultipleScaAvailable_rdh
/** * Is the current consent authorization using multiple SCA methods (SMS,email,etc.) */ public boolean isMultipleScaAvailable(Xs2aContext ctx) { return (null != ctx.getAvailableSca()) && (!ctx.getAvailableSca().isEmpty()); }
3.26
open-banking-gateway_Xs2aConsentInfo_isZeroScaAvailable_rdh
/** * Is the current consent authorization using zero SCA flow */ public boolean isZeroScaAvailable(Xs2aContext ctx) { return ((null == ctx.getAvailableSca()) || ((null != ctx.getAvailableSca()) && ctx.getAvailableSca().isEmpty())) && (null == ctx.getScaSelected()); }
3.26
open-banking-gateway_Xs2aConsentInfo_isEmbedded_rdh
/** * Is the current consent authorization in EMBEDDED mode. */ public boolean isEmbedded(Xs2aContext ctx) { return EMBEDDED.name().equalsIgnoreCase(ctx.getAspspScaApproach()); }
3.26
open-banking-gateway_Xs2aConsentInfo_isDecoupledScaFailed_rdh
/** * Is decoupled SCA was failed (i.e. took too long) */ public boolean isDecoupledScaFailed(Xs2aContext ctx) { return false;// FIXME - check if authorization is taking too much time }
3.26
open-banking-gateway_Xs2aConsentInfo_isOauth2TokenAvailableAndReadyToUse_rdh
/** * Is the Oauth2 token available and ready to use (not expired) */ public boolean isOauth2TokenAvailableAndReadyToUse(Xs2aContext ctx) { // FIXME - Token validity check return null != ctx.getOauth2Token(); }
3.26
open-banking-gateway_Xs2aConsentInfo_isStartConsentAuthorizationWithPin_rdh
/** * If ASPSP needs startConsentAuthorization with User Password. */ public boolean isStartConsentAuthorizationWithPin(Xs2aContext ctx) { return ctx.aspspProfile().isXs2aStartConsentAuthorizationWithPin(); }
3.26
open-banking-gateway_Xs2aConsentInfo_isOkRedirectConsent_rdh
/** * Was the redirection from ASPSP in REDIRECT mode using OK (consent granted) or NOK url (consent denied). */ public boolean isOkRedirectConsent(Xs2aContext ctx) { return ctx.isRedirectConsentOk(); }
3.26
open-banking-gateway_Xs2aConsentInfo_isDecoupled_rdh
/** * Is the current consent authorization in DECOUPLED mode. */public boolean isDecoupled(Xs2aContext ctx) { return DECOUPLED.name().equalsIgnoreCase(ctx.getAspspScaApproach());}
3.26
open-banking-gateway_Xs2aConsentInfo_isEmbeddedPreAuthNeeded_rdh
/** * Is the Oauth2 pre-step or authorization required */ public boolean isEmbeddedPreAuthNeeded(Xs2aContext ctx) {return ctx.isEmbeddedPreAuthNeeded(); }
3.26
open-banking-gateway_Xs2aConsentInfo_isOauth2AuthenticationPreStep_rdh
/** * Is the current consent in OAUTH-Pre-step (authentication) mode. */ public boolean isOauth2AuthenticationPreStep(Xs2aContext ctx) { return ctx.isOauth2PreStepNeeded() || ctx.isEmbeddedPreAuthNeeded(); }
3.26
open-banking-gateway_Xs2aConsentInfo_isWrongScaChallenge_rdh
/** * Was the SCA challenge result that was sent to ASPSP wrong. */ public boolean isWrongScaChallenge(Xs2aContext ctx) { return (null != ctx.getWrongAuthCredentials()) && ctx.getWrongAuthCredentials(); }
3.26
open-banking-gateway_FintechRegistrar_registerFintech_rdh
/** * Register Fintech in the OBG database. * * @param fintechId * Fintech ID to register * @param finTechPassword * Fintechs' KeyStore password * @return Newly created FinTech */ @Transactional public Fintech registerFintech(String fintechId, Supplier<char[]> finTechPassword) { Fintech fintech = fintechRepository.save(Fintech.builder().globalId(fintechId).build()); fintechSecureStorage.registerFintech(fintech, finTechPassword); for (int i = 0; i < fintechOnlyKeyPairConfig.getPairCount(); ++i) { UUID id = UUID.randomUUID(); KeyPair pair = fintechOnlyEncryptionServiceProvider.generateKeyPair(); fintechSecureStorage.fintechOnlyPrvKeyToPrivate(id, new PubAndPrivKey(pair.getPublic(), pair.getPrivate()), fintech, finTechPassword); FintechPubKey pubKey = FintechPubKey.builder().prvKey(entityManager.find(FintechPrvKey.class, id)).build(); pubKey.setKey(pair.getPublic()); pubKeyRepository.save(pubKey); } return fintech; }
3.26
open-banking-gateway_Xs2aFlowNameSelector_getNameForValidation_rdh
/** * Sub-process name for current context (PSU/FinTech input) validation. */ public String getNameForValidation(Xs2aContext ctx) { return actionName(ctx); }
3.26
open-banking-gateway_ServiceAccountsOper_m0_rdh
// Unfortunately @PostConstruct can't have Transactional annotation @PostConstruct public void m0() { txOper.execute(callback -> { users.deactivateAllServiceAccounts(); if (null == serviceAccounts.getAccounts()) { return null; } for (ServiceAccountsConfig.ServiceAccount account : serviceAccounts.getAccounts()) { UserEntity user = users.findById(account.getLogin()).map(it -> authorizeService.updatePasswordButDontSave(it, account.getPassword())).orElseGet(() -> authorizeService.createUserEntityWithPasswordEnabledButDontSave(account.getLogin(), account.getPassword())); user.setActive(true); user.setServiceAccount(true); users.save(user); } return null; }); }
3.26
open-banking-gateway_QuirkUtil_pushBicToXs2aAdapterHeaders_rdh
// TODO: Needed because of https://github.com/adorsys/xs2a/issues/73 and because we can't set "X-OAUTH-PREFERRED" header directly public static RequestHeaders pushBicToXs2aAdapterHeaders(Xs2aContext context, RequestHeaders toEnhance) { // TODO: Warning, for Adorsys Sandbox for Oauth2-Integrated the adapter should be configured to send proper header // due to https://github.com/adorsys/xs2a/issues/73 String bankCode = context.getRequestScoped().aspspProfile().getBankCode(); if (!Strings.isNullOrEmpty(bankCode)) { Map<String, String> headers = toEnhance.toMap(); headers.put(X_GTW_BANK_CODE, bankCode); return RequestHeaders.fromMap(headers); } return toEnhance; }
3.26
open-banking-gateway_PsuEncryptionServiceProvider_forPublicAndPrivateKey_rdh
/** * Public and Private key (read/write) encryption. * * @param keyId * Key ID * @param key * Public-Private key pair * @return Encryption service for both reading and writing */ public EncryptionService forPublicAndPrivateKey(UUID keyId, PubAndPrivKey key) { return oper.encryptionService(keyId.toString(), key.getPrivateKey(), key.getPublicKey()); }
3.26
open-banking-gateway_PsuEncryptionServiceProvider_generateKeyPair_rdh
/** * Generate random key pair. * * @return Random key pair. */ public KeyPair generateKeyPair() { return oper.generatePublicPrivateKey(); }
3.26
open-banking-gateway_PsuEncryptionServiceProvider_forPrivateKey_rdh
/** * Private key (read only) encryption. * * @param keyId * Key ID * @param key * Private key * @return Encryption service for reading only */ public EncryptionService forPrivateKey(UUID keyId, PrivateKey key) { return oper.encryptionService(keyId.toString(), key); }
3.26
open-banking-gateway_PsuEncryptionServiceProvider_forPublicKey_rdh
/** * Public key (write only) encryption. * * @param keyId * Key ID * @param key * Public key * @return Encryption service for writing only */ public EncryptionService forPublicKey(UUID keyId, PublicKey key) { return oper.encryptionService(keyId.toString(), key); }
3.26
open-banking-gateway_ExportableAccountService_exportableAccounts_rdh
// This is mostly example code how to use an application @Transactional @SuppressWarnings("CPD-START") public ResponseEntity<List<ExportableAccount>> exportableAccounts(String fireFlyToken, UUID bankProfileId) { ResponseEntity<AccountList> accounts = aisApi.getAccounts(bankingConfig.getUserId(), apiConfig.getRedirectOkUri(UUID.randomUUID().toString()), apiConfig.getRedirectNokUri(), UUID.randomUUID(), null, null, null, null, bankingConfig.getDataProtectionPassword(), bankProfileId, null, consentRepository.findFirstByBankProfileUuidOrderByModifiedAtDesc(bankProfileId).map(BankConsent::getConsentId).orElse(null), "", null, null, true, null, null, null, null, null, true, null); if (accounts.getStatusCode() == HttpStatus.ACCEPTED) { String redirectTo = consentService.createConsentForAccountsAndTransactions(bankProfileId);return ResponseEntity.accepted().header(LOCATION, redirectTo).build();} if (accounts.getStatusCode() != HttpStatus.OK) {return ResponseEntity.status(accounts.getStatusCode()).build(); } tokenProvider.setToken(fireFlyToken); ResponseEntity<AccountArray> fireflyAccounts = accountsApi.listAccount(null, null, null); if (fireflyAccounts.getStatusCode() != HttpStatus.OK) { return ResponseEntity.status(fireflyAccounts.getStatusCode()).build(); }Set<String> fireflyIbans = fireflyAccounts.getBody().getData().stream().map(it -> it.getAttributes().getIban()).filter(Objects::nonNull).collect(Collectors.toSet()); List<ExportableAccount> result = accounts.getBody().getAccounts().stream().filter(it -> fireflyIbans.contains(it.getIban())).map(it -> new ExportableAccount(it.getIban(), it.getResourceId())).collect(Collectors.toList()); return ResponseEntity.ok(result); }
3.26
open-banking-gateway_RequestScopedProvider_registerForFintechSession_rdh
/** * Registers scoped services for the FinTech request. * * @param fintech * FinTech to provide services for. * @param profile * ASPSP profile (i.e. FinTS or Xs2a) * @param session * Owning session for current scoped services * @param bankProtocolId * Bank protocol id to scope the services more precisely * @param encryptionServiceProvider * Consent encryption services for the FinTech * @param futureAuthorizationSessionKey * Authorization session key that is going to be used (if the session is not opened yet) * or current session key if it is already opened * @param fintechPassword * Fintech Datasafe/KeyStore access password * @return Request scoped services for FinTech */ public RequestScoped registerForFintechSession(Fintech fintech, BankProfile profile, ServiceSession session, Long bankProtocolId, ConsentAuthorizationEncryptionServiceProvider encryptionServiceProvider, SecretKeyWithIv futureAuthorizationSessionKey, Supplier<char[]> fintechPassword) { ConsentAccess consentAccess = consentAccessProvider.consentForFintech(fintech, profile.getBank(), session, fintechPassword); PaymentAccess paymentAccess = paymentAccessProvider.paymentForFintech(fintech, session, fintechPassword); EncryptionService authorizationSessionEncService = sessionEncryption(encryptionServiceProvider, futureAuthorizationSessionKey);return doRegister(profile, fintechConfig.getConsumers().get(fintech.getGlobalId()), consentAccess, paymentAccess, authorizationSessionEncService, futureAuthorizationSessionKey, bankProtocolId); }
3.26
open-banking-gateway_ServiceContextProviderForFintech_fintechFacingSecretKeyBasedEncryption_rdh
/** * To be consumed by {@link de.adorsys.opba.protocol.facade.services.AuthSessionHandler} if new auth session started. */ private <REQUEST extends FacadeServiceableGetter> RequestScoped fintechFacingSecretKeyBasedEncryption(REQUEST request, ServiceSession session, Long bankProtocolId) { BankProfile profile = session.getBankProfile(); // FinTech requests should be signed, so creating Fintech entity if it does not exist. Fintech fintech = authenticator.authenticateOrCreateFintech(request.getFacadeServiceable(), session); return provider.registerForFintechSession(fintech, profile, session, bankProtocolId, consentAuthorizationEncryptionServiceProvider, consentAuthorizationEncryptionServiceProvider.generateKey(), () -> request.getFacadeServiceable().getSessionPassword().toCharArray()); }
3.26
open-banking-gateway_ServiceContextProviderForFintech_validateRedirectCode_rdh
/** * Validates redirect code (Xsrf protection) for current request * * @param request * Request to validate for * @param session * Service session that has expected redirect code value * @param <REQUEST> * Request class */ protected <REQUEST extends FacadeServiceableGetter> void validateRedirectCode(REQUEST request, AuthSession session) { if (Strings.isNullOrEmpty(request.getFacadeServiceable().getRedirectCode())) { throw new IllegalArgumentException("Missing redirect code"); } if (!Objects.equals(session.getRedirectCode(), request.getFacadeServiceable().getRedirectCode())) {throw new IllegalArgumentException("Wrong redirect code"); } }
3.26
open-banking-gateway_FintechUserAuthSessionTuple_toDatasafePathWithoutParent_rdh
/** * Computes current tuples' Datasafe storage path. * * @return Datasafe path corresponding to current tuple */ public String toDatasafePathWithoutParent() { return this.authSessionId.toString(); }
3.26
open-banking-gateway_FintechUserAuthSessionTuple_buildFintechConsentSpec_rdh
/** * Creates FinTech template requirements to the consent if any. * * @param path * Datasafe path * @param em * Entity manager to persist to * @return FinTech consent specification */ public static FintechConsentSpec buildFintechConsentSpec(String path, EntityManager em) { FintechUserAuthSessionTuple tuple = new FintechUserAuthSessionTuple(path); return FintechConsentSpec.builder().id(tuple.getAuthSessionId()).user(em.find(FintechUser.class, tuple.getFintechUserId())).build(); }
3.26
open-banking-gateway_PairIdPsuAspspTuple_buildPrvKey_rdh
/** * Creates PSU - ASPSP private key pair entity. * * @param path * Datasafe path * @param em * Entity manager to persist to * @return KeyPair template */ public static PsuAspspPrvKey buildPrvKey(String path, EntityManager em) { PairIdPsuAspspTuple tuple = new PairIdPsuAspspTuple(path); if (null == tuple.getPairId()) { throw new IllegalArgumentException("Pair id missing"); } return PsuAspspPrvKey.builder().id(tuple.getPairId()).psu(em.find(Psu.class, tuple.getPsuId())).aspsp(em.find(Bank.class, tuple.getAspspId())).build(); }
3.26
open-banking-gateway_PairIdPsuAspspTuple_toDatasafePathWithoutPsu_rdh
/** * Computes current tuples' Datasafe storage path. * * @return Datasafe path corresponding to current tuple */ public String toDatasafePathWithoutPsu() { return (pairId.toString() + "/") + this.f0; }
3.26
open-banking-gateway_UpdateAuthMapper_updateContext_rdh
/** * Due to JsonCustomSerializer, Xs2aContext will always have the type it had started with, for example * {@link de.adorsys.opba.protocol.xs2a.context.ais.AccountListXs2aContext} will be * always properly deserialized. */ public Xs2aContext updateContext(Xs2aContext context, AuthorizationRequest request) { if (context instanceof AccountListXs2aContext) { return f0.map(request, ((AccountListXs2aContext) (context))); } if (context instanceof TransactionListXs2aContext) { return aisTransactionsMapper.map(request, ((TransactionListXs2aContext) (context))); } if (context instanceof SinglePaymentXs2aContext) { return pisRequestSinglePaymentInitiation.map(request, ((SinglePaymentXs2aContext) (context))); }throw new IllegalArgumentException("Can't update authorization for: " + context.getClass().getCanonicalName()); }
3.26
open-banking-gateway_Xs2aValidator_validate_rdh
/** * Validates that all parameters necessary to perform ASPSP API call is present. * In {@link de.adorsys.opba.protocol.bpmnshared.dto.context.ContextMode#MOCK_REAL_CALLS} * reports all violations into {@link BaseContext#getViolations()} (merging with already existing ones) * * @param exec * Current execution that will be updated with violations if present. * @param dtosToValidate * ASPSP API call parameter objects to validate. */ public <T> void validate(DelegateExecution exec, Xs2aContext context, Class<T> invokerClass, Object... dtosToValidate) { Set<ConstraintViolation<Object>> allErrors = new HashSet<>(); FieldsToIgnoreLoader fieldsToIgnoreLoader = context.getRequestScoped().fieldsToIgnoreLoader(); Map<FieldCode, IgnoreValidationRule> rulesMap = fieldsToIgnoreLoader.getIgnoreValidationRules(invokerClass, context.getActiveScaApproach()); for (Object value : dtosToValidate) { Set<ConstraintViolation<Object>> errors = validator.validate(value).stream().filter(f -> isFieldMandatory(f, context, rulesMap)).collect(Collectors.toSet()); allErrors.addAll(errors); } if (allErrors.isEmpty()) { return; } ContextUtil.getAndUpdateContext(exec, (BaseContext ctx) -> {ctx.getViolations().addAll(allErrors.stream().map(this::toIssue).collect(Collectors.toSet())); // Only when doing real calls validations cause termination of flow // TODO: Those validation in real call should be propagated and handled if (REAL_CALLS == ctx.getMode()) { log.error("Fatal validation error for requestId={},sagaId={} - violations {}", ctx.getRequestId(), ctx.getSagaId(), allErrors); throw new ValidationIssueException(); } }); }
3.26
open-banking-gateway_HbciRedirectExecutor_redirect_rdh
/** * Redirects PSU to some page (or emits FinTech redirection required) by performing interpolation of the * string returned by {@code uiScreenUriSpel} * * @param execution * Execution context of the current process * @param context * Current HBCI context * @param uiScreenUriSpel * UI screen SpEL expression to interpolate * @param destinationUri * URL where UI screen should redirect user to if he clicks OK (i.e. to ASPSP redirection * where user must click OK button in order to be redirected to ASPSP) * @param eventFactory * Allows to construct custom event with redirection parameters. */ public void redirect(DelegateExecution execution, HbciContext context, String uiScreenUriSpel, String destinationUri, Function<Redirect.RedirectBuilder, ? extends Redirect> eventFactory) { setDestinationUriInContext(execution, destinationUri); URI screenUri = ContextUtil.buildAndExpandQueryParameters(uiScreenUriSpel, context); Redirect.RedirectBuilder redirect = Redirect.builder(); redirect.processId(execution.getRootProcessInstanceId()); redirect.executionId(execution.getId()); redirect.redirectUri(screenUri); setUiUriInContext(execution, screenUri); applicationEventPublisher.publishEvent(eventFactory.apply(redirect)); }
3.26
open-banking-gateway_FintechSecureStorage_m0_rdh
/** * Validates FinTechs' Datasafe/KeyStore password * * @param fintech * Target FinTech to check password for * @param password * Password to validate */ public void m0(Fintech fintech, Supplier<char[]> password) { if (fintech.getFintechOnlyPrvKeys().isEmpty()) { throw new IllegalStateException("FinTech has no private keys"); } var keys = fintech.getFintechOnlyPrvKeys().stream().map(it -> this.fintechOnlyPrvKeyFromPrivate(it, fintech, password)).collect(Collectors.toList()); if (keys.isEmpty()) { throw new IllegalStateException("Failed to extract FintTech keys"); } }
3.26
open-banking-gateway_FintechSecureStorage_registerFintech_rdh
/** * Registers FinTech in Datasafe and DB. * * @param fintech * new FinTech to register * @param password * FinTechs' KeyStore password. */ public void registerFintech(Fintech fintech, Supplier<char[]> password) { this.userProfile().createDocumentKeystore(fintech.getUserIdAuth(password), config.defaultPrivateTemplate(fintech.getUserIdAuth(password)).buildPrivateProfile()); }
3.26
open-banking-gateway_FintechSecureStorage_fintechOnlyPrvKeyToPrivate_rdh
/** * Register Fintech private key in FinTechs' private Datasafe storage * * @param id * Key ID * @param key * Key to store * @param fintech * Owner of the key * @param password * Keystore/Datasafe protection password */ @SneakyThrows public void fintechOnlyPrvKeyToPrivate(UUID id, PubAndPrivKey key, Fintech fintech, Supplier<char[]> password) { try (OutputStream os = datasafeServices.privateService().write(WriteRequest.forPrivate(fintech.getUserIdAuth(password), FINTECH_ONLY_KEYS_ID, new FintechOnlyPrvKeyTuple(fintech.getId(), id).toDatasafePathWithoutParent()))) { serde.writeKey(key.getPublicKey(), key.getPrivateKey(), os); } }
3.26
open-banking-gateway_FintechSecureStorage_psuAspspKeyToPrivate_rdh
/** * Sends PSU/Fintechs' to FinTechs' private storage. * * @param authSession * Authorization session for this PSU/Fintech user * @param fintech * FinTech to store to * @param psuKey * Key to store * @param password * FinTechs Datasafe/Keystore password */ @SneakyThrows public void psuAspspKeyToPrivate(AuthSession authSession, Fintech fintech, PubAndPrivKey psuKey, Supplier<char[]> password) { try (OutputStream os = datasafeServices.privateService().write(WriteRequest.forDefaultPrivate(fintech.getUserIdAuth(password), new FintechPsuAspspTuple(authSession).toDatasafePathWithoutParent()))) { serde.writeKey(psuKey.getPublicKey(), psuKey.getPrivateKey(), os); } }
3.26
open-banking-gateway_FintechSecureStorage_psuAspspKeyFromPrivate_rdh
/** * Reads PSU/Fintechs' user private key from FinTechs' private storage. * * @param session * Service session with which consent is associated. * @param fintech * Owner of the private storage. * @param password * FinTechs' Datasafe/KeyStore password. * @return PSU/Fintechs' user consent protection key. */ @SneakyThrows public PubAndPrivKey psuAspspKeyFromPrivate(ServiceSession session, Fintech fintech, Supplier<char[]> password) { try (InputStream is = datasafeServices.privateService().read(ReadRequest.forDefaultPrivate(fintech.getUserIdAuth(password), new FintechPsuAspspTuple(session).toDatasafePathWithoutParent()))) { return serde.readKey(is); } }
3.26
open-banking-gateway_FintechSecureStorage_psuAspspKeyToInbox_rdh
/** * Sends PSU/Fintech user private key to FinTechs' inbox at the consent confirmation. * * @param authSession * Authorization session for this PSU/Fintech user * @param psuKey * Private Key to send to FinTechs' inbox */ @SneakyThrows public void psuAspspKeyToInbox(AuthSession authSession, PubAndPrivKey psuKey) { try (OutputStream os = datasafeServices.inboxService().write(WriteRequest.forDefaultPublic(ImmutableSet.of(authSession.getFintechUser().getFintech().getUserId()), new FintechPsuAspspTuple(authSession).toDatasafePathWithoutParent()))) {serde.writeKey(psuKey.getPublicKey(), psuKey.getPrivateKey(), os); } }
3.26
open-banking-gateway_FintechSecureStorage_fintechOnlyPrvKeyFromPrivate_rdh
/** * Reads Fintechs' private key from its private Datasafe storage * * @param prvKey * Private key definition to tead * @param fintech * Private key owner * @param password * Keystore/Datasafe protection password * @return FinTechs' private key */ @SneakyThrows public PubAndPrivKey fintechOnlyPrvKeyFromPrivate(FintechPrvKey prvKey, Fintech fintech, Supplier<char[]> password) { try (InputStream is = datasafeServices.privateService().read(ReadRequest.forPrivate(fintech.getUserIdAuth(password), FINTECH_ONLY_KEYS_ID, new FintechOnlyPrvKeyTuple(fintech.getId(), prvKey.getId()).toDatasafePathWithoutParent()))) { return serde.readKey(is); }}
3.26
open-banking-gateway_PathHeadersBodyMapperTemplate_forExecution_rdh
/** * Converts context object into object that can be used for ASPSP API call. * * @param context * Context to convert * @return Object that can be used with {@code Xs2aAdapter} to perform ASPSP API calls */ public ValidatedPathHeadersBody<P, H, B> forExecution(C context) { return new ValidatedPathHeadersBody<>(f0.map(context), toHeaders.map(context), toBody.map(toValidatableBody.map(context))); }
3.26
open-banking-gateway_EncryptionConfigurationConfig_encryptionConfig_rdh
/** * Datasafe configuration, persisted in DB * * @param config * Encryption configuration default values * @return Current Datasafe encryption config */ @Bean @SneakyThrows @Transactional public EncryptionConfig encryptionConfig(MutableEncryptionConfig config) { long dbConfigCount = datasafeConfigRepository.count(); if (dbConfigCount == 1) { return mapper.readValue(datasafeConfigRepository.findAll().stream().findFirst().orElseThrow(() -> new IllegalStateException(INCORRECT_ENCRYPTION_CONFIG_RECORDS_AMOUNT_EXCEPTION)).getConfig(), MutableEncryptionConfig.class).toEncryptionConfig(); } else if (dbConfigCount == 0) { storeEncryptionConfigInDb(config); return config.toEncryptionConfig(); } throw new IllegalStateException(INCORRECT_ENCRYPTION_CONFIG_RECORDS_AMOUNT_EXCEPTION); }
3.26
open-banking-gateway_TppTokenConfig_loadPrivateKey_rdh
/** * See {@code de.adorsys.opba.tppauthapi.TokenSignVerifyTest#generateNewTppKeyPair()} for details of how to * generate the encoded key. */ @SneakyThrows private PrivateKey loadPrivateKey(TppTokenProperties tppTokenProperties) { byte[] v0 = Base64.getDecoder().decode(tppTokenProperties.getPrivateKey()); PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(v0); KeyFactory kf = KeyFactory.getInstance(tppTokenProperties.getSignAlgo()); return kf.generatePrivate(ks);}
3.26
open-banking-gateway_TppTokenConfig_loadPublicKey_rdh
/** * See {@code de.adorsys.opba.tppauthapi.TokenSignVerifyTest#generateNewTppKeyPair()} for details of how to * generate the encoded key. */ @SneakyThrows private RSAPublicKey loadPublicKey(TppTokenProperties tppTokenProperties) { byte[] publicKeyBytes = Base64.getDecoder().decode(tppTokenProperties.getPublicKey()); X509EncodedKeySpec ks = new X509EncodedKeySpec(publicKeyBytes); KeyFactory kf = KeyFactory.getInstance(tppTokenProperties.getSignAlgo()); return ((RSAPublicKey) (kf.generatePublic(ks))); }
3.26
open-banking-gateway_ProcessResultEventHandler_handleEvent_rdh
/** * Spring event-bus listener to listen for BPMN process result. * * @param result * BPMN process message to notify with the subscribers. */ @TransactionalEventListener public void handleEvent(InternalProcessResult result) { Consumer<InternalProcessResult> consumer; synchronized(lock) { InternalProcessResult handledResult = result; if (handledResult instanceof ProcessError) { handledResult = replaceErrorProcessIdWithParentProcessIdIfNeeded(((ProcessError) (handledResult))); } consumer = subscribers.remove(handledResult.getProcessId()); if (null == consumer) { deadLetterQueue.put(handledResult.getProcessId(), result); return; } } consumer.accept(result); }
3.26
open-banking-gateway_IgnoreFieldsLoaderFactory_createIgnoreFieldsLoader_rdh
/** * Creates ignore rules for a given protocol * * @param protocolId * Protocol to load ignore rules for * @return Field code to Ignore Rule loader */public FieldsToIgnoreLoader createIgnoreFieldsLoader(Long protocolId) { if (null == protocolId) { return new NoopFieldsToIgnoreLoader(); } return new FieldsToIgnoreLoaderImpl(protocolId, ignoreValidationRuleRepository); }
3.26
open-banking-gateway_HbciAccountListing_tryToParseIban_rdh
// IbanFormatException is skippable exception if account IBAN can't be calculated @SuppressWarnings("PMD.EmptyCatchBlock")private void tryToParseIban(BankAccount account) { if (Strings.isNullOrEmpty(account.getCountry())) { return; } // See https://www.iban.com/country/germany // IBAN is DEKK BBBB BBBB CCCC CCCC CC // Where: // K = MOD 97 (ISO 7064) Checksum // B = Bank Code aka BLZ ( Bankleitzahl in German ) // C = Account number ( Kontonummer in German ) try { Iban iban = new Iban.Builder().countryCode(CountryCode.getByCode(account.getCountry())).bankCode(Strings.padStart(account.getBlz(), BLZ_LEN, '0')).accountNumber(Strings.padStart(account.getAccountNumber(), ACCOUNT_NUMBER_LEN, '0')).build(); account.setIban(iban.toString()); } catch (IbanFormatException ex) { // NOP, it can be internal account without IBAN } }
3.26
open-banking-gateway_EncryptionWithInitVectorOper_encryptionService_rdh
/** * Symmetric Key based encryption. * * @param keyId * Key ID * @param keyWithIv * Key value * @return Encryption service that encrypts data with symmetric key provided */ public EncryptionService encryptionService(String keyId, SecretKeyWithIv keyWithIv) { return new SymmetricEncryption(keyId, () -> encryption(keyWithIv), () -> decryption(keyWithIv)); }
3.26
open-banking-gateway_EncryptionWithInitVectorOper_decryption_rdh
/** * Decryption cipher * * @param keyWithIv * Symmetric key and initialization vector * @return Symmetric decryption cipher */ @SneakyThrows public Cipher decryption(SecretKeyWithIv keyWithIv) {Cipher cipher = Cipher.getInstance(encSpec.getCipherAlgo()); cipher.init(Cipher.DECRYPT_MODE, keyWithIv.getSecretKey(), new IvParameterSpec(keyWithIv.getIv())); return cipher; }
3.26
open-banking-gateway_EncryptionWithInitVectorOper_encryption_rdh
/** * Encryption cipher * * @param keyWithIv * Symmetric key and initialization vector * @return Symmetric encryption cipher */ @SneakyThrows public Cipher encryption(SecretKeyWithIv keyWithIv) { Cipher cipher = Cipher.getInstance(encSpec.getCipherAlgo()); cipher.init(Cipher.ENCRYPT_MODE, keyWithIv.getSecretKey(), new IvParameterSpec(keyWithIv.getIv())); return cipher; }
3.26
open-banking-gateway_EncryptionWithInitVectorOper_generateKey_rdh
/** * Generate random symmetric key with initialization vector (IV) * * @return Secret key with IV */@SneakyThrows public SecretKeyWithIv generateKey() { byte[] iv = new byte[encSpec.getIvSize()]; SecureRandom random = new SecureRandom(); random.nextBytes(iv); KeyGenerator keyGen = KeyGenerator.getInstance(encSpec.getKeyAlgo()); keyGen.init(encSpec.getLen()); return new SecretKeyWithIv(iv, keyGen.generateKey()); }
3.26
open-banking-gateway_HbciSandboxPayment_getHbciStatus_rdh
// It is magic number mapped to enum (see InstantPaymentStatusJob class of multibanking) @SuppressWarnings("checkstyle:MagicNumber") public int getHbciStatus() { switch (getStatus()) { case CANC : return 1; case RJCT : return 2; case ACTC : return 3; case ACSC : return 4; case ACCC : return 7; default : throw new IllegalStateException("Unmappable payment status: " + getStatus()); } }
3.26
open-banking-gateway_AuthorizationPossibleErrorHandler_m0_rdh
/** * Swallows retryable (like wrong password) authorization exceptions. * * @param tryAuthorize * Authorization function to call * @param onFail * Fallback function to call if retryable exception occurred. */ public void m0(Runnable tryAuthorize, Consumer<ErrorResponseException> onFail) { try { tryAuthorize.run(); } catch (ErrorResponseException ex) { rethrowIfNotAuthorizationErrorCode(ex); onFail.accept(ex); } }
3.26
open-banking-gateway_TransactionService_listTransactions_rdh
// FIXME - It is just too many lines of text @SuppressWarnings("checkstyle:MethodLength") @SneakyThrows public ResponseEntity listTransactions(SessionEntity sessionEntity, String fintechOkUrl, String fintechNOkUrl, String bankProfileID, String accountId, String createConsentIfNone, LocalDate dateFrom, LocalDate dateTo, String entryReferenceFrom, String bookingStatus, Boolean deltaList, LoTRetrievalInformation loTRetrievalInformation, Boolean psuAuthenticationRequired, Boolean online) { log.info("LoT {}", loTRetrievalInformation); String fintechRedirectCode = UUID.randomUUID().toString(); Optional<ConsentEntity> optionalConsent = Optional.empty(); if (loTRetrievalInformation.equals(LoTRetrievalInformation.FROM_TPP_WITH_AVAILABLE_CONSENT)) { optionalConsent = consentRepository.findFirstByUserEntityAndBankIdAndConsentTypeAndConsentConfirmedOrderByCreationTimeDesc(sessionEntity.getUserEntity(), bankProfileID, ConsentType.AIS, Boolean.TRUE); } if (optionalConsent.isPresent()) { log.info("LoT found valid {} consent for user {} bank {} from {}", optionalConsent.get().getConsentType(), optionalConsent.get().getUserEntity().getLoginUserName(), optionalConsent.get().getBankId(), optionalConsent.get().getCreationTime()); } else { log.info("LoT no valid ais consent for user {} bank {} available", sessionEntity.getUserEntity().getLoginUserName(), bankProfileID); } ResponseEntity<TransactionsResponse> transactions = tppAisClient.getTransactions(accountId, sessionEntity.getUserEntity().getLoginUserName(), RedirectUrlsEntity.buildOkUrl(uiConfig, fintechRedirectCode), RedirectUrlsEntity.buildNokUrl(uiConfig, fintechRedirectCode), UUID.fromString(restRequestContext.getRequestId()), COMPUTE_X_TIMESTAMP_UTC, COMPUTE_X_REQUEST_SIGNATURE, COMPUTE_FINTECH_ID, null, tppProperties.getFintechDataProtectionPassword(), UUID.fromString(bankProfileID), psuAuthenticationRequired, optionalConsent.map(ConsentEntity::getTppServiceSessionId).orElse(null), createConsentIfNone, null, null, HEADER_COMPUTE_PSU_IP_ADDRESS, null, dateFrom, dateTo, entryReferenceFrom, bookingStatus, deltaList, online, "DISABLED", null, null); switch (transactions.getStatusCode()) { case OK : return new ResponseEntity<>(ManualMapper.fromTppToFintech(transactions.getBody()), HttpStatus.OK); case ACCEPTED : log.info("create redirect entity for lot for redirectcode {}", fintechRedirectCode); redirectHandlerService.registerRedirectStateForSession(fintechRedirectCode, fintechOkUrl, fintechNOkUrl); return handleAcceptedService.handleAccepted(consentRepository, ConsentType.AIS, bankProfileID, fintechRedirectCode, sessionEntity, transactions.getHeaders()); case UNAUTHORIZED : return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); default : throw new RuntimeException("DID NOT EXPECT RETURNCODE:" + transactions.getStatusCode()); } }
3.26
open-banking-gateway_DatasafeMetadataStorage_getIdValue_rdh
/** * Converts String id value into Entity id * * @param id * Entity id */ protected Long getIdValue(String id) { return Long.valueOf(id); }
3.26
open-banking-gateway_DatasafeMetadataStorage_read_rdh
/** * Reads user profile data * * @param id * Entity id * @return User profile data */ @Override @Transactional public Optional<byte[]> read(String id) { return repository.findById(Long.valueOf(id)).map(getData); }
3.26
open-banking-gateway_DatasafeMetadataStorage_delete_rdh
/** * Deletes user profile data * * @param id * Entity id */ @Override @Transactional public void delete(String id) { throw new IllegalStateException("Not allowed"); }
3.26
open-banking-gateway_DatasafeMetadataStorage_update_rdh
/** * Updates user profile data * * @param id * Entity id * @param data * New entry value */ @Override @Transactional public void update(String id, byte[] data) { T toSave = repository.findById(getIdValue(id)).get(); setData.accept(toSave, data); repository.save(toSave); }
3.26
open-banking-gateway_PaymentAccess_getFirstByCurrentSession_rdh
/** * Available consent for current session execution with throwing exception */ default ProtocolFacingPayment getFirstByCurrentSession() { List<ProtocolFacingPayment> payments = findByCurrentServiceSessionOrderByModifiedDesc(); if (payments.isEmpty()) { throw new IllegalStateException("Context not found");}return payments.get(0); }
3.26
open-banking-gateway_Xs2aOauth2Parameters_toParameters_rdh
// TODO - MapStruct? public Parameters toParameters() { Oauth2Service.Parameters parameters = new Oauth2Service.Parameters(); parameters.setRedirectUri(oauth2RedirectBackLink); parameters.setState(state); parameters.setConsentId(consentId); parameters.setPaymentId(paymentId); parameters.setScaOAuthLink(scaOauthLink); parameters.setScope(scope); return parameters; }
3.26
open-banking-gateway_Xs2aRedirectExecutor_redirect_rdh
/** * Redirects PSU to some page (or emits FinTech redirection required) by performing interpolation of the * string returned by {@code uiScreenUriSpel} * * @param execution * Execution context of the current process * @param context * Current XS2A context * @param uiScreenUriSpel * UI screen SpEL expression to interpolate * @param destinationUri * URL where UI screen should redirect user to if he clicks OK (i.e. to ASPSP redirection * where user must click OK button in order to be redirected to ASPSP) * @param eventFactory * Allows to construct custom event with redirection parameters. */ public void redirect(DelegateExecution execution, Xs2aContext context, String uiScreenUriSpel, String destinationUri, Function<Redirect.RedirectBuilder, ? extends Redirect> eventFactory) { m0(execution, destinationUri); URI screenUri = ContextUtil.buildAndExpandQueryParameters(uiScreenUriSpel, context); Redirect.RedirectBuilder redirect = Redirect.builder();redirect.processId(execution.getRootProcessInstanceId()); redirect.executionId(execution.getId()); redirect.redirectUri(screenUri); setUiUriInContext(execution, screenUri); applicationEventPublisher.publishEvent(eventFactory.apply(redirect));}
3.26
open-banking-gateway_FintechPsuAspspTuple_buildFintechInboxPrvKey_rdh
/** * Creates PSU-ASPSP template key pair for FinTechs' INBOX * * @param path * Datasafe path * @param em * Entity manager to persist to * @return FinTech scoped private key for a given PSU to be used in its inbox. */ public static FintechPsuAspspPrvKeyInbox buildFintechInboxPrvKey(String path, EntityManager em) { FintechPsuAspspTuple tuple = new FintechPsuAspspTuple(path); return FintechPsuAspspPrvKeyInbox.builder().fintech(em.find(Fintech.class, tuple.getFintechId())).psu(em.find(Psu.class, tuple.getPsuId())).aspsp(em.find(Bank.class, tuple.getAspspId())).build(); }
3.26
open-banking-gateway_FintechPsuAspspTuple_m0_rdh
/** * Converts current tuple to Datasafe storage path. * * @return Datasafe path corresponding to current tuple */ public String m0() { return (this.f0 + "/") + this.aspspId; }
3.26
open-banking-gateway_Xs2aTransactionParameters_toParameters_rdh
// TODO - MapStruct? @Override public RequestParams toParameters() { var requestParamsMap = RequestParams.builder().withBalance(super.getWithBalance()).bookingStatus(bookingStatus).dateFrom(dateFrom).dateTo(dateTo).build().toMap(); Optional.ofNullable(page).ifPresent(p -> requestParamsMap.put(PAGE_INDEX_QUERY_PARAMETER_NAME, p.toString())); Optional.ofNullable(pageSize).ifPresent(ps -> requestParamsMap.put(PAGE_SIZE_QUERY_PARAMETER_NAME, ps.toString())); return RequestParams.fromMap(requestParamsMap); }
3.26
open-banking-gateway_FlowableConfig_mapper_rdh
/** * Dedicated ObjectMapper to be used in XS2A protocol. */ @Bean FlowableObjectMapper mapper(List<? extends JacksonMixin> mixins) { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mixins.forEach(it -> mapper.addMixIn(it.getType(), it.getMixin())); // Ignoring getters and setters as we are using 'rich' domain model: mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE).withSetterVisibility(JsonAutoDetect.Visibility.NONE).withCreatorVisibility(JsonAutoDetect.Visibility.ANY)); return new FlowableObjectMapper(mapper); }
3.26
open-banking-gateway_FlowableConfig_productionCustomizeListenerAndJsonSerializer_rdh
/** * Customizes flowable so that it can store custom classes (not ones that implement Serializable) as * JSON as variables in database. */ @Bean EngineConfigurationConfigurer<SpringProcessEngineConfiguration> productionCustomizeListenerAndJsonSerializer(RequestScopedServicesProvider scopedServicesProvider, FlowableProperties flowableProperties, FlowableObjectMapper mapper, FlowableJobEventListener eventListener) { int maxLength = flowableProperties.getSerialization().getMaxLength();List<String> serializeOnlyPackages = flowableProperties.getSerialization().getSerializeOnlyPackages(); return processConfiguration -> { processConfiguration.setCustomPreVariableTypes(new ArrayList<>(ImmutableList.of(new JsonCustomSerializer(scopedServicesProvider, mapper.getMapper(), serializeOnlyPackages, maxLength), new LargeJsonCustomSerializer(scopedServicesProvider, mapper.getMapper(), serializeOnlyPackages, maxLength)))); processConfiguration.setEnableEventDispatcher(true); processConfiguration.setEventListeners(ImmutableList.of(eventListener)); processConfiguration.setAsyncExecutorNumberOfRetries(flowableProperties.getNumberOfRetries()); }; }
3.26
open-banking-gateway_ContextUtil_getContext_rdh
/** * Utility class to work with Flowable BPMN engine process context. */ // Lombok generates private ctor. @UtilityClass @SuppressWarnings("checkstyle:HideUtilityClassConstructor") public class ContextUtil { /** * Read context from current execution. */ public <T> T getContext(DelegateExecution execution, Class<T> ctxType) { return execution.getVariable(GlobalConst.CONTEXT, ctxType); }
3.26
open-banking-gateway_ContextUtil_buildAndExpandQueryParameters_rdh
/** * Allows to perform string interpolation like '/ais/{sessionId}' using the process context. */ public URI buildAndExpandQueryParameters(String urlTemplate, UrlContext context) { Map<String, String> expansionContext = new HashMap<>();expansionContext.put("authSessionId", context.getAuthSessionId()); expansionContext.put("selectedScaType", context.getSelectedScaType()); expansionContext.put("redirectCode", context.getRedirectCode()); expansionContext.put("aspspRedirectCode", context.getAspspRedirectCode()); expansionContext.put("isWrongCreds", null == context.getIsWrongCreds() ? null : context.getIsWrongCreds().toString()); return UriComponentsBuilder.fromHttpUrl(urlTemplate).buildAndExpand(expansionContext).toUri(); }
3.26
open-banking-gateway_Xs2aRestorePreValidationContext_lastRedirectionTarget_rdh
// FIXME SerializerUtil does not support nestedness private LastRedirectionTarget lastRedirectionTarget(BaseContext current) {if (null == current.getLastRedirection()) { return null; } LastRedirectionTarget target = current.getLastRedirection(); target.setRequestScoped(current.getRequestScoped()); return target; }
3.26
open-banking-gateway_HbciConsentInfo_noAccountsConsentPresent_rdh
/** * Any kind of consent exists? */ public boolean noAccountsConsentPresent(AccountListHbciContext ctx) { if (ctx.isConsentIncompatible()) {return true; } Optional<HbciResultCache> cached = cachedResultAccessor.resultFromCache(ctx); return cached.map(hbciResultCache -> null == hbciResultCache.getAccounts()).orElse(true); }
3.26
open-banking-gateway_HbciConsentInfo_noTransactionConsentPresent_rdh
/** * Any kind of consent exists? */ public boolean noTransactionConsentPresent(TransactionListHbciContext ctx) { if (ctx.isConsentIncompatible()) { return true; } Optional<HbciResultCache> cached = cachedResultAccessor.resultFromCache(ctx); return cached.map(hbciResultCache -> (null == hbciResultCache.getTransactionsById()) || (null == hbciResultCache.getTransactionsById().get(ctx.getAccountIban()))).orElse(true); }
3.26
open-banking-gateway_HbciConsentInfo_isWrongPassword_rdh
/** * Was the PSU password that was sent to ASPSP wrong. */ public boolean isWrongPassword(HbciContext ctx) { return (null != ctx.getWrongAuthCredentials()) && ctx.getWrongAuthCredentials(); }
3.26
open-banking-gateway_HbciConsentInfo_isWrongScaChallenge_rdh
/** * Was the SCA challenge result that was sent to ASPSP wrong. */ public boolean isWrongScaChallenge(HbciContext ctx) { return (null != ctx.getWrongAuthCredentials()) && ctx.getWrongAuthCredentials(); }
3.26
open-banking-gateway_HbciConsentInfo_isPasswordPresentInConsent_rdh
/** * Check that password present in consent (needed for getting payment status without new interactive authorization). */ public boolean isPasswordPresentInConsent(HbciContext ctx) { HbciConsent hbciDialogConsent = ctx.getHbciDialogConsent(); if (hbciDialogConsent == null) { return false; } Credentials credentials = hbciDialogConsent.getCredentials(); if (credentials == null) { return false; } return null != credentials.getPin(); }
3.26
open-banking-gateway_HbciFlowNameSelector_m0_rdh
/** * Sub-process name for current context (PSU/FinTech input) execution (real calls to ASPSP API). */ public String m0(HbciContext ctx) { return actionName(ctx); }
3.26
open-banking-gateway_HbciFlowNameSelector_getNameForValidation_rdh
/** * Sub-process name for current context (PSU/FinTech input) validation. */ public String getNameForValidation(HbciContext ctx) { return actionName(ctx); }
3.26
open-banking-gateway_PsuLoginService_anonymousPsuAssociateAuthSession_rdh
/** * Used for the cases when there is no need to identify PSU - i.e. single time payment, so that requesting FinTech can * manage associated entities. */ public CompletableFuture<Outcome> anonymousPsuAssociateAuthSession(UUID authorizationId, String authorizationPassword) { var exchange = oper.execute(callback -> { AuthSession session = authRepository.findById(authorizationId).orElseThrow(() -> new IllegalStateException("Missing authorization session: " + authorizationId)); if (!session.isPsuAnonymous()) { throw new IllegalStateException("Session does not support anonymous PSU: " + authorizationId); } FintechConsentSpecSecureStorage.FinTechUserInboxData inbox = associationService.readInboxFromFinTech(session, authorizationPassword); session.setStatus(SessionStatus.STARTED); authRepository.save(session); return new SessionAndInbox(session.getRedirectCode(), inbox); }); return executeOnLoginAndMap(exchange.getInbox(), authorizationId, exchange.getRedirectCode()); }
3.26
open-banking-gateway_PsuLoginService_loginInPsuScopeAndAssociateAuthSession_rdh
/** * Used for the cases when PSU should be identified i.e. for consent sharing, so that PSU can manage associated entities. */ public CompletableFuture<Outcome> loginInPsuScopeAndAssociateAuthSession(String psuLogin, String psuPassword, UUID authorizationId, String authorizationPassword) { var exchange = oper.execute(callback -> { AuthSession session = authRepository.findById(authorizationId).orElseThrow(() -> new IllegalStateException("Missing authorization session: " + authorizationId)); session.setPsu(psus.findByLogin(psuLogin).orElseThrow(() -> new IllegalStateException("No PSU found: " + psuLogin))); associationService.sharePsuAspspSecretKeyWithFintech(psuPassword, session); FintechConsentSpecSecureStorage.FinTechUserInboxData inbox = associationService.readInboxFromFinTech(session, authorizationPassword); session.setStatus(SessionStatus.STARTED); authRepository.save(session); return new SessionAndInbox(session.getRedirectCode(), inbox); }); return executeOnLoginAndMap(exchange.getInbox(), authorizationId, exchange.getRedirectCode()); }
3.26
open-banking-gateway_JsonTemplateInterpolation_injectKonto6IfNeeded_rdh
// kapott creates does not handle which element to create properly if 2 entries have same name like KInfo5 and KInfo6 // It simply creates 1st one (KInfo5) that does not have IBAN @SneakyThrows private void injectKonto6IfNeeded(Message message, String key, Map<String, String> values, Set<String> kontos6Injected) { Pattern konto6Pattern = Pattern.compile("UPD\\.KInfo.*\\.iban"); Pattern targetPattern = Pattern.compile("(UPD\\.KInfo.*?\\.)"); Pattern v8 = Pattern.compile("UPD\\.KInfo.*"); if (!v8.matcher(key).find()) { return; } Matcher matcher = targetPattern.matcher(key); matcher.find(); String root = matcher.group(1); boolean hasKonto6 = values.entrySet().stream().filter(it -> it.getKey().startsWith(root)).anyMatch(it -> konto6Pattern.matcher(it.getKey()).matches());if ((!hasKonto6) || kontos6Injected.contains(root)) { return; } log.info("Injecting Konto6 for {}", key); kontos6Injected.add(root); SyntaxElement updElem = message.getElement(message.getPath() + ".UPD"); XPath xPath = XPathFactory.newInstance().newXPath();Node konto6 = ((Node) (xPath.compile("/hbci/SFs/SFdef[@id='UPD']/SEG[@type='KInfo6']").evaluate(ParsingUtil.SYNTAX, XPathConstants.NODE))); int konto6Idx = ((Double) (xPath.compile("count(/hbci/SFs/SFdef[@id='UPD']/SEG[@type='KInfo6']/preceding-sibling::*)+1").evaluate(ParsingUtil.SYNTAX, XPathConstants.NUMBER))).intValue(); Method createNewChildContainer = SyntaxElement.class.getDeclaredMethod("createNewChildContainer", Node.class, Document.class); createNewChildContainer.setAccessible(true); MultipleSyntaxElements newKonto6Elem = ((MultipleSyntaxElements) (createNewChildContainer.invoke(updElem, konto6, ParsingUtil.SYNTAX))); // Ensure correct element position Method setIdx = MultipleSyntaxElements.class.getDeclaredMethod("setSyntaxIdx", int.class); setIdx.setAccessible(true); setIdx.invoke(newKonto6Elem, konto6Idx); updElem.getChildContainers().add(newKonto6Elem); }
3.26
open-banking-gateway_SandboxXs2aTransactionListingService_doRealExecution_rdh
// Hardcoded as it is POC, these should be read from context @Override @SuppressWarnings("checkstyle:MagicNumber") protected void doRealExecution(DelegateExecution execution, TransactionListXs2aContext context) { // XS2A sandbox quirk... we need to list accounts before listing transactions accountListingService.execute(execution); super.doRealExecution(execution, context); }
3.26
open-banking-gateway_PsuFintechAssociationService_sharePsuAspspSecretKeyWithFintech_rdh
/** * Share PSUs' ASPSP encryption key with the FinTech - sends the key to INBOX. * * @param psuPassword * PSU password * @param session * Session where consent granting was executed */ @Transactional public void sharePsuAspspSecretKeyWithFintech(String psuPassword, AuthSession session) { var psuAspspKey = psuVault.getOrCreateKeyFromPrivateForAspsp(psuPassword::toCharArray, session, this::storePublicKey); fintechVault.psuAspspKeyToInbox(session, psuAspspKey); }
3.26
open-banking-gateway_PsuFintechAssociationService_readInboxFromFinTech_rdh
/** * Allows to read consent specification that was required by the FinTech * * @param session * Authorization session for the consent grant * @param fintechUserPassword * PSU/Fintech users' password * @return Consent specification */ @Transactional public FinTechUserInboxData readInboxFromFinTech(AuthSession session, String fintechUserPassword) { return vault.fromInboxForAuth(session, fintechUserPassword::toCharArray); }
3.26
open-banking-gateway_ExpirableDataConfig_protocolCacheBuilder_rdh
/** * * @param flowableProperties * contains 'expire-after-write' property - Duration for which the record will be alive * and it will be removed when this time frame passes. * @return Builder to build expirable maps. */ @Bean(PROTOCOL_CACHE_BUILDER) CacheBuilder protocolCacheBuilder(FlowableProperties flowableProperties) { Duration expireAfterWrite = flowableProperties.getExpirable().getExpireAfterWrite(); if (expireAfterWrite.getSeconds() < MIN_EXPIRE_SECONDS) { throw new IllegalArgumentException("It is not recommended to have short transient data expiration time, " + "it must be at least equal to request timeout"); } return newBuilder().expireAfterWrite(expireAfterWrite).maximumSize(Integer.MAX_VALUE); }
3.26
open-banking-gateway_ExpirableDataConfig_m0_rdh
/** * Expirable subscribers to the process results. They will be alive for some time and then if no message * comes in - will be removed. */ @Bean Map<String, Consumer<InternalProcessResult>> m0(@Qualifier(PROTOCOL_CACHE_BUILDER) CacheBuilder builder) { return builder.build().asMap(); }
3.26
open-banking-gateway_ProtocolSelector_selectProtocolFor_rdh
/** * Selects protocol service into internal context * * @param ctx * Facade context * @param protocolAction * Protocol action to execute * @param actionBeans * Available beans for this action. * @param <REQUEST> * Request being executed * @param <ACTION> * Action associated * @return Internal context with protocol service to handle the request. */ @Transactional public <REQUEST, ACTION> Optional<InternalContext<REQUEST, ACTION>> selectProtocolFor(InternalContext<REQUEST, ACTION> ctx, ProtocolAction protocolAction, Map<String, ? extends ACTION> actionBeans) { Optional<BankAction> bankAction; if (null == ctx.getAuthSession()) { bankAction = bankActionRepository.findByBankProfileUuidAndAction(ctx.getServiceCtx().getBankProfileId(), protocolAction); } else { Long id = (isForAuthorization(protocolAction)) ? ctx.getServiceCtx().getAuthorizationBankProtocolId() : ctx.getServiceCtx().getServiceBankProtocolId(); bankAction = bankActionRepository.findById(id); } return bankAction.map(action -> { ACTION actionBean = findActionBean(action, actionBeans, protocolAction); return ctx.toBuilder().serviceCtx(ctx.getServiceCtx().toBuilder().serviceBankProtocolId(action.getId()).build()).action(actionBean).build(); }); }
3.26
open-banking-gateway_ProtocolSelector_requireProtocolFor_rdh
/** * Selects protocol service into internal context, throws if none available. * * @param ctx * Facade context * @param protocolAction * Protocol action to execute * @param actionBeans * Available beans for this action. * @param <REQUEST> * Request being executed * @param <ACTION> * Action associated * @return Internal context with protocol service to handle the request. */ @Transactional public <REQUEST, ACTION> InternalContext<REQUEST, ACTION> requireProtocolFor(InternalContext<REQUEST, ACTION> ctx, ProtocolAction protocolAction, Map<String, ? extends ACTION> actionBeans) { return selectProtocolFor(ctx, protocolAction, actionBeans).orElseThrow(() -> new IllegalStateException((("No action bean for " + protocolAction.name()) + " of: ") + ctx.getServiceCtx().loggableBankId())); }
3.26
open-banking-gateway_AuthorizeService_loginWithPassword_rdh
/** * * @param loginRequest * @return empty, if user not found or password not valid. otherwise optional of userprofile */ @Transactional public Optional<UserEntity> loginWithPassword(LoginRequest loginRequest) { generateUserIfUserDoesNotExistYet(loginRequest); // find user by id Optional<UserEntity> optionalUserEntity = findUser(loginRequest.getUsername()); if (((!optionalUserEntity.isPresent()) || (!optionalUserEntity.get().isActive())) || (!optionalUserEntity.get().isEnablePasswordLogin())) { // user not found return Optional.empty(); } if (!encoder.matches(loginRequest.getPassword(), optionalUserEntity.get().getPassword())) { // wrong password return Optional.empty(); } log.debug("User {} is going to be logged in", loginRequest.getUsername()); return optionalUserEntity; }
3.26
open-banking-gateway_ConsentAuthorizationEncryptionServiceProvider_m0_rdh
/** * Generates random symmetric key. * * @return Symmetric key */ public SecretKeyWithIv m0() { return oper.generateKey(); }
3.26
open-banking-gateway_ConsentAuthorizationEncryptionServiceProvider_forSecretKey_rdh
/** * Create encryption service for a given secret key. * * @param key * Secret key to encrypt/decrypt data with. * @return Symmetric encryption service. */ public EncryptionService forSecretKey(SecretKeyWithIv key) { String keyId = Hashing.sha256().hashBytes(key.getSecretKey().getEncoded()).toString(); return oper.encryptionService(keyId, key); }
3.26
open-banking-gateway_FintechConsentAccessImpl_createAnonymousConsentNotPersist_rdh
/** * Creates consent template, but does not persist it */ public ProtocolFacingConsent createAnonymousConsentNotPersist() { return anonymousPsuConsentAccess.createDoNotPersist(); }
3.26
open-banking-gateway_FintechConsentAccessImpl_findByCurrentServiceSessionOrderByModifiedDesc_rdh
/** * Lists all consents that are associated with current service session. */ @Override public List<ProtocolFacingConsent> findByCurrentServiceSessionOrderByModifiedDesc() { ServiceSession serviceSession = entityManager.find(ServiceSession.class, serviceSessionId); if (null == serviceSession) { return Collections.emptyList(); } List<Consent> consent = consents.findByServiceSessionIdOrderByModifiedAtDesc(serviceSession.getId()); // Anonymous consent session: if ((null == serviceSession.getAuthSession()) || (null == serviceSession.getAuthSession().getPsu())) { return anonymousConsent(consent); } Optional<FintechPsuAspspPrvKey> v2 = keys.findByFintechIdAndPsuIdAndAspspId(fintech.getId(), serviceSession.getAuthSession().getPsu().getId(), serviceSession.getAuthSession().getAction().getBankProfile().getBank().getId()); if ((!v2.isPresent()) || consent.isEmpty()) { return Collections.emptyList(); } var psuAspspKey = fintechVault.psuAspspKeyFromPrivate(serviceSession, fintech, fintechPassword); EncryptionService enc = encryptionService.forPublicAndPrivateKey(v2.get().getId(), psuAspspKey); return consent.stream().map(it -> new ProtocolFacingConsentImpl(it, enc, encServiceProvider, encryptionKeySerde)).collect(Collectors.toList()); }
3.26
open-banking-gateway_FintechConsentAccessImpl_delete_rdh
/** * Deletes consent from the database. */ @Override public void delete(ProtocolFacingConsent consent) { consents.delete(((ProtocolFacingConsentImpl) (consent)).getConsent()); }
3.26
open-banking-gateway_FintechConsentAccessImpl_getAvailableConsentsForCurrentPsu_rdh
/** * Returns available consents to the PSU (not FinTech). */ @Override public Collection<ProtocolFacingConsent> getAvailableConsentsForCurrentPsu() { return Collections.emptyList(); }
3.26
open-banking-gateway_FintechConsentAccessImpl_save_rdh
/** * Saves consent to the database. */ @Override public void save(ProtocolFacingConsent consent) { consents.save(((ProtocolFacingConsentImpl) (consent)).getConsent()); }
3.26
open-banking-gateway_FireFlyAccountExporter_exportToFirefly_rdh
// Method length is mostly from long argument list to API call @Async @SuppressWarnings("checkstyle:MethodLength") public void exportToFirefly(String fireFlyToken, long exportJobId, AccountList accountList) { tokenProvider.setToken(fireFlyToken); int numExported = 0; int numErrored = 0; String lastError = null; for (AccountDetails account : accountList.getAccounts()) { try {exportAccountToFireFly(account); } catch (Exception ex) { log.error("Failed to export account: {}", account.getResourceId(), ex); numErrored++; lastError = ex.getMessage(); } numExported++; updateAccountsExported(exportJobId, numExported, numErrored, accountList.getAccounts().size(), lastError); } txOper.execute(callback -> { AccountExportJob toUpdate = exportJobRepository.getOne(exportJobId); toUpdate.setCompleted(true); return exportJobRepository.save(toUpdate); }); }
3.26
open-banking-gateway_AccountService_consentNotYetAvailable_rdh
// Long method argument list written in column style for clarity @SuppressWarnings("checkstyle:MethodLength") private ResponseEntity consentNotYetAvailable(String bankProfileID, SessionEntity sessionEntity, String redirectCode, UUID xRequestId, Boolean psuAuthenticationRequired, Optional<ConsentEntity> optionalConsent, boolean withBalance, Boolean online, String createConsentIfNone, Boolean fintechDecoupledPreferred, String fintechBrandLoggingInformation, String fintechNotificationURI, String fintechNotificationContentPreferred) { log.info("do LOT (instead of loa) for bank {} {} consent", bankProfileID, optionalConsent.isPresent() ? "with" : "without"); UUID serviceSessionID = optionalConsent.map(ConsentEntity::getTppServiceSessionId).orElse(null); var response = tppAisClient.getTransactionsWithoutAccountId(sessionEntity.getUserEntity().getFintechUserId(), RedirectUrlsEntity.buildOkUrl(uiConfig, redirectCode), RedirectUrlsEntity.buildNokUrl(uiConfig, redirectCode), xRequestId, COMPUTE_X_TIMESTAMP_UTC, COMPUTE_X_REQUEST_SIGNATURE, COMPUTE_FINTECH_ID, null, tppProperties.getFintechDataProtectionPassword(), UUID.fromString(bankProfileID), psuAuthenticationRequired, serviceSessionID, createConsentIfNone, null, null, HEADER_COMPUTE_PSU_IP_ADDRESS, null, null, null, null, null, null, null, null); if (response.getStatusCode() != HttpStatus.OK) { return response; } return consentAvailable(bankProfileID, sessionEntity, redirectCode, UUID.randomUUID(), optionalConsent, createConsentIfNone, withBalance, psuAuthenticationRequired, online, fintechDecoupledPreferred, fintechBrandLoggingInformation, fintechNotificationURI, fintechNotificationContentPreferred); }
3.26
open-banking-gateway_DateTimeFormatConfig_addFormatters_rdh
/** * Swagger-codegen is not able to produce @DateTimeFormat annotation: * https://github.com/swagger-api/swagger-codegen/issues/1235 * https://github.com/swagger-api/swagger-codegen/issues/4113 * To fix this - forcing formatters globally. */ @Overridepublic void addFormatters(FormatterRegistry registry) { DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(registry); }
3.26