Access denied to SQS via AWS SDK - symfony

I'm currently working on a website developed with Symfony2 and I need to send messages in an Amazon SQS. In order to do that I added to my composer.json:
"aws/aws-sdk-php": "2.4.*"
Then when I try to create a queue or list queues I've got a 403 error saying:
Access to the resource https://sqs.us-west-2.amazonaws.com/ is denied.
EDIT:
added the full error message
AWS Error Code: AccessDenied, Status Code: 403, AWS Request ID:
2fe34c11-7af8-5445-a768-070159a0953e, AWS Error Type: client, AWS
Error Message: Access to the resource
https://sqs.us-west-2.amazonaws.com/ is denied., User-Agent:
aws-sdk-php2/2.4.11 Guzzle/3.7.4 curl/7.25.0 PHP/5.4.3
Here is a sample code of what I do:
$aws = Aws::factory(array(
'key' => 'my-key',
'secret' => 'my-secret',
'region' => 'us-west-2'
));
$sqs = $aws->get('sqs');
return new Response(var_dump($sqs->listQueues()));
What do I do wrong to get this error ?

After digging I discovered that the account I was using wasn't granted the access to SQS service.
To give a SQS access to an account you have to go to the amazon management console. Then click on IAM. Under this section click on Users and then you can manage permission for each account you created.

