release version 1.10.0

This commit is contained in:
2024-12-14 04:07:49 +03:00
parent a5088587f7
commit c6b3d793c4
1916 changed files with 254306 additions and 0 deletions

View File

@ -0,0 +1,175 @@
ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ
Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой)
версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего
Правообладателю Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН
7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова,
д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу
https://www.emdev.ru/about (далее - Компания).
Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями»
(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения,
Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в
настоящем документе, в противном случае, он должен не использовать или не получать доступ
к Программному обеспечению.
1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ
a) ПО Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии
или редакции, исключительные права на которую принадлежат Правообладателю.
b) Правообладатель (Компания) ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные
права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ
для ЭВМ № 2021610848 от 19.01.2021 года.
c) Пользователь юридическое или физическое лицо, получившее через скачивание с сайта
https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО.
d) ИС интеллектуальная собственность закреплённое законом исключительное право, а также
личные неимущественные права авторов произведений на результат интеллектуальной деятельности.
e) Подписка это коммерческое предложение Правообладателя, состоящее из Лицензии на использование
ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка
включает предоставление Пользователю неисключительного права использования ПО, в том числе
получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение
патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается
Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается
для каждого Пользователя индивидуально в Сертификате.
f) Сертификат документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром),
подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное
обеспечение в ограниченном объёме и на определённый период времени.
g) Лицензия (простая (неисключительная) совокупность ограниченных прав использования ПО,
предоставленных Пользователю согласно условиям Подписки.
h) Библиотека совокупность подпрограмм и объектов, используемых для разработки программного
обеспечения.
i) Исходный код текст компьютерной программы на каком-либо языке программирования, состоящий
из одного или нескольких файлов, который может быть прочтён человеком.
j) Объектный код файл (часть машинного кода) с промежуточным представлением отдельного модуля
программы, полученный в результате обработки исходного кода, еще не связанный в полную программу.
Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый
продукт.
k) Некоммерческое использование индивидуальное личное использование Пользователем программного
обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации
возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая
выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения.
2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного
обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом
воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения
в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ.
2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит
неисключительный характер.
2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию,
лицензия на ограниченное использование Программного обеспечения.
2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования
имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан
обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения
вида лицензии с Базовой бесплатной версии на Подписки.
2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для
пробного использования программного обеспечения не ограничен.
2.6. Использование Пользователем настоящего программного обеспечения в целях разработки,
модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю,
без разрешения Правообладателя не допускается.
3. АВТОРСКОЕ ПРАВО.
3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение
и любые его копии принадлежат Правообладателю.
3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента,
к которому можно получить доступ с помощью Программного обеспечения, является собственностью
соответствующего владельца контента и защищается применимым законодательством об авторском
праве или другими законами и договорами об интеллектуальной собственности.
3.3. Условия использования Программного обеспечения.
Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь
придерживается следующих условий:
3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять
какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании
Программного обеспечения или на нем.
3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать,
расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать
Программное обеспечение.
3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования
ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне.
3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено
использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам.
4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС»
4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю
на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с
использованием Пользователем:
4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в
Программное обеспечение;
4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями
настоящего соглашения;
4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием,
или данными, не предоставленными Пользователю Правообладателем;
4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем.
5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ
ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ
И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ
ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ
И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ
ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО.
6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ.
НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ
ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ,
ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ;
ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ.
ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ
ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ;
КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ
ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ.
7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ:
Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия
(включая, но не ограничиваясь) по:
-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код)
Программного обеспечения;
-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный
код Программного обеспечения, за исключением тех изменений, которые вносятся средствами,
включёнными в Программное обеспечение и описанными непосредственно в документации к нему;
-созданию условий для использования Программного обеспечения лицами, не имеющими прав на
использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство
третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа
к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку;
-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию).
8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА.
8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из
лицензионных продуктов, используемых на законных основаниях, а
именно https://entaxy.ru/libs/licenses/root-aggregated.deps.
8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть
совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения.
8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться
Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения,
содержащих все изменения и дополнения программного обеспечения.
9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ.
9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым
программным обеспечением.
9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно
с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм
«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public.
9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий
пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя,
прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер
ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства
Российской Федерации.
10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ.
10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет
право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб,
недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий
пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере
2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения
исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy).
10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое
законодательство Российской Федерации.
10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -0,0 +1,42 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.platform.security</groupId>
<artifactId>keystore</artifactId>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.platform.security.keystore</groupId>
<artifactId>keystore-runtime</artifactId>
<packaging>bundle</packaging>
<name>ENTAXY :: SECURITY :: KEYSTORE :: RUNTIME</name>
<description>ENTAXY :: SECURITY :: KEYSTORE :: RUNTIME</description>
<properties>
<bundle.osgi.private.pkg>
ru.entaxy.security.keystore.runtime.impl,
ru.entaxy.security.keystore.runtime.internal
</bundle.osgi.private.pkg>
<bundle.osgi.export.pkg>
ru.entaxy.security.keystore.runtime
</bundle.osgi.export.pkg>
</properties>
<dependencies>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.base.resources</groupId>
<artifactId>resources-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.base.resources</groupId>
<artifactId>resources-service</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>object-runtime-core</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,45 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime;
public interface EntaxyKeystore {
String KEYSTORE_RUNTIME_TYPE = "entaxy.security.keystore";
String KEYSTORE_TYPE_JKS = "jks";
String KEYSTORE_TYPE_PKSC12 = "pkcs12";
String KEYSTORE_TYPE_JWK = "jwk";
String KEYSTORE_TYPE_DEFAULT = KEYSTORE_TYPE_PKSC12;
String KEYSTORE_META_SECTION_NAME = "keystore";
String KEYSTORE_META_PROP_ALIASES = "aliases";
String KEYSTORE_META_PROP_VALID = "isValid";
String KEYSTORE_META_PROP_PROCESSED = "isProcessed";
String KEYSTORE_META_PROP_TYPE = "type";
String JWK_PROP_KEYS = "keys";
String JWK_PROP_KID = "kid";
}

