Failed to generate HMAC with hash: sha256 in Yii app intermittently - yii

Our yii2 app generates this exception intermittently. The issue appears to have generated from the core framework. We are not sure why it occurs intermittently.

$test = #hash_hmac(self::MAC_HASH, '', '', $rawHash);
if (!$test) {
throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . self::MAC_HASH);
}
The fragment of code generating the error. It seems to me its a problem more related with your PHP environment, that doesn't allows to run this native function (hash_hmac). The # is used to avoid exceptions.
This snippet runs on my system with php in interactive mode (php -a in CLI):
var_dump(hash_hmac('sha1', '', '', false));
> string(40) "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d"
var_dump(hash_hmac('sha256', '', '', false));
> string(64) "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"
I'm running Ubuntu 20.04, PHP 7.4.3, hash support enabled. checked with php -i | grep hash.
Hope this give you a hint.

Related

Failing authentication test, using Laravel, phpunit and Homestead

So, I'm trying to test the register and login features on a Laravel 5.8 project, running on Homestead.
My problem is that I can't get the tests (for login and for register) to pass the assertAuthenticated() and assertAuthenticatedAs() functions.
I created the login feature using php artisan make:auth and didn't changed a lot, just created a "username" field to use instead of email.
When I test things like assertStatus(), $this->get(url), everything works fine but when I add the line $this->assertAuthenticatedAs($user) for example, the test crashes.
This is my actual passing function:
public function test_login_valid_user()
{
$user = factory(User::class)->create();
$response = $this->post('/login', [
'username' => $user->username,
'password' => 'secret'
]);
$response->assertStatus(302);
}
If I add the line $this->assertAuthenticatedAs($user) at the end, I get the following error:
There was 1 failure:
1) Tests\Feature\Auth\LoginTest::test_login_valid_user
The current user is not authenticated.
Failed asserting that null is not null.
/home/vagrant/code/my_project/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php:89
/home/vagrant/code/my_project/tests/Feature/Auth/LoginTest.php:39
The same is happening on my register test, after the user is registered, when I try to check $this->assertAuthenticated() I get the same error.
So, I thought about session problems related to Vagrant/Homestead, but I just started to use them and couldn't find any hint about it. And I'm very new to PHPUnit and testing in general, I'm just starting to understand how it works.
The problem is connected with caches.
First of all file phpunit.xml must be read because you need: <server name="APP_ENV" value="testing"/>
Before your tests use command
php artisan config:clear
After that your dump(config('app.env')); will be testing (not local).
Then all works.
I'd been experiencing same problem. For unit tests CSRF token verification should be disabled, but only if you are running under APP_ENV=testing. I though phpunit.xml was overriding my "local" config so it was set to "testing". It was not, because PhpStorm was not reading this file.
If you are using PHPStorm don't forget to check path to default config file - phpunit.xml. (Settings -> Languages&Frameworks -> PHP -> Test frameworks)

Parsoid: Unexpected Token error and failing to initialize

mwApis:
- # This is the only required parameter,
# the URL of you MediaWiki API endpoint.
uri: 'http://spgenerations.com/wiki/api.php'
On my linux box, I can curl this URL and receive the api data.
Regardless of using the apt-get installation or developer installation (ngm install) both instances give me this error:
{"name":"parsoid","hostname":"play.projecttidal.com.KVM","pid":12636,"level":30,"levelPath":"info/service-runner","msg":"master(12636) initializing 2 workers","time":"2019-03-12T03:55:47.504Z","v":0}
{"name":"parsoid","hostname":"play.projecttidal.com.KVM","pid":12645,"level":60,"moduleName":"lib/index.js","levelPath":"fatal/service-runner/worker","msg":"Unexpected token ...","time":"2019-03-12T03:55:47.917Z","v":0}
{"name":"parsoid","hostname":"play.projecttidal.com.KVM","pid":12636,"level":40,"message":"first worker died during startup, continue startup","worker_pid":12645,"exit_code":1,"startup_attempt":1,"levelPath":"warn/service-runner/master","msg":"first worker died during startup, continue startup","time":"2019-03-12T03:55:48.925Z","v":0}
For context, the hostname here is incorrect and the domain has been removed.
This is my parsoid config:
// Parsoid configuration
$wgVirtualRestConfig['modules']['parsoid'] = array(
'url' => 'server.spgenerations.com',
'forwardCookies' => true
);
I have tried everything under the hidden voodoo sun to get this thing to work and I'm beyond frustrated. 4 hours spent tinkering with URL links to no avail, so please, if you know anything relating to this error, lend a hand.
Check what Node.JS version you are running with:
nodejs --version
If it is 4.x: That's too old for Parsoid. I had the same situation (Debian 9, still such an old Node.JS version in the repositories..). After upgrading to 10.x it ran fine for me.
I used the following guide (see Install using a PPA) to update to a newer Node.JS release: https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-debian-9

