Issues (2)

Security Analysis    no request data  

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/ProcessRegistry.php (2 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
 * Defines the ProcessRegistry class which uses MongoDB as a backend.
4
 */
5
6
namespace DominionEnterprises\Cronus;
7
8
/**
9
 * Class that adds/removes from a process registry.
10
 */
11
final class ProcessRegistry
12
{
13
    /** example doc:
14
     * {
15
     *     '_id': 'a unique id',
16
     *     'hosts': {
17
     *         'a hostname' : {
18
     *             'a pid': \MongoDB\BSON\UTCDateTime(expire time),
19
     *             ...
20
     *         },
21
     *         ...
22
     *     },
23
     *     'version' => \MongoDB\BSON\ObjectID(an id),
24
     * }
25
     */
26
27
    const MONGO_INT32_MAX = 2147483647;//2147483648 can overflow in php mongo without using the MongoInt64
28
29
    /**
30
     * Add to process registry. Adds based on $maxGlobalProcesses and $maxHostProcesses after a process registry cleaning.
31
     *
32
     * @param \MongoDB\Collection $collection the collection
33
     * @param string $id a unique id
34
     * @param int $minsBeforeExpire number of minutes before a process is considered expired.
35
     * @param int $maxGlobalProcesses max processes of an id allowed to run across all hosts.
36
     * @param int $maxHostProcesses max processes of an id allowed to run across a single host.
37
     *
38
     * @return boolean true if the process was added, false if not or there is too much concurrency at the moment.
39
     *
40
     * @throws \InvalidArgumentException if $id was not a string
41
     * @throws \InvalidArgumentException if $minsBeforeExpire was not an int
42
     * @throws \InvalidArgumentException if $maxGlobalProcesses was not an int
43
     * @throws \InvalidArgumentException if $maxHostProcesses was not an int
44
     */
45
    public static function add(
46
        \MongoDB\Collection $collection,
47
        $id,
48
        $minsBeforeExpire = PHP_INT_MAX,
49
        $maxGlobalProcesses = 1,
50
        $maxHostProcesses = 1
51
    )
52
    {
53
        if (!is_string($id)) {
54
            throw new \InvalidArgumentException('$id was not a string');
55
        }
56
57
        if (!is_int($minsBeforeExpire)) {
58
            throw new \InvalidArgumentException('$minsBeforeExpire was not an int');
59
        }
60
61
        if (!is_int($maxGlobalProcesses)) {
62
            throw new \InvalidArgumentException('$maxGlobalProcesses was not an int');
63
        }
64
65
        if (!is_int($maxHostProcesses)) {
66
            throw new \InvalidArgumentException('$maxHostProcesses was not an int');
67
        }
68
69
        $thisHostName = self::_getEncodedHostname();
70
        $thisPid = getmypid();
71
72
        //loop in case the update fails its optimistic concurrency check
73
        for ($i = 0; $i < 5; ++$i) {
74
            $collection->findOneAndUpdate(
75
                ['_id' => $id],
76
                ['$setOnInsert' => ['hosts' => [], 'version' => new \MongoDB\BSON\ObjectID()]],
77
                ['upsert' => true]
78
            );
79
            $existing = $collection->findOne(['_id' => $id], ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]);
80
81
            $replacement = $existing;
82
            $replacement['version'] = new \MongoDB\BSON\ObjectID();
83
84
            //clean $replacement based on their pids and expire times
85
            foreach ($existing['hosts'] as $hostname => $pids) {
86
                foreach ($pids as $pid => $expires) {
87
                    //our machine and not running
88
                    //the task expired
89
                    //our machine and pid is recycled (should rarely happen)
90
                    if (
91
                        ($hostname === $thisHostName && !file_exists("/proc/{$pid}"))
92
                        || time() >= $expires->toDateTime()->getTimestamp()
93
                        || ($hostname === $thisHostName && $pid === $thisPid)
94
                    ) {
95
                        unset($replacement['hosts'][$hostname][$pid]);
96
                    }
97
                }
98
99
                if (empty($replacement['hosts'][$hostname])) {
100
                    unset($replacement['hosts'][$hostname]);
101
                }
102
            }
103
104
            $totalPidCount = 0;
105
            foreach ($replacement['hosts'] as $hostname => $pids) {
106
                $totalPidCount += count($pids);
107
            }
108
109
            $thisHostPids = array_key_exists($thisHostName, $replacement['hosts']) ? $replacement['hosts'][$thisHostName] : [];
110
111
            if ($totalPidCount >= $maxGlobalProcesses || count($thisHostPids) >= $maxHostProcesses) {
112
                return false;
113
            }
114
115
            // add our process
116
            $expireSecs = time() + $minsBeforeExpire * 60;
117 View Code Duplication
            if (!is_int($expireSecs)) {
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...
118
                if ($minsBeforeExpire > 0) {
119
                    $expireSecs = self::MONGO_INT32_MAX;
120
                } else {
121
                    $expireSecs = 0;
122
                }
123
            }
124
125
            $thisHostPids[$thisPid] = new \MongoDB\BSON\UTCDateTime($expireSecs * 1000);
126
            $replacement['hosts'][$thisHostName] = $thisHostPids;
127
128
            $status = $collection->replaceOne(
129
                ['_id' => $existing['_id'], 'version' => $existing['version']],
130
                $replacement,
131
                ['writeConcern' => new \MongoDB\Driver\WriteConcern(1, 100, true)]
132
            );
133
            if ($status->getMatchedCount() === 1) {
134
                return true;
135
            }
136
137
            //@codeCoverageIgnoreStart
138
            //hard to test the optimistic concurrency check
139
        }
140
141
        //too much concurrency at the moment, return false to signify not added.
142
        return false;
143
        //@codeCoverageIgnoreEnd
144
    }
145
146
    /**
147
     * Removes from process registry. Does not do anything needed for use of the add() method. Most will only use at the end of their script
148
     * so the mongo collection is up to date.
149
     *
150
     * @param \MongoDB\Collection $collection the collection
151
     * @param string $id a unique id
152
     *
153
     * @return void
154
     *
155
     * @throws \InvalidArgumentException if $id was not a string
156
     */
157
    public static function remove(\MongoDB\Collection $collection, $id)
158
    {
159
        if (!is_string($id)) {
160
            throw new \InvalidArgumentException('$id was not a string');
161
        }
162
163
        $thisHostName = self::_getEncodedHostname();
164
        $thisPid = getmypid();
165
166
        $collection->updateOne(
167
            ['_id' => $id],
168
            ['$unset' => ["hosts.{$thisHostName}.{$thisPid}" => ''], '$set' => ['version' => new \MongoDB\BSON\ObjectID()]]
169
        );
170
    }
171
172
    /**
173
     * Reset a process expire time in the registry.
174
     *
175
     * @param \MongoDB\Collection $collection the collection
176
     * @param string $id a unique id
177
     * @param int $minsBeforeExpire number of minutes before a process is considered expired.
178
     *
179
     * @return void
180
     *
181
     * @throws \InvalidArgumentException if $id was not a string
182
     * @throws \InvalidArgumentException if $minsBeforeExpire was not an int
183
     */
184
    public static function reset(\MongoDB\Collection $collection, $id, $minsBeforeExpire)
185
    {
186
        if (!is_string($id)) {
187
            throw new \InvalidArgumentException('$id was not a string');
188
        }
189
190
        if (!is_int($minsBeforeExpire)) {
191
            throw new \InvalidArgumentException('$minsBeforeExpire was not an int');
192
        }
193
194
        $expireSecs = time() + $minsBeforeExpire * 60;
195 View Code Duplication
        if (!is_int($expireSecs)) {
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...
196
            if ($minsBeforeExpire > 0) {
197
                $expireSecs = self::MONGO_INT32_MAX;
198
            } else {
199
                $expireSecs = 0;
200
            }
201
        }
202
203
        $thisHostName = self::_getEncodedHostname();
204
        $thisPid = getmypid();
205
206
        $collection->updateOne(
207
            ['_id' => $id],
208
            [
209
                '$set' => [
210
                    "hosts.{$thisHostName}.{$thisPid}" => new \MongoDB\BSON\UTCDateTime($expireSecs * 1000),
211
                    'version' => new \MongoDB\BSON\ObjectID(),
212
                ],
213
            ]
214
        );
215
    }
216
217
    /**
218
     * Encodes '.' and '$' to be used as a mongo field name.
219
     *
220
     * @return string the encoded hostname from gethostname().
221
     */
222
    private static function _getEncodedHostname()
223
    {
224
        return str_replace(['.', '$'], ['_DOT_', '_DOLLAR_'], gethostname());
225
    }
226
}
227