5 Commits

Author SHA1 Message Date
444ff687fc Base API, and more solid key and check 2024-03-20 23:07:49 -03:00
f3a5fa2cdc Tests 2024-03-20 23:06:38 -03:00
2ed265dcf1 Merge branch 'testing' into develop 2024-03-20 21:11:32 -03:00
f1e29e3b0b Ignore testing results 2024-03-20 13:50:04 -03:00
6617a92f5f Tests 2024-03-20 13:49:58 -03:00
16 changed files with 266 additions and 6 deletions

13
app/.phpunit-watcher.yml Normal file
View File

@ -0,0 +1,13 @@
watch:
directories:
- src
- tests
- common
fileMask: '*.php'
notifications:
passingTests: false
failingTests: false
hideManual: true
phpunit:
arguments: '--log-events-text /logs/output.txt --stop-on-failure'
timeout: 180

43
app/phpunit.xml Normal file
View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheDirectory=".phpunit.cache"
executionOrder="depends,defects"
requireCoverageMetadata="false"
beStrictAboutCoverageMetadata="false"
beStrictAboutOutputDuringTests="true"
colors="true"
failOnRisky="false"
failOnWarning="false">
<testsuites>
<testsuite name="unit">
<directory>tests/units</directory>
</testsuite>
<testsuite name="acceptance">
<directory>tests/integration</directory>
</testsuite>
<testsuite name="performance">
<directory>tests/performance</directory>
</testsuite>
</testsuites>
<source restrictDeprecations="true" restrictNotices="true" restrictWarnings="true">
<include>
<directory>src</directory>
<directory>common</directory>
</include>
</source>
<coverage includeUncoveredFiles="true" pathCoverage="false" ignoreDeprecatedCodeUnits="true" disableCodeCoverageIgnore="true">
<report>
<html outputDirectory="/code/public/coverage/html" />
<php outputFile="/code/public/coverage/coverage.php" />
</report>
</coverage>
<logging>
<junit outputFile="/logs/junit.xml" />
<teamcity outputFile="/logs/teamcity.txt" />
<testdoxHtml outputFile="/logs/testdox.html" />
<testdoxText outputFile="/logs/testdox.txt" />
</logging>
</phpunit>

View File

@ -1,4 +1,6 @@
<?php
use Incoviba\Controller\API\Base;
$app->group('/api', function($app) {
$folder = implode(DIRECTORY_SEPARATOR, [__DIR__, 'api']);
if (file_exists($folder)) {
@ -10,4 +12,5 @@ $app->group('/api', function($app) {
include_once $file->getRealPath();
}
}
$app->get('[/]', Base::class);
})->add($app->getContainer()->get(Incoviba\Middleware\API::class));

View File

@ -2,6 +2,13 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.3/semantic.min.js" integrity="sha512-gnoBksrDbaMnlE0rhhkcx3iwzvgBGz6mOEj4/Y5ZY09n55dYddx6+WYc72A55qEesV8VX2iMomteIwobeGK1BQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
function cleanNoCache() {
const url = new URL(window.location.href)
if (url.searchParams.has('nocache')) {
url.searchParams.delete('nocache')
window.location.href = url.href
}
}
function fetchAPI(url, options=null) {
if (options === null) {
options = {}
@ -10,7 +17,11 @@
options['headers'] = {}
}
if (!Object.hasOwn(options['headers'], 'Authorization')) {
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}'
@if (!$login->isIn())
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}'
@else
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}{{$login->getSeparator()}}{{$login->getToken()}}'
@endif
}
return fetch(url, options).then(response => {
if (response.ok) {
@ -36,6 +47,7 @@
date: 'DD-MM-YYYY'
},
}
cleanNoCache()
</script>
@stack('page_scripts')

View File

@ -14,6 +14,7 @@ return [
Incoviba\Middleware\API::class => function(ContainerInterface $container) {
return new Incoviba\Middleware\API(
$container->get(Psr\Http\Message\ResponseFactoryInterface::class),
$container->get(Incoviba\Service\Login::class),
$container->get('API_KEY')
);
}

View File

@ -9,7 +9,8 @@ return [
$container->get('COOKIE_NAME'),
$container->get('MAX_LOGIN_HOURS'),
$container->has('COOKIE_DOMAIN') ? $container->get('COOKIE_DOMAIN') : '',
$container->has('COOKIE_PATH') ? $container->get('COOKIE_PATH') : ''
$container->has('COOKIE_PATH') ? $container->get('COOKIE_PATH') : '',
$container->has('COOKIE_SEPARATOR') ? $container->get('COOKIE_SEPARATOR') : 'g'
);
},
Incoviba\Service\Money::class => function(ContainerInterface $container) {

View File

@ -0,0 +1,20 @@
<?php
namespace Incoviba\Controller\API;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal\Controller;
class Base extends Controller
{
use withJson;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$output = [
'version' => '2.0.0',
'organization' => 'Ingenieria y Construccion Vial Balmaceda Sociedad Anonima'
];
return $this->withJson($response, $output);
}
}

View File

@ -6,10 +6,12 @@ use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Incoviba\Exception\MissingAuthorizationHeader;
use Incoviba\Service;
class API
{
public function __construct(protected ResponseFactoryInterface $responseFactory, protected string $key) {}
public function __construct(protected ResponseFactoryInterface $responseFactory, protected Service\Login $loginService,
protected string $key) {}
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
@ -18,7 +20,7 @@ class API
} catch (MissingAuthorizationHeader $exception) {
return $this->responseFactory->createResponse(401);
}
if ($this->validate($key)) {
if ($this->validate($request, $key)) {
return $handler->handle($request);
}
return $this->responseFactory->createResponse(403);
@ -33,8 +35,26 @@ class API
}
throw new MissingAuthorizationHeader();
}
protected function validate($incoming_key): bool
protected function validate(ServerRequestInterface $request, $incoming_key): bool
{
if (str_contains($incoming_key, $this->loginService->getSeparator())) {
list($incoming_key, $selector, $token) = explode($this->loginService->getSeparator(), $incoming_key);
if (!$this->loginService->isIn()) {
return false;
}
}
if (!$this->loginService->isIn() and !$this->validPermitted($request)) {
return false;
}
return $incoming_key === md5($this->key);
}
protected function validPermitted(ServerRequestInterface $request): bool
{
$uri = $request->getUri();
$validPaths = [
'/api',
'/api/'
];
return in_array($uri->getPath(), $validPaths);
}
}

