Cakephp get details about security component error - security

I am using security component in my projects and is there any way to get the detailed description about the error while developing ? For ex:- if any field is added in view without using cakephp's form method, it is returning error as 'auth' in my blackHoleCallback function. Instead I need beacuse of what reason it returned that error. Because it is taking so much time to rectify the problem. Is there any way to get the detailed error description ?

All you have to do is look in the right place
Check your app/tmp/logs/error.log file
If you look in the error log you'll see an entry like this:
2013-03-16 17:24:29 Error: [BadRequestException] The request has been black-holed
#0 root/lib/Cake/Controller/Component/SecurityComponent.php(228): SecurityComponent->blackHole(Object(FacebookUsersController), 'csrf')
#1 [internal function]: SecurityComponent->startup(Object(FacebookUsersController))
#2 root/lib/Cake/Utility/ObjectCollection.php(130): call_user_func_array(Array, Array)
#3 [internal function]: ObjectCollection->trigger(Object(CakeEvent))
#4 root/lib/Cake/Event/CakeEventManager.php(246): call_user_func(Array, Object(CakeEvent))
#5 root/lib/Cake/Controller/Controller.php(670): CakeEventManager->dispatch(Object(CakeEvent))
#6 root/lib/Cake/Routing/Dispatcher.php(183): Controller->startupProcess()
#7 root/lib/Cake/Routing/Dispatcher.php(161): Dispatcher->_invoke(Object(FacebookUsersController), Object(CakeRequest), Object(CakeResponse))
#8 root/app/webroot/index.php(96): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
#9 {main}
Read the error that is on screen
If you are in debug mode, this error is also shown on screen when the error happens. e.g.:
The request has been black-holed
Error: The requested address '/admin/fooby/edit/1' was not found on this server.
Stack Trace
CORE/Cake/Controller/Component/SecurityComponent.php line 228 → SecurityComponent->blackHole(FacebookUsersController, string)
[internal function] → SecurityComponent->startup(FacebookUsersController)
CORE/Cake/Utility/ObjectCollection.php line 130 → call_user_func_array(array, array)
[internal function] → ObjectCollection->trigger(CakeEvent)
CORE/Cake/Event/CakeEventManager.php line 246 → call_user_func(array, CakeEvent)
CORE/Cake/Controller/Controller.php line 670 → CakeEventManager->dispatch(CakeEvent)
CORE/Cake/Routing/Dispatcher.php line 183 → Controller->startupProcess()
CORE/Cake/Routing/Dispatcher.php line 161 → Dispatcher->_invoke(FacebookUsersController, CakeRequest, CakeResponse)
APP/webroot/index.php line 96 → Dispatcher->dispatch(CakeRequest, CakeResponse)
Handling csrf errors
With the details of a specific error (i.e. the data you are posting, and the exact token data in your session at the time) it would be possible to answer what problem brought you here, in the absense of that:
look at the line throwing the error.
In the stack trace above, the error is coming from CORE/Cake/Controller/Component/SecurityComponent.php line 228 - Open the file and look what that code is:
if ($isPost && $isNotRequestAction && $this->csrfCheck) {
if ($this->_validateCsrf($controller) === false) {
return $this->blackHole($controller, 'csrf');
}
}
What should be obvious from this is that the function _validateCsrf is responsible for the request being blackholed. This should not really be much of a surprise.
Look at the source of that function:
protected function _validateCsrf(Controller $controller) {
$token = $this->Session->read('_Token');
$requestToken = $controller->request->data('_Token.key');
if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
if ($this->csrfUseOnce) {
$this->Session->delete('_Token.csrfTokens.' . $requestToken);
}
return true;
}
return false;
}
Depending on why that function returns false, determines how you continue to debug.
Correct configuration of the component
The inevitable consequence of debugging a CSRF error is you'll need to modify the configuration of the Security component.
Do you, for example, want to be reusing tokens, because your app is submitting the same form multiple times between page loads?
Are you self-invalidating the form requests by adding new fields to the form data - You can use the unlockedFields property to exclude these fields from the csrf checks.
You can also simply disable CSRF checks completey. That has obvious security consequences - but if you're struggling to work with the component, it's an easy way to work around and problems you currently face.

