Boto3 IAM waiter isn't waiting - python

I'm using boto3 to create an IAM user, wait until the IAM user is created, then update the login profile of that user. My python code to create the user works fine, and the user is created successfully. IAM is eventually consistent, so I know that I need to wait for the user to be created before I can do anything else with it, and I am using a waiter for that purpose. But when I try to update the login profile, it errors out saying that the user doesn't exist yet.
So basically the waiter isn't waiting like it should.
Anyone know what I'm doing wrong here?
import boto3
password = 'not_the_real_password'
client = boto3.client('iam')
# Create the user
response = client.create_user(
UserName='someuser'
)
# Creating the user works fine. But IAM is eventually consistent, so we have
# to wait for the user to be created before we can do anything with it.
waiter = client.get_waiter('user_exists')
waiter.wait(UserName='someuser')
# If the waiter worked correctly, then it should have waited for the user
# to be created before updating the login profile.
response = client.update_login_profile(
UserName='someuser',
Password=password,
PasswordResetRequired=True
)
Expected result: the waiter should wait long enough that the IAM user exists, and then updating the login profile would work as expected.
Actual result:
Traceback (most recent call last):
File "add_user.py", line 20, in <module>
PasswordResetRequired=True
File "/home/myuser/.local/lib/python3.6/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/home/myuser/.local/lib/python3.6/site-packages/botocore/client.py", line 661, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.NoSuchEntityException: An error occurred (NoSuchEntity) when calling the UpdateLoginProfile operation: Login Profile for User someuser cannot be found.

The error says:
Login Profile for User someuser cannot be found.
The Login Profile is separate to the User. It needs to be specifically created.
Change update_login_profile() into create_login_profile().

Related

Sharepy library freezes at entering username in PyCharm

I'm trying to authenticate to SharePoint Online. Using sharepy v 2.0, pyCharm community edition, and python 3.9.
When I run:
'sharepy.connect('siteurl')'
From within PyCharm, Sharepy will freeze after I input my username in the run dialog box.
If I add the 'username' parameter and run it. Nothing happens. I'm never prompted for a password
If I use the console and enter in sharepy.connect('siteurl') then username and password (same goes for passing those parameters) I will get an error:
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 75, in _get_token
token = root.find('.//wsse:BinarySecurityToken', ns).text
AttributeError: 'NoneType' object has no attribute 'text'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\session.py", line 15, in connect
return SharePointSession(site, auth=autoauth)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\session.py", line 61, in __init__
self.auth.login(self.site)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 27, in login
self._get_token()
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 77, in _get_token
raise errors.AuthError('Token request failed. Invalid server response')
sharepy.errors.AuthError: Token request failed. Invalid server response
It should be noted I'm getting O365 from godaddy and the login page is federated? I think is the correct term.
According to the new release of Sharepy, this shouldn't matter.
Has anyone else had this freezing problem happen for them?
How would I authenticate with sharepoint using sharepy given my current situation?
The source of this problem ended up being GoDaddy. As we were federated using GoDaddy as the O365 provider. There was no way to authenticate correctly using sharepy.
The ultimate solution was to defederate away from GoDaddy (pretty easy to do thanks to this guy: Defederation Guide)
The reason we were unable to authenticate was because our provider redirects the login to their own login site. And unfortunately the sharepy builtin method of "auth" wouldn't work with GoDaddy.
I tested this theory before migrating away from GoDaddy. By using a fresh tenant. I also found that when you enable MFA the password/username method of authentication doesn't work.
NOTE: When new tenants are created they utilize a blanket security protocol which forces MFA. Even though MFA is shown as disabled in the Azure AD > Users section. To turn this off you must disable "Security Defaults": portal.azure.com > Azure Active Directory > Properties > "Manage security defaults" (at the bottom of the screen, its a small hyperlink).
A note on MFA and authentication with sharepy. There are methods to leave MFA enabled which work with other sharepoint/python things. I haven't tested them using sharepy yet, but will be turning on MFA and using one of the following methods:
App Password
Sharepoint API client secret
Azure App Registration (Azure App Reg)

Non-interactive authentication fails with WsTrust server issue MSIS7068

Setup:
Users are created on On-Prem AD and synced to Azure AD via Azure AD Connect
I have a single-tenant app set up on Azure AD
I created a user (On-Prem, synced to AAD) that can authenticate without MFA (we need to use username-password authentication due to an internal limitation).
Here is the non-interactive authentication code:
import msal
# create a public client app
authority_url = f"https://login.microsoftonline.com/{TENANT_ID}"
msal_app = msal.PublicClientApplication(client_id=CLIENT_ID, authority=authority_url)
# acquire token
token = msal_app.acquire_token_by_username_password(username=USERNAME, password=PASSWORD, scopes=SCOPES)
I'm getting the following error:
Traceback (most recent call last):
File "/./scripts/aad.py", line 8, in <module>
token = msal_app.acquire_token_by_username_password(
File "/usr/local/lib/python3.10/site-packages/msal/application.py", line 1420, in acquire_token_by_username_password
response = _clean_up(self._acquire_token_by_username_password_federated(
File "/usr/local/lib/python3.10/site-packages/msal/application.py", line 1447, in _acquire_token_by_username_password_federated
wstrust_result = wst_send_request(
File "/usr/local/lib/python3.10/site-packages/msal/wstrust_request.py", line 60, in send_request
return parse_response(resp.text)
File "/usr/local/lib/python3.10/site-packages/msal/wstrust_response.py", line 49, in parse_response
raise RuntimeError("WsTrust server returned error in RSTR: %s" % (error or body))
RuntimeError: WsTrust server returned error in RSTR: {'reason': 'MSIS7068: Access denied.', 'code': 'a:FailedAuthentication'}
Searching through Google I found that this can be caused by MFA, but the user is excluded from MFA. I've also verified that there are no Conditional Access policies in place to block the user accessing the app.
Using Interactive auth works as expected. Any ideas on how to get non-interactive auth to work or what might be the issue here?
First, no guesswork! You would need to login to Azure AD with elevated privilege (Security Reader at the least if not Global Administrator).
Go to Enterprise Applications and locate your application by client id.
One you are at the application, go to Sign-in tab/pane.
Review the sign-in activities. You should see the reason authentication failed in overview tab. Look at the Conditional Access tab and you will know if there is any policy that blocked the sign-in.
Take action based on what you identified in sign-in activity.
Okay, I am going to make an educated guess! When you login as non-interactive, you have two authentication choices - ROPC and Client Credential- both requires client_secret to be passed in the request but you have not! Since you are using username and password, it implies that msal is using ROPC and you must include client secret.

Issue with request for user input from Telegram bot on Heroku

I am trying to deploy this Telegram bot* on Heroku: https://github.com/radinshayanfar/TGCopyBot. The bot first needs to sign in to my account, which requires a login code that's sent to my devices on which I'm already logged in. When running the bot locally from a terminal, it requests input from the user, Enter code:, upon which I enter the login code in the terminal and press Enter, and the bot proceeds to do its work. But after deploying the bot on Heroku and running the dyno, it fails and this shows in the logs:
2021-06-26T12:55:33.312544+00:00 app[worker.1]: Enter code:Traceback (most recent call last):
2021-06-26T12:55:33.312546+00:00 app[worker.1]: File "/app/app/main.py", line 77, in <module>
2021-06-26T12:55:33.312729+00:00 app[worker.1]: tg.login()
2021-06-26T12:55:33.312730+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/telegram/client.py", line 493, in login
2021-06-26T12:55:33.312946+00:00 app[worker.1]: result = actions[authorization_state]()
2021-06-26T12:55:33.312948+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/telegram/client.py", line 585, in _send_telegram_code
2021-06-26T12:55:33.313163+00:00 app[worker.1]: code = input('Enter code:')
2021-06-26T12:55:33.313168+00:00 app[worker.1]: EOFError: EOF when reading a line
2021-06-26T12:55:33.373308+00:00 heroku[worker.1]: Process exited with status 1
2021-06-26T12:55:33.427790+00:00 heroku[worker.1]: State changed from up to crashed
It may then automatically start the bot again, and proceed to crash and output the same errors as above. What's the problem here, and how can it be fixed?
If the issue is its request for the login code, then I do receive the login code on my other devices, but how do I give the login code to the bot? More generally, how do you repsond to a request for user input from any bot deployed on Heroku?
*not really a Telegram bot made with #BotFather; it just uses the Telegram API development tools
On your local environment, the built-in input works fine because you have access to the Terminal and can provide the input.
On Heroku there is no such an option so the command returns the EOFError exception because the function hits the end-of-file condition (EOF) without reading anything.
A possible solution might be to request the user to enter the login code via the Telegram Bot, for example as first step after the user starts chatting.
It seems the issue is with the request for user input, and that there is no direct way for the user to input anything on Heroku as they would on a terminal. The code can be modified to accept what would be inputted as an environment variable in this case, by using e.g. a session string: https://docs.pyrogram.org/topics/storage-engines#session-strings, https://docs.telethon.dev/en/latest/concepts/sessions.html#string-sessions

Slack bot using python makes the error during github action

I am making a simple slack bot using github action:
But every time I tried to post a message to my channel, the error ocurrs
Traceback (most recent call last):
File "4_distributed_mlblogbot_to_py_update.py", line 130, in <module>
text = "{0} \n*{1}* \n<{2}|{3}> :bell:".format(today, bible1, 'https://sum.su.or.kr:8888/bible/today' , script) )
File "/opt/hostedtoolcache/Python/3.6.12/x64/lib/python3.6/site-packages/slacker/__init__.py", line 515, in post_message
'mrkdwn': mrkdwn,
File "/opt/hostedtoolcache/Python/3.6.12/x64/lib/python3.6/site-packages/slacker/__init__.py", line 126, in post
api, **kwargs
File "/opt/hostedtoolcache/Python/3.6.12/x64/lib/python3.6/site-packages/slacker/__init__.py", line 102, in _request
raise Error(response.error)
slacker.Error: account_inactive
So everytime I try, I reinstall the app and invite my bot to mychannel
But It doesn't work
Meanwhile, In my personal python env(ex, colab) there are no errors.
Should I give up the token based BOT and get the webhook based bot?
Thank you
Every time I get a new auth(ex webhooks, tokens) and I run the github action, Always failed about the auth.
The hint was my "blabla.py" and the failed alarm email
I mistakenly expose my auth(IT SHOULD BE A SECRET) and Github and slack automatically drop my auth for security issue.
So after I used secret function in Github action, It works

Azure ADAL for Python - facing issue with acquire_token_with_username_password method

I am trying to retrieve access token using azure user id and password .
Initially I tried with the following python code block
import adal
context = adal.AuthenticationContext(AUTHORITY)
token = context.acquire_token_with_client_credentials(
"https://management.azure.com/",
CLIENT_ID,
CLIENT_SECRET)
This is returning the token without any issue .
I am following an example from https://github.com/AzureAD/azure-activedirectory-library-for-python for retrieving the token using username and password and the code block is the the following
token2 = context.acquire_token_with_username_password("https://management.azure.com/",USER_NAME,PASSWORD,CLIENT_ID)
In this case ,no token is returned , instead following response is returned .
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 145, in acquire_token_with_username_password
return self._acquire_token(token_func)
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 109, in _acquire_token
return token_func(self)
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 143, in token_func
return token_request.get_token_with_username_password(username, password)
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 286, in get_token_with_username_password
token = self._get_token_username_password_federated(username, password)
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 252, in _get_token_username_password_federated
username, password)
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 211, in _perform_username_password_for_access_token_exchange
username, password)
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 198, in _perform_wstrust_exchange
result = wstrust.acquire_token(username, password)
File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\wstrust_request.py", line 160, in acquire_token
raise AdalError(return_error_string, error_response)
adal.adal_error.AdalError: WS-Trust RST request returned http error: 500 and server response: <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><s:Header><a:Action s:mustUnderstand="1">http://www.w3.org/2005/08/addressing/soap/fault</a:Action><o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><u:Timestamp u:Id="_0"><u:Created>2017-06-07T12:12:56.567Z</u:Created><u:Expires>2017-06-07T12:17:56.567Z</u:Expires></u:Timestamp></o:Security></s:Header><s:Body><s:Fault><s:Code><s:Value>s:Sender</s:Value><s:Subcode><s:Value xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">a:FailedAuthentication</s:Value></s:Subcode></s:Code><s:Reason><s:Text xml:lang="en-US">ID3242: The security token could not be authenticated or authorized.</s:Text></s:Reason></s:Fault></s:Body></s:Envelope>
Process finished with exit code 1
If anybody has any idea on this, please let me know .
According to the information of error stack, per my experience, due to the error comes from the method _get_token_username_password_federated and 500 error code for WS-Trust RST request, it seems that the user/password you used for acquiring token not created in the Azure AD of your app registed, but looks like that created in a federated AD.
Please try to do the two ways below for inspection the issue.
Create a new user in the Azure AD of your app registed on Azure portal with your admin accout, then use the new user/password for retrieving the token.
Inspect your Azure AD configuration to make sure whether deployed Active Directory Federation Services and the current use/password created in a federated AD instance.

Categories