View File

@ -51,7 +51,7 @@ class Authentication
return true;
}
$valid_subpaths = [
'/api'
'/api/'
];
foreach ($valid_subpaths as $path) {
if (str_starts_with($current_path, $path)) {
@ -60,6 +60,7 @@ class Authentication
}
$valid_uris = [
$this->login_url,
"{$this->login_url}/",
];
if (in_array($current_url, $valid_uris, true)) {
return true;

View File

@ -47,6 +47,14 @@ class Login
}
return $login->user;
}
public function getToken(): string
{
return implode($this->cookie_separator, [$this->selector, $this->token]);
}
public function getSeparator(): string
{
return $this->cookie_separator;
}
public function validateUser(Model\User $user, string $encryptedPassword): bool
{
list($passphrase, $encrypted) = $this->splitPassword($encryptedPassword);

View File

@ -0,0 +1,17 @@
<?php
namespace ProVM\Performance;
use GuzzleHttp\Client;
use PHPUnit\Framework;
class APITest extends Framework\TestCase
{
public function testLoad(): void
{
$client = new Client(['base_uri' => 'http://proxy']);
$start = microtime(true);
$response = $client->get('/api', ['headers' => ['Authorization' => 'Bearer ' . md5($_ENV['API_KEY'])]]);
$end = microtime(true);
$this->assertLessThanOrEqual(1000, $end - $start);
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace ProVM\Performance;
use GuzzleHttp\Client;
use PHPUnit\Framework;
class HomeTest extends Framework\TestCase
{
public function testLoad(): void
{
$client = new Client(['base_uri' => 'http://proxy']);
$start = microtime(true);
$response = $client->get('');
$end = microtime(true);
$this->assertLessThanOrEqual(1000, $end - $start);
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace ProVM\Test\Common\Alias;
use Incoviba\Common\Alias\View;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
class ViewTest extends TestCase
{
public function testRender(): void
{
$contents = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>Test</title>
</head>
<body>
Test
</body>
</html>
HTML;
mkdir('/tmp/views');
mkdir('/tmp/cache', 777);
file_put_contents('/tmp/views/test.blade.php', $contents);
$view = new View('/tmp/views', '/tmp/cache');
$body = $this->getMockBuilder(StreamInterface::class)->getMock();
$body->method('getContents')->willReturn($contents);
$response = $this->getMockBuilder(ResponseInterface::class)->getMock();
$response->method('getBody')->willReturn($body);
$output = $view->render($response, 'test');
$this->assertEquals($contents, $output->getBody()->getContents());
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace ProVM\Test\Common\Implement;
use PHPUnit\Framework\TestCase;
class ConnectionTest extends TestCase
{
}

View File

@ -0,0 +1,50 @@
<?php
namespace ProVM\Test\Service;
use PHPUnit\Framework\TestCase;
use Incoviba\Common\Define;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class MenuTest extends TestCase
{
public function testBuild(): void
{
$tests = mt_rand(10, 100);
for ($i = 0; $i < $tests; $i ++) {
list($expected, $menu) = $this->generateBuildTest();
$this->assertEquals($expected, $menu->build(1));
}
}
protected function generateBuildTest(): array
{
$modelCount = mt_rand(3, 100);
$expected = [];
$models = [];
for ($j = 0; $j < $modelCount; $j ++) {
$model = $this->generateModel();
$models []= $model;
$expected []= "<a class=\"item\" href=\"http://localhost/url{$model->id}\">title{$model->id}</a>";
}
$expected = implode(PHP_EOL, $expected);
$connection = $this->getMockBuilder(Define\Connection::class)->getMock();
$repository = $this->getMockBuilder(Repository\Menu::class)->setConstructorArgs(compact('connection'))->getMock();
$permissionsRepository = $this->getMockBuilder(Repository\Permission::class)->setConstructorArgs(compact('connection'))->getMock();
$permissions = $this->getMockBuilder(Service\Permission::class)->setConstructorArgs([$permissionsRepository])->getMock();
$repository->method('fetchByUser')->willReturn($models);
$menu = new Service\Menu($repository, $permissions, (object) ['base' => 'http://localhost']);
return [$expected, $menu];
}
protected function generateModel(): Model\Menu
{
$id = mt_rand(1, 100000);
$model = $this->getMockBuilder(Model\Menu::class)->getMock();
$model->id = $id;
$model->url = "url{$id}";
$model->title = "title{$id}";
return $model;
}
}

View File

@ -83,6 +83,16 @@ services:
- ${CLI_PATH:-.}:/code
- ./logs/cli:/logs
testing:
profiles:
- testing
container_name: incoviba_tests
extends:
service: web
volumes:
- ./logs/test:/logs
command: [ '/code/vendor/bin/phpunit-watcher', 'watch' ]
volumes:
dbdata: {}
incoviba_redis: {}