Amplify custom #auth rule on relation - graphql

I'm new to Amplify and having trouble configuring #auth rules on a model.
The app has two user groups, event organisers, and club managers. Event organisers can login and create Events. Club managers can login and create Teams, which they can register for Events. When a Team is registered for an Event an EventRegistration is created. The models (simplified) look like this:
type Event
#model
#auth(rules: [
# Event organisers create these and can perform CRUD operations.
{ allow: owner },
# Anyone logged into the system can view events, so they can register.
{ allow: private, operations: [read] },
])
{
id: ID!
name: String!
# Many teams can register for the same event.
eventRegistrations: [EventRegistration!] #hasMany
}
type EventRegistration
#model
#auth(rules: [
# Club managers create these when they register their team for an event. Once
# created, registrations are read-only from the club managers perspective.
{ allow: owner, operations: [create, read] }
# Event organisers can read and update registrations for their events.
{ allow: owner, ownerField: "organiser", operations: [read, update] },
])
{
id: ID!
organiser: String!
event: Event! #belongsTo
# I want to make this readable by event organisers, so they can see teams who have
# registered for their event. Currently they can't because of the auth rule on Team.
team: Team! #belongsTo
}
type Team
#model
#auth(rules: [
{ allow: owner }
])
{
id: ID!
name: String!
eventRegistrations: [EventRegistration!] #hasMany
}
The problem is, when an event organiser queries a list of registrations, the team property is not available, because organisers don't have read access to teams.
Note - Event organisers shouldn't be able to read all teams, just the teams registered for their event.
One option is to add organisers: [String] to the Team model. Then add organisers to that list when a team registers for an event, and remove them again when the event is finished, or the team de-registers. This seem quite error prone, remembering to add / remove access programatically in different scenarios, especially as the application becomes more complex.
I've tried adding field level #auth rules to EventRegistration.team hoping they would take precedence over the Team rules, but that doesn't seem to work.
I've also considered having a seperate RegisteredTeam model which is essentially a copy of the Team model, with different auth rules, but that seems bad.
Custom authorisation rules is maybe another option?
Any pointers much appreciated!
Thanks

Related

AWS Amplify GraphQL authorization based on field values

I have an AWS Amplify project that has three different user groups in Cognito. An Admin, Instructor, and Student group. I also have a GraphQL Schema that looks like this.
type DriveTime #model {
id: ID!
start: AWSDateTime!
end: AWSDateTime!
openRegistration: AWSDateTime!
closeRegistration: AWSDateTime!
vehicle: Vehicle #connection(name: "VehicleDriveConnection")
instructor: Instructor #connection(name: "InstructorDriveConnection")
student: Student #connection(name: "StudentDriveConnection")
evaluation: DriveEvaluation #connection(name: "DriveEvaluationConnection")
}
Basically Admins or Instructors put in times that the students can then register for.
I want to create authorization rules that allow for the following:
Admin group can read, write, update, and delete anything anything.
Instructor group can read, write, update, and delete anything anything.
Student group can only read if (the current date is within the openRegistration and closeRegistration fields) or (the student field matches the logged in student).
If the current date is within the openRegistration and closeRegistration fields and the student field is null, then the student can register themself for the DriveTime.
If the student field matches the logged in student, and the current date is before the start field, the student can write to the student field to unregister or cancel.
Is Amplify GraphQL #Auth capable of this?
Have a read through the documentation:
[1] https://docs.amplify.aws/cli/graphql-transformer/auth
[2] https://docs.amplify.aws/cli/graphql-transformer/directives#aws-appsync-provided-directives
[3] https://aws.amazon.com/blogs/mobile/graphql-security-appsync-amplify/
Some of your requirements may have no out the box support which means you may have to create custom logic- check out Lambda Resolvers: https://docs.amplify.aws/cli/graphql-transformer/function#usage

What is best practice for adding number of views to an object using GraphQL API?

I presently have an AWS Amplify project using a graphQL schema and want to track the number of times an object is viewed. Suppose in the following schema a user creates a blog. Now I want to track the number of time other users view this blog. Although users can obviously view it as many times as they like I want to only count a maximum of one view per user.
type Blog #model {
id: ID!
name: String
views: Int
Author: User #connection
}
type User #model {
id: ID!
name: String!
}
At the moment I'm thinking to create an additional table with just the BlogId and UserId and do this in two steps. Firstly to check that table for whether or not the user has viewed the blog and if not incrementing the blog views. But wondering if there is a better way to achieve this?
type BlogViews #model {
id: ID!
BlogId: ID!
UserId: ID!
}