In order to see the mechanisms I dug into the code to see how the FormHelper hash is created vs. how the SecurityComponent validation checks the hash. Here's how to see exactly what is happening behind the scenes.
Checking the input to the FormHelper. Open CORE/Cake/View/Helper/FormHelper.php. In the secure() function add some pr lines around the $files=Security::hash line to see how the tokens are built:
pr($fields);//hashed into computed token on next line
$fields = Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt'), 'sha1');
pr($unlocked); //hashed into computed token
pr(Configure::read('Security.salt')); //hashed into computed token
pr($fields); //computed token passed via hidden token field in form
Check how form is processed
Now check how the submitted form is processed and compared to the passed token:
Open the CORE/Cake/Controller/Component/SecurityComponent.php. Insert some pr lines in the _validatePost() routine at the end:
pr($fieldList); //hashed into computed token
pr($unlocked); //hashed into computed token
pr(Configure::read('Security.salt')); //hashed into computed token
pr($token); //passed token from FormHelper
pr($check); //computed token
Hopefully this helps someone else who has problems with locked/unlocked or missing fields quickly figure out what is going on inside of your cake.

Remember also that you have to have an exact match between the Token generated by the FormHelper and that retrieved bu cake using Session. The mismatch can happen, as the doc says, when you dynamically generate input or when make ajax call: remember to serialize the form and submit it via ajax!
If you have input tag generated not generated by using the FormHelper, you have to unlock'em. For example in your beforeFilter():
$this->Security->unlockedFields =
array('MyModel.some_field1','MyModel.some_field2')
where field1 and field2 are fields generated "by hand", i.e. by not using the Helper.

To answer the question: "Is there any way to get the detailed error description?"
First thing is to add more valuable debugging to your controller when it comes to SecurityComponent. Here's one way to do it:
public function beforeFilter() {
parent::beforeFilter();
//your beforeFilter code
//Enable CSRF and other protections
$this->Security->csrfExpires = '+1 hour';
$this->Security->csrfUseOnce = true;
$this->Security->blackHoleCallback = 'blackhole';
}
public function blackhole($errorType) {
$errorMap['auth'] = 'form validation error, or a controller/action mismatch error.';
$errorMap['csrf'] = 'CSRF error.';
$errorMap['get'] = 'HTTP method restriction failure.';
$errorMap['post'] = $errorMap['get'];
$errorMap['put'] = $errorMap['get'];
$errorMap['delete'] = $errorMap['get'];
$errorMap['secure'] = 'SSL method restriction failure.';
$errorMap['myMoreValuableErrorType'] = 'My custom and very ' .
'specific reason for the error type.';
CakeLog::notice("Request to the '{$this->request->params['action']}' " .
"endpoint was blackholed by SecurityComponent due to a {$errorMap[$errorType]}");
}
As AD7six mentioned take a look at the CORE/Cake/Controller/Component/SecurityComponent.php. Specifically SecurityComponent::startup(). In that method you will notice that SecurityComponent::blackhole() method is ran a few times. It's ran whenever the criteria fails a security check and looks like this:
return $this->blackHole($controller, 'auth');
In this case 'auth' represents the type of security check that failed. You could customize the 'auth' string to be more valuable. For example instead of 'auth' use 'myMoreValuableErrorType' and then map that to something more meaningful.
So instead of running $this->blackHole($controller, 'auth') when a security check fails, you would run $this->blackHole($controller, 'myMoreValuableErrorType') and then map 'myMoreValuableErrorType' to a specific reason on why it failed by using the code above.

Related

Why do I fail to submit data to textarea with python requests.post()

I want to use the requests.post tool to automatically query domain name attribution on this websitea website,But the return value is always empty, I guess it is because the post method failed to transfer the data to the textarea
url = 'http://icp.chinaz.com/searchs'
data = {
'hosts':'qq.com',
'btn_search':'%E6%9F%A5%E8%AF%A2', '__RequestVerificationToken=':'CfDJ8KmGV0zny1FLtrcRZkGCczG2owvCRigVmimqp33mw5t861kI7zU2VfQBri65hIwu_4VXbmtqImMmTeZzqxE7NwwvAtwWcZSMnk6UDuzP3Ymzh9YrHPJkj_cy8vSLXvUYXrFO0HnCb0pSweHIL9pkReY',
}
requests.post(url=url,data=data,headers=headers).content.decode('utf-8')
I'd be very grateful if you could point out where I'm going wrong
I have tried to replace headers and so on.

