Issues (126)

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/Db/MongoFileService.php (4 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
declare(strict_types=1);
3
/**
4
 * Minotaur
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7
 * use this file except in compliance with the License. You may obtain a copy of
8
 * the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
 * License for the specific language governing permissions and limitations under
16
 * the License.
17
 *
18
 * @copyright 2015-2017 Appertly
19
 * @license   Apache-2.0
20
 */
21
namespace Minotaur\Db;
22
23
use MongoDB\Driver\ReadPreference;
24
use MongoDB\BSON\ObjectID;
25
use MongoDB\GridFS\Bucket;
26
use Psr\Http\Message\StreamInterface;
27
use Psr\Http\Message\UploadedFileInterface;
28
29
/**
30
 * File upload service backed by GridFS.
31
 *
32
 * Requires the `mongodb/mongodb` composer package to be installed.
33
 */
34
class MongoFileService implements \Minotaur\Io\FileService
35
{
36
    use MongoHelper;
37
38
    /**
39
     * @var \MongoDB\GridFS\Bucket
40
     */
41
    private $bucket;
42
43
    /**
44
     * Creates a new MongoFileService
45
     *
46
     * @param $bucket - The GridFS Bucket
47
     */
48 2
    public function __construct(Bucket $bucket)
49
    {
50 2
        $this->bucket = $bucket;
51 2
    }
52
53
    /**
54
     * Stores an uploaded file.
55
     *
56
     * You should specify `contentType` in the `metadata` Map.
57
     *
58
     * @param \Psr\Http\Message\UploadedFileInterface $file The uploaded file
59
     * @param array<string,mixed> $metadata Any additional fields to persist. At the very least, try to supply `contentType`.
60
     * @return ObjectID The document ID of the stored file
61
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
62
     * @throws \Caridea\Dao\Exception\Violating If a constraint is violated
63
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
64
     */
65 1
    public function store(UploadedFileInterface $file, array $metadata): ObjectID
66
    {
67
        $meta = [
68 1
            "contentType" => $metadata['contentType'] ?? $file->getClientMediaType(),
69 1
            'metadata' => $metadata
70
        ];
71 1
        return $this->bucket->uploadFromStream(
72 1
            $file->getClientFilename(),
73 1
            $file->getStream()->detach(),
74 1
            $meta
75
        );
76
    }
77
78
    /**
79
     * Gets the file as a PSR-7 Stream.
80
     *
81
     * @param $id - The document identifier, either a string or `ObjectID`
82
     * @return \Psr\Http\Message\StreamInterface The readable stream
83
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
84
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
85
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
86
     */
87
    public function messageStream($id): StreamInterface
88
    {
89
        $file = $this->read($id);
90
        $collectionWrapper = $this->getCollectionWrapper($this->bucket);
91
        return new MongoDownloadStream(
92
            new \MongoDB\GridFS\ReadableStream($collectionWrapper, $file)
0 ignored issues
show
It seems like $file defined by $this->read($id) on line 89 can be null; however, MongoDB\GridFS\ReadableStream::__construct() 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...
93
        );
94
    }
95
96
    /**
97
     * Gets a readable stream resource for the given ID.
98
     *
99
     * @param $id - The document identifier, either a string or `ObjectID`
100
     * @return resource The readable stream
101
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
102
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
103
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
104
     */
105
    public function resource($id)
106
    {
107
        return $this->bucket->openDownloadStream($id instanceof ObjectID ? $id : new ObjectID((string) $id));
0 ignored issues
show
The class MongoDB\BSON\ObjectID does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
108
    }
109
110
    /**
111
     * Efficiently writes the contents of a file to a Stream.
112
     *
113
     * @param \stdClass $file The file
114
     * @param \Psr\Http\Message\StreamInterface $stream The stream
115
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
116
     * @throws \Caridea\Dao\Exception\Violating If a constraint is violated
117
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
118
     */
119
    public function stream($file, StreamInterface $stream): void
120
    {
121
        if (!is_object($file)) {
122
            throw new \InvalidArgumentException("Expected object, got: " . gettype($file));
123
        }
124
        $this->bucket->downloadToStream(
125
            $file->_id,
126
            \Labrys\Io\StreamWrapper::getResource($stream)
127
        );
128
    }
129
130
    /**
131
     * Gets a stored file.
132
     *
133
     * @param mixed $id The document identifier, either a string or `ObjectID`
134
     * @return \stdClass|null The stored file, or `null`
135
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
136
     * @throws \Caridea\Dao\Exception\Unretrievable If the result cannot be retrieved
137
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
138
     */
139 1
    public function read($id): ?\stdClass
140
    {
141 1
        $mid = $this->toId($id);
142 1
        return $this->doExecute(function (Bucket $bucket) use ($mid) {
143 1
            return $this->getCollectionWrapper($bucket)->findFileById($mid);
144 1
        });
145
    }
146
147
    /**
148
     * Deletes a stored file.
149
     *
150
     * @param mixed $id The document identifier, either a string or `ObjectID`
151
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
152
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
153
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
154
     */
155
    public function delete($id): void
156
    {
157
        $mid = $this->toId($id);
158
        $this->doExecute(function (Bucket $bucket) use ($mid) {
159
            $bucket->delete($mid);
160
        });
161
    }
162
163
    /**
164
     * Finds several files by some arbitrary criteria.
165
     *
166
     * @param array<string,mixed> $criteria Field to value pairs
167
     * @return Traversable<\stdClass> The objects found
0 ignored issues
show
The doc-type Traversable<\stdClass> could not be parsed: Expected "|" or "end of type", but got "<" at position 11. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
168
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
169
     * @throws \Caridea\Dao\Exception\Unretrievable If the result cannot be retrieved
170
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
171
     */
172
    public function readAll(array $criteria): \Traversable
173
    {
174
        $readPreference = new ReadPreference(ReadPreference::RP_PRIMARY);
175
        return $this->doExecute(function (Bucket $bucket) use ($criteria, $readPreference) {
176
            return $bucket->find(
177
                $criteria,
178
                ['sort' => ['filename' => 1], 'readPreference' => $readPreference]
179
            );
180
        });
181
    }
182
183
    /**
184
     * Executes something in the context of the collection.
185
     *
186
     * Exceptions are caught and translated.
187
     *
188
     * @param callable $cb The closure to execute, takes the Bucket.
189
     * @return - Whatever the function returns, this method also returns
0 ignored issues
show
The doc-type - could not be parsed: Unknown type name "-" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
190
     * @throws \Caridea\Dao\Exception If a database problem occurs
191
     */
192 1
    protected function doExecute(callable $cb)
193
    {
194
        try {
195 1
            return $cb($this->bucket);
196
        } catch (\Exception $e) {
197
            throw \Caridea\Dao\Exception\Translator\MongoDb::translate($e);
198
        }
199
    }
200
201
    /**
202
     * @return \MongoDB\GridFS\CollectionWrapper
203
     */
204 1
    private function getCollectionWrapper(Bucket $b)
205
    {
206 1
        $p = new \ReflectionProperty(Bucket::class, 'collectionWrapper');
207 1
        $p->setAccessible(true);
208 1
        return $p->getValue($b);
209
    }
210
}
211