Way to limit number of records a user can create in Amplify GraphQL API

I have an app where Auth is implemented using Cognito User Pools and API is a GraphQL API implemented using Amplify. In the Schema definitions, is there an easy way to limit the number of records a user can create. For example in the following schema...
type Product #model #auth(rules: [{ allow: owner }]) {
id: ID!
name: String!
description: String
}
I would like to limit the users to a maximum of 100 Products.
One way is via my front-end. When I detect that a user has reached 100 limit, I can just make the UI stop giving them the ability to add more. But if someone were to bypass the UI, they could create more than 100. Hence, I prefer to enforce this limit in the backend.
Is there a way to do this in the Schema definition, or elsewhere in AWS / DynamoDB ?
Thanks!
There isn't a straightforward way to do this that I'm aware of.
Below is how I would solve this.
Create a #key on Product on the owner property, so that you can query by owner.
Overwrite the CreateProduct mutation. In your custom resolver, before creating a new Product, query the Product table byOwner, using the owner id passed in, to count how many already exist.
Here is the documentation: https://docs.amplify.aws/cli/graphql-transformer/resolvers#add-a-custom-geolocation-search-resolver-that-targets-an-elasticsearch-domain-created-by-searchable
I think the easiest solution would be processing the API request in a lambda function that validates the request (product count < 100) before having the script write to the DB. Then you can null out the built-in mutations for the model to prevent unintended access.
Example Schema:
type Mutation {
addProduct(input: ProductAddInput): ProductAddOutput #function(name: "productLambda-${env}")
}
type Product
#model(queries: null, mutations: null, subscriptions: null) /* update these to what you need */
#auth(rules: [{ allow: owner }]) {
id: ID!
name: String!
description: String
}
In Lambda you can pull the username from the event.identity property and that should correlate to the owner field in the db. Since the AWS package is automatically loaded you should be looking at very fast script execution as long as your db indexes are set properly.
For the user product count, I see a couple of options:
A secondary index set up on the owner field so you don't do a ton of
scans
If you have a user table, you could add a field that counts
the products for each user and just update that table any time you
update the product table.

AWS Amplify authorization based on db field value or relationship