View File

@ -0,0 +1,42 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime;
public class EntaxyKeystoreCausedException extends EntaxyKeystoreException {
private static final long serialVersionUID = 1L;
public EntaxyKeystoreCausedException(String keystoreId, Throwable t) {
super(keystoreId, t);
}
@Override
protected String getDetails() {
return String.format("exception [%s] is thrown: []%s", getCause().getClass().getName(),
getCause().getMessage());
}
}

View File

@ -0,0 +1,61 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime;
public class EntaxyKeystoreException extends Exception {
private static final long serialVersionUID = 1L;
protected String keystoreId = "undefined";
public EntaxyKeystoreException(String keystoreId) {
super();
setKeystoreId(keystoreId);
}
public EntaxyKeystoreException(String keystoreId, Throwable t) {
super(t);
setKeystoreId(keystoreId);
}
public String getKeystoreId() {
return keystoreId;
}
public void setKeystoreId(String keystoreId) {
this.keystoreId = keystoreId;
}
@Override
public String getMessage() {
return String.format("Keystore [%s]: %s", getKeystoreId(), getDetails());
}
protected String getDetails() {
return "unknown error";
}
}

View File

@ -0,0 +1,39 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime;
public class EntaxyKeystoreNotFoundException extends EntaxyKeystoreException {
public EntaxyKeystoreNotFoundException(String keystoreId) {
super(keystoreId);
}
@Override
protected String getDetails() {
return "not found";
}
}

View File

@ -0,0 +1,41 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime;
public class EntaxyKeystoreUrlNotDefinedException extends EntaxyKeystoreException {
private static final long serialVersionUID = 1L;
public EntaxyKeystoreUrlNotDefinedException(String keystoreId) {
super(keystoreId);
}
@Override
protected String getDetails() {
return "URL not defined";
}
}

View File

