Skip to content
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

[SPN-1440] Web Api Documentation Check and Deprecated API Attribute Metric #125

Merged
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
3 changes: 2 additions & 1 deletion src/Checks/ErrorConstants.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ class ErrorConstants {
const TYPE_VARIABLE_FUNCTION_NAME = 'Standard.VariableFunctionCall';
const TYPE_VARIABLE_VARIABLE = 'Standard.VariableVariable';
const TYPE_COUNTABLE_EMPTINESS_CHECK = 'Standard.Countable.Emptiness';
const TYPE_WEB_API_DOCUMENTATION_CHECK = 'Standard.WebApi.Documentation';
const TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_CHECK = 'Standard.OpenApiAttribute.Documentation';
const TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_SEARCH_PHRASES_CHECK = 'Standard.OpenApiAttribute.Documentation.SearchPhrases';
const TYPE_SERVICE_METHOD_DOCUMENTATION_CHECK = 'Standard.ServiceMethod.Documentation';


Expand Down
94 changes: 94 additions & 0 deletions src/Checks/OpenApiAttributeDocumentationCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

namespace BambooHR\Guardrail\Checks;

use BambooHR\Guardrail\Metrics\Metric;
use BambooHR\Guardrail\Metrics\MetricOutputInterface;
use BambooHR\Guardrail\Scope;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassLike;

class OpenApiAttributeDocumentationCheck extends BaseCheck {
private const string ATTRIBUTE_NAMESPACE = 'OpenApi\Attributes';
private const string SEARCH_PHRASES_KEY = 'vector-search-phrases';
private const string DEPRECATED_KEY = 'deprecated';
private const string X_KEY = 'x';

function __construct($index, $output, private readonly MetricOutputInterface $metricOutput) {
parent::__construct($index, $output);
}

/**
* getCheckNodeTypes
*
* @return string[]
*/
function getCheckNodeTypes() {
return [Node\Stmt\ClassMethod::class];
}

/**
* @param string $fileName The name of the file we are parsing
* @param Node $node Instance of the Node
* @param ClassLike|null $inside Instance of the ClassLike (the class we are parsing) [optional]
* @param Scope|null $scope Instance of the Scope (all variables in the current state) [optional]
*
* @return void
*/
public function run($fileName, Node $node, ClassLike $inside = null, Scope $scope = null) {
if ($node instanceof Node\Stmt\ClassMethod && $node->isPublic()) {
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attribute) {
$attributeName = $attribute->name->toString();
if (str_starts_with($attributeName, self::ATTRIBUTE_NAMESPACE)) {
$hasDefinedSearchPhrases = false;
foreach ($attribute->args as $arg) {
$this->checkDeprecatedAttribute($arg, $fileName, $node);
$hasDefinedSearchPhrases = $hasDefinedSearchPhrases ?: $this->hasVectorSearchPhrase($arg);
}
if (!$hasDefinedSearchPhrases) {
$this->emitErrorOnLine(
$fileName,
$node->getLine(),
ErrorConstants::TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_SEARCH_PHRASES_CHECK,
"OpenAPI Attribute must have a vector-search-phrases key defined. Method: {$node->name->name}"
);
}
return;
}
}
}
$className = $inside->namespacedName->toString();
$this->emitErrorOnLine(
$fileName,
$node->getLine(),
ErrorConstants::TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_CHECK,
"All public controller methods should be associated with a route and must have
documentation through an OpenAPI Attribute. Method: {$node->name->name}, Class: $className"
);
}
}

private function checkDeprecatedAttribute($arg, $fileName, $node) {
if ($arg->name->name === self::DEPRECATED_KEY && $arg->value->name->toString() == 'true') {
$this->metricOutput->emitMetric(new Metric(
$fileName,
$node->getLine(),
ErrorConstants::TYPE_METRICS_DEPRECATED_FUNCTIONS,
[]
));
}
}

