How to get user information of the user while running load tests in locust - locust

I provide number of users=12 and hatch rate=2.
How can I get user id(s) of all users hitting my web page, as I would like to do some customizations based on the object names which are getting created (say an article title).
How to pass user information (say user id) while creating new articles. So that if I run a test with 12 users, I would know that articles were created by a certain user.
from locust import HttpLocust, TaskSet, task
def create_new_article(self):
with self.client.request('post',"/articles",data={"article[title]":"computer","article[content]":"pc"},catch_response=True) as response:
print response

How can I get user id(s) of all users hitting my web page?
This depends on how your web server is set up. What exactly is a user ID in your application's context?
I'll proceed with the assumption that you have some mechanism by which you can generate a user ID.
You could have your client side get the user ID(s) (using Javascript for example) and then pass each ID along to the server in a HTTP request where you could custom define a header to contain your user ID for that request.
For example, if you're using Flask/Python to handle all the business logic of your web application, then you might have some code like:
from flask import Flask, request
app = Flask(__name__)
#app.route("/articles")
def do_something_with_user_id():
do_something(request.headers.get("user-id"))
if __name__ == "__main__":
app.run()
How to pass user information (say user id) while creating new
articles?
You could change your POST request line in your Locust script to something like:
with self.client.request('post',"/articles",headers=header_with_user_id,data={"article[title]":"computer","article[content]":"pc"},catch_response=True) as response:
where header_with_user_id could be defined as follows:
header_with_user_id = { "user-id": <some user ID>}
where <some user ID> would be a stringified version of whatever your mechanism to obtain the user ID gets you.

Related

How to add dedicated scope to Keycloak via kcadm

I'd like to add dedicated scopes to a client so that it can access information from other clients.
Turning full access on works but grants too many permissions.
The scopes are already created with their respective clients. It is “only” a matter of assigning scope from client a to client b. I have a list of names and client ids available locally. How can I efficiently assign them via kcadm.sh?
I already tried with the network tab open but I couldn't wrap my head around what the logic behind assigning scopes is.
E.g., there is a
POST /admin/realms/master/clients/968c7b36-95dd-4121-b92b-37b324298890/scope-mappings/realm with an empty array as payload
POST /admin/realms/master/clients/968c7b36-95dd-4121-b92b-37b324298890/scope-mappings/clients/74cb7b05-34d5-4657-8fe6-bb19a7c8a07f from the APIDOC it just says client. But I don't know what that client should be.
How to reproduce on Keycloak (X) 20.0.3
Login to the Keycloak Admin Console
Click on the client tab
Click createClient
Create client id and click next.
Click save.
On the new client. Click on the upper tab 'Client scopes'.
Click on the first blue item.
Click on the upper tab 'scope' and turn off full scope allowed.
Click assign role and add one of the items.
This is what I want to achieve with the help of the kcadm.sh as clients are added dynamically. You can't even export the client from Actions->Export and Import it again from the UI. Every scope is lost when imported again.
To assign role from client A to client B at the bear minimal you need the following Rest Full API call:
POST /admin/realms/ <REALM NAME> /clients/< ID OF THE CLIENT >/scope-mappings/clients/< ID OF THE CLIENT where the role comes from>
so in your case /admin/realms/ <REALM NAME> /clients/< ID OF CLIENT B >/scope-mappings/clients/ < ID OF CLIENT A>
the payload should be [{"id":"<ID OF ROLE>","name":"<ROLE NAME>"}]
You will need the call to get the id of the client for that you can call:
GET /{realm}/clients
with clientId as query parameter.
And then you will need the call to get the ID of the role, for that you can use:
GET /{realm}/clients/{id}/roles/{role-name}
id is the id of the client.

Stop Facebook/Other Apps from crawling my web application via private sharelink

