Giter Club home page Giter Club logo

intellij-firebase-highlighter's Introduction

logo
Firebase Rules Syntax Highlighter


Plugin

What is it?

intellij-firebase-highlighter is an Intellij plugin for highlighting firebase rules.

How to use it?

  • Add plugin to Intellij IDE
  • Configure colors

Add plugin to Intellij IDE

  • Clone repo
git clone https://github.com/anboralabs/intellij-firebase-highlighter
- Find grammar directory
- FirebaseRules.bnf -> Right click -> Generate Parser Code
- FirebaseRules.flex -> Right click -> Run JFlex Generator
  • Install from disk
- Go to https://github.com/anboralabs/intellij-firebase-highlighter/releases/tag/v1.0.0
- download firebase-syntax-highlighting-1.0-SNAPSHOT.jar
- Plugins -> Install From disk -> choose the file downloaded
  • Install from plugin store

Market Place

Configure colors

  • Editor -> Color Schema -> Firebase Rules

Color Settings

Credits

The main ideas used here were borrowed from:

License

MIT License

Copyright (c) 2020 Anbora Labs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

intellij-firebase-highlighter's People

Contributors

dalgarins avatar restyled-commits avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

intellij-firebase-highlighter's Issues

False Error when using substring

The following Firestore security rule file:

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
            allow read, write: if false;
        }

        match /my-collection/{doc} {
            allow read, write: if doc[0:3] == 'ABC';
        }
    }
}

shows error ',', <number operator> or ']' expected, got ':'

Realtime Database rules

Is your feature request related to a problem? Please describe.
No Firebase Realtime Database support.

Describe the solution you'd like
Firebase Realtime Database support. Should activate with files database.rules.json

Describe alternatives you've considered
Fireabse Realtime Database security rules web UI.

feature request: folding code to minimize footprint or distractions

I would like to request the addition of code folding inside the rules-file.

I believe it would be beneficial to have such functionality if you have large and/or are implementing a large amount of custom functions to help validate.

We have a case where code folding would come in handy, and be able to collapse the entire match path for a collection.
We have - for now- 3 functions within the scope of the match path of a collection, and we are unit testing our rules, so after our tests pass there's no need to focus on that section anymore and it would be beneficial to be able to collapse it down again.

match /users/{user} {
  function isSelf() {
    return request.auth.uid == resource.id;
  }

  function isAllowedToReadAnotherUser() {
    let user = get(/databases/$(database)/documents/users/$(request.auth.uid));
    return userHasRole(user, ["role_1", "role_2"]);
  }

  function isAllowedToChangeAnotherUser() {
    let user = get(/databases/$(database)/documents/users/$(request.auth.uid));
    return userHasRole(user, ["role_2"]);
  }

  allow read: if isSignedIn() && (isSelf() || isAllowedToReadAnotherUser());
  allow write: if isSignedIn() && isAllowedToChangeAnotherUser();
}

the above is an example block which would have been nice to have to collapse into the following

match /users/{user} { ... }

I believe this reference should be of help. https://plugins.jetbrains.com/docs/intellij/folding-builder.html#define-a-folding-builder

list type is not recongized

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        allow read, write: if  request.resource.data.someList is list; // <expression> expected, got 'list'
    }
}

Fails to lint new map

Describe the bug
Fails to lint new map.

To Reproduce

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    allow read, write: if false;

    function test() {
      let a = {};
      return a;
    }
  }
}

Expected behavior
No linted errors expected.

Screenshots
изображение

Wrong duplicate definition error for nested functions

Describe the bug
Wrong duplicate definition error for nested functions.

To Reproduce
Steps to reproduce the behavior:

  1. Create a function named "example()" in a nested match /databases/{database}/documents/collectionA
  2. Create a function named "example()" in a nested match /databases/{database}/documents/collectionB
  3. See error Duplicate definions with name example

Expected behavior
The plugin should not search for duplicated functions in sibling matches structures.

Screenshots
image

Possible solution
In src/main/kotlin/co/anbora/labs/firebase/ide/inspections/DuplicateFunctionsInspection.kt
DuplicateFunctionsInspection.kt

Concat the match path of the function in the key for comparison, at line: 29
val key = it.identifierExpr?.text + "_" + it.functionParameterList?.functionParameterList?.size

Issue with Math operations

The rule file:

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
            allow read, write: if false;
        }

        function testMath() {
            let a = 1;
            let b = 1;
            let c = a + b;
            return 1 + b == c;
        }
    }
}

Errors:

  • line 11: '(', '.', ';', <boolean operator>, LET_KEYWORD, RETURN_KEYWORD or '[' expected, got '+'
  • line 12: number expected, got 'b'

The plugin shows the error when storing the math operation results into the variable using already existing variables.