Using prestashop app from script located outside prestashop folder

I would like to use the prestashop app from a php script (external_script.php) located outside prestashop folder but still on the same server.
I could do that with Magento using :
require_once external_folder/magento/app/Mage.php;
I've tried to include prestashop/config/config.inc.php and prestashop/init.php but it redirects external_script.php to prestashop index.php
Any help would be greatly appreciated.
STEF
Add the following 2 lines at the start of your PHP script and then you can use all the classes and functions of PrestaShop:
include(dirname(__FILE__).'/../../config/config.inc.php');
include(_PS_ROOT_DIR_.'/init.php');
Also, include the main class file whose functions you want to call in the external script, it must be some of your module's file. For example:
include_once(__PATH__TO__CLASS__FILE__.'/xyzmodule.php');
After adding the above codes to include required files you can simply create objects of the class file you want to call and use its code. For example:
$xObj = new Xyzmodule();
$xObj->callingXFunction();
Hope this helps.
Magento is a well structured Zend project and it's easy to bootstrap the app to use it outside HTTP front controller, PrestaShop is another story it's really a big mess of spaghetti code, to bootstrap the app really depends os PS version and in some cases on installed modules that changes core behaviour.
To start you can first include the config/config.inc.php file that is on PS root dir, this will init the PS classloader and a bunch of configuration defines, if you use another autoloader and a old version on PS (<1.6) you need to workaround it, this is a simple bootstrap code that allow make any PS call:
<?php
// Load PS config and autoloader
define ('PS_DIR', __DIR__ . '/../ps-wtf');
require_once PS_DIR .'/config/config.inc.php';
// I use this to load compoper dependencies
require_once __DIR__ . '/../vendor/autoload.php';
// Call old __autoload() if present, required for PrestaShop old versions
if (function_exists('__autoload')) {
spl_autoload_register(function ($className) {
__autoload($className);
});
}
// Init Shop context, required some operation will fail without it
// adust accordly to multistore PS >= 1.6
Shop::setContext(Shop::CONTEXT_ALL);
// Init PS context, some modules require that this context was initialized and with correct data
// some core function fired in the admin require at least a employee
define ('PS_DEFAULT_EMPLOYEE', 1);
$psContext = Context::getContext();
if (!$psContext->employee) {
$psContext->employee = new Employee(PS_DEFAULT_EMPLOYEE);
}
// You can make any API call
$cat = new Category();
$cat->name = [
1 => 'New',
2 => 'Nuevo',
];
$cat->id_parent = 1;
$cat->save();
echo $cat->id;
Some PS functionality depends on correct initialization of some core classes (Yes it's crazy), you can take a look at ControllerCore and FrontControllerCore to see what is happening in the normal PS request flow.
I hope that this can help.
The way prestashop is designed won't let you do this kind of thing easily.
I think your best bet is to use their web service API : http://doc.prestashop.com/display/PS16/Using+the+PrestaShop+Web+Service
There is a PHP client library for this : https://github.com/PrestaShop/PrestaShop-webservice-lib/blob/master/PSWebServiceLibrary.php
You can also use curl, but be warned : they use a lot of different tokens on differents pages, this is quite annoying.
Here is some bash code to log yourself in, grab some tokens and upload an import file. You can adapt it to PHP curl and do anything else you want :
r=$(curl -k -c cookies -b cookies -s --request POST -d "ajax=1&token=&controller=AdminLogin&submitLogin=1&passwd=[YOU_PASSWORD_URL_ENCODED]&email=[YOUR_EMAIl_URL_ENCODED]" 'https://[YOUR_PRESTASHOP_HOST_OR_LOCALHOST]/[YOUR_PRESTASHOP_ADMIN_DIR]/index.php')
token=$(echo $r | sed -n 's/.*token=\([0-9a-zA-Z]*\).*/\1/gp')
admin_token=$(curl -k -c cookies -b cookies 'https://[YOUR_PRESTASHOP_HOST_OR_LOCALHOST]/[YOUR_PRESTASHOP_ADMIN_DIR]/index.php?controller=AdminDashboard&token='"$token" | sed -n '0,/.*?_token=\([-_0-9a-zA-Z]*\).*/s/.*?_token=\([-_0-9a-zA-Z]*\).*/\1/p')
brand_file_name=$(curl -k -c cookies -b cookies -F 'file=#local_path_of_a_file.xlsx' 'https://[YOUR_PRESTASHOP_HOST_OR_LOCALHOST]/[YOUR_PRESTASHOP_ADMIN_DIR]/index.php/configure/advanced/import/file/upload?_token='"$admin_token" | sed -nE 's/.*"name":"([^"]*).*/\1/gp')

Titanium ACS issue

trying to create an ACS server using Titanium Studio. Following the example of pixgrid (https://github.com/appcelerator/pixgrid/), but always get an error when trying to run locally; console output:
[INFO] Installing dependencies...
[INFO] Dependencies installed.
[INFO] socket.io started
[ERROR] Error occurred. TypeError: Cannot call method 'init' of undefined
at Object.start (/app.js:8:7)
app.js listing:
var ACS = require('acs').ACS,
logger = require('acs').logger,
express = require('express'),
partials = require('express-partials');
// initialize app (setup ACS library and logger)
function start(app) {
ACS.init('***', '***');
logger.setLevel('DEBUG');
//use connect.session
app.use(express.cookieParser());
app.use(express.session({ key: 'node.acs', secret: "secret" }));
//set favicon
app.use(express.favicon(__dirname + '/public/images/favicon.ico'));
//set to use express-partial for view
app.use(partials());
//Request body parsing middleware supporting JSON, urlencoded, and multipart
app.use(express.bodyParser());
}
// release resources
function stop() {
}
Ofcourse I have my OATH key and secret at the ***. Same when running from command line (acs run).
I am running Titanium Studio, build 3.4.1.201410281727.
I can however publish the service, and then run it from the cloud without any issues. For development this is not ideal, so want to run it locally (local node.ACS server).
I guess there must be something wrong with where things are installed (only used default), or permissions. Anyone that got a clue how to fix this? Have spent some hours now searching the internet, but seem to be the only one with this exact problem. No clue what else to try.
Thanks for reading this far. If you require more information to help me, let me know.
Ok, I found the problem. They changed the way to use ACS in the last upgrade.
Classic mode was:
var ACS = require('acs').ACS;
ACS.init('<ACS Key>', '<ACS secret');
Now they changed it and ACS is a "module", like any other one, so you must use the new way. In the package.json file add it as a dependecy:
"dependencies": {
"acs-node": ">=0.9.2"
}
Install it: npm install acs-node
Now you can use it in its new format, on the app.js file:
var ACS = require('acs-node');
ACS.init('<App Key>');
It's all explained here: http://docs.appcelerator.com/cloud/latest/#!/guide/node_acs

Behat 2.4 upgrade issues, or Unrecognized options "extensions" under "behat" - error when attempting to activate sahi extension via behat.yml

Fairly new to this Behat stuff, and I've run into a roadblock I can't seem to get around. I've been staring at the docs, googling like it's my job, and doing my best to refrain from tossing my computer off the fire escape.
I'm working with a fairly complex project, and I'm not the one who set it up. So I'm a little lost in some areas.
Currently, I'm trying to use the Sahi driver, because selenium isn't cutting it for some dynamic forms I need to test. I can run the tests fine with the default selenium driver, but the tests fail because it doesn't adequately trigger JavaScript events on form input. Specifically, it'll work with the workarounds covered in that link, but only if I have the browser in focus. Which means it fails when the tests are run in sauce or via jenkins with xvfb.
I'm explaining all this only because this is my larger issue, which I'm attempting to address by using the Sahi driver. Which brings me to:
[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized options "extensions" under "behat"
That's what I get when I try to activate the Sahi driver for a particular profile in my bahat.yml the way the documentation says to.
Here's the default profile and the profile I'm currently working with in my behat.yml (slightly modifies for public consumption):
default:
paths:
features: 'features'
bootstrap: '%behat.paths.features%/bootstrap'
sahi:
extensions:
Behat\MinkExtension\Extension:
sahi: ~
context:
class: 'FeatureContext'
parameters:
environment: 'staging'
mink: 'sahi'
Fwiw, the tests are on a vm, which I ssh -X into, then run the test using
$ behat --tags #test_name_tag --profile=sahi
When I'm using the default selenium driver and the #javascript tag, the browser pops up and the tests run and pass (assuming I keep the browser in focus, of course).
I installed the additional drivers using composer:
{
"require": {
"behat/behat": "2.4.*#stable",
"behat/mink": "1.4#stable",
"behat/mink-extension": "*",
"behat/mink-selenium2-driver": "*",
"behat/mink-sahi-driver": "*"
}
}
I've added use Behat\Mink\Driver\SahiDriver; to my MinkContext.php, EnvironmentContext.php and FeatureContext.php, though I'm guessing that's probably either overkill or not necessary. It doesn't seem to be making a difference at this point, though. I get the same error with or without it.
I also added a sahi.php which lives in features/bootstrap/mink:
<?php
return
array(
'default_session' => 'sahi',
'sahi' => array(
'capabilities' => array(
'browserName' => 'firefox',
'browserVersion' => 7,
),
),
);
I thought maybe adding a directory in features/bootstrap called exensions might help for some reason. Even stuck a file in there called sahi.php. That didn't help much.
I think that covers everything. Thanks in advance for any help, and if this is covered elsewhere, please direct me to it, because I've spent countless hours looking and haven't found anything that helps me.
Update:
I uninstalled the old versions of behat, mink and gherkin, and installed 2.4, et al as per this https://lestbddphp.wordpress.com/2012/08/31/behatcomposer/
I've been making my way through "Migrating from Behat 2.3 to 2.4" in the docs. (Sorry, SO won't let me post any more links, but it's in the official Behat docs.)
My composer.json:
{
"require": {
"behat/behat": "2.4.*#stable",
"behat/mink": "1.4#stable",
"behat/mink-goutte-driver": "*",
"behat/symfony2-extension": "*",
"symfony/class-loader": "2.1.*",
"symfony/form": "2.1.*",
"symfony/validator": "2.1.*",
"behat/mink-selenium-driver": "*",
"behat/mink-selenium2-driver": "*",
"behat/mink-extension": "*",
"behat/mink-sahi-driver": "*"
},
"minimum-stability": "dev",
"config": {
"bin-dir": "bin/"
}
}
I moved my behat.yml file to the root of the project, as directed. I updated my default profile to:
default:
paths:
features: 'features'
bootstrap: '%behat.paths.features%/bootstrap'
extensions:
Behat\Symfony2Extension\Extension:
mink_driver: true
kernel:
env: test
debug: true
Behat\MinkExtension\Extension:
default_session: symfony2
sahi: ~
though I'm not entirely sure that's what I need. Just going by the example given in the docs.
I updated my vendor/autoload.php by replacing the require_once with require:
<?php
// autoload.php generated by Composer
require __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit::getLoader();
but I'm a little confused by this, because that file is different from the example code in the docs. If I were to add the line in the docs here, instead of what was already there, then it would just be loading itself. (I tried. It barfed.) Am I completely dense, or is the wording here confusing/misleading? Did I do this correctly?
As I mentioned before, I have 3 context files in features/bootstrap:
FeatureContext.php
EnvironmentContext.php
MinkContext.php
When running the tests via cli, I pass it a --profile, and then it uses the appropriate profile in behat.yml. In almost all of the profiles, FeatureContext is used.
context:
class: 'FeatureContext'
FeatureContext then gets EnvironmentContext and MinkContext, from what I can tell. So, theoretically, everything should be working there.
Only it's not.
$ bin/behat --profile=sahi
[ReflectionException]
Class AppKernel does not exist
Before I added all the Symfony stuff, I was getting this:
Warning: require(Behat\Symfony2Extension\Extension): failed to open stream: No such file or directory in /path/to/project/vendor/behat/behat/src/Behat/Behat/Extension/ExtensionManager.php on line 112
Fatal error: require(): Failed opening required 'Behat\Symfony2Extension\Extension' (include_path='/usr/share/pear:/usr/share/php:/usr/share/git core/templates/hooks:.') in /path/to/project/vendor/behat/behat/src/Behat/Behat/Extension/ExtensionManager.php on line 112
Which is why I added the Symfony stuff via composer.
Also possibly of note: when I forgot to pass it a --profile, before installing the Symfony stuff via composer, I got this:
Notice: Undefined index: environment in /home/lbaron/development/BeHat-Functional/features/bootstrap/FeatureContext.php on line 43
Warning: include(/path/to/project/features/bootstrap/environment/.php): failed to open stream: No such file or directory in /path/to/project/features/bootstrap/FeatureContext.php on line 44
Warning: include(): Failed opening '/path/to/project/features/bootstrap/environment/.php' for inclusion (include_path='/usr/share/pear:/usr/share/php:/usr/share/git-core/templates/hooks:.') in /path/to/project/features/bootstrap/FeatureContext.php on line 44
Catchable fatal error: Argument 1 passed to EnvironmentContext::__construct() must be an array, boolean given, called in /path/to/project/features/bootstrap/FeatureContext.php on line 44 and defined in /path/to/project/features/bootstrap/EnvironmentContext.php on line 27
Which I guess is to be expected.
So I'm at a loss now. Ideas?
I'm going to keep banging on it to see if I can figure it out, but any ideas/input would be greatly appreciated.
Update again:
Removing the extensions section from yml gives me this:
Catchable fatal error: Argument 2 passed to Symfony\Component\BrowserKit\Client::__construct() must be an instance of Symfony\Component\BrowserKit\History, array given, called in /usr/share/pear/mink/src/Behat/Mink/Behat/Context/MinkContext.php on line 163 and defined in /home/lbaron/development/BeHat-Functional/vendor/symfony/browser-kit/Symfony/Component/BrowserKit/Client.php on line 52
Current state of behat.yml:
default:
paths:
features: 'features'
bootstrap: '%behat.paths.features%/bootstrap'
formatter:
parameters:
language: 'en'
extensions:
Behat\MinkExtension\Extension:
sahi: ~
goutte: ~
You are running a version of behat which is older that 2.4 (the current version). I can tell because the command you use is "behat" instead of "bin/behat". Older versions had a different architecture and did not use extensions. The documentation on the behat.org website is all for the new 2.4 version and, as far as I know, does not have the documentation for older versions available anymore. You should upgrade your behat version to 2.4, there is a guide on how to do this here