Issues (35)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Adapter.php (8 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace As3\Modlr\Api\JsonApiOrg;
4
5
use As3\Modlr\Api\AbstractAdapter;
6
use As3\Modlr\Api\AdapterException;
7
use As3\Modlr\Metadata\EntityMetadata;
8
use As3\Modlr\Rest;
9
10
/**
11
 * Adapter for handling API operations using the JSON API specification.
12
 *
13
 * @author Jacob Bare <[email protected]>
14
 */
15
final class Adapter extends AbstractAdapter
16
{
17
    /**
18
     * {@inheritDoc}
19
     */
20
    public function buildUrl(EntityMetadata $metadata, $identifier, $relFieldKey = null, $isRelatedLink = false)
21
    {
22
        $url = sprintf('%s://%s%s/%s/%s',
23
            $this->config->getScheme(),
24
            $this->config->getHost(),
25
            $this->config->getRootEndpoint(),
26
            $metadata->type,
27
            $identifier
28
        );
29
30
        if (null !== $relFieldKey) {
31
            if (false === $isRelatedLink) {
32
                $url .= '/relationships';
33
            }
34
            $url .= sprintf('/%s', $relFieldKey);
35
        }
36
        return $url;
37
    }
38
39
    /**
40
     * {@inheritDoc}
41
     */
42
    public function processRequest(Rest\RestRequest $request)
43
    {
44
        $this->request = $request;
45
        switch ($request->getMethod()) {
46
            case 'GET':
47
                return $this->handleGetRequest($request);
48 View Code Duplication
            case 'POST':
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
49
                // @todo Must validate JSON content type
50
                if (false === $request->hasIdentifier()) {
51
                    if (true === $request->hasPayload()) {
52
                        return $this->createRecord($request->getEntityType(), $request->getPayload(), $request->getFieldset(), $request->getInclusions());
0 ignored issues
show
It seems like $request->getPayload() can be null; however, createRecord() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
The call to Adapter::createRecord() has too many arguments starting with $request->getFieldset().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
53
                    }
54
                    throw AdapterException::requestPayloadNotFound('Unable to create new entity.');
55
                }
56
                throw AdapterException::badRequest('Creating a new record while providing an id is not supported.');
57 View Code Duplication
            case 'PATCH':
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
                // @todo Must validate JSON content type
59
                if (false === $request->hasIdentifier()) {
60
                    throw AdapterException::badRequest('No identifier found. You must specify an ID in the URL.');
61
                }
62
                if (false === $request->hasPayload()) {
63
                    throw AdapterException::requestPayloadNotFound('Unable to update entity.');
64
                }
65
                return $this->updateRecord($request->getEntityType(), $request->getIdentifier(), $request->getPayload(), $request->getFieldset(), $request->getInclusions());
0 ignored issues
show
It seems like $request->getPayload() can be null; however, updateRecord() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
The call to Adapter::updateRecord() has too many arguments starting with $request->getFieldset().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
66
            case 'DELETE':
67
                if (false === $request->hasIdentifier()) {
68
                    throw AdapterException::badRequest('No identifier found. You must specify an ID in the URL.');
69
                }
70
                return $this->deleteRecord($request->getEntityType(), $request->getIdentifier());
71
                throw AdapterException::badRequest('No DELETE request handler found.');
0 ignored issues
show
throw \As3\Modlr\Api\Ada...quest handler found.'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
72
            default:
73
                throw AdapterException::badRequest(sprintf('The request method "%s" is not supported.', $request->getMethod()));
74
        }
75
    }
76
77
    /**
78
     * {@inheritDoc}
79
     */
80
    protected function createRestResponse($status, Rest\RestPayload $payload = null)
81
    {
82
        $restResponse = new Rest\RestResponse($status, $payload);
83
        $restResponse->addHeader('content-type', 'application/json');
84
        return $restResponse;
85
    }
86
87
    /**
88
     * Validates that the payload type key matches the endpoint type key.
89
     * Also handles proper type keys for polymorphic endpoints.
90
     *
91
     * @param   string  $payloadTypeKey
92
     * @param   string  $endpointTypeKey
93
     * @throws  AdpaterException
94
     */
95
    protected function validatePayloadType($payloadTypeKey, $endpointTypeKey)
96
    {
97
        $metadata = $this->getStore()->getMetadataForType($endpointTypeKey);
98
99
        if (false === $metadata->isPolymorphic() && $payloadTypeKey === $endpointTypeKey) {
100
            return;
101
        }
102
103
        if (true === $metadata->isPolymorphic() && in_array($payloadTypeKey, $metadata->ownedTypes)) {
104
            return;
105
        }
106
        $expected = (true === $metadata->isPolymorphic()) ? implode(', ', $metadata->ownedTypes) : $endpointTypeKey;
107
        throw AdapterException::badRequest(sprintf('The payload "type" member does not match the API endpoint. Expected one of "%s" but received "%s"', $expected, $payloadTypeKey));
108
    }
109
110
    /**
111
     * {@inheritDoc}
112
     */
113
    protected function validateCreatePayload($typeKey, array $normalized)
114
    {
115
        if (isset($normalized['id'])) {
116
            throw AdapterException::badRequest('An "id" member was found in the payload. Client-side ID generation is currently not supported.');
117
        }
118
119
        if (!isset($normalized['type'])) {
120
            throw AdapterException::badRequest('An "type" member was found in the payload. All creation payloads must contain the model type.');
121
        }
122
123
        $this->validatePayloadType($normalized['type'], $typeKey);
124
        return $normalized;
125
    }
126
127
    /**
128
     * {@inheritDoc}
129
     */
130
    protected function validateUpdatePayload($typeKey, $identifier, array $normalized)
131
    {
132
        // @todo Does the type still need to be validated here? Yes, most likely - need to compare the endpoint versus the type.
133
        if (!isset($normalized['id'])) {
134
            throw AdapterException::badRequest('No "id" member was found in the payload.');
135
        }
136
        if ($identifier !== $normalized['id']) {
137
            throw AdapterException::badRequest('The request URI id does not match the payload id.');
138
        }
139
        if (!isset($normalized['type'])) {
140
            throw AdapterException::badRequest('An "type" member was found in the payload. All creation payloads must contain the model type.');
141
        }
142
        $this->validatePayloadType($normalized['type'], $typeKey);
143
144
        return $normalized;
145
    }
146
147
    /**
148
     * Handles a GET request.
149
     *
150
     * @param   Rest\RestRequest     $request
151
     * @return  Rest\RestResponse
152
     * @throws  AdapterException
153
     */
154
    private function handleGetRequest(Rest\RestRequest $request)
155
    {
156
        if (true === $request->hasIdentifier()) {
157
            if (false === $request->isRelationship() && false === $request->hasFilters()) {
158
                return $this->findRecord($request->getEntityType(), $request->getIdentifier());
159
            }
160
            if (true === $request->isRelationshipRetrieve()) {
161
                return $this->findRelationship($request->getEntityType(), $request->getIdentifier(), $request->getRelationshipFieldKey());
162
            }
163
            throw AdapterException::badRequest('No GET handler found.');
164
        } else {
165
            if (true === $request->isAutocomplete()) {
166
                // @todo Eventually add pagination (limit/skip)
167
                return $this->autocomplete($request->getEntityType(), $request->getAutocompleteKey(), $request->getAutocompleteValue());
168
            }
169
            if (true === $request->isQuery()) {
170
                return $this->findQuery($request->getEntityType(), $request->getQueryCriteria(), $request->getFieldset(), $request->getSorting(), $request->getPagination(), $request->getInclusions());
171
            }
172
            return $this->findAll($request->getEntityType(), [], $request->getFieldset(), $request->getSorting(), $request->getPagination(), $request->getInclusions());
173
        }
174
        throw AdapterException::badRequest('No GET handler found.');
0 ignored issues
show
throw \As3\Modlr\Api\Ada...o GET handler found.'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
175
    }
176
177
}
178