@ -0,0 +1,43 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime;
import java.io.InputStream;
import java.util.List;
public interface KeystoreManager {
List<String> getKeystoreNames();
List<String> getKeystoreAliases(String keystoreId) throws EntaxyKeystoreException;
void updateKeystore(String keystoreId, InputStream inputStream) throws EntaxyKeystoreException;
void removeKey(String keystoreId, String alias) throws EntaxyKeystoreException, UnsupportedOperationException;
void addKey(String keystoreId, String alias, String keyContent)
throws EntaxyKeystoreException, UnsupportedOperationException;
}

View File

@ -0,0 +1,41 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime;
public class UnsupportedKeyFormatException extends EntaxyKeystoreException {
String keyContent;
public UnsupportedKeyFormatException(String keystoreId, String keyContent) {
super(keystoreId);
this.keyContent = keyContent;
}
@Override
protected String getDetails() {
return String.format("unsupported key format: [%s]", keyContent);
}
}

View File

@ -0,0 +1,131 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.impl;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreCausedException;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreException;
import ru.entaxy.security.keystore.runtime.UnsupportedKeyFormatException;
public class JWKKeystoreHelper extends KeystoreHelper {
@Override
public void addKey(String alias, String keyContent) throws EntaxyKeystoreException {
JsonObject jo = null;
try {
jo = JSONUtils.getJsonRootObjectUnsafe(keyContent);
} catch (Exception e) {
throw new UnsupportedKeyFormatException(keystoreResource.keystoreId, keyContent);
}
// TODO check content
if (CommonUtils.isValid(alias)) {
if (jo.has(EntaxyKeystore.JWK_PROP_KID))
jo.remove(EntaxyKeystore.JWK_PROP_KID);
jo.addProperty(EntaxyKeystore.JWK_PROP_KID, alias);
}
JsonObject keystoreContent = JSONUtils.getJsonRootObject(keystoreResource.entaxyResource.getAsString());
if (!keystoreContent.has(EntaxyKeystore.JWK_PROP_KEYS))
keystoreContent.add(EntaxyKeystore.JWK_PROP_KEYS, new JsonArray());
JsonElement keys = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS);
if (!keys.isJsonArray()) {
keystoreContent.remove(EntaxyKeystore.JWK_PROP_KEYS);
keystoreContent.add(EntaxyKeystore.JWK_PROP_KEYS, new JsonArray());
}
JsonArray keysArray = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS).getAsJsonArray();
keysArray.add(jo);
try (InputStream is = new ByteArrayInputStream(keystoreContent.toString().getBytes())) {
updateKeystore(is);
} catch (Exception e) {
throw new EntaxyKeystoreCausedException(keystoreResource.keystoreId, e);
}
}
@Override
public void removeKey(String alias) throws EntaxyKeystoreException {
if (!CommonUtils.isValid(alias))
return;
JsonObject keystoreContent = JSONUtils.getJsonRootObject(keystoreResource.entaxyResource.getAsString());
if (!keystoreContent.has(EntaxyKeystore.JWK_PROP_KEYS))
return;
JsonElement keys = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS);
if (!keys.isJsonArray()) {
return;
}
JsonArray keysArray = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS).getAsJsonArray();
JsonArray newKeysArray = new JsonArray();
for (JsonElement item : keysArray) {
if (!item.isJsonObject()) {
// item is invalid, but we just keep it
newKeysArray.add(item);
continue;
}
JsonObject itemObject = item.getAsJsonObject();
if (!itemObject.has(EntaxyKeystore.JWK_PROP_KID)) {
// item is invalid, but we just keep it
newKeysArray.add(item);
continue;
}
try {
String itemKid = itemObject.get(EntaxyKeystore.JWK_PROP_KID).getAsString();
if (!alias.equals(itemKid)) {
newKeysArray.add(item);
}
} catch (Exception ignore) {
newKeysArray.add(item);
continue;
}
}
JSONUtils.replaceValue(keystoreContent, EntaxyKeystore.JWK_PROP_KEYS, newKeysArray);
try (InputStream is = new ByteArrayInputStream(keystoreContent.toString().getBytes())) {
updateKeystore(is);
} catch (Exception e) {
throw new EntaxyKeystoreCausedException(keystoreResource.keystoreId, e);
}
}
}

View File

