/** * @param \Jose\Object\JWSInterface $jws * @param array $data */ private static function populatePayload(JWSInterface &$jws, array $data) { $is_encoded = null; foreach ($jws->getSignatures() as $signature) { if (null === $is_encoded) { $is_encoded = self::isPayloadEncoded($signature); } Assertion::eq($is_encoded, self::isPayloadEncoded($signature), 'Foreign payload encoding detected. The JWS cannot be loaded.'); } if (array_key_exists('payload', $data)) { $payload = $data['payload']; $jws = $jws->withAttachedPayload(); $jws = $jws->withEncodedPayload($payload); if (false !== $is_encoded) { $payload = Base64Url::decode($payload); } $json = json_decode($payload, true); if (null !== $json && !empty($payload)) { $payload = $json; } $jws = $jws->withPayload($payload); } else { $jws = $jws->withDetachedPayload(); } }
public function it_should_create_configured_connection(ConnectionRegistry $registry) { /** @var Connection $connection */ $connection = $this->createNamed('default')->shouldReturnAnInstanceOf(Connection::class); $registry->addConnection($connection)->shouldHaveBeenCalled(); Assertion::eq($connection->getWrappedConnection()->getVhost(), 'foo'); }
/** * @param \stdClass $obj * @param array $context * @return \Twitter\Object\Tweet */ public function unserialize($obj, array $context = []) { Assertion::true($this->canUnserialize($obj), 'object is not unserializable'); $createdAt = new \DateTimeImmutable($obj->created_at); Assertion::eq(new \DateTimeZone('UTC'), $createdAt->getTimezone()); return Tweet::create(TwitterMessageId::create($obj->id), $this->userSerializer->unserialize($obj->user), $obj->text, $obj->lang, $createdAt, $obj->entities ? $this->twitterEntitiesSerializer->unserialize($obj->entities) : TwitterEntities::create(), $obj->coordinates ? $this->coordinatesSerializer->unserialize($obj->coordinates) : null, $obj->place ? $this->placeSerializer->unserialize($obj->place) : null, $obj->in_reply_to_status_id, $obj->in_reply_to_user_id, $obj->in_reply_to_screen_name, $obj->retweeted, $obj->retweet_count, $obj->favorited, $obj->favorite_count, $obj->truncated, $obj->source, isset($obj->retweeted_status) ? $this->unserialize($obj->retweeted_status) : null); }
/** * @param JWKInterface $key */ private function checkKey(JWKInterface $key) { Assertion::eq($key->get('kty'), 'OKP', 'Wrong key type.'); Assertion::true($key->has('x'), 'The key parameter "x" is missing.'); Assertion::true($key->has('crv'), 'The key parameter "crv" is missing.'); Assertion::inArray($key->get('crv'), ['Ed25519'], 'Unsupported curve'); }
/** * @param \stdClass $obj * @param array $context * @return TwitterEvent */ public function unserialize($obj, array $context = []) { Assertion::true($this->canUnserialize($obj), 'object is not unserializable'); $createdAt = new \DateTimeImmutable($obj->created_at); Assertion::eq(new \DateTimeZone('UTC'), $createdAt->getTimezone()); return TwitterEvent::create($obj->event, $this->userSerializer->unserialize($obj->source), isset($obj->target) ? $this->userSerializer->unserialize($obj->target) : null, isset($obj->target_object) ? $this->targetSerializer->unserialize($obj->target_object) : null, $createdAt); }
/** * @return $this */ public function validate() { $this->rewind(); $firstBytes = fread($this->resource, 1); $this->rewind(); Assertion::eq($firstBytes, "<", "Stream is no valid xml file. Does not start with '<'."); return $this; }
/** * @param \stdClass $directMessage * @param array $context * @return TwitterDirectMessage */ public function unserialize($directMessage, array $context = []) { Assertion::true($this->canUnserialize($directMessage), 'object is not unserializable'); $dm = $directMessage->direct_message; $createdAt = new \DateTimeImmutable($dm->created_at); Assertion::eq(new \DateTimeZone('UTC'), $createdAt->getTimezone()); return TwitterDirectMessage::create(TwitterMessageId::create($dm->id), $this->userSerializer->unserialize($dm->sender), $this->userSerializer->unserialize($dm->recipient), $dm->text, $createdAt, $this->twitterEntitiesSerializer->canUnserialize($dm->entities) ? $this->twitterEntitiesSerializer->unserialize($dm->entities) : TwitterEntities::create()); }
/** * @Then All users with a pending and outdated activation should be removed */ public function allUsersWithAPendingAndOutdatedActivationShouldBeRemoved() { $em = $this->getEntityManager(); for ($i = 0; $i < 2; ++$i) { Assertion::eq(null, $em->getRepository('Account:User')->findOneBy(['username' => (string) $i])); } Assertion::notEq(null, $em->getRepository('Account:User')->findOneBy(['username' => 'foo'])); }
/** * @Then /^the following users should be active:$/ * * @param TableNode $node */ public function checkUserActivity(TableNode $node) { /** @var \AppBundle\Service\Doctrine\Repository\UserRepository $repository */ $repository = $this->getContainer()->get('app.repository.user'); Assertion::eq($response = $this->apiContext->getResponse(), array_combine(array_map(function (array $data) use($repository) : string { return $repository->findOneBy(['username' => $data['username']])->getId(); }, $node->getHash()), array_fill(0, count($response), 1))); }
/** * {@inheritdoc} */ public function checkClaim(JWTInterface $jwt) { if (!$jwt->hasClaim('iss')) { return []; } $issuer = $jwt->getClaim('iss'); Assertion::eq($this->issuer, $issuer, sprintf('The issuer "%s" is not allowed.', $issuer)); return ['iss']; }
/** * @param string $offset * @param TechnicalData $value */ public function offsetSet($offset, $value) { Assertion::isInstanceOf($value, TechnicalData::class); $name = $value->getName(); if (null !== $offset) { Assertion::eq($name, $offset); } $this->data[$name] = $value; }
/** * @param array $data */ private static function checkData(array &$data) { foreach (['scheme', 'host', 'path', 'query'] as $key) { Assertion::keyExists($data, $key, 'Not a valid OTP provisioning URI'); } Assertion::eq('otpauth', $data['scheme'], 'Not a valid OTP provisioning URI'); parse_str($data['query'], $data['query']); Assertion::keyExists($data['query'], 'secret', 'Not a valid OTP provisioning URI'); }
/** * Init. * * @param TwitterMessageId $id * @param TwitterUser $sender * @param string $text * @param TwitterEntities $entities * @param \DateTimeInterface $date */ public function init(TwitterMessageId $id, TwitterUser $sender, $text, TwitterEntities $entities, \DateTimeInterface $date) { Assertion::eq(new \DateTimeZone('UTC'), $date->getTimezone()); $this->entities = $entities; $this->id = $id; $this->sender = $sender; $this->text = $text; $this->date = $date; }
/** * @Then I should see the following result: */ public function iShouldSeeTheFollowingResult(TableNode $table) { foreach ($table->getHash() as $row) { $userId = (int) $row['user_id']; $state = $row['state'] === 'true'; Assertion::keyExists($this->result, $userId); Assertion::eq($state, $this->result[$userId]); } Assertion::eq(count(iterator_to_array($table)), count($this->result)); }
/** * Because your neighbors keep defeating you in the holiday house decorating contest year after year, * you've decided to deploy one million lights in a 1000x1000 grid. * * Furthermore, because you've been especially nice this year, Santa has mailed you instructions * on how to display the ideal lighting configuration. * * Lights in your grid are numbered from 0 to 999 in each direction; * the lights at each corner are at 0,0, 0,999, 999,999, and 999,0. * The instructions include whether to turn on, turn off, or toggle various * inclusive ranges given as coordinate pairs. Each coordinate pair represents * opposite corners of a rectangle, inclusive; a coordinate pair like 0,0 through 2,2 * therefore refers to 9 lights in a 3x3 square. * The lights all start turned off. * * To defeat your neighbors this year, all you have to do is set up your lights * by doing the instructions Santa sent you in order. * * For example: * * - turn on 0,0 through 999,999 would turn on (or leave on) every light. * - toggle 0,0 through 999,0 would toggle the first line of 1000 lights, * turning off the ones that were on, and turning on the ones that were off. * - turn off 499,499 through 500,500 would turn off (or leave off) the middle four lights. * * After following the instructions, how many lights are lit? */ public function lights(string $input, array &$grid = null) : int { $pattern = '/^(?<command>\\w+)(?: (?<value>[\\w-]+))? (?<x1>\\d+),(?<y1>\\d+) through (?<x2>\\d+),(?<y2>\\d+)\\n?$/i'; if ($grid === null) { $grid = $this->createGrid(1000, 1000); } foreach (explode("\n", trim($input)) as $line) { $valid = preg_match($pattern, $line, $matches); Assertion::eq($valid, true, sprintf('Invalid input line: %s', $line)); $instruction = $this->marshallInstruction($matches); $this->execute($grid, ...$instruction); } return $this->count($grid); }
/** * {@inheritdoc} */ public function checkClaim(JWTInterface $jwt) { if (!$jwt->hasClaim('aud')) { return []; } $audience = $jwt->getClaim('aud'); if (is_string($audience)) { Assertion::eq($audience, $this->getAudience(), 'Bad audience.'); } elseif (is_array($audience)) { Assertion::inArray($this->getAudience(), $audience, 'Bad audience.'); } else { throw new \InvalidArgumentException('Bad audience.'); } return ['aud']; }
/** * {@inheritdoc} */ public function checkClaim(JWTInterface $jwt) { if (!$jwt->hasClaim('aud')) { return []; } $audience = $jwt->getClaim('aud'); if (is_string($audience)) { Assertion::eq($audience, $this->audience, sprintf('The audience "%s" is not known.', $audience)); } elseif (is_array($audience)) { Assertion::inArray($this->audience, $audience, sprintf('The audience "%s" is not known.', $audience)); } else { throw new \InvalidArgumentException('The claim "aud" has a bad format'); } return ['aud']; }
/** * @Then I should have an activation email */ public function iShouldHaveAnActivationEmail() { $client = $this->recentClient; /** @var \Symfony\Bundle\SwiftMailerBundle\DataCollector\MessageDataCollector $mailCollector */ $mailCollector = $client->getProfile()->getCollector('swiftmailer'); Assertion::eq(1, $mailCollector->getMessageCount()); /** @var \Swift_Message $message */ $message = $mailCollector->getMessages()[0]; Assertion::eq($message->getSubject(), 'Sententiaregum Notifications'); Assertion::eq(key($message->getTo()), '*****@*****.**'); $crawler = new Crawler(); $crawler->addContent($message->getChildren()[1]->getBody()); Assertion::count($message->getChildren(), 2); Assertion::eq(1, $crawler->filter('#n-ac-l-p')->count()); Assertion::notEq(0, preg_match('/!\\/activate\\/(.*)/', $message->getChildren()[0]->getBody())); }
/** * @Then /^I should've gotten an email$/ */ public function checkEmail() { /** @var \Symfony\Bundle\SwiftmailerBundle\DataCollector\MessageDataCollector $profile */ $profile = $this->apiContext->getProfile()->getCollector('swiftmailer'); Assertion::eq(1, $profile->getMessageCount()); /** @var \Swift_Message $message */ $message = $profile->getMessages()[0]; // user registers as "de", so email should be in german Assertion::eq($message->getSubject(), 'Benachrichtigungen von Sententiaregum'); Assertion::eq(key($message->getTo()), '*****@*****.**'); $crawler = new Crawler(); $crawler->addContent($message->getChildren()[1]->getBody()); Assertion::count($message->getChildren(), 2); Assertion::eq(1, $crawler->filter('#n-ac-l-p')->count()); Assertion::notEq(0, preg_match('/\\/activate\\/(.*)/', $message->getChildren()[0]->getBody())); }
/** * @param \Jose\Object\JWKInterface $key * @param bool $is_private */ private function checkKey(JWKInterface $key, $is_private) { Assertion::true($key->has('x'), 'The key parameter "x" is missing.'); Assertion::true($key->has('crv'), 'The key parameter "crv" is missing.'); switch ($key->get('crv')) { case 'P-256': case 'P-384': case 'P-521': Assertion::eq($key->get('kty'), 'EC', 'Wrong key type.'); Assertion::true($key->has('y'), 'The key parameter "y" is missing.'); break; case 'X25519': Assertion::eq($key->get('kty'), 'OKP', 'Wrong key type.'); break; default: throw new \InvalidArgumentException(sprintf('The curve "%s" is not supported', $key->get('crv'))); } if (true === $is_private) { Assertion::true($key->has('d'), 'The key parameter "d" is missing.'); } }
/** * @Then I should get an error */ public function ensureError() { Assertion::isInstanceOf($this->exception, \RuntimeException::class); Assertion::eq($this->exception->getMessage(), 'Role "ROLE_USER" is not present!'); }
public function testEq() { Assertion::eq(1, "1"); Assertion::eq("foo", true); Assertion::eq($obj = new \stdClass(), $obj); $this->setExpectedException('Assert\\AssertionFailedException', null, Assertion::INVALID_EQ); Assertion::eq("2", 1); }
/** * @param string $url * * @throws \OAuth2\Exception\BadRequestExceptionInterface * * @return string */ private function checkSectorIdentifierUri($url) { $allowed_protocols = ['https']; if (true === $this->allow_http_connections) { $allowed_protocols[] = 'http'; } Assertion::inArray(mb_substr($url, 0, mb_strpos($url, '://', 0, '8bit'), '8bit'), $allowed_protocols, sprintf('The provided sector identifier URI is not valid: scheme must be one of the following: %s.', json_encode($allowed_protocols))); $client = new Client(['verify' => !$this->allow_unsecured_connections]); $response = $client->get($url); Assertion::eq(200, $response->getStatusCode()); $body = $response->getBody()->getContents(); $data = json_decode($body, true); Assertion::isArray($data, 'The provided sector identifier URI is not valid: bad response.'); Assertion::notEmpty($data, 'The provided sector identifier URI is not valid: it must contain at least one URI.'); foreach ($data as $sector_url) { Assertion::url($sector_url, 'The provided sector identifier URI is not valid: it must contain only URIs.'); Assertion::inArray(mb_substr($sector_url, 0, mb_strpos($sector_url, '://', 0, '8bit'), '8bit'), $allowed_protocols, sprintf('An URL provided in the sector identifier URI is not valid: scheme must be one of the following: %s.', json_encode($allowed_protocols))); } }
/** * @Then /^I should have an account with name "(.*)" and locale "(.*)"$/ * * @param string $username * @param string $locale */ public function ensureUserLocale(string $username, string $locale) { $actual = $this->retrieveUserByName($username)->getLocale(); Assertion::eq($locale, $actual, sprintf('User locale ("%s") and actual locale ("%s") don\'t match!', $actual, $locale)); }
/** * @param string $url * * @throws \OAuth2\Exception\BadRequestExceptionInterface * * @return string */ private function downloadContent($url) { $client = new Client(['verify' => !$this->areUnsecuredConnectionsAllowed()]); $response = $client->get($url); Assertion::eq(200, $response->getStatusCode()); $content = $response->getBody()->getContents(); if (!is_string($content)) { throw $this->getExceptionManager()->getBadRequestException(ExceptionManagerInterface::ERROR_INVALID_REQUEST_URI, 'Unable to get content.'); } return $content; }
/** * @param string $kek The Key Encryption Key */ protected static function checkKEKSize($kek) { Assertion::eq(mb_strlen($kek, '8bit'), 32, 'Bad KEK size'); }
/** * @param JWKInterface $key */ protected function checkKey(JWKInterface $key) { Assertion::eq($key->get('kty'), 'oct', 'Wrong key type.'); Assertion::true($key->has('k'), 'The key parameter "k" is missing.'); }
/** * @param \Jose\Object\JWEInterface $jwe * * @return \Jose\Algorithm\ContentEncryptionAlgorithmInterface */ private function getContentEncryptionAlgorithm(Object\JWEInterface $jwe) { $algorithm = null; foreach ($jwe->getRecipients() as $recipient) { $complete_headers = array_merge($jwe->getSharedProtectedHeaders(), $jwe->getSharedHeaders(), $recipient->getHeaders()); Assertion::keyExists($complete_headers, 'enc', 'Parameter "enc" is missing.'); if (null === $algorithm) { $algorithm = $complete_headers['enc']; } else { Assertion::eq($algorithm, $complete_headers['enc'], 'Foreign content encryption algorithms are not allowed.'); } } $content_encryption_algorithm = $this->getJWAManager()->getAlgorithm($algorithm); Assertion::isInstanceOf($content_encryption_algorithm, Algorithm\ContentEncryptionAlgorithmInterface::class, sprintf('The content encryption algorithm "%s" is not supported or not a content encryption algorithm instance.', $algorithm)); return $content_encryption_algorithm; }
/** * @Then the hit count should be :hits */ public function theHitCountShouldBe($hits) { $body = $this->getLastResponse()->json(); Assertion::eq($body['search']['hits'], $hits); }
/** * @param string $pem * @param string[] $matches * @param null|string $password * * @return string */ private static function decodePem($pem, array $matches, $password = null) { Assertion::notNull($password, 'Password required for encrypted keys.'); $iv = pack('H*', trim($matches[2])); $iv_sub = mb_substr($iv, 0, 8, '8bit'); $symkey = pack('H*', md5($password . $iv_sub)); $symkey .= pack('H*', md5($symkey . $password . $iv_sub)); $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $pem); $ciphertext = base64_decode(preg_replace('#-.*-|\\r|\\n#', '', $key)); $decoded = openssl_decrypt($ciphertext, strtolower($matches[1]), $symkey, true, $iv); $number = preg_match_all('#-{5}.*-{5}#', $pem, $result); Assertion::eq($number, 2, 'Unable to load the key'); $pem = $result[0][0] . PHP_EOL; $pem .= chunk_split(base64_encode($decoded), 64); $pem .= $result[0][1] . PHP_EOL; return $pem; }