Error when logging in with Machinist in Shoulda test - authlogic

I am having some trouble getting the right usage of Machinist and Shoulda in my testing.
Here is my test:
context "on POST method rating" do
p = Product.make
u = nil
setup do
u = login_as
post :vote, :rating => 3, :id => p
end
should "set rating for product to 3" do
assert_equal p.get_user_vote(u), 3
end
And here's my blueprints:
Sham.login { Faker::Internet.user_name }
Sham.name { Faker::Lorem.words}
Sham.email { Faker::Internet.email}
Sham.body { Faker::Lorem.paragraphs(2)}
User.blueprint do
login
password "testpass"
password_confirmation { password }
email
end
Product.blueprint do
name {Sham.name}
user {User.make}
end
And my authentication test helper:
def login_as(u = nil)
u ||= User.make()
#controller.stubs(:current_user).returns(u)
u
end
The error I get is:
/home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/validations.rb:1090:in `save_without_dirty!': Validation failed: Login has already been taken, Email has already been taken (ActiveRecord::RecordInvalid)
from /home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/dirty.rb:87:in `save_without_transactions!'
from /home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/transactions.rb:200:in `save!'
from /home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:136:in `transaction'
from /home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/transactions.rb:182:in `transaction'
from /home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/transactions.rb:200:in `save!'
from /home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/transactions.rb:208:in `rollback_active_record_state!'
from /home/jason/moderndarwin/vendor/rails/activerecord/lib/active_record/transactions.rb:200:in `save!'
from /usr/lib/ruby/gems/1.8/gems/machinist-1.0.6/lib/machinist/active_record.rb:55:in `make'
from /home/jason/moderndarwin/test/blueprints.rb:37
from /usr/lib/ruby/gems/1.8/gems/machinist-1.0.6/lib/machinist.rb:77:in `generate_attribute_value'
from /usr/lib/ruby/gems/1.8/gems/machinist-1.0.6/lib/machinist.rb:46:in `method_missing'
from /home/jason/moderndarwin/test/blueprints.rb:37
from /usr/lib/ruby/gems/1.8/gems/machinist-1.0.6/lib/machinist.rb:20:in `instance_eval'
from /usr/lib/ruby/gems/1.8/gems/machinist-1.0.6/lib/machinist.rb:20:in `run'
from /usr/lib/ruby/gems/1.8/gems/machinist-1.0.6/lib/machinist/active_record.rb:53:in `make'
from ./test/functional/products_controller_test.rb:25:in `__bind_1269805681_945912'
from /home/jason/moderndarwin/vendor/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:293:in `call'
from /home/jason/moderndarwin/vendor/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:293:in `merge_block'
from /home/jason/moderndarwin/vendor/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:288:in `initialize'
from /home/jason/moderndarwin/vendor/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:169:in `new'
from /home/jason/moderndarwin/vendor/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:169:in `context'
from ./test/functional/products_controller_test.rb:24
I can't figure out what it is I'm doing wrong... I have tested the login_as with my auth (Authlogic) in my user_controller testing.
Any pointers in the right direction would be much appreciated!

