How to add mock data containing authorized owner to Amplify (either through GraphiQL or directly to AppSync)? - amazon-s3

I'm working on a React app and testing some CRUD functionality by mocking the backend, creating some data through GraphiQL, and running the app (amplify mock, then yarn start).
I want to be able to create mock data tied to my user as the owner because most types in the schema are set up with owner authorization:
type XYZ
#auth(rules: [{ allow: owner, operations: [update, delete, create] }]) {
id: ID!
...more types...etc
}
Right now, I
run amplify mock
Go to GraphiQL local endpoint (192.etc....)
Run some createXYZ mutations to create data
Run my app w yarn start
login with testUser & password
Test the deleteXYZ button which should ideally remove a particular XYZ from the mocked data this is what doesn't work
I suspect what's happening is that I didn't run the createXYZ mutation as testUser, just as a generic GraphiQL user, so the owner property isn't tied to "myUserId". Is that the problem here?
How would I specify owner on my create mutations in GraphiQL?
This is the error I'm getting, pretty sure it means the XYZ object's owner is different than my testUser submitting the deleteXYZ request:
Error while executing Local DynamoDB
{
"version": "2018-05-29",
"operation": "DeleteItem",
"key": {
"id": {
"S": "18b152a6-c98d-4336-be74-1e122191"
}
},
"condition": {
"expression": "( #owner0 = :identity0) AND attribute_exists(#id)",
"expressionNames": {
"#owner0": "owner",
"#id": "id"
},
"expressionValues": {
":identity0": {
"S": "fd2a7758-f7ba-4d57-bdb0-e5346492"
}
}
}
}
Could I have to add the owner id in Amplify's GraphiQL Auth options popup?

I just ran into this issue. I was able to work around it by putting my Cognito User Sub in the username field.

Related

AWS Cognito: How to get the user pool username form an identity ID of an identity pool?

We allow our users to upload data to a S3 bucket, which then triggers a Python lambda which again updates a DynamoDB entry based on the uploaded file. In the lambda, we struggle to get the username of the user who put the item. Since the Lambda is triggered by the put event from the S3 storage, we don't have the authorizer information available in the request context. The username is required as it needs to be part of the database record.
Here some more background: Every user should only have access to her own files, so we use this IAM policy (created with CDK):
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['s3:PutObject', 's3:GetObject'],
resources: [
bucket.arnForObjects(
'private/${cognito-identity.amazonaws.com:sub}/*'
),
],
})
Since the IAM policy validates the cognito-identity.amazonaws.com:sub field (which translates to the identity ID) we should be able to trust this value. This is the Python lambda and an example of a record we receive:
import json
import boto3
'''
{
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "my-region-1",
"eventTime": "2023-02-13T19:50:56.886Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:XXXX:CognitoIdentityCredentials"
},
"requestParameters": {
"sourceIPAddress": "XXX"
},
"responseElements": {
"x-amz-request-id": "XXX",
"x-amz-id-2": "XX"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "XXX",
"bucket": {
"name": "XXX",
"ownerIdentity": {
"principalId": "XXX"
},
"arn": "arn:aws:s3:::XXX"
},
"object": {
"key": "private/my-region-1%00000000-0000-0000-0000-000000000/my-file",
"size": 123,
"eTag": "XXX",
"sequencer": "XXX"
}
}
}
]
}
'''
print('Loading function')
dynamodb = boto3.client('dynamodb')
cognito = boto3.client('cognito-idp')
cognito_id = boto3.client('cognito-identity')
print("Created clients")
def handler(event, context):
# context.identity returns None
print("Received event: " + json.dumps(event, indent=2))
for record in event['Records']:
time = record['eventTime']
key = record['s3']['object']['key']
identityId = key.split('/')[1]
# How to get the username from the identityId?
return "Done"
Things we tried:
Try to find an alternative to cognito-identity.amazonaws.com:sub which validates the username, but from the documentation there is no option for that
Encode the username in the bucket key, but this opens a security hole as then a client can pretend to have a different username
Make a lookup with https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-identity.html to find the username for an identity ID, but so far we haven't found anything there
Tried to follow How to get user attributes (username, email, etc.) using cognito identity id, but in the Lambda we don't have an ID or access token available
Getting cognito user pool username from cognito identity pool identityId, but since the Lambda is triggered by a S3 put event, we don't have an authorizer context
We could store the identity ID as custom attribute of every Cognito user (as suggested here How to map Cognito (federated) identity ID to Cognito user pool ID?), but before I do that I would like to be sure that there isn't a better option as I fear that the duplication of this information could lead to issues in the long run.

How to set Strapi user role programmatically?

I'm using Strapi 3.6.10.
When I create user via http://host:1337/auth/local/register, I'm not able to achieve desirable user's role. It's always Authenticated, even if I directly set it to another in my request
{
"username": "user",
"email": "user#mail.com",
"password": "123456789",
"role": {
"_id": "626eacea45f0a420ccb35094"
}
}
I've also tried using API documented in generated by Documentation plugin Swagger - PUT /users/{id}. But if I send request with new role nothing happens to my user's entry

Github GraphQL API V4: INSUFFICIENT_SCOPES

When I query GitHub's GraphQL API with the following:
query RetrievePackagesAssociatedWithRepo($repo: String!, $owner: String!) {
repository(name: $repo, owner: $owner) {
packages(packageType: NPM, first: 10) {
edges {
node {
id
name
packageType
}
}
}
}
}
I received an error stating:
{
"errors": [
{
"type": "INSUFFICIENT_SCOPES",
"locations": [
{
"line": 6,
"column": 11
}
],
"message": "Your token has not been granted the required scopes to execute this query. The 'id' field requires one of the following scopes: ['read:packages'], but your token has only been granted the: ['read:gpg_key', 'read:org', 'read:public_key', 'read:repo_hook', 'repo', 'user'] scopes. Please modify your token's scopes at: https://github.com/settings/tokens."
},
I followed the link https://github.com/settings/tokens and added the necessary permissions.
I tried to Authorizing a personal access token for use with SAML single sign-on but, the SSO button to enable is not present.
development settings token
Documentations I Followed: Creating Personal Token! | Authorizing Personal Token!
After trying out theses methods, the same error message persists "Your token has not been granted the required scopes".
My goal, through Github's API, is to retrieve packages associated with its repository.
Is there something I'm missing.

How to get user info (role) from loopback token from client after login

I have a instance of User and instance of Role attached to it. Both are basic models provided from Loopback and they show up in RoleMapping and they work in ACL fine.
So, lets say I logg user in from my Vue client, then I get the response containing the access token in id field so I can make further auth requests, how do I then retrieve basic user info from that access token. Is there a way of parsing it or should I somehow modify the /login remote hook?
Any thoughts?
you need to call the login api with "include" option
/api/users/login?include=User
in response you will get something like this
{
"id": "CZY4lbJbJ2J6DrEIAjYAHfTEZbLMC2tWpyM7sZaKs7rZ1PhIY3mycua0kOHlDXfR",
"ttl": 1209600,
"created": "2018-01-21T17:01:20.183Z",
"userId": "5a3e614339e67f0e580642af",
"user": {
"createdAt": "2017-12-23T13:59:31.314Z",
"email": "dummy#dummy.co",
"id": "5a3e614339e67f0e580642af",
"name": "dummy",
}
you can try it in explorer

Create MasterCard tokenization API

I have a mobile app containing payment method via MasterCard. I have this tutorial:
https://ap-gateway.mastercard.com/api/documentation/apiDocumentation/rest-json/version/latest/api.html?locale=en_US
I want to create Tokenization which contains customer's master detail, I have followed this tutorial part:
https://ap-gateway.mastercard.com/api/documentation/apiDocumentation/rest-json/version/latest/operation/Tokenization%3a Create or Update Token (with system-generated token).html?locale=en_US
I tried with :
POST https://ap-gateway.mastercard.com/api/rest/version/41/merchant/{{MyMerchantID}}/token
Params:
{
"sourceOfFunds": {
"type": "CARD",
"provided": {
"card":{
"number": "5123450000000008",
"expiry": {
"month": "05",
"year": "17"
}
}
}
Note: The number is a mastercard test number.
I am always get this error:
error
cause "INVALID_REQUEST"
explanation "Invalid credentials."
result "ERROR"
I followed the params in second URL.
Can anyone help? Are the params correct or I missed something?
In your configuration file, you need to set the following:
$configArray["merchantId"] = "[merchantId]";
// API username in the format below where Merchant ID is the same as above
$configArray["apiUsername"] = "merchant.[merchantId]";
// API password which can be configured in Merchant Administration
$configArray["password"] = "your api password";
Setting the above parameters in the config file will solve your problem
Try replacing "ap-gateway" with the real gateway provided for you. Your merchantID is not supported in test gateway.
First, you should ask you bank to enable the tokenization for your merchant account
POST
https://ap-gateway.mastercard.com/api/rest/version/61/merchant/{{MyMerchantID}}/token
you have to set Authorization->Basic Auth
Username : Your_MerchantID
Password : ApiPassword
Params:
{
"session": {
"id": "SESSION0002510583427E2239608H32"
}
}