@ -0,0 +1,48 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.impl;
import java.io.InputStream;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreException;
public abstract class KeystoreHelper {
protected KeystoreResource keystoreResource;
public void init(KeystoreResource keystoreResource) {
this.keystoreResource = keystoreResource;
}
public abstract void addKey(String alias, String keyContent) throws EntaxyKeystoreException;
public abstract void removeKey(String alias) throws EntaxyKeystoreException;
protected void updateKeystore(InputStream is) throws Exception {
keystoreResource.entaxyResource.save(is);
}
}

View File

@ -0,0 +1,160 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.impl;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreCausedException;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreException;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreNotFoundException;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreUrlNotDefinedException;
import ru.entaxy.security.keystore.runtime.KeystoreManager;
@Component(service = KeystoreManager.class, immediate = true)
public class KeystoreManagerImpl implements KeystoreManager {
private static final Logger LOG = LoggerFactory.getLogger(KeystoreManagerImpl.class);
protected static Map<String, Class<? extends KeystoreHelper>> helpers;
static {
helpers = new HashMap<>();
helpers.put(EntaxyKeystore.KEYSTORE_TYPE_JWK, JWKKeystoreHelper.class);
}
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY)
volatile EntaxyResourceService entaxyResourceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY)
volatile EntaxyRuntimeObjectService entaxyRuntimeObjectService;
protected class KeystoreDescriptor {
String url;
EntaxyRuntimeObject entaxyRuntimeObject;
EntaxyResource entaxyResource;
}
protected KeystoreDescriptor getDescriptor(String keystoreId) throws EntaxyKeystoreException {
KeystoreDescriptor result = new KeystoreDescriptor();
result.entaxyRuntimeObject =
entaxyRuntimeObjectService
.getRuntimeObject(keystoreId.concat(":").concat(EntaxyKeystore.KEYSTORE_RUNTIME_TYPE));
if (result.entaxyRuntimeObject == null)
throw new EntaxyKeystoreNotFoundException(keystoreId);
result.url = result.entaxyRuntimeObject.getAttributeOrDefault("keystoreUrl", "").toString();
if (!CommonUtils.isValid(result.url))
throw new EntaxyKeystoreUrlNotDefinedException(keystoreId);
result.entaxyResource = entaxyResourceService.getResource(result.url);
return result;
}
@Override
public void updateKeystore(String keystoreId, InputStream inputStream) throws EntaxyKeystoreException {
KeystoreDescriptor descriptor = getDescriptor(keystoreId);
descriptor.entaxyResource.save(inputStream);
}
@Override
public List<String> getKeystoreNames() {
return entaxyRuntimeObjectService.getObjects().stream()
.filter(obj -> obj.getType().equals(EntaxyKeystore.KEYSTORE_RUNTIME_TYPE))
.map(obj -> obj.getId())
.collect(Collectors.toList());
}
@Override
public List<String> getKeystoreAliases(String keystoreId) throws EntaxyKeystoreException {
KeystoreDescriptor descriptor = getDescriptor(keystoreId);
KeystoreResource resource = new KeystoreResource(descriptor.entaxyResource);
return resource.getAliases();
}
protected KeystoreHelper createHelper(KeystoreResource resource)
throws EntaxyKeystoreException, UnsupportedOperationException {
Class<? extends KeystoreHelper> helperClass = helpers.get(resource.getType());
if (helperClass == null)
throw new UnsupportedOperationException(
String.format("Operation not supported for keystore type [%s]", resource.getType()));
KeystoreHelper helper = null;
try {
helper = helperClass.getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new EntaxyKeystoreCausedException(resource.keystoreId, e);
}
if (helper == null)
throw new UnsupportedOperationException(
String.format("Helper not created for keystore type [%s]", resource.getType()));
helper.init(resource);
return helper;
}
@Override
public void addKey(String keystoreId, String alias, String keyContent)
throws EntaxyKeystoreException, UnsupportedOperationException {
KeystoreDescriptor descriptor = getDescriptor(keystoreId);
KeystoreResource resource = new KeystoreResource(descriptor.entaxyResource);
KeystoreHelper helper = createHelper(resource);
helper.addKey(alias, keyContent);
}
@Override
public void removeKey(String keystoreId, String alias)
throws EntaxyKeystoreException, UnsupportedOperationException {
KeystoreDescriptor descriptor = getDescriptor(keystoreId);
KeystoreResource resource = new KeystoreResource(descriptor.entaxyResource);
KeystoreHelper helper = createHelper(resource);
helper.removeKey(alias);
}
}

