Skip to content
Snippets Groups Projects
Commit 270ef81a authored by Marko Ivancic's avatar Marko Ivancic
Browse files

Relate histories

parent b5232771
Branches
No related tags found
1 merge request!1Relate histories
Showing
with 9300 additions and 66 deletions
/.idea/
/vendor/
/build/
.phpunit.result.cache
\ No newline at end of file
LICENSE 0 → 100644
This diff is collapsed.
# simpleSAMLphp
# simplesamlphp-module-accounting
SimpleSAMLphp module providing user accounting functionality using SimpleSAMLphp authentication processing
filters feature.
## Features
- Enables tracking of authentication events, synchronously (during authentication event) or
asynchronously (in a separate process using SimpleSAMLphp Cron feature)
- Provides endpoints for end users to check their personal data, summary on connected
Service Providers, and list of authentication events
- Comes with default [DBAL backend storage](https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/index.html),
meaning the following database vendors can be used: MySQL, Oracle, Microsoft SQL Server, PostgreSQL, SQLite. Other
backend storages can be added by following proper interfaces.
- Comes with setup procedure which sets up backend storage. In case of Doctrine DBAL this means running SQL migrations
which create proper tables in configured database.
- Each backend storage connection can have master and slave configuration (master for writing, slave for reading)
- Has "trackers" which persist authentication data to backend storage. Currently, there is one default Doctrine DBAL
compatible tracker which stores authentication events, versioned Idp and SP metadata, and versioned user attributes.
Other trackers can be added by following proper interfaces.
- Trackers can run in two ways:
- synchronously - authentication data persisted during authentication event typically with multiple
queries / inserts / updates to backend storage.
- asynchronously - only authentication event job is persisted during authentication event
(one insert to backend storage). With this approach, authentication event jobs can be executed later in a separate
process using SimpleSAMLphp cron module
## Installation
Module requires SimpleSAMLphp version 2 or higher.
Module is installable using Composer:
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```shell
composer require cicnavi/simplesamlphp-module-accounting
```
cd existing_repo
git remote add origin https://gitlab.geant.org/TI_Incubator/personal-profile-page/simplesamlphp.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.geant.org/TI_Incubator/personal-profile-page/simplesamlphp/-/settings/integrations)
Depending on used features, module also requires:
- ext-redis: if PhpRedis is to be used as a store
## Collaborate with your team
## Configuration
As usual with SimpleSAMLphp modules, copy the module template configuration
to the SimpleSAMLphp config directory:
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
```shell
cp modules/accounting/config-templates/module_accounting.php config/
```
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
Next step is configuring available options in file config/module_accounting.php. Each option has an explanation,
however, the description of the overall concept follows.
***
For accounting processing, the default data tracker and data provider class must be set. This tracker will be used
to persist tracking data and also to show data in the SimpleSAMLphp user interface. Here is an example excerpt
of setting the Doctrine DBAL compatible tracker class which will store authentication events, versioned Idp
and SP metadata, and versioned user attributes in a relational database:
# Editing this README
```php
use SimpleSAML\Module\accounting\ModuleConfiguration;
use SimpleSAML\Module\accounting\Trackers;
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
// ...
ModuleConfiguration::OPTION_DEFAULT_DATA_TRACKER_AND_PROVIDER =>
Trackers\Authentication\DoctrineDbal\Versioned\Tracker::class,
// ...
```
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
The deployer can choose if the accounting processing will be performed during authentication event (synchronously),
or in a separate process (asynchronously), for example:
## Name
Choose a self-explaining name for your project.
```php
use SimpleSAML\Module\accounting\ModuleConfiguration;
use SimpleSAML\Module\accounting\ModuleConfiguration\AccountingProcessingType;
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
// ...
ModuleConfiguration::OPTION_ACCOUNTING_PROCESSING_TYPE =>
ModuleConfiguration\AccountingProcessingType::VALUE_ASYNCHRONOUS,
// ...
```
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
If the processing type is asynchronous, then the deployer must also configure the job store related options:
- Jobs store class which will be used to store and fetch jobs from the backend store
- Accounting cron tag for job runner
- Cron module configuration (if the used tag is different from the ones available in cron module, which is the case
by default)
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
For each tracker or job store, the "connection key" must be set. Connection key determines which connection
parameters will be forwarded for tracker / job store initialization process.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
Also review / edit all other configuration options, and set appropriate values.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
### Running Setup
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
After you have configured everything in config/module_accounting.php, go to the SimpleSAMLphp Admin > Configuration
Page. There you will find a link "Accounting configuration status", which will take you on the
module configuration overview page.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
If the configured trackers / jobs store require any setup, you will see a "Run Setup" button, so go ahead
and click it. In the case of default Doctrine DBAL tracker / jobs store, the setup will run all migration
classes used to create necessary tables in the database.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
When the setup is finished, you'll be presented with the "Profile Page" link, which can be used by end
users to see their activity.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
### Adding Authentication Processing Filter
Last step to start tracking user data using the configured tracker classes / jobs store is to add an [authentication
processing filter](https://simplesamlphp.org/docs/stable/simplesamlphp-authproc.html) from the accounting module
to the right place in SimpleSAMLphp configuration. Here is an example of setting it globally for all IdPs
in config/config.php:
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
```php
// ...
'authproc.idp' => [
// ...
1000 => 'accounting:Accounting',
],
// ...
```
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## TODO
- [ ] Translation
## License
For open source projects, say how it is licensed.
## Tests
To run phpcs, psalm and phpunit:
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
```shell
composer pre-commit
```
\ No newline at end of file
#!/usr/bin/env php
<?php
// TODO mivanci remove this file before release
declare(strict_types=1);
use SimpleSAML\Module\accounting\Entities\Authentication\Event;
use SimpleSAML\Module\accounting\Entities\Authentication\Event\Job;
use SimpleSAML\Module\accounting\Entities\Authentication\State;
use SimpleSAML\Module\accounting\Services\HelpersManager;
use SimpleSAML\Module\accounting\Services\Logger;
use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection;
use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\Store\Repository;
use SimpleSAML\Module\accounting\Stores\Jobs\PhpRedis\RedisStore;
require 'vendor/autoload.php';
$helpersManager = new HelpersManager();
$start = new DateTime();
$newLine = "\n";
echo "Start: " . $start->format(DateTime::ATOM);
echo $newLine;
$job = new Job(new Event(new State(SimpleSAML\Test\Module\accounting\Constants\StateArrays::FULL)));
$options = getopt('c:');
$numberOfItems = $options['c'] ?? 1000;
echo 'Number of items: ' . $numberOfItems;
echo $newLine;
$spinnerChars = ['|', '/', '-', '\\'];
/**/
echo 'Starting simulating MySQL: ';
$mysqlStartTime = new DateTime();
echo $mysqlStartTime->format(DateTime::ATOM);
echo $newLine;
$mysqlParameters = [
'driver' => 'pdo_mysql', // (string): The built-in driver implementation to use
'user' => 'apps', // (string): Username to use when connecting to the database.
'password' => 'apps', // (string): Password to use when connecting to the database.
'host' => '127.0.0.1', // (string): Hostname of the database to connect to.
'port' => 33306, // (integer): Port of the database to connect to.
'dbname' => 'accounting', // (string): Name of the database/schema to connect to.
//'unix_socket' => 'unix_socet', // (string): Name of the socket used to connect to the database.
'charset' => 'utf8', // (string): The charset used when connecting to the database.
//'url' => 'mysql://user:secret@localhost/mydb?charset=utf8', // ...alternative way of providing parameters.
// Additional parameters not originally avaliable in Doctrine DBAL
'table_prefix' => '', // (string): Prefix for each table.
];
$logger = new Logger();
$jobsStoreRepository = new Repository(new Connection($mysqlParameters), 'job', $logger);
$mysqlDurationInSeconds = (new DateTime())->getTimestamp() - $mysqlStartTime->getTimestamp();
$mysqlItemsInCurrentSecond = 0;
$mysqlItemsPerSecond = [];
for ($i = 1; $i <= $numberOfItems; $i++) {
$mysqlUpdatedDurationInSeconds = (new DateTime())->getTimestamp() - $mysqlStartTime->getTimestamp();
if ($mysqlDurationInSeconds === $mysqlUpdatedDurationInSeconds) {
$mysqlItemsInCurrentSecond++;
} else {
$mysqlItemsPerSecond[] = $mysqlItemsInCurrentSecond;
$mysqlItemsInCurrentSecond = 0;
}
$mysqlItemsInCurrentSecond = $mysqlDurationInSeconds === $mysqlUpdatedDurationInSeconds ?
$mysqlItemsInCurrentSecond++ : 0;
$mysqlDurationInSeconds = (new DateTime())->getTimestamp() - $mysqlStartTime->getTimestamp();
$mysqlItemsPerSeconds = count($mysqlItemsPerSecond) ?
array_sum($mysqlItemsPerSecond) / count($mysqlItemsPerSecond) : 0;
$mysqlPercentage = $i / $numberOfItems * 100;
$spinnerChar = $spinnerChars[array_rand($spinnerChars)];
$line = sprintf(
'%1$s percentage: %2$ 3d%%, items/s: %3$04d, duration: %4$ss',
$spinnerChar, $mysqlPercentage, $mysqlItemsPerSeconds, $mysqlDurationInSeconds
);
echo $line;
echo "\r";
$jobsStoreRepository->insert($job);
}
echo $newLine;
echo $newLine;
echo 'Starting simulating Redis: ';
$redisStartTime = new DateTime();
echo $redisStartTime->format(DateTime::ATOM);
echo $newLine;
$redisClient = new Redis();
$redisClient->connect(
'127.0.0.1',
6379,
1,
null,
500,
1
);
$redisClient->auth('apps');
$redisClient->setOption(Redis::OPT_PREFIX, 'ssp_accounting:');
$redisDurationInSeconds = (new DateTime())->getTimestamp() - $redisStartTime->getTimestamp();
$redisItemsInCurrentSecond = 0;
$redisItemsPerSecond = [];
for ($i = 1; $i <= $numberOfItems; $i++) {
$redisUpdatedDurationInSeconds = (new DateTime())->getTimestamp() - $redisStartTime->getTimestamp();
if ($redisDurationInSeconds === $redisUpdatedDurationInSeconds) {
$redisItemsInCurrentSecond++;
} else {
$redisItemsPerSecond[] = $redisItemsInCurrentSecond;
$redisItemsInCurrentSecond = 0;
}
$redisItemsInCurrentSecond = $redisDurationInSeconds === $redisUpdatedDurationInSeconds ?
$redisItemsInCurrentSecond++ : 0;
$redisDurationInSeconds = $redisUpdatedDurationInSeconds;
$redisItemsPerSeconds = count($redisItemsPerSecond) ?
array_sum($redisItemsPerSecond) / count($redisItemsPerSecond) : 0;
$redisPercentage = $i / $numberOfItems * 100;
$spinnerChar = $spinnerChars[array_rand($spinnerChars)];
$line = sprintf(
'%1$s percentage: %2$ 3d%%, items/s: %3$04d, duration: %4$ss',
$spinnerChar, $redisPercentage, $redisItemsPerSeconds, $redisDurationInSeconds
);
echo $line;
echo "\r";
$redisClient->rPush(RedisStore::LIST_KEY_JOB . ':' . sha1($job->getType()), serialize($job));
// $redisClient->rPush(RedisStore::LIST_KEY_JOB, serializgit add .e($job));
}
echo $newLine;
echo 'End: ' . (new DateTime())->format(DateTime::ATOM);
echo $newLine;
\ No newline at end of file
{
"name": "cicnavi/simplesamlphp-module-accounting",
"description": "The SimpleSAMLphp accounting module",
"type": "simplesamlphp-module",
"license": "LGPL-2.1-or-later",
"authors": [
{
"name": "Marko Ivančić",
"email": "marko.ivancic@srce.hr"
}
],
"config": {
"allow-plugins": {
"simplesamlphp/composer-module-installer": true
}
},
"autoload": {
"psr-4": {
"SimpleSAML\\Module\\accounting\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"SimpleSAML\\Test\\Module\\accounting\\": "tests/src/"
}
},
"require": {
"php": "^7.4 || ^8.0",
"ext-pdo": "*",
"ext-pdo_sqlite": "*",
"doctrine/dbal": "^3",
"psr/log": "^1|^2|^3",
"simplesamlphp/composer-module-installer": "^1",
"cicnavi/simple-file-cache-php": "^2.0"
},
"require-dev": {
"vimeo/psalm": "^4",
"phpunit/phpunit": "^9",
"squizlabs/php_codesniffer": "^3",
"simplesamlphp/simplesamlphp": "^2@beta",
"simplesamlphp/simplesamlphp-test-framework": "^1"
},
"suggest": {
"ext-pcntl": "Enables job runner to gracefully respond to SIGTERM signal.",
"ext-redis": "Mandatory if PhpRedis is to be used as a store."
},
"scripts": {
"pre-commit": [
"vendor/bin/phpcs -p",
"vendor/bin/psalm",
"vendor/bin/phpunit"
]
}
}
This diff is collapsed.
<?php
declare(strict_types=1);
use SimpleSAML\Module\accounting\ModuleConfiguration;
use SimpleSAML\Module\accounting\Providers;
use SimpleSAML\Module\accounting\Stores;
use SimpleSAML\Module\accounting\Trackers;
$config = [
/**
* User ID attribute, one that is always available and that is unique to all users.
* If this attribute is not available, accounting will not be performed for that user.
*
* Examples:
* urn:oasis:names:tc:SAML:attribute:subject-id
* eduPersonTargetedID
* eduPersonPrincipalName
* eduPersonUniqueID
*/
ModuleConfiguration::OPTION_USER_ID_ATTRIBUTE_NAME => 'urn:oasis:names:tc:SAML:attribute:subject-id',
/**
* Default authentication source which will be used when authenticating users in SimpleSAMLphp Profile Page.
*/
ModuleConfiguration::OPTION_DEFAULT_AUTHENTICATION_SOURCE => 'default-sp',
/**
* Accounting processing type. There are two possible types: 'synchronous' and 'asynchronous'.
*/
ModuleConfiguration::OPTION_ACCOUNTING_PROCESSING_TYPE =>
/**
* Synchronous option, meaning accounting processing will be performed during authentication itself
* (slower authentication).
*/
ModuleConfiguration\AccountingProcessingType::VALUE_SYNCHRONOUS,
/**
* Asynchronous option, meaning for each authentication event a new job will be created for later processing
* (faster authentication, but requires setting up job storage and a cron entry).
*/
//ModuleConfiguration\AccountingProcessingType::VALUE_ASYNCHRONOUS,
/**
* Jobs store class. In case of the 'asynchronous' accounting processing type, this determines which class
* will be used to store jobs. The class must implement Stores\Interfaces\JobsStoreInterface.
*/
ModuleConfiguration::OPTION_JOBS_STORE =>
/**
* Default jobs store class which expects Doctrine DBAL compatible connection to be set below.
*/
Stores\Jobs\DoctrineDbal\Store::class,
/**
* PhpRedis class Redis jobs store. Expects class Redis compatible connection to be set bellow.
* Note: PhpRedis must be installed: https://github.com/phpredis/phpredis#installation
*/
//Stores\Jobs\PhpRedis\RedisStore::class,
/**
* Default data tracker and provider to be used for accounting and as a source for data display in SSP UI.
* This class must implement Trackers\Interfaces\AuthenticationDataTrackerInterface and
* Providers\Interfaces\AuthenticationDataProviderInterface
*/
ModuleConfiguration::OPTION_DEFAULT_DATA_TRACKER_AND_PROVIDER =>
/**
* Track each authentication event for idp / sp / user combination, and any change in idp / sp metadata or
* released user attributes. Each authentication event record will have data used and released at the
* time of the authentication event (versioned idp / sp / user data). This tracker can also be
* used as an authentication data provider. It expects Doctrine DBAL compatible connection
* to be set below. Internally it uses store class
* Stores\Data\DoctrineDbal\DoctrineDbal\Versioned\Store::class.
*/
Trackers\Authentication\DoctrineDbal\Versioned\Tracker::class,
/**
* Additional trackers to run besides default data tracker. These trackers will typically only process and
* persist authentication data to proper data store, and won't be used to display data in SSP UI.
* These tracker classes must implement Trackers\Interfaces\AuthenticationDataTrackerInterface.
*/
ModuleConfiguration::OPTION_ADDITIONAL_TRACKERS => [
// tracker-class
],
/**
* Map of classes (stores, trackers, providers, ...) and connection keys, which defines which connections will
* be used. Value for connection key can be string, or it can be an array with two connection types as keys:
* master or slave. Master connection is single connection which will be used to write data to, and it
* must be set. If no slave connections are set, master will also be used to read data from. Slave
* connections are defined as array of strings. If slave connections are set, random one will
* be picked to read data from.
*/
ModuleConfiguration::OPTION_CLASS_TO_CONNECTION_MAP => [
/**
* Connection key to be used by jobs store class.
*/
Stores\Jobs\DoctrineDbal\Store::class => 'doctrine_dbal_pdo_mysql',
Stores\Jobs\PhpRedis\RedisStore::class => 'phpredis_class_redis',
/**
* Connection key to be used by this data tracker and provider.
*/
Trackers\Authentication\DoctrineDbal\Versioned\Tracker::class => [
ModuleConfiguration\ConnectionType::MASTER => 'doctrine_dbal_pdo_mysql',
ModuleConfiguration\ConnectionType::SLAVE => [
'doctrine_dbal_pdo_mysql',
],
],
],
/**
* Connections and their parameters.
*/
ModuleConfiguration::OPTION_CONNECTIONS_AND_PARAMETERS => [
/**
* Examples for Doctrine DBAL compatible mysql and sqlite connection parameters are provided below (more info
* on https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html).
* There are additional parameters for: table prefix.
*/
'doctrine_dbal_pdo_mysql' => [
'driver' => 'pdo_mysql', // (string): The built-in driver implementation to use.
'user' => 'user', // (string): Username to use when connecting to the database.
'password' => 'password', // (string): Password to use when connecting to the database.
'host' => 'host', // (string): Hostname of the database to connect to.
'port' => 3306, // (integer): Port of the database to connect to.
'dbname' => 'dbname', // (string): Name of the database/schema to connect to.
//'unix_socket' => 'unix_socet', // (string): Name of the socket used to connect to the database.
'charset' => 'utf8', // (string): The charset used when connecting to the database.
//'url' => 'mysql://user:secret@localhost/mydb?charset=utf8', // ...alternative way of providing parameters.
// Additional parameters not originally available in Doctrine DBAL
'table_prefix' => '', // (string): Prefix for each table.
],
'doctrine_dbal_pdo_sqlite' => [
'driver' => 'pdo_sqlite', // (string): The built-in driver implementation to use.
'path' => '/path/to/db.sqlite', // (string): The filesystem path to the database file.
// Mutually exclusive with memory. path takes precedence.
'memory' => false, // (boolean): True if the SQLite database should be in-memory (non-persistent).
// Mutually exclusive with path. path takes precedence.
//'url' => 'sqlite:////path/to/db.sqlite // ...alternative way of providing path parameter.
//'url' => 'sqlite:///:memory:' // ...alternative way of providing memory parameter.
// Additional parameters not originally available in Doctrine DBAL
'table_prefix' => '', // (string): Prefix for each table.
],
/**
* Example for PhpRedis class Redis (https://github.com/phpredis/phpredis#class-redis).
*/
'phpredis_class_redis' => [
'host' => '127.0.0.1', // (string): can be a host, or the path to a unix domain socket.
'port' => 6379, // (int): default port is 6379, should be -1 for unix domain socket.
'connectTimeout' => 1, // (float): value in seconds (default is 0 meaning unlimited).
//'retryInterval' => 500, // (int): value in milliseconds (optional, default 0)
//'readTimeout' => 0, // (float): value in seconds (default is 0 meaning unlimited)
'auth' => ['phpredis', 'phpredis'], // (mixed): authentication information
'keyPrefix' => 'ssp_accounting:'
],
],
/**
* Job runner fine-grained configuration options.
*
* Maximum execution time for the job runner. You can use this option to limit job runner activity by combining
* when the job runner will run (using cron configuration) and how long the job runner will be active
* (execution time). This can be null, meaning it will run indefinitely, or can be set as a duration
* for DateInterval, examples being below. Note that when the job runner is run using Cron user
* interface in SimpleSAMLphp, the duration will be taken from the 'max_execution_time' ini
* setting, and will override this setting if ini setting is shorter.
* @see https://www.php.net/manual/en/dateinterval.construct.php
*/
ModuleConfiguration::OPTION_JOB_RUNNER_MAXIMUM_EXECUTION_TIME => null,
//ModuleConfiguration::OPTION_JOB_RUNNER_MAXIMUM_EXECUTION_TIME => 'PT9M', // 9 minutes
//ModuleConfiguration::OPTION_JOB_RUNNER_MAXIMUM_EXECUTION_TIME => 'PT59M', // 59 minutes
//ModuleConfiguration::OPTION_JOB_RUNNER_MAXIMUM_EXECUTION_TIME => 'P1D', // 1 day
/**
* Number of processed jobs after which the job runner should take a 1-second pause.
*
* This option was introduced so that the job runner can act in a more resource friendly fashion when facing
* backend store. If the value is null, there will be no pause.
*/
ModuleConfiguration::OPTION_JOB_RUNNER_SHOULD_PAUSE_AFTER_NUMBER_OF_JOBS_PROCESSED => 10,
/**
* Tracker data retention policy.
*
* Determines how long the tracked data will be stored. If null, data will be stored indefinitely. Otherwise, it
* can be set as a duration for DateInterval, examples being below. For this to work, a cron tag must also
* be configured.
*/
ModuleConfiguration::OPTION_TRACKER_DATA_RETENTION_POLICY => null,
//ModuleConfiguration::OPTION_TRACKER_DATA_RETENTION_POLICY => 'P30D', // 30 days
//ModuleConfiguration::OPTION_TRACKER_DATA_RETENTION_POLICY => 'P6M', // 6 months
//ModuleConfiguration::OPTION_TRACKER_DATA_RETENTION_POLICY => 'P1Y', // 1 year
/**
* Cron tags.
*
* Job runner tag designates the cron tag to use when running accounting jobs. Make sure to add this tag to
* the cron module configuration in case of the 'asynchronous' accounting processing type.
*/
ModuleConfiguration::OPTION_CRON_TAG_FOR_JOB_RUNNER => 'accounting_job_runner',
/**
* Tracker data retention policy tag designates the cron tag to use for enforcing data retention policy. Make sure
* to add this tag to the cron module configuration if data retention policy is different from null.
*/
ModuleConfiguration::OPTION_CRON_TAG_FOR_TRACKER_DATA_RETENTION_POLICY =>
'accounting_tracker_data_retention_policy',
];
<?php
declare(strict_types=1);
use SimpleSAML\Locale\Translate;
use SimpleSAML\Module\accounting\Helpers\ModuleRoutesHelper;
use SimpleSAML\Module\accounting\ModuleConfiguration;
function accounting_hook_adminmenu(\SimpleSAML\XHTML\Template &$template): void
{
$menuKey = 'menu';
$moduleRoutesHelper = new ModuleRoutesHelper();
$profilePageEntry = [
ModuleConfiguration::MODULE_NAME => [
'url' => $moduleRoutesHelper->getUrl(ModuleRoutesHelper::PATH_USER_PERSONAL_DATA),
'name' => Translate::noop('Profile Page'),
],
];
if (!isset($template->data[$menuKey]) || !is_array($template->data[$menuKey])) {
return;
}
// Use array_splice to put our entry before the "Log out" entry.
array_splice($template->data[$menuKey], -1, 0, $profilePageEntry);
$template->getLocalization()->addModuleDomain(ModuleConfiguration::MODULE_NAME);
}
\ No newline at end of file
<?php
declare(strict_types=1);
use SimpleSAML\Locale\Translate;
use SimpleSAML\Module\accounting\Helpers\ModuleRoutesHelper;
use SimpleSAML\Module\accounting\ModuleConfiguration;
use SimpleSAML\XHTML\Template;
function accounting_hook_configpage(Template &$template): void
{
$moduleRoutesHelper = new ModuleRoutesHelper();
$dataLinksKey = 'links';
if (!isset($template->data[$dataLinksKey]) || !is_array($template->data[$dataLinksKey])) {
return;
}
$template->data[$dataLinksKey][] = [
'href' => $moduleRoutesHelper->getUrl(ModuleRoutesHelper::PATH_ADMIN_CONFIGURATION_STATUS),
'text' => Translate::noop('Accounting configuration status'),
];
$template->getLocalization()->addModuleDomain(ModuleConfiguration::MODULE_NAME);
}
<?php
declare(strict_types=1);
use Psr\Log\LoggerInterface;
use SimpleSAML\Configuration;
use SimpleSAML\Module\accounting\Services\HelpersManager;
use SimpleSAML\Module\accounting\Services\JobRunner;
use SimpleSAML\Module\accounting\ModuleConfiguration;
use SimpleSAML\Module\accounting\Services\Logger;
use SimpleSAML\Module\accounting\Trackers\Builders\AuthenticationDataTrackerBuilder;
function accounting_hook_cron(array &$cronInfo): void
{
$moduleConfiguration = new ModuleConfiguration();
$logger = new Logger();
/** @var ?string $currentCronTag */
$currentCronTag = $cronInfo['tag'] ?? null;
if (!isset($cronInfo['summary']) || !is_array($cronInfo['summary'])) {
$cronInfo['summary'] = [];
}
/**
* Job runner handling.
*/
$cronTagForJobRunner = $moduleConfiguration->getCronTagForJobRunner();
try {
if ($currentCronTag === $cronTagForJobRunner) {
$state = (new JobRunner($moduleConfiguration, Configuration::getConfig()))->run();
foreach ($state->getStatusMessages() as $statusMessage) {
$cronInfo['summary'][] = $statusMessage;
}
$message = sprintf(
'Job processing finished with %s successful jobs, %s failed jobs; total: %s.',
$state->getSuccessfulJobsProcessed(),
$state->getFailedJobsProcessed(),
$state->getTotalJobsProcessed()
);
$cronInfo['summary'][] = $message;
}
} catch (Throwable $exception) {
$message = 'Job runner error: ' . $exception->getMessage();
$cronInfo['summary'][] = $message;
}
if (!isset($cronInfo['summary']) || !is_array($cronInfo['summary'])) {
$cronInfo['summary'] = [];
}
/**
* Tracker data retention policy handling.
*/
$cronTagForTrackerDataRetentionPolicy = $moduleConfiguration->getCronTagForTrackerDataRetentionPolicy();
try {
if (
$currentCronTag === $cronTagForTrackerDataRetentionPolicy &&
($retentionPolicy = $moduleConfiguration->getTrackerDataRetentionPolicy()) !== null
) {
$helpersManager = new HelpersManager();
$message = sprintf('Handling data retention policy.');
$logger->info($message);
$cronInfo['summary'][] = $message;
handleDataRetentionPolicy($moduleConfiguration, $logger, $helpersManager, $retentionPolicy);
}
} catch (Throwable $exception) {
$message = 'Error enforcing tracker data retention policy: ' . $exception->getMessage();
$cronInfo['summary'][] = $message;
}
}
function handleDataRetentionPolicy(
ModuleConfiguration $moduleConfiguration,
LoggerInterface $logger,
HelpersManager $helpersManager,
DateInterval $retentionPolicy
): void {
// Handle default data tracker and provider
(new AuthenticationDataTrackerBuilder($moduleConfiguration, $logger, $helpersManager))
->build($moduleConfiguration->getDefaultDataTrackerAndProviderClass())
->enforceDataRetentionPolicy($retentionPolicy);
$additionalTrackers = $moduleConfiguration->getAdditionalTrackers();
foreach ($additionalTrackers as $tracker) {
(new AuthenticationDataTrackerBuilder($moduleConfiguration, $logger, $helpersManager))
->build($tracker)
->enforceDataRetentionPolicy($retentionPolicy);
}
}
\ No newline at end of file
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: SimpleSAMLphp 2.0.0\n"
"Report-Msgid-Bugs-To: simplesamlphp-translation@googlegroups.com\n"
"POT-Creation-Date: 2016-10-12 09:31+0200\n"
"PO-Revision-Date: 2022-01-09 12:14+0200\n"
"Last-Translator: Marko Ivancic <mivanci@srce.hr\n"
"Language: en\n"
"Language-Team: \n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.3.4\n"
msgid "Accounting"
msgstr "Accounting"
<?xml version="1.0"?>
<ruleset name="SimpleSAMLphp accounting module ruleset">
<file>config-templates</file>
<file>src</file>
<file>tests</file>
<file>www</file>
<!-- Use this to exclude paths. You can have multiple patterns -->
<!--<exclude-pattern>*/tests/*</exclude-pattern>-->
<!--<exclude-pattern>*/other/*</exclude-pattern>-->
<exclude-pattern>www/assets/*</exclude-pattern>
<!-- This is the rule we inherit from. If you want to exlude some specific rules, see the docs on how to do that -->
<rule ref="PSR12"/>
</ruleset>
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheResultFile="build/.phpunit.cache/test-results"
executionOrder="depends,defects"
forceCoversAnnotation="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
convertDeprecationsToExceptions="true"
failOnRisky="true"
failOnWarning="true"
verbose="true">
<testsuites>
<testsuite name="default">
<directory>tests</directory>
</testsuite>
</testsuites>
<coverage cacheDirectory="build/.phpunit.cache/code-coverage"
processUncoveredFiles="true">
<include>
<directory suffix=".php">src</directory>
</include>
<report>
<clover outputFile="build/coverage/clover.xml"/>
<html outputDirectory="build/coverage/html"/>
<text outputFile="php://stdout"/>
</report>
</coverage>
<logging>
<junit outputFile="build/logs/junit.xml"/>
</logging>
<php>
<env name="SIMPLESAMLPHP_CONFIG_DIR" value="tests/config-templates"/>
</php>
</phpunit>
<?xml version="1.0"?>
<psalm
errorLevel="1"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="src" />
<directory name="config-templates" />
<directory name="tests" />
<directory name="www" />
<directory name="hooks" />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
<issueHandlers>
<!-- Ignore the fact that $config variable is not used in particular config files. -->
<UnusedVariable>
<errorLevel type="suppress">
<directory name="config-templates" />
<directory name="tests/config-templates" />
<directory name="tests/attributemap" />
</errorLevel>
</UnusedVariable>
<!--
Ignore PropertyNotSetInConstructor for phpunit tests. For example, this will ignore things like
"Property SomeTestClass::$backupStaticAttributes is not defined in constructor of SomeTestClass..."
-->
<PropertyNotSetInConstructor>
<errorLevel type="suppress">
<directory name="tests" />
</errorLevel>
</PropertyNotSetInConstructor>
</issueHandlers>
</psalm>
# TODO mivanci delete test route
accounting-test:
path: /test
defaults: { _controller: 'SimpleSAML\Module\accounting\Http\Controllers\Test::test' }
accounting-admin-configuration-status:
path: /admin/configuration/status
defaults: { _controller: 'SimpleSAML\Module\accounting\Http\Controllers\Admin\Configuration::status' }
accounting-user-personal-data:
path: /user/personal-data
defaults: { _controller: 'SimpleSAML\Module\accounting\Http\Controllers\User\Profile::personalData' }
accounting-user-connected-organizations:
path: /user/connected-organizations
defaults: { _controller: 'SimpleSAML\Module\accounting\Http\Controllers\User\Profile::connectedOrganizations' }
accounting-user-activity:
path: /user/activity
defaults: { _controller: 'SimpleSAML\Module\accounting\Http\Controllers\User\Profile::activity' }
accounting-user-logout:
path: /user/logout
methods:
- GET
- POST
defaults: { _controller: 'SimpleSAML\Module\accounting\Http\Controllers\User\Profile::logout' }
services:
# default configuration for services in *this* file
_defaults:
autowire: true
public: false
bind:
Psr\Log\LoggerInterface: '@accounting.logger'
# Services
SimpleSAML\Module\accounting\:
resource: '../../src/*'
exclude: '../../src/{Http/Controllers}'
# Service aliases
accounting.logger:
class: SimpleSAML\Module\accounting\Services\Logger
# Controllers
SimpleSAML\Module\accounting\Http\Controllers\:
resource: '../../src/Http/Controllers/*'
tags: ['controller.service_arguments']
\ No newline at end of file
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\accounting\Auth\Process;
use Psr\Log\LoggerInterface;
use SimpleSAML\Auth\ProcessingFilter;
use SimpleSAML\Module\accounting\Entities\Authentication\Event;
use SimpleSAML\Module\accounting\Entities\Authentication\State;
use SimpleSAML\Module\accounting\Exceptions\StoreException;
use SimpleSAML\Module\accounting\ModuleConfiguration;
use SimpleSAML\Module\accounting\Services\HelpersManager;
use SimpleSAML\Module\accounting\Services\Logger;
use SimpleSAML\Module\accounting\Stores\Builders\JobsStoreBuilder;
use SimpleSAML\Module\accounting\Trackers\Builders\AuthenticationDataTrackerBuilder;
class Accounting extends ProcessingFilter
{
protected ModuleConfiguration $moduleConfiguration;
protected JobsStoreBuilder $jobsStoreBuilder;
protected LoggerInterface $logger;
protected AuthenticationDataTrackerBuilder $authenticationDataTrackerBuilder;
protected HelpersManager $helpersManager;
/**
* @param array $config
* @param mixed $reserved
* @param ModuleConfiguration|null $moduleConfiguration
* @param LoggerInterface|null $logger
* @param HelpersManager|null $helpersManager
* @param JobsStoreBuilder|null $jobsStoreBuilder
* @param AuthenticationDataTrackerBuilder|null $authenticationDataTrackerBuilder
*/
public function __construct(
array &$config,
$reserved,
ModuleConfiguration $moduleConfiguration = null,
LoggerInterface $logger = null,
HelpersManager $helpersManager = null,
JobsStoreBuilder $jobsStoreBuilder = null,
AuthenticationDataTrackerBuilder $authenticationDataTrackerBuilder = null
) {
parent::__construct($config, $reserved);
$this->moduleConfiguration = $moduleConfiguration ?? new ModuleConfiguration();
$this->logger = $logger ?? new Logger();
$this->helpersManager = $helpersManager ?? new HelpersManager();
$this->jobsStoreBuilder = $jobsStoreBuilder ??
new JobsStoreBuilder($this->moduleConfiguration, $this->logger, $this->helpersManager);
$this->authenticationDataTrackerBuilder = $authenticationDataTrackerBuilder ??
new AuthenticationDataTrackerBuilder($this->moduleConfiguration, $this->logger, $this->helpersManager);
}
/**
*/
public function process(array &$state): void
{
try {
$authenticationEvent = new Event(new State($state));
if ($this->isAccountingProcessingTypeAsynchronous()) {
// Only create authentication event job for later processing...
$this->createAuthenticationEventJob($authenticationEvent);
return;
}
// Accounting type is synchronous, so do the processing right away...
$configuredTrackers = array_merge(
[$this->moduleConfiguration->getDefaultDataTrackerAndProviderClass()],
$this->moduleConfiguration->getAdditionalTrackers()
);
foreach ($configuredTrackers as $tracker) {
($this->authenticationDataTrackerBuilder->build($tracker))->process($authenticationEvent);
}
} catch (\Throwable $exception) {
$message = sprintf('Accounting error, skipping... Error was: %s.', $exception->getMessage());
$this->logger->error($message, $state);
}
}
protected function isAccountingProcessingTypeAsynchronous(): bool
{
return $this->moduleConfiguration->getAccountingProcessingType() ===
ModuleConfiguration\AccountingProcessingType::VALUE_ASYNCHRONOUS;
}
/**
* @throws StoreException
*/
protected function createAuthenticationEventJob(Event $authenticationEvent): void
{
($this->jobsStoreBuilder->build($this->moduleConfiguration->getJobsStoreClass()))
->enqueue(new Event\Job($authenticationEvent));
}
}
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\accounting\Entities;
use DateTimeImmutable;
class Activity
{
protected ServiceProvider $serviceProvider;
protected User $user;
protected DateTimeImmutable $happenedAt;
protected ?string $clientIpAddress;
public function __construct(
ServiceProvider $serviceProvider,
User $user,
DateTimeImmutable $happenedAt,
?string $clientIpAddress
) {
$this->serviceProvider = $serviceProvider;
$this->user = $user;
$this->happenedAt = $happenedAt;
$this->clientIpAddress = $clientIpAddress;
}
/**
* @return ServiceProvider
*/
public function getServiceProvider(): ServiceProvider
{
return $this->serviceProvider;
}
/**
* @return User
*/
public function getUser(): User
{
return $this->user;
}
/**
* @return DateTimeImmutable
*/
public function getHappenedAt(): DateTimeImmutable
{
return $this->happenedAt;
}
/**
* @return string|null
*/
public function getClientIpAddress(): ?string
{
return $this->clientIpAddress;
}
}
<?php
namespace SimpleSAML\Module\accounting\Entities\Activity;
use SimpleSAML\Module\accounting\Entities\Activity;
class Bag
{
protected array $activities = [];
public function add(Activity $activity): void
{
$this->activities[] = $activity;
}
public function getAll(): array
{
return $this->activities;
}
}
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\accounting\Entities\Authentication;
use SimpleSAML\Module\accounting\Entities\Bases\AbstractPayload;
class Event extends AbstractPayload
{
protected State $state;
protected \DateTimeImmutable $happenedAt;
public function __construct(State $state, \DateTimeImmutable $happenedAt = null)
{
$this->state = $state;
$this->happenedAt = $happenedAt ?? new \DateTimeImmutable();
}
public function getState(): State
{
return $this->state;
}
public function getHappenedAt(): \DateTimeImmutable
{
return $this->happenedAt;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment