Search code examples
firebasegoogle-cloud-firestoregoogle-cloud-functionsfirebase-security

Firestore prevent malicious user to add more data than wanted


I'm using Angular for my frontend and Cloud functions + Firestore for my backend.

When I set data in Firestore, I want to limit the users to a certain model of data. For example let's say that my "model" is:

    interface Person {
        name: string
        age: number
    }

Nothing prevents a malicious user to send an object like the following:

    {
       name: 'Anna', 
       age: 22,
       unWantedData: 'Some unwanted data' 
    }

What is the best way to prevent that ? I've seen the Firestore converters but is it really the way to go ?

I also have another related question. I'm quite familiar working with SQL and ORM's using Entities, for example with TypeORM:

    @Entity()
    export class Post {
        @PrimaryGeneratedColumn()
        id: number
    
        @Column()
        @Length(10, 20)
        title: string
    
        @Column()
        @IsInt()
        @Min(0)
        @Max(10)
        rating: number
    
        @Column()
        @IsEmail()
        email: string
    
        @Column()
        @IsDate()
        createDate: Date
    }

Is there a way to have validators like that with Firestore ? Maybe using rules ?


Solution

  • You have the answer in the last line of your question: you can indeed use Firebase's server-side security rules to validate the data.

    The security rules only apply to access from the client-side SDKs, not from connections over the Admin SDK (such as those from Cloud Functions that you mention). If writes happen through such a trusted environment, you will have to validate the data in your application code before passing it to Firebase.