The following examples works very well:

  • return 1 + 2 == c;
  • return 1 + 1 == 2;

Error about any signed-in account should be a warning

Describe the bug
I have some documents that I would like any signed-in user to be able to access, but the plugin is treating this as an error.

To Reproduce
Steps to reproduce the behavior:

  1. implement rule allowing some operation if only request.auth != null
  2. trigger rules analysis (I'm using Android Studio)
  3. See error:
    Error:(34, 22) 'allow read' rule inside 'match /Doc/{docId}'checks for 'request.auth != null', which allows any signed in account (including anonymous accounts if enabled in Firebase Auth) to access data

Expected behavior
I think it could be reasonable to make this a warning, but even then I'd want to disable it. I think allowing access to any signed-in user can be reasonable (though I'm new to Firestore, so maybe I'm misunderstanding what I'm actually doing). Even if it's a warning, I'd want to be able to disable it instead of it popping up when I want to commit a change as something I need to then review and click again to commit ignoring warnings.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS
  • Editor: Android Studio Dolphin | 2021.3.1 Patch 1
  • Version: 2023.1.2

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

'>=" and "<=" are parsed/formatted incorrectly

Describe the bug
'>=" and "<=" are parsed/formatted incorrectly

To Reproduce

            allow create, update: if (request.auth != null &&
            request.auth.uid == userId &&
            request.resource.data.keys().hasOnly(['firstName', 'middleName', 'lastName', 'birthDate', 'phone']) &&
            request.resource.data.firstName is string &&
            request.resource.data.firstName.size() >= 1 &&
            request.resource.data.middleName is string &&
            request.resource.data.lastName is string &&
            request.resource.data.lastName.size() >= 1);

Result

image

Expected

image

Plugin completely not working on Android Studio / macOS Big Sur

This plugin is not usable on Android Studio on macOS Big Sur 11.2.3.
Specifically, it:

  • Does not highlights the syntax
  • Prevent me from editing .rules files (I mean, when I have it installed, I cannot edit anyway my .rules files)

The only clue I have that it is installed is that the icon of .rules files changes and become the little flame icon like Firebase.

I have not been able to recover any log file which may be useful to resolve this error...

Missing "in" operator

Hi, great work on this plugin by the way!

Almost everything is covered in my rules file except the "in" operator on an array.

Ex:
image

<expression> or FirebaseRulesTokenType.) expected, got '['

Hello!

Thanks for the awesome plugin!
By the way I ran into a bug. I wish I could fix it myself, but...
In the meantime, I'll report back to you.

Environment

Version: 1.1.1-SNAPSHOT

Result

or FirebaseRulesTokenType.) expected, got '['

image

rules_version = '2';

service cloud.firestore {
    match /databases/{database}/documents {
        function documentRef(paths) {
            return path([['databases', database, 'documents'].join('/'), paths.join('/')].join('/'));
        }
    }
}

Does not work

This is a great idea, we all need it, thanks for making this plugin.

Unfortunately, it does not seem to work on my version of WebStorm
Screen Shot 2021-07-03 at 1 24 35 PM

This is what it displays after install
Screen Shot 2021-07-03 at 1 27 39 PM

and my firestore.rules file is still displayed monochromatically.

a little more flexibility regarding e.g. indentations

Is your feature request related to a problem? Please describe.
I want to be able to use 2-space indentations for nesting. The plugin seems to force 4. If I try to delete the extra 2 after creating a new line, it deletes the entire line.

Describe the solution you'd like
I'd like this to either be configurable, or for the plugin to be less pushy about trying to force 4 space indents. As it is now, I need to work around it by e.g. selecting 2 spaces I want to delete and then hitting delete.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

False positive for database references

I wrote some time ago a function that is acceptable for firebase rules that looks as follow:

function isResourceAuthor() {
  return isSignedIn()
         && resource.data.author == /databases/$(database)/documents/authors/$(request.auth.uid);
}

The first slash in the reference after the comparison is recognized as error with the message <expression> expected, got '/'.

Screenshot_1

Syntax support request: Path

Snippet:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{path=**}/{item} {
      allow read: if path != /users;
    }
  }
}

Firestore Rules supports Path datatype which is created as

"raw" form beginning with a forward slash /

/path/to/resource

Actual result

The plugin doesn't support this syntax and breaks highlighting on them, and on the rest of the document

image

Expected result

Plugin should support this syntax

Please note, the '/users' and /users is not the same, fisrts one is a String where the second one is Path. Comparison from the snippet above would always be falsy if compared to string ex: if path != '/users';

Shows error when path starts with dot