View File

@ -0,0 +1,106 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
public class KeystoreResource {
EntaxyResource entaxyResource;
EntaxyResourceMetadata meta;
JsonObject metaContent;
String keystoreId;
String keystoreType = EntaxyKeystore.KEYSTORE_TYPE_DEFAULT;
public KeystoreResource(EntaxyResource resource) {
super();
this.entaxyResource = resource;
String name = this.entaxyResource.getName();
int index = name.lastIndexOf('.');
if (index > 0) {
this.keystoreId = name.substring(0, index);
this.keystoreType = name.substring(index + 1);
} else {
this.keystoreId = name;
}
this.meta = this.entaxyResource.getMetadata(true);
this.metaContent = this.meta.getSection(EntaxyKeystore.KEYSTORE_META_SECTION_NAME).getContent();
}
public boolean isValid() {
JsonElement je = this.metaContent.get(EntaxyKeystore.KEYSTORE_META_PROP_VALID);
try {
return je.getAsBoolean();
} catch (Exception e) {
return false;
}
}
public boolean isProcessed() {
JsonElement je = this.metaContent.get(EntaxyKeystore.KEYSTORE_META_PROP_PROCESSED);
try {
return je.getAsBoolean();
} catch (Exception e) {
return false;
}
}
public String getType() {
JsonElement je = this.metaContent.get(EntaxyKeystore.KEYSTORE_META_PROP_TYPE);
try {
return je.getAsString();
} catch (Exception e) {
return EntaxyKeystore.KEYSTORE_TYPE_DEFAULT;
}
}
public List<String> getAliases() {
JsonElement je = this.metaContent.get(EntaxyKeystore.KEYSTORE_META_PROP_ALIASES);
if (!je.isJsonArray())
return Collections.emptyList();
List<String> result = new ArrayList<>();
for (JsonElement elem : je.getAsJsonArray()) {
if (elem.isJsonPrimitive() && elem.getAsJsonPrimitive().isString())
result.add(elem.getAsString());
}
return result;
}
}

View File

@ -0,0 +1,114 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.internal;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
import ru.entaxy.security.keystore.runtime.internal.KeystoreProcessorHelper.KeyData;
public class JKSResourceProcessor implements EntaxyResourceProcessor {
private static final Logger LOG = LoggerFactory.getLogger(JKSResourceProcessor.class);
@Override
public InputStream preProcess(InputStream origin, EntaxyResource resource) {
// TODO Auto-generated method stub
return null;
}
@Override
public void postProcess(EntaxyResource resource) {
if (!resource.exists())
return;
String keystoreType = resource.getName().substring(resource.getName().lastIndexOf('.') + 1);
if (!(EntaxyKeystore.KEYSTORE_TYPE_JKS.equals(keystoreType)
|| EntaxyKeystore.KEYSTORE_TYPE_PKSC12.equals(keystoreType)))
return;
KeystoreProcessorHelper helper = new KeystoreProcessorHelper(resource);
helper.reset();
helper.clearData();
helper.setKeystoreType(keystoreType);
helper.update();
try (InputStream resourceIs = resource.getInputStream()) {
String pwdResourceUrl = resource.getURL().concat(".pwd");
EntaxyResourceService entaxyResourceService =
OSGIUtils.services().ofClass(EntaxyResourceService.class).waitService(10000).get();
helper.setResourceService(entaxyResourceService);
EntaxyResource pwdResource = entaxyResourceService.getResource(pwdResourceUrl);
String pwd = pwdResource.getAsString();
KeyStore keyStore = KeyStore.getInstance(keystoreType);
keyStore.load(resourceIs, pwd.toCharArray());
Enumeration<String> existingAliases = keyStore.aliases();
List<KeyData> keyDataList = new ArrayList<>();
while (existingAliases.hasMoreElements()) {
String alias = existingAliases.nextElement();
KeyData keyData = new KeyData();
keyData.alias = alias;
keyDataList.add(keyData);
}
helper.setKeys(keyDataList);
helper.createKeysResources();
helper.setValid();
} catch (Exception e) {
// something's wrong: log exception and clear metadata
LOG.error("Erorr in JKS postProcess", e);
helper.setKeys(Collections.emptyList());
helper.setValid(false);
}
helper.setProcessed();
helper.update();
}
}