Make sure that both the following policies allow access to the SQS queue
Resource (SQS) based policy: The SQS queue should allow your identity to use the queue. You define this using the queue policy (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-iam.html#scenario-sqs-policy). The default queue policy will allow access only to the owner of the queue (owner of the queue is the identity that created the queue).
Identity based policies: The policy for the identity that is accessing the queue should have permission to invoke operations on the queue.
Make sure that the access is not restricted by either one of them.
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-using-identity-based-policies.html

I had the same strange issue, I had everything set up including policies and permission, after a couple of hrs I found out I was getting 403 error because of wrong aws region was configured in my application it was supposed to be ap-south-1 by default it was us-east-1

Related

Getting different errors when try to run report for GA4 with regular account

I am trying to run a simple report on GA4 by using Google Analytics Data API Python client with a regular user credentials:
request = RunReportRequest(
property=f"properties/11111",
dimensions=[Dimension(name=f['name']) for f in report_definition['dimensions']],
metrics=[Metric(name=f['expression']) for f in report_definition['metrics']],
date_ranges=[DateRange(start_date=date, end_date=date)],
)
response = client.run_report(request)
And the client is BetaAnalyticsDataClient as also mentioned in the documentation:
credentials = Credentials(
token=None,
refresh_token=config['refresh_token'],
client_id=config['client_id'],
client_secret=config['client_secret'],
token_uri="https://accounts.google.com/o/oauth2/token",
scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)
client = BetaAnalyticsDataClient(credentials=credentials)
It is not a Service Account so I am using google.oauth2.credentials.Credentials class as same in other Google APIs.
However, this operation is throwing an exception during the run_report function:
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "Getting metadata from plugin failed with error: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})"
debug_error_string = "UNKNOWN:Error received from peer analyticsdata.googleapis.com:443 {created_time:"2023-01-14T14:12:10.907813+03:00", grpc_status:14, grpc_message:"Getting metadata from plugin failed with error: (\'invalid_grant: Bad Request\', {\'error\': \'invalid_grant\', \'error_description\': \'Bad Request\'})"}"
>
And when I try to use my access token in the credentials:
credentials = Credentials(
token=config["token"],
refresh_token=config['refresh_token'],
client_id=config['client_id'],
client_secret=config['client_secret'],
token_uri="https://accounts.google.com/o/oauth2/token",
scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)
This time I am getting following error:
google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
I am sure that my credentials is correct since I am using same account in my other repos.
Also, note that, I tried same operation with a service account and it does not give any error. However, for this purpose, I need to use a regular developer account since the OAuth flow is on a frontend project.
What are the suggestions on that issue? Is it possible to use a developer account in here and if yes, how?
I was able to fix the issue. The app just needs a sign-out sign-in (or refreshing the access token).

AWS Amplify Build Issue - StackUpdateComplete

When running amplify push -y in the CLI, my project errors with this message:
["Index: 0 State: {\"deploy\":\"waitingForDeployment\"} Message: Resource is not in the state stackUpdateComplete"]
How do I resolve this error?
The "Resource is not in the state stackUpdateComplete" is the message that comes from the root CloudFormation stack associated with the Amplify App ID. The Amplify CLI is just surfacing the error message that comes from the update stack operation. This indicates that the Amplify's CloudFormation stack may have been still be in progress or stuck.
Solution 1 – “deployment-state.json”:
To fix this issue, go to the S3 bucket containing project settings and deleted the “deployment-state.json” file in root folder as this file holds the app deployment states. The bucket should end with, or contain the word “deployment”.
Solution 2 – “Requested resource not found”:
Check the status of the CloudFormation stack and see if you can notice that the stack failed because of a “Requested resource not found” error indicating that the DynamoDB table “tableID” was missing and confirm that you have deleted it (possibly accidentally). Manually create the above DynamoDB table and retry to push again.
Solution 3A - “#auth directive with 'apiKey':
If you recieve an error stating that “#auth directive with 'apiKey' provider found, but the project has no API Key authentication provider configured”. This error appears when you define a public authorisation in your GraphQL schema without specifying a provider. The public authorization specifies that everyone will be allowed to access the API, behind the scenes the API will be protected with an API Key. To be able to use the public API you must have API Key configured.
The #auth directive allows the override of the default provider for a given authorization mode. To fix the issue specify “IAM” as the provider which allows to use an "Unauthenticated Role" from Cognito Identity Pools for public access instead of an API Key.
Below is the sample code for public authorisation rule:
type Todo #model #auth(rules: [{ allow: public, provider: iam, operations: [create, read, update, delete] }]) {
id: ID!
name: String!
description: String
}
After making the above changes, you can run “amplify update api” and add a IAM auth provider, the CLI generated scoped down IAM policies for the "UnAuthenticated" role automatically.
Solution 3B - Parameters: [AuthCognitoUserPoolId] must have values:
Another issue could occur here, where the default authorization type is API Key when you run the command “amplify add api” without specifying the API type. To fix this issue, follow these steps:
Deleted the the API
Recreate a new one by specifying the “Amazon Cognito user pool” as the authorization mode
Add IAM as an additional authorization type
Re-enable #auth directive in the newly created API Schema
Run “amplify push”
Documentation:
Public Authorisation
Troubleshoot CloudFormation stack issues in my AWS Amplify project

Google_Drive_API_comments_error

Good afternoon. I am trying to write a function that will read the comments on a jpg file in google drive. However, when I try to run it it gives me the following error:
An error occurred:
<HttpError 403 when requesting https://www.googleapis.com/drive/v2/files/1SbB4VwCIhaS9mdJ_xqcyjenZfxxrpTsY/comments?alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.". Details: "[{'domain': 'global', 'reason': 'insufficientPermissions', 'message': 'Insufficient Permission: Request had insufficient authentication scopes.'}]">
def retrieve_comments(service, file_id):
"""Retrieve a list of comments.
Args:
service: Drive API service instance.
file_id: ID of the file to retrieve comments for.
Returns:
List of comments.
"""
try:
comments = service.comments().list(fileId=file_id).execute()
return comments.get('items', [])
except errors.HttpError as error:
print('An error occurred: %s' % error)
return None
SCOPES = ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', ]
credentials = Credentials.from_authorized_user_file('token.json', SCOPES)
service = build('drive', 'v2', credentials=credentials)
print(retrieve_comments(service, '1SbB4VwCIhaS9mdJ_xqcyjenZfxxrpTsY'))
Update: this is what my token.json file looks like:
{"token": "ya29.a0ARrdaM-lbQRcrOHcWXHXVCZ--FHEBFmhetZy5mtKyE-KYg7kkqc7DCB3ELoGWm7DSFFqZ5n7MZ2qtpomhhhh3YjyPlDmFNiBFqW8jfzQcq2bUboJVHWly7w5KajgYBW6vXfpUG7XB-NiSRIGbgGXg7pADS9E", "refresh_token": "1//03RuSdM4_a83LCgYIARAAGAMSNwF-L9Ir99uSssRC7-EDBGOchESXQuY8uQh3BIAUSnUFmT60dipjtvqGslz9wyAl_OnLkoLWdko", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "936594993582-hm55manlg9g4hkdeeisq6i4ogqk6are2.apps.googleusercontent.com", "client_secret": "irvWegrf57dztuP6_OigoGIT", "scopes": ["https://www.googleapis.com/auth/drive.metadata.readonly", "https://www.googleapis.com/auth/drive.file"], "expiry": "2021-08-19T12:26:14.658525Z"}
This is how my code looks like. any ideas why this might be happening and what I can do to solve it?
Edit: For anyone who runs into the same problem, remember the scopes in the quickstart must be the same as the ones in your python file.
Insufficient Permission
Means that the user you are authenticated with does not have permission to do what you are trying to do, or that user has not granted your application permission.
You are trying to use comments.list this method requires that you have been authorized with one of the following scopes
Now you appear to be using the following scopes
'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file',
Im not sure why you have drive.file twice, but lets ignore that for now.
As you can see you appear to be using the proper scopes needed by this endpoint. What i suspect has happened is that you have already authorized the user using a different set of scopes and you then changed the scopes in your application. When you change the scopes you need to be sure that you have revoked the users access in your application and prompt the user to authorize your application again. You are probably running on a stored access token and or refresh token which have the old scopes.
The solution will be to simply force your application to authorize your user again, make sure the consent screen popsup.

AccessDeniedExceptionnull (Service: AWSLambdaInternal; Status Code: 403 Amplify

I have issues pushing to amplify after adding resource same problem, after adding auth with
amplify add auth
amplify push
I get
Following resources failed
Resource Name: UserPoolClientLambda (AWS::Lambda::Function)
Event Type: create
Reason: AccessDeniedExceptionnull (Service: AWSLambdaInternal; Status Code: 403; Error Code: AccessDeniedException; Request ID: 8434d2a2-4287-4b79-b22f-5d95094436a0; Proxy: null)
× An error occurred when pushing the resources to the cloud
Resource is not in the state stackUpdateComplete
An error occurred during the push operation: Resource is not in the state stackUpdateComplete
How I resolve this ?
PS: amplify cli is version 4.41.2
Finally able to figure it out.
My issue has something to do with my exposed api key case with my users.
I had help from the AWS support. Initially, I was just going to fix my billing payment method, and they mentioned that they locked my account due to the exposed api key. They walked me through it to rotate my API key and I just waited around 3-5 hours to get my account unlocked.
I tried it after following the same steps and it worked
$ amplify add auth
$ amplify push

Exception using Azure Managed Service Identity across tenants

I'm building an Azure web app for a client that will be provisioned into many other directories for their customers. This app will call a web API in my client's directory, which will then call back to another web API in the customer's directory. Something like this:
Other Customer AAD1 --------- My client AAD2
App --------------------------------> Web API 2
Web API 1 <-------------------------- Web API 2
We have been able to get the first call to work. This requires a corresponding App Registation for Web API 2 in AAD1. We figure that we could get the callback to work by following the same pattern, with a registration for Web API1 in AAD2. However, that might be a LOT of these 'proxy' registration in my client's AAD, so we're looking at alternatives.
We are exploring using Managed Service Identity, which we think will allow us to get tokens that are valid for resources in other tenants. If there's a better way, I'm certainly interested in knowing about it.
I've followed the code example from here using the Microsoft.Azure.Services.AppAuthentication library: https://learn.microsoft.com/en-us/azure/app-service/app-service-managed-service-identity#obtaining-tokens-for-azure-resources
// In Web API 2
using Microsoft.Azure.Services.AppAuthentication;
// ...
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(
"https://<App ID URI for Web API1>");
Web API2 is configured to have a Managed Service Identity.
I'm currently running this on my local machine, and I've installed Azure CLI and I'm logged in. I've tried 'az account get-access-token', and I get a valid token.
When Web API2 tries to get the token to be able to call Web API1, I get an exception:
Parameters: Connectionstring: [No connection string specified], Resource: , Authority: . Exception Message: Tried the following 2 methods to get an access token, but none of them worked.
Parameters: Connectionstring: [No connection string specified], Resource: , Authority: . Exception Message: Tried to get token using Managed Service Identity. Unable to connect to the Managed Service Identity (MSI) endpoint. Please check that you are running on an Azure resource that has MSI setup.
Parameters: Connectionstring: [No connection string specified], Resource: , Authority: . Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. ERROR: Get Token request returned http error: 400 and server response: {"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID '04b07795-8ddb-461a-bbee-02f9e1bf7b46' named 'Web API 1'. Send an interactive authorization request for this user and resource.\r\nTrace ID: f5bb0d4d-6f92-4fdd-81b7-e82a78720a00\r\nCorrelation ID: 04f92114-8d9d-40c6-b292-965168d6a919\r\nTimestamp: 2017-10-19 16:39:22Z","error_codes":[65001],"timestamp":"2017-10-19 16:39:22Z","trace_id":"f5bb0d4d-6f92-4fdd-81b7-e82a78720a00","correlation_id":"04f92114-8d9d-40c6-b292-965168d6a919"}
What's interesting is that there's no application with ID '04b07795-8ddb-461a-bbee-02f9e1bf7b46' in either AAD1 or AAD2. Is this a known Azure app? I thought that it might be the Service Management API, but I'm not sure.
In any case, I'm not sure of the proper way to grant permission. I've tried building different content URLs like this into my browser, but none of them seem to have done the trick:
https://login.microsoftonline.com/(AAD1 ID)/adminconsent
?client_id=(App ID)
&redirect_uri=https://localhost:44341
&resource=(App ID URI for Web API1)
&prompt=admin_consent
https://login.microsoftonline.com/(AAD1 ID)/adminconsent
?client_id=04b07795-8ddb-461a-bbee-02f9e1bf7b46
&redirect_uri=https://localhost:44341
&resource=(App ID URI for Web API1)
&prompt=admin_consent
(This last one tells me that the reply URL is incorrect; since it's not one of my apps, I can't find the reply URL)
Note that the tenant is AAD1.
Am I missing something, or am I not using this feature correctly?
Thanks in advance.
AzureServiceTokenProvider uses Azure CLI (among other options) for local development. For a scenario where a service calls an Azure Service, this works using the developer identity from Azure CLI, since Azure services allow access to both users and applications.
For a scenario where a service calls another custom service (like your scenario), you need to use a service principal for local development. For this, you have two options:
Login to Azure CLI using a service principal.
First, create a service principal for local development
https://learn.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli?view=azure-cli-latest
Then login to Azure CLI using it.
az login --service-principal -u 25922285-eab9-4262-ba61-8083533a929b --password <<pwd>> --tenant 72f988bf-86f1-41af-91ab-2d7cd011db47 --allow-no-subscriptions
Use the --allow-no-subscriptions argument since this service principal may not have access to any subscription.
Now, AzureServiceTokenProvider will get a token using this service principal for local development.
Specify service principal details in an environment variable. AzureServiceTokenProvider will use the specified service principal for local development. Please see the section Running the application using a service principal in local development environment in this sample on how to do that. https://github.com/Azure-Samples/app-service-msi-keyvault-dotnet
Note: Ths is only for local development. AzureServiceTokenProvider will use MSI when deployed to App Service.

Resources