I am creating a webapp with Amplify ( GraphQL api ) and Quasar Framework.
Using Amazon Cognito for authentication.
Lets say the db has these entities:
A User who has his own profile where he can manage his own data, and even make it public if he turns the 'public' boolean field to true.
An Organization who have todos etc.
A User can become an Employee of one ( or maybe more ) organization(s) and should be able to manage for example the todos that belong to the organization where he became an employee.
I am stuck at figuring out how to add authorization rules to make this happen.
Owner authorization should be suitable for the user profile, but even there its not clear how to setup a rule that makes the profile public if the user sets the 'public' boolean field setting to true in his profile.
For example:
type Todo #model #searchable #auth(rules: [{allow: owner, operations: [read, create, update, delete]}]) {
id: ID!
Title: String!
Description: String
}
This way if a user logs in he can manage and list his own todos, but how can I allow him to view and manage todos that belong to an organization where he is an employee ( employee would be a join table which connects the user and the organization )?
I have undertaken some research on this issue, and although it is far from complete, I would like to share it.
Despite amplify docs say, that there is possibility to combine multiple autorization types, they don't specify explicitly, that you can't combine them in one request (my be, it's evident for them, but not for novice like me).
When you configure your AppSync GraphQL API with amplify update api, you choose default authorization type. All subsequent requests from your front by await API.graphql() will use this default unless you explicitly specify different type like this await API.graphql(Object.assign(graphqlOperation(listTodos),{authMode: auth_mode})), where auth_mode can take one of next values: "API_KEY", "AWS_IAM", "AMAZON_COGNITO_USER_POOLS" and "OPENID_CONNECT".
There are two "true" public authorization types in Amplify - "API_KEY" and "AWS_IAM". To activate any of them (or both), you should do something like that:
type Todo #model
#auth(rules: [
{ allow: public },
{ allow: public, provider: iam},
])
{
id: ID!
name: String!
description: String
owner: String
editors: [String]
entity: String
}
{ allow: public } stands for "API_KEY", { allow: public, provider: iam} - for "AWS_IAM".
For "API_KEY"to work propery you should configure API KEY (for ex - with amplify update api). For "AWS_IAM" you should configure Cognito and enable unauthenticated identities in Cognito Identity Pool.
After that, any request without prior user sign-in of the form await API.graphql(Object.assign(graphqlOperation(listTodos),{authMode: auth_mode})) with auth_mode=API_KEY or auth_mode=AWS_IAM will succeed (also updateTodo, createTodo and deleteTodo).
In either case you can't implement your workflow with public field, enabled by user, "out of the box", because permission evaluation get accomplished prior to any database info gets available. For ex, IAM authorization uses unauthenticated role policy, generated for you by amplify update api. You can see it in your AWS console in IAM service.
To partially implement your private/public workflow I can suggest to use so called dynamic group authorization(We assume "AMAZON_COGNITO_USER_POOLS" auth mode). In that case you implement "public" group in your Cognito User Pool and make any user member of this group (you can automate this by using post signUp hooks).
Your #auth could be something like that
type Todo #model
#auth(rules: [
{ allow: owner },
{ allow: groups, groupsField: "groupsCanAccess", operations: [read] },
])
{
id: ID!
name: String!
description: String
owner: String
editors: [String]
entity: String
groupsCanAccess: [String]
}
When your user decides that it's time to go public, she request updateTodo with groupsCanAccess set to public. As you can see, this is partial solution because to read todos your "public" user should be registered.
To partially implement your employee-organization workflow I could suggest next approach (We again assume "AMAZON_COGNITO_USER_POOLS"):
type User #model
#auth( rules: [
{ allow: owner },
{ allow: groups, groupsField: "groupsCanAccess", operations: [read] },
{allow: groups, groups: ["Admin"] }
]) {
id: ID!
owner: String! #auth(rules[{allow: groups, groups: ["Admin"] }])
groupsCanAccess:[String]
#auth(rules[{allow: owner},{allow: groups, groups: ["Admin"] }])
todo: [Todo] #connection(keyName: "byUser", fields: ["owner"])
type Todo #model
(queries: null)
#auth ({allow: owner, operations[delete]})
#key [(name: "byUser", fields: ["owner", "description"])
{
id: ID!
name: String!
description: String
owner: String! #auth(rules[{allow: owner}])
}
Here everybody can create, update and read Todo, but read operation is possible only through User (queries: null), so nobody can get particular id to update particular Todo except owner. There is though some little possibility that someone can guess this id and it's drawback of this approach. It's impossible to create Todo without owner (exclamation sign on field), and nobody can create Todo but owner (nobody can alter owner field but owner). Note that operations[delete] is important, because without that nobody can query Todo through User ( {allow: owner} equivalent to {allow: owner, operations[create,update,read,delete]}).
Owner can do everything with User, but she can't create or delete User because she can't alter owner field protected by perfield #auth directive
Admins can create User and set owner to particular user.
Admins and owner can alter groupsCanAccess field. Every element in this array corresponds to some organization. When Admins or owner add some organization, every member of this group gains access to this User and to all of her Todos through this User. Drawback - owner can forbid access granted by Admins. Because Todos aren't protected from update - every group member can alter Todos of particular User.
Operations of adding Cognito User Pool user to group performed by admins and are out of scope of this document. Drawback - only 300 Groups per Cognito Pool.
And last - you of course have option to manually adjust resolvers, automatically generated by Amplify. You may for ex use "AWS_IAM" and organize owner check by analyzing $context.identity.cognitoIdentityId inside your rezolver mapping template. As you know - there is one-to-one correspondence between this Cognito Identity Pool paramener and user from User Pool. It's especially convinient when you need to store public and owner's Todos (there is some unique per Identity Pool cognitoIdentityId corresponding to unauthenticated user).
Have exact the same problem
My hopefully temporarily solution is : Adding a lamdaFunction : myResolver and adding this function to the graqphl-schema. in that function a can do all the filtering thru the databaseClient Class
the schema
type Query {
myqueryresolver(params: String): String #function (name: "myqueryresolver-${env}")
}
Now You define a lamda (In my case I use a generic form ....) in which you perform all the non standard queries.
You call this function :
const dataObj = await API.graphql(
{
query: myqueryresolver,
variables: {"params": JSON.stringify(params)}
}
);
All the public access goes thru this function call.
Additional hint
You can run it locally with "amplify mock" and you can see all the output from your console.log locally - no need to deploy during dev.

Nested GraphQL mutations with AWS Amplify/AppSync

I've reached out on the AWS forums but am hoping to get some attention here with a broader audience. I'm looking for any guidance on the following question.
I'll post the question below:
Hello, thanks in advance for any help.
I'm new to Amplify/GraphQL and am struggling to get mutations working. Specifically, when I add a connection to a Model, they never appear in the mock api generator. If I write them out, they say "input doesn't exist". I've searched around and people seem to say "Create the sub item before the main item and then update the main item" but I don't want that. I have a large form that has several many-to-many relationships and they all need to be valid before I can save the main form. I don't see how I can create every sub item and then the main.
However, the items are listed in the available data for the response. In the example below, addresses, shareholders, boardofdirectors are all missing in the input.
None of the fields with '#connection' appear in the create api as inputs. I'll take any help/guidance I can get. I seem to not be understanding something core here.
Here's my Model:
type Company #model(queries: { get: "getEntity", list: "listEntities" }, subscriptions: null) {
id: ID!
name: String!
president: String
vicePresident: String
secretary: String
treasurer: String
shareholders: Shareholder #connection
boardOfDirectors: BoardMember #connection
addresses: [Address]! #connection
...
}
type Address #model{
id: ID!
line1: String!
line2: String
city: String!
postalCode: String!
state: State!
type: AddressType!
}
type BoardMember #model{
id: ID!
firstName: String!
lastName: String!
email: String!
}
type Shareholder #model {
id: ID!
firstName: String!
lastName: String!
numberOfShares: String!
user: User!
}
----A day later----
I have made some progress, but still lacking some understanding of what's going on.
I have updated the schema to be:
type Company #model(queries: { get: "getEntity", list: "listEntities" }, subscriptions: null) {
id: ID!
name: String!
president: String
vicePresident: String
secretary: String
treasurer: String
...
address: Address #connection
...
}
type Address #model{
id: ID!
line1: String!
line2: String
city: String!
postalCode: String!
state: State!
type: AddressType!
}
I removed the many-to-many relationship that I was attempting and now I'm limited to a company only having 1 address. I guess that's a future problem. However, now in the list of inputs a 'CompanyAddressId' is among the list of inputs. This would indicate that it expects me to save the address before the company. Address is just 1 part of the company and I don't want to save addresses if they aren't valid and some other part of the form fails and the user quits.
I don't get why I can't write out all the fields at once? Going along with the schema above, I'll also have shareholders, boardmembers, etc. So I have to create the list of boardmembers and shareholders before I can create the company? This seems backwards.
Again, any attempt to help me figure out what I'm missing would be appreciated.
Thanks
--Edit--
What I'm seeing in explorer
-- Edit 2--
Here is the newly generated operations based off your example. You'll see that Company takes an address Id now -- which we discussed prior. But it doesn't take anything about the shareholder. In order to write out a shareholder I have to use 'createShareholder' which needs a company Id, but the company hasn't been created yet. Thoroughly confused.
#engam I'm hoping you can help out the new questions. Thank you very much!
Here are some concepts that you can try out:
For the #model directive, try it out without renaming the queries. AWS Amplify gives great names for the automatically generated queries. For example to get a company it will be getCompany and for list it will be listCompanys. If you still want to give it new names, you may change this later.
For the #connection directive:
The #connection needs to be set on both tables of the connection. Also if you want many-to-many connections you need to add a third table that handles the connections. It is also usefull to give the connection a name, when you have many connections in your schema.
Only Scalar types that you have created in the schema, standard schalars like String, Int, Float and Boolean, and AWS specific schalars (like AWSDateTime) can be used as schalars in the schema. Check out this link:
https://docs.aws.amazon.com/appsync/latest/devguide/scalars.html
Here is an example for some of what I think you want to achieve:
type Company #model {
id: ID!
name: String
president: String
vicePresident: String
secretary: String
treasurer: String
shareholders: [Shareholder] #connection(name: "CompanySharholderConnection")
address: Address #connection(name: "CompanyAdressConnection") #one to many example
# you may add more connections/attributes ...
}
# table handling many-to-many connections between users and companies, called Shareholder.
type Shareholder #model {
id: ID!
company: Company #connection(name: "CompanySharholderConnection")
user: User #connection(name: "UserShareholderConnection")
numberOfShares: Int #or String
}
type User #model {
id: ID!
firstname: String
lastname: String
company: [Shareholder] #connection(name: "UserShareholderConnection")
#... add more attributes / connections here
}
# address table, one address may have many companies
type Address #model {
id: ID!
street: String
city: String
code: String
country: String
companies: [Company] #connection(name: "CompanyAdressConnection") #many-to-one connection
}
Each of this type...#model generates a new dynamoDB table. This example will make it possible for u to create multiple companies and multiple users. To add users as shareholders to a company, you only need to create a new item in the Shareholder table, by creating a new item with the ID in of the user from the User table and the ID of the company in the Company table + adding how many shares.
Edit
Be aware that when you generate a connection between two tables, the amplify cli (which uses cloudformation to do backend changes), will generate a new global index to one or more of the dynamodb tables, so that appsync can efficient give you data.
Limitations in dynamodb, makes it only possible to generate one index (#connection) at a time, when you edit a table. I think you can do more at a time when you create a new table (#model). So when you edit one or more of your tables, only remove or add one connection at a time, between each amplify push / amplify publish. Or else cloudformation will fail when you push the changes. And that can be a mess to clean up. I have had to, multiple times, delete a whole environment because of this, luckily not in a production environment.
Update
(I also updated the Address table in the schema with som values);
To connect a new address when you are creating a new company, you will first have to create a new address item in the Address table in dynamoDb.
The mutation for this generated from appsync is probably named createAddress() and takes in a createAddressInput.
After you create the address you will recieve back the whole newly createdItem, including the automatically created ID (if you did not add one yourself).
Now you may save the new company that you are creating. One of the attributes the createCompany mutation takes is the id of the address that you created, probably named as companyAddressId. Store the address Id here. When you then retrieves your company with either getCompany or listCompanys you will get the address of your company.
Javascript example:
const createCompany = async (address, company) => {
// api is name of the service with the mutations and queries
try {
const newaddress = await this.api.createAddress({street: address.street, city: address.city, country: address.country});
const newcompany = await this.api.createCompany({
name: company.name,
president: company.president,
...
companyAddressId: newaddress.id
})
} catch(error) {
throw error
}
}
// and to retrieve the company including the address, you have to update your graphql statement for your query:
const statement = `query ListCompanys($filter: ModelPartiFilterInput, $limit: Int, $nextToken: String) {
listCompanys(filter: $filter, limit: $limit, nextToken: $nextToken) {
__typename
id
name
president
...
address {
__typename
id
street
city
code
country
}
}
}
`
AppSync will now retrive all your company (dependent on your filter and limit) and the addresses of those companies you have connected an address to.
Edit 2
Each type with #model is a referance to a dynamoDb table in aws. So when you are creating a one-to-many relationship between two tables, when both items are new you first have to create the the 'many' in the one-to-many realationships. In the dynamoDb Company tables when an address can have many companies, and one company only can have one address, you have to store the id (dynamoDB primary key) for the address on the company. You could of course generate the address id in frontend, and using that for the id of the address and the same for the addressCompanyId in for the company and use await Promise.all([createAddress(...),createCompany(...)) but then if one fails the other one will be created (but generally appsync api's are very stable, so if the data you send is correct it won't fail).
Another solution, if you generally don't wont to have to create/update multiple items in multiple tables, you could store the address directly in the company item.
type Company #model {
name: String
...
address: Address # or [Address] if you want more than one Address on the company
}
type Address {
street: String
postcode: String
city: string
}
Then the Address type will be part of the same item in the same table in dynamoDb. But you will loose the ability to do queries on addresses (or shareholders) to look up a address and see which companies are located there (or simulary look up a person and see which companies that person has a share in). Generally i don't like this method because it locks your application to one specific thing and it's harder to create new features later on.
As far as I'm aware of, it is not possible to create multiple items in multiple dynamoDb tables in one graphql (Amplify/AppSync) mutation. So async await with Promise.all() and you manually generate the id attributes frontendside before creating the items might be your best option.

Resources