return codes for Jira workflow script validators

I'm writing a workflow validator in Groovy to link two issues based on a custom field value input at case creation. It is required that the custom filed value to Jira issue link be unique. In other words, I need to ensure only one issue has a particular custom field value. If there is more than one issue that has the input custom field value, the validation should fail.
How or what do I return to cause a workflow validator to fail?
Example code:
// Set up jqlQueryParser object
jqlQueryParser = ComponentManager.getComponentInstanceOfType(JqlQueryParser.class) as JqlQueryParser
// Form the JQL query
query = jqlQueryParser.parseQuery('<my_jql_query>')
// Set up SearchService object used to query Jira
searchService = componentManager.getSearchService()
// Run the query to get all issues with Article number that match input
results = searchService.search(componentManager.getJiraAuthenticationContext().getUser(), query, PagerFilter.getUnlimitedFilter())
// Throw a FATAL level log statement because we should never have more than one case associated with a given KB article
if (results.getIssues().size() > 1) {
for (r in results.getIssues()) {
log.fatal('Custom field has more than one Jira ssue associated with it. ' + r.getKey() + ' is one of the offending issues')
}
return "?????"
}
// Create link from new Improvement to parent issue
for (r in results) {
IssueLinkManager.createIssueLink(issue.getId(), r.getId(), 10201, 1, getJiraAuthenticationContext().getUser())
}
try something like
import com.opensymphony.workflow.InvalidInputException
invalidInputException = new InvalidInputException("Validation failure")
this is based of the groovy script runner. If it doesn't work for you, i would recommend you using some sort of framework to make scripting easier, I like using either groovy script runner , Jira Scripting Suite or Behaviours Plugin
. All of them really makes script writing easier and much more intuitive.

Coded UI Test SetProper issues

public HtmlComboBox NetworkSelectBox
{
get
{
HtmlComboBox networkSelectBox = new HtmlComboBox(ConfigVMPage);
networkSelectBox.SearchProperties[HtmlComboBox.PropertyNames.Id] = "vnic";
networkSelectBox.SearchProperties[HtmlComboBox.PropertyNames.Name] = "vnic";
networkSelectBox.FilterProperties[HtmlComboBox.PropertyNames.ControlDefinition] = "style=\"WIDTH: auto\" id=vnic name=vnic r";
return networkSelectBox;
}
}
Above is the code I define an UI element and I want to set the property
NetworkSelectBox.SelectedItem = "LabNetworkSwitch";
I've used this way on other elements and all success, but in this one i got the error message
Microsoft.VisualStudio.TestTools.UITest.Extension.ActionNotSupportedOnDisabledControlException: Cannot perform 'SetProperty of SelectedItem with value "LabNetwokrSwitch"' on the disabled or read-only control.
How can I change the control type?
I don't think you want to change the control type. I would suggest trying either waitforready() or find(). What is likely happening is when the control is initially found it is disabled, and find() will sync the actual control with the current networkSelectBox. WaitForReady() is probably the preferable method here though it will implicitly refresh the values of the combo box until it is available for input or the time out has expired.
I doubt you will run into this issue with HtmlComboBoxes but with a couple of WinComboBoxes I have had issues where they could not be set using SelectedItem or SelectedIndex. I ended up doing KeyBoardSendkeys(Combobox,"firstLetterOfItem") until the selected value was correct.

ActionDispatch::ClosedError when testing Rails 3.1 model creation (RSpec/Cucumber)

