Set Up A Pre-Commit Hook
To automatically validate Polar syntax when you try to commit a change to your policy, you can optionally set up a pre-commit hook.
Copy the script below and save it to .git/hooks/pre-commit
in the repository that contains your policy code:
Change the value of "POLAR_FILES" to the locations of your .polar files.
#!/bin/sh## An example hook script to verify that Polar code that# is about to be committed is syntactically valid.# Change this to the paths to your polar filesdeclare -a POLAR_FILES=( "policy/authorization.polar" "policy/authorization2.polar")POLAR_FILES_CHANGED=false# See whether any of the polar files changed in this commitfor POLAR_FILE in "${POLAR_FILES[@]}" ; do if git --no-pager diff --cached --name-status | grep -v "^D" | grep "${POLAR_FILE}" >> /dev/null ; then POLAR_FILES_CHANGED=true break fidone# If at least one Polar file has changed, then validate the syntax of all Polar files.## NOTE: This is necessary because Polar files may reference objects in other Polar files.! $POLAR_FILES_CHANGED || oso-cloud validate "${POLAR_FILES[@]}"
If you have multiple Polar files, then if any of the files change, you need to
revalidate all of them by calling oso-cloud validate
on the full list of files.
This is because Polar files can reference objects in other Polar files, so a change to one Polar file could break something in a different Polar file.
To make the hook executable:
$ chmod 0755 .git/hooks/pre-commit
Now, whenever you commit code that updates your Polar files, git
will run the oso-cloud validate
command. If the command fails, the commit will be blocked. For example, if you have two syntax errors in two files:
$ git commit -m "Try to commit multiple invalid policies"Policy failed validation:Policy failed validation due to parser error: did not expect to find the token 'not' at line 1, column 1 of file policy/authorization.polar: 001: not-an-actor User { } ^Policy failed validation:Policy failed validation due to parser error: Expected 'actor' or 'resource' but found 'resorce'. at line 25, column 1 of file policy/authorization2.polar: 025: resorce Repository { ^
If you fix the errors and try the commit again, it succeeds:
$ git commit -m "Try to commit multiple valid policies"Policy validated successfully.[add-policy-tests 76d4809] Try to commit multiple valid policies 2 files changed, 147 insertions(+), 1 deletion(-)
This ensures that your Polar code is always syntactically valid before you commit it to version control.