View File

@ -0,0 +1,119 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.internal;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
import ru.entaxy.security.keystore.runtime.internal.KeystoreProcessorHelper.KeyData;
public class JWKResourceProcessor implements EntaxyResourceProcessor {
private static final Logger LOG = LoggerFactory.getLogger(JWKResourceProcessor.class);
@Override
public InputStream preProcess(InputStream origin, EntaxyResource resource) {
// TODO Auto-generated method stub
return null;
}
@Override
public void postProcess(EntaxyResource resource) {
if (!resource.exists())
return;
if (!resource.getName().endsWith(".".concat(EntaxyKeystore.KEYSTORE_TYPE_JWK)))
return;
KeystoreProcessorHelper helper = new KeystoreProcessorHelper(resource);
helper.reset();
helper.clearData();
helper.setKeystoreType(EntaxyKeystore.KEYSTORE_TYPE_JWK);
helper.update();
try {
EntaxyResourceService entaxyResourceService =
OSGIUtils.services().ofClass(EntaxyResourceService.class).waitService(10000).get();
helper.setResourceService(entaxyResourceService);
JsonArray ja =
JSONUtils.getJsonRootObject(resource.getAsString()).getAsJsonObject()
.get(EntaxyKeystore.JWK_PROP_KEYS).getAsJsonArray();
List<KeyData> keyDataList = new ArrayList<>();
for (int i = 0; i < ja.size(); i++) {
JsonElement je = ja.get(i);
if (!je.isJsonObject())
continue;
JsonObject jo = je.getAsJsonObject();
if (!jo.has(EntaxyKeystore.JWK_PROP_KID))
continue;
try {
String kid = jo.get(EntaxyKeystore.JWK_PROP_KID).getAsString();
KeyData keyData = new KeyData();
keyData.alias = kid;
keyDataList.add(keyData);
} catch (Exception ignore) {
// NOOP
}
}
helper.setKeys(keyDataList);
helper.createKeysResources();
helper.setValid();
} catch (Exception e) {
// something's wrong: log exception and clear metadata
LOG.error("Erorr in JWK postProcess", e);
helper.setKeys(Collections.emptyList());
helper.setValid(false);
}
helper.setProcessed();
helper.update();
}
}

View File

@ -0,0 +1,56 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.internal;
import java.util.ArrayList;
import java.util.List;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceProviderProxy;
import ru.entaxy.esb.resources.impl.AbstractResourceProviderProxy;
@Component(service = EntaxyResourceProviderProxy.class, immediate = true)
public class KeyStoreResourceProvider extends AbstractResourceProviderProxy {
@Activate
public void activate() {
setProtocol("entaxy-keystore");
setTargetProtocol("entaxy-file-internal");
setTargetPath(".security/.keystore");
List<EntaxyResourceProcessor> processors = new ArrayList<>();
processors.add(new JWKResourceProcessor());
processors.add(new JKSResourceProcessor());
setProcessors(processors);
}
}

View File

