Skip to content

Fix: Add support for empty Security Requirement Object ({}) in security requirement #238 #239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# php-openapi

TODO docs related to issue 242, 238

Read and write [OpenAPI](https://www.openapis.org/) 3.0.x YAML and JSON files and make the content accessible in PHP objects.

It also provides a CLI tool for validating and converting OpenAPI 3.0.x Description files.
Expand Down
54 changes: 46 additions & 8 deletions src/spec/SecurityRequirements.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,20 @@ public function __construct(array $data)
parent::__construct($data);

foreach ($data as $index => $value) {
if (is_numeric($index)) { // read
$this->_securityRequirements[array_keys($value)[0]] = new SecurityRequirement(array_values($value)[0]);
} else { // write
$this->_securityRequirements[$index] = $value;
if (is_numeric($index) && $value === []) { # empty Security Requirement Object (`{}`) = anonymous access
$this->_securityRequirements[$index] = [];
continue;
}

if (is_string($index)) {
$this->_securityRequirements[] = [$index => $value instanceof SecurityRequirement ? $value : new SecurityRequirement($value)];
} elseif (is_numeric($index)) {
foreach ($value as $innerIndex => $subValue) {
$this->_securityRequirements[$index][$innerIndex] = $subValue instanceof SecurityRequirement ? $subValue : new SecurityRequirement($subValue);
}
}
}

if ($data === []) {
$this->_securityRequirements = [];
}
Expand Down Expand Up @@ -59,20 +67,50 @@ protected function performValidation()
public function getSerializableData()
{
$data = [];
foreach ($this->_securityRequirements ?? [] as $name => $securityRequirement) {
/** @var SecurityRequirement $securityRequirement */
$data[] = [$name => $securityRequirement->getSerializableData()];

foreach ($this->_securityRequirements ?? [] as $outerIndex => $content) {
if (is_string($outerIndex)) {
$data[] = [$outerIndex => $content->getSerializableData()];
} elseif (is_numeric($outerIndex)) {
if ($content === []) {
$data[$outerIndex] = (object)$content;
continue;
}
$innerResult = [];
foreach ($content as $innerIndex => $innerContent) {
$result = is_object($innerContent) && method_exists($innerContent, 'getSerializableData') ? $innerContent->getSerializableData() : $innerContent;
$innerResult[$innerIndex] = $result;
}
$data[$outerIndex] = (object)$innerResult;
}
}
return $data;
}

public function getRequirement(string $name)
{
return $this->_securityRequirements[$name] ?? null;
return static::searchKey($this->_securityRequirements, $name);
}

public function getRequirements()
{
return $this->_securityRequirements;
}

private static function searchKey(array $array, string $searchKey)
{
foreach ($array as $key => $value) {
if ($key === $searchKey) {
return $value;
}
if (is_array($value)) {
$mt = __METHOD__;
$result = $mt($value, $searchKey);
if ($result !== null) {
return $result; // key found in deeply nested/associative array
}
}
}
return null; // key not found
}
}
28 changes: 28 additions & 0 deletions tests/data/issue/238/spec.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
openapi: 3.0.0
info:
title: Secured API
version: 1.0.0
paths:
/global-secured:
get:
responses:
'200':
description: OK
/path-secured:
get:
security:
- {}
responses:
'200':
description: OK
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
BearerAuth:
type: http
scheme: bearer
security:
- ApiKeyAuth: []
41 changes: 41 additions & 0 deletions tests/data/issue/242/spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"openapi": "3.0.0",
"info": {
"title": "My API",
"version": "1, 2"
},
"paths": {
"/v1/users/profile": {
"get": {
"operationId": "V1GetUserProfile",
"summary": "Returns the user profile",
"responses": {
"200": {
"description": "dummy"
}
},
"security": [
{
"test_test": ["test:scope:foo"]
}
]
}
}
},
"components": {
"securitySchemes": {
"test_test": {
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": "https://example.com/openid-connect/auth",
"tokenUrl": "https://example.com/openid-connect/token",
"scopes": {
"test:scope:foo": "test_scope"
}
}
}
}
}
}
}
45 changes: 45 additions & 0 deletions tests/data/issue/242/spec2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"openapi": "3.0.0",
"info": {
"title": "API Documentation",
"description": "All API endpoints are presented here.",
"version": "1.0.0"
},
"servers": [
{
"url": "http://127.0.0.1:8080/"
}
],
"paths": {
"/endpoint": {
"get": {
"responses": {
"200": {
"description": "OK"
}
},
"security": [
{
"apiKey": [],
"bearerAuth": []
}
]
}
}
},
"components": {
"securitySchemes": {
"apiKey": {
"type": "apiKey",
"in": "header",
"name": "X-APi-Key"
},
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "JWT Authorization header using the Bearer scheme."
}
}
}
}
31 changes: 31 additions & 0 deletions tests/data/issue/242/spec2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# https://github.com/cebe/php-openapi/issues/242#issuecomment-2886431173
openapi: 3.0.0
info:
title: API Documentation
description: All API endpoints are presented here.
version: 1.0.0
servers:
- url: http://127.0.0.1:8080/