private function hasVectorSearchPhrase($arg): bool {
if ($arg->name->name === self::X_KEY && $arg->value instanceof Node\Expr\Array_) {
foreach ($arg->value->items as $item) {
if ($item->key->value === self::SEARCH_PHRASES_KEY) {
return true;
}
}
}

return false;
}
}
4 changes: 2 additions & 2 deletions src/NodeVisitors/StaticAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
use BambooHR\Guardrail\Checks\UnsafeSuperGlobalCheck;
use BambooHR\Guardrail\Checks\UnusedPrivateMemberVariableCheck;
use BambooHR\Guardrail\Checks\UseStatementCaseCheck;
use BambooHR\Guardrail\Checks\WebApiDocumentationCheck;
use BambooHR\Guardrail\Checks\OpenApiAttributeDocumentationCheck;
use BambooHR\Guardrail\Config;
use BambooHR\Guardrail\Evaluators as Ev;
use BambooHR\Guardrail\Evaluators\ExpressionInterface;
Expand Down Expand Up @@ -159,7 +159,7 @@ function __construct(SymbolTable $index, OutputInterface $output, MetricOutputIn
new ThrowsCheck($this->index, $output),
new CountableEmptinessCheck($this->index, $output),
new DependenciesOnVendorCheck($this->index, $output, $metricOutput),
new WebApiDocumentationCheck($this->index, $output, $metricOutput),
new OpenApiAttributeDocumentationCheck($this->index, $output, $metricOutput),
new ServiceMethodDocumentationCheck($this->index, $output, $metricOutput),
//new ClassStoredAsVariableCheck($this->index, $output)
];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
use OpenApi\Attributes as OA;


class MyController {
/**
* @return bool
*/
#[\Onsen\SecurityAudit\Sensitivity\Low]
#[OA\Get(path: "/test")]
public function hasAttribute() {
return false;
}

/**
* @return int
*/
public function doesNotHaveAttribute() {
return 123;
}

/**
* @return int
*/
#[\Onsen\SecurityAudit\Sensitivity\Low]
public function hasFakeAttribute() {
return 456;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php
use OpenApi\Attributes as OA;

class MyController {
function undefinedVisibilityMethod() {
return false;
}
public function publicMethod() {
return false;
}
protected function protectedMethod() {
return false;
}
private function privateMethod() {
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php
use OpenApi\Attributes as OA;


class MyController {
/**
* @return bool
*/
#[OA\Get(path: "/test", deprecated: true)]
public function hasDeprecatedAttribute() {
return false;
}

#[OA\Get(path: "/test")]
public function doesNotHaveDeprecatedAttribute() {
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php
use OpenApi\Attributes as OA;


class MyController {
#[OA\Get(path: "/test")]
public function withoutSearchPhrases() {
return false;
}

#[OA\Get(path: "/test", x: ['vector-search-phrases' => []])]
public function withEmptySearchPhrases() {
return false;
}

#[OA\Get(path: "/test", x: ['vector-search-phrases' => ['my test search phrase']])]
public function withSearchPhrases() {
return false;
}
}
39 changes: 39 additions & 0 deletions tests/units/Checks/TestOpenApiAttributeDocumentationCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace BambooHR\Guardrail\Tests\units\Checks;

use BambooHR\Guardrail\Checks\ErrorConstants;
use BambooHR\Guardrail\Tests\TestSuiteSetup;

class TestOpenApiAttributeDocumentationCheck extends TestSuiteSetup {
/**
* testApiAttributeIsPresent
*
* @return void
*/
public function testApiAttributeIsPresent() {
$this->assertEquals(2, $this->runAnalyzerOnFile('.1.inc', ErrorConstants::TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_CHECK), "");
}

/**
* @return void
*/
public function testOnlyErrorsOnPublicMethods() {
$this->assertEquals(2, $this->runAnalyzerOnFile('.2.inc', ErrorConstants::TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_CHECK), "");
}

/**
* @return void
*/
public function testMethodWithDeprecatedAttribute() {
$output = $this->getOutputFromAnalyzer('.3.inc', ErrorConstants::TYPE_METRICS_DEPRECATED_FUNCTIONS);
$this->assertEquals(1, $this->getMetricCountByName($output, ErrorConstants::TYPE_METRICS_DEPRECATED_FUNCTIONS));
}

/**
* @return void
*/
public function testWithAndWithoutVectorSearchPhrases() {
$this->assertEquals(1, $this->runAnalyzerOnFile('.4.inc', ErrorConstants::TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_SEARCH_PHRASES_CHECK), "");
}
}
2 changes: 1 addition & 1 deletion tests/units/Checks/TestTemplates.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class TestTemplates extends TestSuiteSetup {
function testValidTemplate() {
$this->assertEquals(0, $this->runAnalyzerOnFile('.1.inc', "Standard.*", [
"ignore-errors" => [
"Standard.Autoload.Unsafe", ErrorConstants::TYPE_WEB_API_DOCUMENTATION_CHECK,
"Standard.Autoload.Unsafe", ErrorConstants::TYPE_OPEN_API_ATTRIBUTE_DOCUMENTATION_CHECK,
ErrorConstants::TYPE_SERVICE_METHOD_DOCUMENTATION_CHECK,
]
]));
Expand Down