@ -0,0 +1,193 @@
/*-
* ~~~~~~licensing~~~~~~
* keystore-runtime
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.security.keystore.runtime.internal;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
public class KeystoreProcessorHelper {
private static final Logger LOG = LoggerFactory.getLogger(KeystoreProcessorHelper.class);
public static class KeyData {
public String alias;
}
EntaxyResource entaxyResource;
String dataFolderLocation;
EntaxyResourceMetadata meta;
EntaxyResourceMetadata.MetadataSection section;
JsonObject sectionContent;
EntaxyResourceService resourceService;
List<KeyData> keys;
public KeystoreProcessorHelper(EntaxyResource entaxyResource) {
super();
this.entaxyResource = entaxyResource;
this.dataFolderLocation = this.entaxyResource.getURL().concat(".data");
this.meta = this.entaxyResource.getMetadata(true);
this.section = this.meta.getSection(EntaxyKeystore.KEYSTORE_META_SECTION_NAME);
this.sectionContent = this.section.getContent();
}
public void reset() {
setProcessed(false);
}
public void clearData() {
if (resourceService == null)
return;
resourceService.getResource(dataFolderLocation).delete();
}
public void createKeysResources() {
if (this.keys == null)
return;
for (KeyData keyData : this.keys)
createKeyResources(keyData);
}
protected void createKeyResources(KeyData keyData) {
StringBuffer propertiesData = new StringBuffer("rs.security.keystore.alias=");
propertiesData.append(keyData.alias).append("\n");
if (resourceService == null) {
LOG.error("Can't create resources for alias [%s]: resourceService not set", keyData.alias);
return;
}
String keyResourcePropertiesLocation =
dataFolderLocation.concat("/").concat(keyData.alias).concat(".data");
EntaxyResource keyPropertiesData = resourceService.getResource(keyResourcePropertiesLocation);
try (InputStream is = new ByteArrayInputStream(propertiesData.toString().getBytes())) {
keyPropertiesData.save(is);
} catch (Exception e) {
LOG.error(String.format("Error saving resource: [%s]", keyResourcePropertiesLocation), e);
return;
}
String keyPropertiesLocation =
dataFolderLocation.concat("/$").concat(keyData.alias).concat(".properties");
EntaxyResource keyProperties = resourceService.getResource(keyPropertiesLocation);
JsonObject jo = new JsonObject();
JSONUtils.JsonBuilder.create(jo).object("@SEQUENCE", true)
.string("delimiter", "__LF__")
.array("items")
.object()
.string("url",
entaxyResource.getURL().substring(0, entaxyResource.getURL().lastIndexOf('.'))
.concat(".properties"))
.bool("required", true)
.up()
.object()
.string("url", keyResourcePropertiesLocation)
.bool("required", true)
.up();
try (InputStream is = new ByteArrayInputStream(jo.toString().getBytes())) {
keyProperties.save(is);
} catch (Exception e) {
LOG.error(String.format("Error saving resource: [%s]", keyPropertiesLocation), e);
return;
}
JSONUtils.replaceValue(
keyProperties.getMetadata(true).getSection(EntaxyResourceMetadata.SECTION_RESOURCE.NAME).getContent(),
"@SEQUENCE",
jo.get("@SEQUENCE"));
keyProperties.getMetadata().update();
update();
}
public EntaxyResourceService getResourceService() {
return resourceService;
}
public void setResourceService(EntaxyResourceService resourceService) {
this.resourceService = resourceService;
}
public void setKeystoreType(String keystoreType) {
if (sectionContent.has(EntaxyKeystore.KEYSTORE_META_PROP_TYPE))
sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_TYPE);
sectionContent.addProperty(EntaxyKeystore.KEYSTORE_META_PROP_TYPE, keystoreType);
}
public void setKeys(List<KeyData> keys) {
this.keys = keys;
sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_ALIASES);
sectionContent.add(EntaxyKeystore.KEYSTORE_META_PROP_ALIASES, getAliasesArray());
}
protected JsonArray getAliasesArray() {
JsonArray result = new JsonArray();
if (this.keys != null)
for (KeyData data : this.keys)
result.add(data.alias);
return result;
}
public void setValid() {
setValid(true);
}
public void setValid(boolean isValid) {
sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_VALID);
sectionContent.addProperty(EntaxyKeystore.KEYSTORE_META_PROP_VALID, isValid);
}
public void setProcessed() {
setProcessed(true);
}
public void setProcessed(boolean isProcessed) {
sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_PROCESSED);
sectionContent.addProperty(EntaxyKeystore.KEYSTORE_META_PROP_PROCESSED, isProcessed);
}
public void update() {
meta.update();
}
}