paths:

/endpoint:
get:
responses:
'200':
description: OK
security:
- apiKey: []
bearerAuth: []
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-APi-Key
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: JWT Authorization header using the Bearer scheme.

137 changes: 137 additions & 0 deletions tests/issues/238/Issue238Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?php

use cebe\openapi\Reader;
use cebe\openapi\spec\OpenApi;
use cebe\openapi\spec\SecurityRequirements;
use cebe\openapi\Writer;

// https://github.com/cebe/php-openapi/issues/238
class Issue238Test extends \PHPUnit\Framework\TestCase
{
public function test238AddSupportForEmptySecurityRequirementObjectInSecurityRequirementRead()
{
$openapi = Reader::readFromYamlFile(dirname(dirname(__DIR__)).'/data/issue/238/spec.yml');
$this->assertInstanceOf(\cebe\openapi\SpecObjectInterface::class, $openapi);
$this->assertInstanceOf(\cebe\openapi\spec\SecurityRequirements::class, $openapi->paths->getPath('/path-secured')->getOperations()['get']->security);
$this->assertSame(json_decode(json_encode($openapi->paths->getPath('/path-secured')->getOperations()['get']->security->getSerializableData()), true), [[]]);

$openapiJson = Reader::readFromJson(<<<JSON
{
"openapi": "3.0.0",
"info": {
"title": "Secured API",
"version": "1.0.0"
},
"paths": {
"/global-secured": {
"get": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/path-secured": {
"get": {
"security": [
{}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {
"securitySchemes": {
"ApiKeyAuth": {
"type": "apiKey",
"in": "header",
"name": "X-API-Key"
},
"BearerAuth": {
"type": "http",
"scheme": "bearer"
}
}
},
"security": [
{
"ApiKeyAuth": []
}
]
}

JSON
);

$this->assertInstanceOf(\cebe\openapi\SpecObjectInterface::class, $openapiJson);
$this->assertInstanceOf(\cebe\openapi\spec\SecurityRequirements::class, $openapiJson->paths->getPath('/path-secured')->getOperations()['get']->security);
$this->assertSame(json_decode(json_encode($openapiJson->paths->getPath('/path-secured')->getOperations()['get']->security->getSerializableData()), true), [[]]);
}

public function test238AddSupportForEmptySecurityRequirementObjectInSecurityRequirementWrite()
{
$openapi = $this->createOpenAPI([
'security' => new SecurityRequirements([
[]
]),
]);

$yaml = Writer::writeToYaml($openapi);

$this->assertEquals(preg_replace('~\R~', "\n", <<<YAML
openapi: 3.0.0
info:
title: 'Test API'
version: 1.0.0
paths: { }
security:
- { }

YAML
),
$yaml
);

$openapiJson = $this->createOpenAPI([
'security' => new SecurityRequirements([
[]
]),
]);

$json = Writer::writeToJson($openapiJson);

$this->assertEquals(preg_replace('~\R~', "\n", <<<JSON
{
"openapi": "3.0.0",
"info": {
"title": "Test API",
"version": "1.0.0"
},
"paths": {},
"security": [
{}
]
}
JSON
),
$json
);
}

private function createOpenAPI($merge = [])
{
return new OpenApi(array_merge([
'openapi' => '3.0.0',
'info' => [
'title' => 'Test API',
'version' => '1.0.0',
],
'paths' => [],
], $merge));
}
}
Loading