Edit: The suggested answer does not work as the robots are not just randomly crawling from my index, they are visiting a specific link when it is entered in a FB message.
I've created a basic chat application in Flask on App Engine. It allows the user to invite others by adding their ID or by giving them a private sharelink that auto-adds who ever goes to it (similar to youtube or google drive).
A serious flaw I have found is that if a user posts the link into a facebook message, Facebook will crawl/visit the link and by design of my system add them as a user to the conversation. All of a sudden you'll see 3 random users join the conversation.
My chat system is completely anonymous and designed to be temporary so theres no login or authentication other than a unique key for each user saved in their session.
So Facebook bots visit the link, get assigned an ID and get authenticated into the conversation because they used the users share-link, is there a way I can stop this via either Flask/Python or App Engine? Could I IP ban facebook?
Some code for the sake of code, does this for every new visitor:
def requires_session(f):
#wraps(f)
def decorated(*args, **kwargs):
if 'profile' not in session:
user_ref = fs_database.collection('users').document()
data = {
'id': user_ref.id,
'date': datetime.now(timezone.utc)
}
# add the user to the database
user_ref.set(data)
# save their id to their session
session['profile'] = data.get('id')
# create a hash for later on to create a sharelink
session['share'] = hashlib.sha256(data.get('id').encode('utf-8')).hexdigest()
return f(*args, **kwargs)
return decorated
I could maybe add a check first if Facebook-bot: return False
For your case I would say that you can avoid that either on your side or on Google Cloud Platform side. To be more precise, you can reject some connections in your code or you can set firewall rules to your App Engine instance to reject connections coming from certain IPs. In the public documentation you can find more information about firewall rules when using GAE:
Using flex environment.
Using standard environment.
Code-wise you can check at this github repo which is addresses the issue of blocking certain IPs to your Flask app.
The last possible option is authentication, but as the chat is anonymous I guess that's not the solution you are looking for.
The accepted answer lead me to this answer, I protected the route with a decorator that would get the 'user agent' of the incoming connection and see where it comes from. If it comes from Facebook, redirect it away.
def check_for_robot(f):
#wraps(f)
def decorated(*args, **kwargs):
if 'not_a_robot' not in session:
agent = request.headers.get('User-Agent')
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
# Stop robots from crawling when sharing conversation links
# Could use the IPs too
if 'facebook' in agent or 'Slackbot' in agent:
return 'No Robots Thanks'
# Real people will get to here and continue on
session['not_a_robot'] = True
return f(*args, **kwargs)
return decorated
#app.route('/')
#check_for_robot
def index()
return 'hello human'
This issue also occurs with ANY messaging service that crawls your links to display data in the chat message (WhatsApp, Slack, etc).
This also exposed a vulnerability in these messaging services as they now return the incorrect metadata back to the chat service, but embed the link you provided, ie. Phishing, Clickjacking

facebook test user no graph API search place result

I have created a test user for my app under development (not public yet), and using the access token generated for the test user to call graph API.
The graph API I am trying is search place (/search type=place distance=1000).
And I specify my current location as parameter.
However, I only get the following data in return:
{"data":[]}
If I specify distance=10000, I get a few place names, but this result is totally different from my result with ordinal (non-tester) user.
Using access token for non-test-user, I get 100s or more place names.
Question:
Why this difference?
Any setting needed for test user creation so that its graph API search result is the same as the ordinal user's?
(In case it is a limitation of test user, how I can test an app which use graph API, with a test user?)
Any help or clue is highly appreciated!

Postman requests keep creating new conversations

I've deployed the "pizza" dialog to my Bluemix account. I'm using Postman to verify the REST interactions prior to my coding implementation. I'm able to retrieve the dialog id using the dialog REST GET. Taking the returned dialog id I establish a new conversation (leave client_id and conversation_id) empty:
https://gateway.watsonplatform.net/dialog/api/v1/dialogs/ee93cf6e-8718-4524-b10c-4f20fee90883/conversation
I use the returned conversation id to send another conversation request but I first set in the header the conversation_id, and the input value to "A large Pizza"
https://gateway.watsonplatform.net/dialog/api/v1/dialogs/ee93cf6e-8718-4524-b10c-4f20fee90883/conversation
Rather than getting the next turn in the dialog asking for toppings I get a new conversation id and new client id, and input asking me again for what size pizza I'd like to order.
Should I be able to test the dialog interaction using Postman, and why are my subsequent dialog requests all being treated as new conversation requests?
Appreciate any advice.
You said you are setting the conversation ID in the header so I am going to assume you may be passing that ID parameter incorrectly. According to the Watson Dialog API Explorer it states that if you do not pass in a conversation_id it will start a new conversation. Since you pass the converation_id incorrectly it thinks you did not provide one and will start a new conversation with you.
Since you are using Postman, try setting the conversation_id in the Body of the POST and not in the header.

Retrieving the action-instance-id from Facebook given the URL

tl;dr: No, there isn't a way.
Calling publish_action using the JS SDK is actually pretty straightforward. However (from the little info I gleaned from reading the documentation), there's no way for me to query facebook to have it return the action instance ID for an object that I have already published... is there?
Example:
User A loads the page, and the page sends an FB.api call to /me/news.reads, which returns an action instance ID.
User A reloads the page, and the page again sends an FB.api call to /me/news.reads, but this time, the Graph API returns:
{
error: {
code: 3501,
message: 'blahblahblah... already associated... blah blah'
type: 'OAuthException'
}
}
Pretty standard stuff, and expected, since I turned off the ability to publish the same URL multiple times.
Now then, is there any way for me to retrieve a previously published action instance ID from the Graph API by passing in the URL, or is it up to me to handle the returned action instance ID (from the original publication attempt) and save it to a database? I was hoping I wouldn't have to do that...
No, there is no way to retrieve instances of published actions other than:
Accessing action by id:
http://graph.facebook.com/ACTION_ID
Accessing all instances published by specific user:
http://graph.facebook.com/USER_ID/NAMESPACE:ACTION (NAMESPACE:ACTION may be replaces by the name of one of built-in actions like news.reads, music.listend, etc.
If you want to access details of published actions connected/referencing specific object you'll need to save that data on your end for later usage.