I wrote security rules for Firestore like this:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }

    match /some-path/{doc} {
      allow write, read: if (request.auth != null);
    }

    match /.some-path/{doc} {
      allow write: if false;
      allow read: if (request.auth != null);
    }
  }
}

This is a valid file and it successfully deployed. But my IDE shows two errors:

  • expected, got '.'
  • '/' expected, got 'some-path'

Security Rules ternary operator not recognized

Hi Darwin(?),

I wonder if it's okay to file support requests / bug reports here? I started evaluating your plugin (2.5.6-SNAPSHOT) today.

Description

Syntax highlighting does not recognise the ternary operator (? :).

Näyttökuva 2021-5-18 kello 14 53 47

There are also some other, unexplained syntax errors shown for what is a working .rules file. Let me know if you want to know about them.

<object method call statement> expected, got 'get'

plugin version: 2.1.0-SNAPSHOT
IDEA version: IntelliJ IDEA 2020.2.4 (Ultimate Edition) Build #IU-202.8194.7, built on November 24, 2020

code which produces an error:

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        function isAuth() {
            return request.auth != null;
        }
        function getData() {
            return request.resource.data;
        }
        function isInt(property) {
            return getData().get(property, 0) is int; // <object method call statement> expected, got 'get'
        }
    }
}

same thing if I call property directly:

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        function isAuth() {
            return request.auth != null;
        }
        function getData() {
            return request.resource.data;
        }
        function isInt(property) {
            return request.resource.data['hello']; // '(', '.', <boolean operator> or DOT_COMMA expected, got '['
        }
    }
}

False positive for Map.get()

Having an issue with this function:

function hasGlobalClaim(claim) {
    return get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.globalClaims.get(claim, false) == true;
}

According to the reference here it looks like this should be valid syntax, but it's identified as being incorrect with IDENTIFIER expected, got 'get'.

image

Firestore accepts this and it works as intended.

Install fails when using Android Studio Dolphin

When trying to install the dowloaded jar file I am getting the error:

Plugin 'Firebase Rules Syntax Highlighter' (version '1.0-SNAPSHOT') is not compatible with the current version of the IDE, because it requires build 202.* or older but the current build is AI-213.7172.25

Is there I way to install it anyway or is it really incompatible?

Invalid syntax for firestore methods in storage.rules

Describe the bug
firestore.get() and firestore.exists() methods inside storage.rules are not properly handled resulting in false syntax errors.

To Reproduce
In the storage.rules file add either of the methods above using the examples provided in the documentation.

Expected behavior
No errors.

Screenshots
Captura de ecrã 2022-12-27, às 01 11 29

Captura de ecrã 2022-12-27, às 01 09 25

Desktop:

  • OS: macOS
  • IDE: IntelliJ IDEA 2022.3.1 (Ultimate Edition) (17.0.5+1-b653.23 aarch64)
  • Plugin Version: 2022.5.4

Unexpected error in map keys

Describe the bug
Unexpected error occurs in the second and subsequent map keys.

To Reproduce

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    allow read, write: if false;

    function test() {
      let a = {'a': 1, 'b': 2, 'c': 3};
      return a;
    }
  }
}

Expected behavior
No unexpected error occurs in maps keys.

Screenshots
Screen Shot 2022-12-19 at 15 06 36

Desktop (please complete the following information):

  • OS: macOS 12.6.2
  • Editor: IntelliJ IDEA 2022.3
  • Plugin Version: 2022.5.3

Bug: plugin incorrect requires semicolons

Consider the following correct syntax of firebase storage rules:

image

The plugin marks it as incorrect because it's picky about having semicolons.

image

How to reproduce:

Open the editor on Windows 11, WebStorm 2023.1, Plugin 2023.4.1 and paste the following in a file called storage.rules.

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false
    }

    match /users/{userId}/songs/{songId}/parts/{partId} {
      allow read: if userId == request.auth.uid
      allow write: if userId == request.auth.uid
        && request.resource.size < 8 * 1024 * 1024
        && request.resource.contentType.matches('audio/.*')
    }
  }
}

some comments are marked as error

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }

    // this comment not working
    match /users/{userId}/{document=**} {
      allow read, write: if request.auth.token.email == '[email protected]';
    }
  }
}
FirebaseRulesTokenType.ALLOW_KEYWORD, FirebaseRulesTokenType.FUNCTION_KEYWORD, FirebaseRulesTokenType.MATCH_KEYWORD or FirebaseRulesTokenType.RIGHT_BRACE expected, got '// this comment not working'

rejects parentheses around expressions

In this code:

    function fieldUnchanged(field) {
      return field in request.resource.data && field in resource.data && resource.data[field] == request.resource.data[field]
        || !(field in request.resource.data) && !(field in resource.data);
    }

it rejects the parentheses around the in expression in this: !(field in request.resource.data)

