diff --git a/cspell.json b/cspell.json index 95bc57ffb..0dc4ffdbe 100644 --- a/cspell.json +++ b/cspell.json @@ -340,7 +340,8 @@ "subkeys", "httponly", "samesite", - "IPCOUNTRY" + "IPCOUNTRY", + "Serviceapikey" ], "ignorePaths": [ "tests/**", diff --git a/src/library/Model/ServiceApiKey.php b/src/library/Model/ServiceApiKey.php new file mode 100644 index 000000000..d2d7841b5 --- /dev/null +++ b/src/library/Model/ServiceApiKey.php @@ -0,0 +1,19 @@ +getService()->updateApiKey($data); + } + + /** + * Used to reset / regenerate an API key. Useful in the event one is accidentally leaked. + * + * @param array $data - An associative array containing either the key or ID of whatever API key you want to reset. + * - string 'key' The API key to reset. + * - int 'order_id' The order ID of the API key to reset. + */ + public function reset($data): bool + { + return $this->getService()->resetApiKey($data); + } +} diff --git a/src/modules/Serviceapikey/Api/Client.php b/src/modules/Serviceapikey/Api/Client.php new file mode 100644 index 000000000..9d209731e --- /dev/null +++ b/src/modules/Serviceapikey/Api/Client.php @@ -0,0 +1,26 @@ +getService()->resetApiKey($data); + } +} diff --git a/src/modules/Serviceapikey/Api/Guest.php b/src/modules/Serviceapikey/Api/Guest.php new file mode 100644 index 000000000..c3c34a1f9 --- /dev/null +++ b/src/modules/Serviceapikey/Api/Guest.php @@ -0,0 +1,36 @@ +getService()->isValid($data); + } + + /** + * Gets the information tied to an API key such as it's validity and any custom parameters tied to it. + * + * @param array $data + * - 'key' What API key to check & get custom parameters for. + */ + public function get_info($data) + { + return $this->getService()->getInfo($data); + } +} diff --git a/src/modules/Serviceapikey/Service.php b/src/modules/Serviceapikey/Service.php new file mode 100644 index 000000000..4227d450c --- /dev/null +++ b/src/modules/Serviceapikey/Service.php @@ -0,0 +1,353 @@ +di = $di; + } + + public function getDi(): ?\Pimple\Container + { + return $this->di; + } + + public function attachOrderConfig(\Model_Product $product, array $data): array + { + !empty($product->config) ? $config = json_decode($product->config, true) : $config = []; + return array_merge($config, $data); + } + + public function create(OODBBean $order) + { + $model = $this->di['db']->dispense('service_apikey'); + $model->client_id = $order->client_id; + $model->config = $order->config; + + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($model); + + return $model; + } + + public function activate(OODBBean $order, OODBBean $model): bool + { + $config = json_decode($order->config, 1); + if (!is_object($model)) { + throw new \Box_Exception('Order does not exist.'); + } + + $model->api_key = $this->generateKey($config); + $model->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($model); + + return true; + } + + public function suspend(OODBBean $order, OODBBean $model): bool + { + $model->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($model); + + return true; + } + + public function unsuspend(OODBBean $order, OODBBean $model): bool + { + $model->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($model); + + return true; + } + + public function cancel(OODBBean $order, OODBBean $model): bool + { + return $this->suspend($order, $model); + } + + public function uncancel(OODBBean $order, OODBBean $model): bool + { + return $this->unsuspend($order, $model); + } + + public function delete(OODBBean $order, OODBBean $model): void + { + if (is_object($model)) { + $this->di['db']->trash($model); + } + } + + public function toApiArray(OODBBean $model): array + { + return [ + 'id' => $model->id, + 'created_at' => $model->created_at, + 'updated_at' => $model->updated_at, + 'api_key' => $model->api_key, + 'config' => json_decode($model->config, true), + ]; + } + + /** + * Checks if an API key is valid or not. + * + * @param array $data + * - 'key' What API key to check. + */ + public function isValid(array $data): bool + { + if (empty($data['key'])) { + throw new \Box_Exception('You must provide an API key to check it\'s validity.'); + } + + $model = $this->di['db']->findOne('service_apikey', 'api_key = :api_key', [':api_key' => $data['key']]); + if (is_null($model)) { + throw new \Box_Exception("API key does not exist"); + } + + return $this->isActive($model); + } + + /** + * Checks if an API key is valid or not and returns that + any configured custom parameters. + * + * @param array $data + * - 'key' What API key to check. + */ + public function getInfo(array $data): array + { + if (empty($data['key'])) { + throw new \Box_Exception('You must provide an API key to check it\'s validity.'); + } + + $model = $this->di['db']->findOne('service_apikey', 'api_key = :api_key', [':api_key' => $data['key']]); + if (is_null($model)) { + throw new \Box_Exception("API key does not exist"); + } + + // Load the stored JSON config from the DB + $rawConfig = json_decode($model->config, true); + $strippedConfig = []; + if (!is_array($rawConfig)) { + $rawConfig = []; + } + + // Then loop through it and only select the custom parameters, removing the 'custom_' prefix & converting numerical strings to a float. + foreach ($rawConfig as $key => $value) { + if (str_starts_with($key, 'custom_')) { + $name = substr($key, 7); + if (is_numeric($value)) { + $strippedConfig[$name] = floatval($value); + } else { + $strippedConfig[$name] = $value; + } + } + } + + $data = [ + 'valid' => $this->isActive($model), + 'config' => $strippedConfig, + ]; + + return $data; + } + + /** + * Used to reset an API key using the API key generator. + * + * @param array $data An array containing what API key to reset. At least one of the possible identification methods must be provided. + * - int 'order_id' (optional) The ID of the API key to rest. + * - string 'key' (optional) The API key to reset. + */ + public function resetApiKey(array $data): bool + { + if (empty($data['key']) && empty($data['order_id'])) { + throw new \Box_Exception("You must provide either the API key or API key order ID in order to reset it."); + } elseif (!empty($data['order_id'])) { + $order = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found'); + $orderService = $this->di['mod_service']('order'); + $model = $orderService->getOrderService($order); + } else { + $model = $this->di['db']->findOne('service_apikey', 'api_key = :api_key', [':api_key' => $data['key']]); + } + + if (is_null($model)) { + throw new \Box_Exception("API key does not exist"); + } + + + try { + $this->di['is_client_logged']; + $client = $this->di['loggedin_client']; + } catch (\Exception) { + $client = null; + } + + if (!is_null($client) && $client->id !== $model->client_id) { + throw new \Box_Exception("API key does not exist"); + } + + $config = json_decode($model->config, true); + + $model->api_key = $this->generateKey($config); + $model->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($model); + return true; + } + + /** + * Used to update an API key, but prevents changing the API key so we can ensure they use the reset function. + * + * @param array $data An array containing what API key to update and what info to update. + * - int 'order_id' The order ID of the API key to update. + * - array 'config' (optional) The new config to attach to the API key. + */ + public function updateApiKey(array $data): bool + { + if (empty($data['order_id'])) { + throw new \Box_Exception("You must provide the API key order ID in order to update it."); + } + + $order = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found'); + $orderService = $this->di['mod_service']('order'); + $model = $orderService->getOrderService($order); + + if (is_null($model)) { + throw new \Box_Exception("API key does not exist"); + } + + if (isset($data['api_key']) && $model->api_key !== $data['api_key']) { + throw new \Box_Exception('To change the API key, please use the reset function rather than updating it.'); + } + + $config = !empty($data['config']) ? json_encode($data['config']) : $model->config; + + //ID and client ID should remain constant so we don't try to update those here. + $model->config = $config; + $model->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($model); + return true; + } + + /** + * Creates the database structure to store the API keys in. + */ + public function install(): bool + { + $sql = " + CREATE TABLE IF NOT EXISTS `service_apikey` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT UNIQUE, + `client_id` bigint(20) NOT NULL, + `api_key` varchar(255), + `config` text NOT NULL, + `created_at` datetime, + `updated_at` datetime, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;"; + $this->di['db']->exec($sql); + + return true; + } + + /** + * Removes the API keys from the database. + */ + public function uninstall(): bool + { + $this->di['db']->exec("DROP TABLE IF EXISTS `service_apikey`"); + return true; + } + + /** + * Generates a new API using PHP's built-in cryptographically secure random_bytes to ensure the API keys are truly random and not predictable. + * + * @param array $config (optional) An array of configuration options. All configuration keys are optional. + * - int 'length' How long of an API key to generate. + * - bool 'split' True to enable splitting of the API key using dashes. Does not count towards the total key length. + * - int 'split_interval' How often the API key should be split with dashes. Example: 8 for every 8 characters. + * - string 'case' What capitalization should be used for the generated API key. 'lower', 'upper', or 'mixed'. + */ + private function generateKey(array $config = []): string + { + $length = $config['length'] ?? 32; + $split = $config['split'] ?? true; + $splitLength = $config['split_interval'] ?? 8; + $case = $config['case'] ?? 'upper'; + + $i = 0; + do { + // Try 10 times to generate a unique API key. Fail if we are unable to. + if ($i++ >= 10) { + throw new \Box_Exception('Maximum number of iterations reached while generating API key'); + } + + // Generate random bytes half the length of the configured length, as the length will doubled when converted to a hex string. + $randomBytes = random_bytes(ceil($length / 2)); + $apiKey = substr(bin2hex($randomBytes), 0, $length); + + if ($split) { + $apiKey = chunk_split($apiKey, $splitLength, '-'); + $apiKey = rtrim($apiKey, '-'); + } + + switch ($case) { + case 'lower': + //Do nothing, the API key generated will be lowercase by default. + break; + case 'upper': + $apiKey = strtoupper($apiKey); + break; + case 'mixed': + $characters = str_split($apiKey); + $result = ''; + + foreach ($characters as $character) { + if (mt_rand(0, 1) <= 0.5) { + $character = strtoupper($character); + } + + $result .= $character; + } + $apiKey = $result; + break; + default: + throw new \Box_Exception("Unknown uppercase option ':case:'. API generator only accepts 'lower', 'upper', or 'mixed'.", [':case:' => $case]); + } + } while (null !== $this->di['db']->findOne('service_apikey', 'api_key = :api_key', [':api_key' => $apiKey])); + + return $apiKey; + } + + private function isActive(\RedBeanPHP\OODBBean $model): bool + { + $order = $this->di['db']->findOne('ClientOrder', 'service_id = :id AND service_type = "apikey"', [':id' => $model->id]); + if (is_null($order)) { + throw new \Box_Exception("API key does not exist"); + } + + return $order->status === 'active'; + } +} diff --git a/src/modules/Serviceapikey/html_admin/mod_serviceapikey_config.html.twig b/src/modules/Serviceapikey/html_admin/mod_serviceapikey_config.html.twig new file mode 100644 index 000000000..4642cadf6 --- /dev/null +++ b/src/modules/Serviceapikey/html_admin/mod_serviceapikey_config.html.twig @@ -0,0 +1,148 @@ +{% import 'macro_functions.html.twig' as mf %} +
+

{{ 'API Key settings'|trans }}

+
+ +
+

{{ 'Here you can configured the length of the API keys that will be generated. We recommend making this no less than 16 at a minimum. When in doubt, leave this at 32.'|trans }}

+ +
+ +
+
+ +
+ +
+

{{ 'FOSSBilling can split the generated API key with dashes depending on the following options. The dashes will not count towards the API key length. If any API key is generated with dashes, they must be included in order for it to be considered valid.'|trans }}

+ +
+
+ + +
+
+ + +
+
+
+ +
+ +
+ +
+
+ +
+ +
+

{{ 'Here you can configure what case you want the API keys to be generated with. "Uppercase" makes all letters uppercase, "lowercase" makes them all lowercase, and "mixed" does a combination of the two options.'|trans }}

+ +
+ +
+
+ +
+ +
+

{{ 'Custom Parameters'|trans }}

+

{{ 'Here, you have the option to include custom parameters that can be requested from the API. This is particularly useful if you want to set specific limits for API keys. Your application can connect to the FOSSBilling API and retrieve the custom parameters you have defined for an API key.'|trans }}

+

{{ 'FOSSBilling will remove the "custom_" prefix from the value name when requesting them from the API. IE: custom_monthlyLimit will be named monthlyLimit when fetched through the API.'|trans}} +

+ {{ 'Add new field'|trans }} + {% for key, value in product.config %} + {% if key starts with 'custom_' %} +
+ +
+ Delete +
+
+ {% endif %} + {% endfor %} +
+
+ + + +
+
+ diff --git a/src/modules/Serviceapikey/html_admin/mod_serviceapikey_manage.html.twig b/src/modules/Serviceapikey/html_admin/mod_serviceapikey_manage.html.twig new file mode 100644 index 000000000..09a132af6 --- /dev/null +++ b/src/modules/Serviceapikey/html_admin/mod_serviceapikey_manage.html.twig @@ -0,0 +1,174 @@ +{% import 'macro_functions.html.twig' as mf %} + +{% set service = admin.order_service({ "id": order.id }) %} + +
+

{{ 'Details'|trans }}

+ + + + + + + +
{{ 'API Key'|trans }}:{{ service.api_key }}
+
+ + + +
+

{{ 'API key configuration'|trans }}

+

{{ 'Changing the API key generation options will not automatically regenerate the API key. You must do so manually.'|trans }}

+ +
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ + +
+
+ + +
+
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+ +
+
+ +
+ +
+

{{ 'Custom Parameters'|trans }}

+
+ {{ 'Add new field'|trans }} + {% for key, value in service.config %} + {% if key starts with 'custom_' %} +
+ +
+ Delete +
+
+ {% endif %} + {% endfor %} +
+
+ + + +
+
+ + diff --git a/src/modules/Serviceapikey/html_client/mod_serviceapikey_manage.html.twig b/src/modules/Serviceapikey/html_client/mod_serviceapikey_manage.html.twig new file mode 100644 index 000000000..c1b5a32f5 --- /dev/null +++ b/src/modules/Serviceapikey/html_client/mod_serviceapikey_manage.html.twig @@ -0,0 +1,41 @@ +{% if order.status == 'active' %} +
+
+
+
+

{{ order.title }}

+
+
+

{{ 'API key details'|trans }}

+ + + + + + + +
{{ 'API key'|trans }} + {{ service.api_key }} +
+ +

{{ 'Reset API key'|trans }}

+
+

+
+
+
+
+
+ + +{% endif %} diff --git a/src/modules/Serviceapikey/html_email/mod_serviceapikey_activated.html.twig b/src/modules/Serviceapikey/html_email/mod_serviceapikey_activated.html.twig new file mode 100644 index 000000000..e968b6e49 --- /dev/null +++ b/src/modules/Serviceapikey/html_email/mod_serviceapikey_activated.html.twig @@ -0,0 +1,49 @@ +{% block subject %}[{{ guest.system_company.name }}] {{ order.title }} Activated{% endblock %} +{% block content %} + + + + + + + +

Order is now active

+

Hello {{ c.first_name }} {{ c.last_name }},

+

Your {{ order.title }} is now activated.

+ +

API key: {{ service.api_key }}

+ +

You may login or manage your order. + +

{{ guest.system_company.signature }}

+ + +{% endblock %} diff --git a/src/modules/Serviceapikey/html_email/mod_serviceapikey_canceled.html.twig b/src/modules/Serviceapikey/html_email/mod_serviceapikey_canceled.html.twig new file mode 100644 index 000000000..0118909a4 --- /dev/null +++ b/src/modules/Serviceapikey/html_email/mod_serviceapikey_canceled.html.twig @@ -0,0 +1,52 @@ +{% block subject %}[{{ guest.system_company.name }}] {{ order.title }} Canceled{% endblock %} +{% block content %} + + + + + + + +

Order canceled

+

Hello {{ c.first_name }} {{ c.last_name }},

+

Your {{ order.title }} that was activated on {{ order.activated_at|format_date }} is now canceled.

+ {% if order.reason %} +

Reason: {{ order.reason }}

+ {% endif %} + +

If you have any questions regarding this, please login to the members area and submit a support ticket.

+ +

You may login or submit a ticket. + +

{{ guest.system_company.signature }}

+ + +{% endblock %} diff --git a/src/modules/Serviceapikey/html_email/mod_serviceapikey_renewed.html.twig b/src/modules/Serviceapikey/html_email/mod_serviceapikey_renewed.html.twig new file mode 100644 index 000000000..e8cf34eb3 --- /dev/null +++ b/src/modules/Serviceapikey/html_email/mod_serviceapikey_renewed.html.twig @@ -0,0 +1,50 @@ +{% block subject %}[{{ guest.system_company.name }}] {{ order.title }} Renewed{% endblock %} +{% block content %} + + + + + + + +

Order renewed

+

Hello {{ c.first_name }} {{ c.last_name }},

+

Your {{ order.title }} has been renewed.

+ {% if order.expires_at %} +

Next renewal date: {{ order.expires_at|format_date }}

+ {% endif %} + +

You may login or manage your order. + +

{{ guest.system_company.signature }}

+ + +{% endblock %} diff --git a/src/modules/Serviceapikey/html_email/mod_serviceapikey_suspended.html.twig b/src/modules/Serviceapikey/html_email/mod_serviceapikey_suspended.html.twig new file mode 100644 index 000000000..761ea95ad --- /dev/null +++ b/src/modules/Serviceapikey/html_email/mod_serviceapikey_suspended.html.twig @@ -0,0 +1,52 @@ +{% block subject %}[{{ guest.system_company.name }}] {{ order.title }} Suspended{% endblock %} +{% block content %} + + + + + + + +

Order suspended

+

Hello {{ c.first_name }} {{ c.last_name }},

+

Your {{ order.title }} that was activated on {{ order.activated_at|format_date }} is now suspended.

+ {% if order.reason %} +

Reason: {{ order.reason }}

+ {% endif %} + +

If you have any questions regarding this, please login to the members area and submit a support ticket.

+ +

You may login or submit a ticket. + +

{{ guest.system_company.signature }}

+ + +{% endblock %} diff --git a/src/modules/Serviceapikey/html_email/mod_serviceapikey_unsuspended.html.twig b/src/modules/Serviceapikey/html_email/mod_serviceapikey_unsuspended.html.twig new file mode 100644 index 000000000..1a1c8dcda --- /dev/null +++ b/src/modules/Serviceapikey/html_email/mod_serviceapikey_unsuspended.html.twig @@ -0,0 +1,47 @@ +{% block subject %}[{{ guest.system_company.name }}] {{ order.title }} Reactivated{% endblock %} +{% block content %} + + + + + + + +

Order unsuspended

+

Hello {{ c.first_name }} {{ c.last_name }},

+

Your {{ order.title }} is now unsuspended.

+ +

You may login or manage your order. + +

{{ guest.system_company.signature }}

+ + +{% endblock %} diff --git a/src/modules/Serviceapikey/icon.svg b/src/modules/Serviceapikey/icon.svg new file mode 100644 index 000000000..16343528b --- /dev/null +++ b/src/modules/Serviceapikey/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/modules/Serviceapikey/manifest.json b/src/modules/Serviceapikey/manifest.json new file mode 100644 index 000000000..f8f74c810 --- /dev/null +++ b/src/modules/Serviceapikey/manifest.json @@ -0,0 +1,8 @@ +{ + "id": "serviceapikey", + "type": "mod", + "name": "API Key Product", + "description": "A simple product type to allow you to generate and sell API keys for use in your applications", + "icon_url": "icon.svg", + "version": "1.0.0" +}