I've got a partial solution... I've solved the problem above, but the should_redirect_to function is still giving me fits...
This is my new test code:
context "on POST method rating" do
setup do
#u = login_as
#p1 = Product.make
#p2 = Product.make # Make a second product that we'll show after rating the first
post :vote, :rating => 3, :id => #p1
end
should "set rating for product to 3" do
assert_equal #p1.get_user_vote(#u), 3
end
should_redirect_to("product page") {show_product_url(:id => #p2)}
end
And my new error:
response to be a redirect to <http://test.host/products/555660218> but was a redirect to <http://test.host/products>.
Any ideas where to go from here?

Is your controller redirecting to products_url?
Side note: you shouldn't use random data (Faker) for any validation that requires uniqueness. That's what Factory Girl's sequences are for. I assume Machinist has something similar.

Related

How do I get the userid of second mention in a command

So I'm trying to make a command where someone can do -kill #firstUser #secondUser. This will increase the first user's kills by 1 and add a role to the second user mentioned. I can access the the first user mentioned by doing const firstUser = message.mentions.users.first(); but I'm not sure how to do the same for the second user.
I've tried accessing the message.mentions.users collection and converting it to an array (and trying to access that) but I can't get it to work.
const firstUser = message.mentions.users.get(0);
const secondUser = message.mentions.users.get(1);
How do I get the user class from a message with multiple mentions?
And what I found was, it returns an object, not a mention, and as you can't send an object, it will return as an empty message error.
So to send a mention, you send:
// Getting the first and second users
const allMentioned = message.mentions.users.array()
// First User `[0]`
const firstUser = allMentioned[0];
// Second User `[1]`
const secondUser = allMentioned[1];
// And so on and so forth...
// Add `<#` to the begginning of the id and `>` to the end of it to make a mention.
const mentionSecondUser = "<#" + secondUser.id + ">";
// Sending a message using the fetched property
message.channel.send(`Hey ${mentionSecondUser}, or whatever.`);
Alternatively, you can try using the other fetched properties using the following format, received from getting the property, say secondUser:
User {
id: '<secondUser's id>',
username: '<secondUser's username>',
bot: <true if secondUser a bot>,
discriminator: '<secondUser's discriminator>',
avatar: '<secondUser's avatarId>',
lastMessageID: <secondUser's lastMessageId>,
lastMessageChannelID: <secondUser's lastMessageChannelId>,
flags: UserFlags { bitfield: 0 }
}
An example of this is in the picture showed above.
You can use:
message.mentions.users.array()[1]
To get the second user in a message. Appropriately, use [2] for the third, [3] for the fourth, and so on.

How to retry a request until i get a valid dynamically generated value in response using karate dsl

I am sending a request to fetch the API ID from backend but because my backend is slow it doesn't give back the ID in one go and that's making my test case fail in the first try. Though it passes if I try again, but that's not ideally it should work. I tried putting a sleep, but that doesn't look promising either.
My test case is :
Given URL storeURL
And param query =
When method get
Then status 200
call read('Sleep.feature')
def APIIDStr = response.list[0].id
print 'APIID from Store is: ', APIIDStr
Can i do something here so that if APIIDStr is empty in the first go , it tries to fetch again until it gets a valid value?
Yes. Please refer to the documentation on how to implement polling using JavaScript: https://github.com/intuit/karate#polling
function(x) {
while (true) {
var result = karate.call('get.feature');
var greeting = result.response;
karate.log('poll response', greeting);
if (greeting.id == x) {
karate.log('condition satisfied, exiting');
return;
}
karate.log('sleeping');
// uncomment / modify the sleep time as per your wish
// java.lang.Thread.sleep(1000);
}
}
EDIT - also see: https://stackoverflow.com/a/55823180/143475
The follow code can correctly run now:
Feature:
Background:
* url 'url'
Scenario:
* def input =
"""
{
'form': {},
'query': {},
}
"""
* path '/rest/n/test'
* params input.query
* form fields input.form
* method post
* status 200
* math response contains { result: 1 }
* eval if (response.result != 1) karate.call('delete-user.feature'))
So, I hope hope retryPost method which can retry-post the scenario (it can auto check status).
or:
...
* eval if (responseStatus == 5xx) retryPost/retryGet/retryPut
* eval if (response.result != 1) retryPost/retryGet/retryPut
Here retryPost/retryGet/retryPut only re-run the section code.
for example:
Feature:
Background:
* url 'url'
Scenario:
# section 1
...
* method post
* eval if () retryPost # only re-run section 1
# section 2
...
* method post
*eval if () retryPost # only re-run section 2
Thanks a lot!

PHPmailer parseAddresses - How to get rid of "notice" messages

I'm trying to get rid of the following message in one of my scripts when using the PHPmailer parseAddresses function:
Notice: Unknown: Must use comma to separate addresses: xxx (errflg=3) in Unknown on line 0
$mailer = new PHPMailer(true);
try {
$a = $mailer->parseAddresses('aaa#aaa.aaa xxx');
}
finally {
...
}
I'm using PHP 7.0.8 with the following error handling presets:
declare(strict_types = 1);
error_reporting(E_ALL);
ini_set('display_errors', 'stdout');
I know that I can just stop the errors from being displayed but this doesn't seem to be the proper way to do. And of course I know that the provided email addresses in my example are not correct...
I'm not sure what you're complaining about: it's telling you you have malformed input when you provide malformed input! The way to avoid the error is not to pass in malformed input!
As the error says, it's expecting one or more addresses in comma-delimited RFC822 format (not what you provided), which might be something like:
xxx <aaa#aaa.aaa>, yyy <bbb#aaa.aaa>
If you don't provide data in that format, it will complain, as you're seeing. This is covered in the docs on the parseAddress method.
Are you expecting it to do something else?
PHPMailer writes notices to output, so you could start an output buffer and just flush it after your call. Something like:
$mailer = new PHPMailer(true);
try {
ob_start();
$a = $mailer->parseAddresses('aaa#aaa.aaa xxx');
//$notices = ob_get_contents();
ob_end_clean();
}
finally {
...
}
I had to deal with the same issues. Simply created a homemade solution that does mostly the same thing in a more flexible way. For anyone that is interested:
/**
* split_addresses Split a list of email addresses with potential validation
* Similar concept as PHPMailer->parseAddresses, but more forgiving
* #param $list - a list of comma delimited email addresses in simple or RFC822 format
* #param $default_name an optional name to add if not present
* #param $validate logical var to indicate to only accept validated emails
* #author Jacques Amar
* #copyright 2019 Amar Micro Inc.
*/
function split_addresses($list, $default_name='', $validate=true) {
$valid_arr = [];
if (empty($list)) { return $valid_arr; }
$split_arr = preg_split('/\s*,\s*/', $list);
foreach ($split_arr as $email_candidate) {
// Validate email_candidate if the form "first last <adrs#email.com>"
$actual_name = $default_name;
$actual_email = $email_candidate;
if (preg_match('/\s*(.+)\s*\<\s*([^#]+#.+)\s*\>/', $email_candidate, $actual_emails) == 1) {
$actual_name = $actual_emails[1];
$actual_email = $actual_emails[2];
}
if ($validate) {
if (filter_var($actual_email, FILTER_VALIDATE_EMAIL)) {
$valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
}
} else {
$valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
}
}
return $valid_arr;
}
Should be self explanatory

Chef custom attributes

I'm working on a custom Chef Cookbook and have defined a custom attribute called default["server"]["apikey"] = nil thats been defined within the cookbook in a separate attributes file that looks like this:
#Default Attributes
default["webhooks"]["get_response"] = ""
default["webhooks"]["put_response"] = ""
default["webhooks"]["post_response"] = ""
default["server"]["username"] = "user"
default["server"]["password"] = "123"
default["server"]["apikey"] = nil
Within my recipe I then do this:
webhooks_request "Request an API key from TPP " do
uri "172.16.28.200/sdk/authorize/"
post_data (
{ 'Username' => node["server"]["username"], 'Password' => node["server"]["password"]}
)
header_data (
{ 'content-type' => 'application/json'}
)
expected_response_codes [ 200, 201, 400 ]
action :post
end
I then follow this with ruby_block that updates the value of the ``default["server"]["apikey"]` attribute with the API key like this:
ruby_block "Extract the API Key" do
block do
jsonData = JSON.parse(node["webhooks"]["post_response"])
jsonData.each do | k, v |
if k == 'APIKey'
node.overide["server"]["apikey"] = v
end
end
end
action :run
end
I can then validate it using this:
ruby_block "Print API Key" do
block do
print "\nKey = : " + node["server"]["apikey"] + "\n"
end
action :run
end
However, if I then try to use the node["server"]["apikey"] attribute in a following block like this:
webhooks_request "Get data from TPP" do
uri "127.0.0.1/vedsdk/certificates/retrieve?apikey=#{node["server"]["apikey"]}"
post_data (
{ 'data' => "NsCVcQg4fd"}
)
header_data (
{ 'content-type' => 'application/json', 'auth' => node["server"] ["username"]}
)
expected_response_codes [ 200, 201, 400, 401 ]
action :post
end
The value of node["server"]["apikey"]} is always empty. Interestingly though the value of the node["server"] ["username"] attribute is available and works as expected.
Obviously, I'm missing something here buy can't work out what :(
Writing it as a generic answer (it will avoid keeping it unanswered in list too ;))
When inside a resource you may evaluate an attribute value at converge time with lazy attribute evaluation.
The correct usage is
resource "name" do
attribute lazy {"any value #{with interpolation} inside"}
end
The common error is to use lazy inside interpolation as we only want the variable to be lazy evaluated and there's only one.
By design lazy is meant to evaluate the attribute value, it can contain Ruby code to compute the value from something done by a previous resource too.

Codeigniter xss vulnerabilities and other problems with security

When i scanned my site with "Acunetix Web Vulnerability Scanner" i was very surprised. Programm show a lot of xss vulnerabilities on page when i use get parameters with xss filtration.
For example:
URL encoded GET input state was set to " onmouseover=prompt(967567) bad="
The input is reflected inside a tag parameter between double quotes.
I think its because i don`t show 404 error when result is empty (it should be). I show message like "the request is empty"
My controller:
$this->pagination->initialize($config);
$this->load->model('aircraft_model');
$data['type'] = $this->input->get('type', TRUE);
$data['year'] = $this->input->get('year', TRUE);
$data['state'] = $this->input->get('state', TRUE);
$type_param = array (
'type' => $this->input->get('type', TRUE),
);
$parameters = array(
'year' => $this->input->get('year', TRUE),
'state_id' => $this->input->get('state', TRUE),
);
foreach ($parameters as $key=>$val)
{
if(!$parameters[$key])
{
unset($parameters[$key]);
}
}
$data['aircraft'] = $this->aircraft_model->get_aircraft($config['per_page'], $this->uri->segment(3, 1),$parameters, $type_param);
$data['title'] = 'Самолеты | ';
$data['error'] = '';
if (empty($data['aircraft']))
{
$data['error'] = '<br /><div class="alert alert-info"><b>По таким критериям не найдено ниодного самолета</b></div>';
}
$name = 'aircraft';
$this->template->index_view($data, $name);
even when i turn on global xss filtering program find xss vulnerabilities.
Maybe Message for possible xss is false?
Also i have one SQL injection.
Attack details:
Path Fragment input / was set to \
Error message found:
You have an error in your SQL syntax
SQL error:
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 10' at line 3
SELECT * FROM (`db_cyclopedia`) LIMIT -10, 10
Controller:
$this->load->model('cyclopedia_model');
$this->load->library('pagination');
$config['use_page_numbers'] = TRUE;
[pagination config]
$config['suffix'] = '/?'.http_build_query(array('type' => $this->input->get('type', TRUE)), '', "&");
$config['base_url'] = base_url().'cyclopedia/page/';
$count_all = $this->cyclopedia_model->count_all($this->input->get('type', TRUE));
if (!empty($count_all)){
$config['total_rows'] = $count_all;
}
else
{
$config['total_rows'] = $this->db->count_all('cyclopedia');
}
$config['per_page'] = 10;
$config['first_url'] = base_url().'cyclopedia/page/1'.'/?'.http_build_query(array('type' => $this->input->get('type', TRUE)), '', "&");
$this->pagination->initialize($config);
$parameters = array(
'cyclopedia_cat_id' => $this->input->get('type', TRUE),
);
foreach ($parameters as $key=>$val)
{
if(!$parameters[$key])
{
unset($parameters[$key]);
}
}
$data['type'] = $this->input->get('type', TRUE);
$data['cyclopedia'] = $this->cyclopedia_model->get_cyclopedia($config['per_page'], $this->uri->segment(3, 1),$parameters);
$data['title'] = 'Энциклопедия | ';
if (empty($data['cyclopedia']))
{
show_404();
}
$name = 'cyclopedia';
$this->template->index_view($data, $name);
And one some problems with HTTP Parameter Pollution (get parameters).
Attack details
URL encoded GET input state was set to &n954725=v953060
Parameter precedence: last occurrence
Affected link: /aircraft/grid/?type=&year=&state=&n954725=v953060
Affected parameter: type=
Sorry for a lot of code, but its my first experience with codeigniter / framework and safety first.
UPDATE:
When site url like this site.com/1 codeigniter show:
An Error Was Encountered
Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.
how to make a show 404 instead of this message?
This takes input from the user:
$config['first_url'] = base_url().'cyclopedia/page/1'.'/?'.http_build_query(array('type' => $this->input->get('type', TRUE)), '', "&");
Then this line in the Pagination.php library spits it into the output page without proper HTML-escaping:
$output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
Although automated scanning tools do generate a lot of false positives in general, this one is a genuine HTML-injection vulnerability leading to a real risk of cross-site scripting attacks.
To fix, wrap all output being injected into HTML context (eg $first_url) with htmlspecialchars(). Unfortunately as this is library code you would have to start your own fork of Pagination. Might be better to use some other library.
Don't rely on xss_clean as it can't reliably protect you. It is attempting to deal with output problems at the input layer, which is never going to work right - it'll miss attacks as well as mangling perfectly valid input. The whole idea betrays a basic, rookie misunderstanding of what the XSS problem actually is.
There are more places in Pagination that need the same fix, but I don't want to spend any more time reading CodeIgniter's painfully poor-quality code than I have to.
I do not understand how CodeIgniter has attained this degree of popularity.

Resources