False negative for incorrect syntax in functions

There are two syntax errors that are not recognized by the syntax highlighter. The first is the starting && which is in some cases correctly recognized and in others not, and the invalid continuation of the statement after a semicolon (see image below).

Screenshot_2

Support for empty array

I wrote function with two arguments and in some cases I want to pass empty array into that function:

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
            allow read, write: if false;
        }

        function validateDocument(requiredFields, optionalFields) {
            let allFields = requiredFields.concat(optionalFields) ;
            let fields = request.resource.data.keys() ;
            return fields.hasAll(requiredFields) && fields.hasOnly(allFields);
        }

        match /my-collections/{doc} {
            allow read: if true;
            allow write: if validateDocument(['foo', 'bar'], []);
        }
    }
}

I see the following error in my IDE:

  • <expr> or '[' expected, got ']'

Array indexing with a variable

function githubExample(value) {
  return request.resource.data[value];
}

The plugin highlights the "value" indexer with: '[' or number expected, got 'value'

False positive syntax error FirebaseRulesTokenType.SERVICE_KEYWORD

I installed the plugin in Webstorm with the version 1.1.0-SNAPSHOT and I get one false positive error on valid rules.

I got currently only one false positive syntax error when I write the following valid rules:

rules_version = '2';

function someFunction() { // Error: "FirebaseRulesTokenType.SERVICE_KEYWORD expected, got 'function' "
  return false;
}

service cloud.firestore {
  ...
}

Same error occurs when I write

rules_version = '2';

// some comment  // Error: "FirebaseRulesTokenType.SERVICE_KEYWORD expected, got '// some comment' "
service cloud.firestore {
  ...
}

P.S. As overall however it is what I was looking for. Good job. :)

Interpolations incorrectly highlighted as an error

Describe the bug
Interpolations incorrectly highlighted as an error

To Reproduce

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /hotels/{hotelId}/availability/{document=**} {
      allow read, write: if get(/databases/$(database)/documents/hotels/$(hotelId)/users/$(request.auth.uid)).data.write == true;
    }
  }
}

Expected behavior
This compiles and works in firestore

Screenshots
image

Desktop (please complete the following information):

  • OS: Mac Os
  • Browser n/a

Add 'Comment with line comment'

The option to 'Comment with line comment' doesn't work, it's grayed out in the menu, the standard Cmd + / [slash] key combination doesn't do anything. Would be nice to see it added.

Syntax check shortcoming... +++

First, it's very nice you have brought an IntelliJ plugin for Firebase security rules to existence. Thank You!

The real benefit from such would be in complex rules, highlighting rule syntax problems. Unfortunately, this is where my 2s test already failed:

      allow create: if isSignedIn() +++

The plugin does not mark the (added) +++ as a breach of syntax. Surely, it is...

For being able to truly put one's weight on such a plugin, would it be possible to bring Firebase authors in the loop, to help make it more aligned with the real rules language.

Subfield indexing

At the moment, this plugin is highlighting as an error the indexes working on subfields.
For instance, the following is highlighted as an error.

            {
                "fieldPath": "geoPoint.geohash",
                "order": "ASCENDING"
            }

I think this should be fixed by admitting dots into the fieldPath value.

erroneous errors about path substitutions

Describe the bug
Path in a rule compiles and works fine, but the plugin treats it as an error.

To Reproduce
Steps to reproduce the behavior:

  1. create a rule with a line like:
    && exists(/databases/$(database)/documents/Dxxxxs/$(userId)/FxxxxxRxxxxxxx/$(xxxxxFxxxxxxxx()[0])))
  2. trigger code analysis (I'm using Android Studio)
  3. See errors:
    Error:(77, 25) ')', '/', <expression> or null expected, got '/'
    Error:(77, 36) '.', <expression>, IDENTIFIER or PATH_BUILT_IN_LITERAL expected, got '$(database)'

Expected behavior
This compiles fine according to the Firestore Rules engine, but the plugin shows these errors. I think the syntax matches what's documented here.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS
  • Browser: Android Studio Dolphin | 2021.3.1 Patch 1
  • Version: 2023.1.2 (plugin version)

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Issue with list indexing syntax

I have the following line:

&& (get(request.resource.data.participants.removeAll(resource.data.participants)[0]).id == request.auth.uid

Which gets a syntax error like so:

image

Even though this is valid syntax. In this case participants is a list which I am indexing at position 0.

See: https://firebase.google.com/docs/reference/rules/rules.List

The error is ')', ',' or '.' expected, got '['.

This also kills the code folding, which seems to not know what's going on because of the error.

Great work though! Always amazed at the breadth of plugins there are out there maintained by some unthanked dev somewhere, so: thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.