I am creating a web application with Ruby on Rails 3.1 (RC1). I am using Factory Girl, RSpec and Cucumber (with Capybara) for testing, but I am experiencing unexpected raised ActionDispatch::ClosedErrors some of the times (not every time) when I am creating new users (through the User model's create action). Below is the error message that I get:
Cannot modify cookies because it was closed. This means it was already streamed
back to the client or converted to HTTP headers. (ActionDispatch::ClosedError)
The error is raised when using these ways of creating users:
Creation using Factory Girl
Factory.create( :user )
Factory.build( :user ).save
Basic creation
User.create( { ... } )
User.new( { ... } ).save
What is funny is that they do work during some test, but not in others, and it does not seem random, although I cannot figure out the reason. Below is an excerpt from my code:
users_controller_spec.rb
require 'spec_helper'
def user
#user ||= Factory.create( :user )
end
def valid_attributes
Factory.attributes_for :user
end
describe UsersController do
describe 'GET index' do
it 'assigns all users as #users' do
users = [ user ] # The call to user() raises the error here
get :index
assigns[ :users ].should == users
end
end
describe 'GET show' do
it 'assigns the requested user as #user' do
get :show, id: user.id # The call to user() raises the error here
assigns[ :user ].should == user
end
end
However, the error is not raised in the following code block:
describe 'GET edit' do
it 'assigns the requested user as #user' do
get :edit, id: user.id # This raises no error
assigns[ :user ].should == user
end
end
Any other method below this does not raise the error, even though I am creating users in the exact same way.
Any suggestions to what I might be doing wrong would be greatly appreciated!
Someone posted a workaround here
https://github.com/binarylogic/authlogic/issues/262#issuecomment-1804988
This is due to the way rails 3 streams the response now. They posted a fix in edge for the same issue in flash but not in cookies yet. For now I have turned off my request specs. I am going to look at the problem this weekend if no one gets to it before then.
https://github.com/rails/rails/issues/1452
Just so we don't have to follow links, here's my modified version of the authlogic workaround:
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.maintain_sessions = false if Rails.env == "test"
end
end
Rather than deal with ensuring session management on every .save call, I just turn them off if I'm testing.

how to check nothing has changed in cucumber?

The business scenario I'm trying to test with cucumber/gherkin (specflow, actually) is that given a set of inputs on a web form, I make a request, and need to ensure that (under certain conditions), when the result is returned, a particular field hasn't changed (under other condition, it does). E.g.
Given I am on the data entry screen
When I select "do not update frobnicator"
And I submit the form
And the result is displayed
Then the frobnicator is not updated
How would I write the step "the frobnicator is not updated"?
One option is to have a step that runs before "I submit the form" that reads something like "I remember the value of the frobnicator", but that's a bit rubbish - it's a horrible leak of an implementation detail. It distracts from the test, and is not how the business would describe this. In fact, I have to explain such a line any time anyone sees it.
Does anyone have any ideas on how this could be implemented a bit nicer, ideally as written?
I disagree with the previous answer.
The gherkin text you felt like you wanted to write is probably right.
I'm going to modify it just a little to make it so that the When step is the specific action that is being tested.
Given I am on the data entry screen
And I have selected "do not update frobnicator"
When I submit the form
Then the frobnicator is not updated
How exactly you Assert the result will depend on how your program updates the frobnicator, and what options that gives you.. but to show it is possible, I'll assume you have decoupled your data access layer from your UI and are able to mock it - and therefore monitor updates.
The mock syntax I am using is from Moq.
...
private DataEntryScreen _testee;
[Given(#"I am on the data entry screen")]
public void SetUpDataEntryScreen()
{
var dataService = new Mock<IDataAccessLayer>();
var frobby = new Mock<IFrobnicator>();
dataService.Setup(x => x.SaveRecord(It.IsAny<IFrobnicator>())).Verifiable();
ScenarioContext.Current.Set(dataService, "mockDataService");
_testee = new DataEntryScreen(dataService.Object, frobby.Object);
}
The important thing to note here, is that the given step sets up the object we are testing with ALL the things it needs... We didn't need a separate clunky step to say "and i have a frobnicator that i'm going to memorise" - that would be bad for the stakeholders and bad for your code flexibility.
[Given(#"I have selected ""do not update frobnicator""")]
public void FrobnicatorUpdateIsSwitchedOff()
{
_testee.Settings.FrobnicatorUpdate = false;
}
[When(#"I submit the form")]
public void Submit()
{
_testee.Submit();
}
[Then(#"the frobnicator is not updated")]
public void CheckFrobnicatorUpdates()
{
var dataService = ScenarioContext.Current.Get<Mock<IDataAccessLayer>>("mockDataService");
dataService.Verify(x => x.SaveRecord(It.IsAny<IFrobnicator>()), Times.Never);
}
Adapt the principle of Arrange, Act, Assert depending on your circumstances.
Think about how you would test it manually:
Given I am on the data entry screen
And the blah is set to "foo"
When I set the blah to "bar"
And I select "do not update frobnicator"
And I submit the form
Then the blah should be "foo"

Resources