├── .github ├── ISSUE_TEMPLATE │ └── custom.md ├── PULL_REQUEST_TEMPLATE │ └── custom.md └── workflows │ ├── go-test.yaml │ ├── rust-test.yaml │ └── wasm-build.yaml ├── .gitignore ├── BUILDING_ON_MAC.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── api.go ├── api_test.go ├── assets └── images │ └── logo.png ├── engine.go ├── engine_test.go ├── eval.go ├── go.mod ├── go.sum ├── helper.go ├── lib ├── .gitignore ├── Cargo.toml ├── LICENSE └── src │ ├── interface.rs │ └── lib.rs └── static └── cedar.wasm /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | ## Expected Behavior 2 | 3 | 4 | ## Actual Behavior 5 | 6 | 7 | ## Steps to Reproduce the Problem 8 | 9 | 1. 10 | 1. 11 | 1. 12 | 13 | ## Specifications 14 | 15 | - Version: 16 | - Platform: 17 | - Subsystem: 18 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | Fixes # 2 | 3 | ## Proposed Changes 4 | 5 | - 6 | - 7 | - 8 | -------------------------------------------------------------------------------- /.github/workflows/go-test.yaml: -------------------------------------------------------------------------------- 1 | name: go-test 2 | 3 | on: 4 | workflow_run: 5 | workflows: [ wasm-build ] 6 | types: 7 | - completed 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | with: 16 | ref: ${{ github.head_ref }} 17 | - name: Set up Go 18 | uses: actions/setup-go@v4 19 | with: 20 | go-version: '1.20' 21 | - name: Install latest nightly Rust 22 | uses: actions-rs/toolchain@v1 23 | with: 24 | toolchain: nightly 25 | override: true 26 | components: rustfmt, clippy 27 | - name: Set up WASM target 28 | run: rustup target add wasm32-unknown-unknown 29 | - name: test 30 | run: make go-test -------------------------------------------------------------------------------- /.github/workflows/rust-test.yaml: -------------------------------------------------------------------------------- 1 | name: rust-test 2 | 3 | on: 4 | workflow_run: 5 | workflows: [ wasm-build ] 6 | types: 7 | - completed 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | - name: Install latest nightly Rust 16 | uses: actions-rs/toolchain@v1 17 | with: 18 | toolchain: nightly 19 | override: true 20 | components: rustfmt, clippy 21 | - name: test 22 | run: make rust-test -------------------------------------------------------------------------------- /.github/workflows/wasm-build.yaml: -------------------------------------------------------------------------------- 1 | name: wasm-build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: write 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Install latest nightly Rust 17 | uses: actions-rs/toolchain@v1 18 | with: 19 | toolchain: nightly 20 | override: true 21 | components: rustfmt, clippy 22 | - name: Set up WASM target 23 | run: rustup target add wasm32-unknown-unknown 24 | - name: Build WASM artifacts 25 | run: make wasm 26 | - uses: stefanzweifel/git-auto-commit-action@v4 27 | with: 28 | commit_message: "Build WASM artifacts" 29 | commit_options: '--no-verify --signoff' 30 | repository: . -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .vscode 3 | -------------------------------------------------------------------------------- /BUILDING_ON_MAC.md: -------------------------------------------------------------------------------- 1 | # Building on macos 2 | 3 | The version of llvm that ships with MacOS is not suitable for compiling to wasm 4 | See below from ChatGPT 5 | 6 | ``` 7 | Installing LLVM from Homebrew on macOS provides the necessary components for building and working with WebAssembly (Wasm) binaries using Rust. LLVM (Low-Level Virtual Machine) is a compiler infrastructure that includes tools and libraries for code generation, optimization, and more. 8 | When you install LLVM from Homebrew, it typically installs the llvm formula, which includes the LLVM compiler, libraries, and utilities. In the context of building WebAssembly with Rust, installing LLVM via Homebrew helps set up the appropriate toolchain and provides the required dependencies for generating Wasm binaries. 9 | Rust leverages LLVM for its powerful optimization capabilities and code generation. The Rust compiler (rustc) uses LLVM in the background to produce machine code for various targets, including the WebAssembly target (wasm32-unknown-unknown). 10 | By installing LLVM through Homebrew, you ensure that the necessary LLVM components and dependencies are available on your macOS system, allowing the Rust compiler to properly target and build WebAssembly binaries. 11 | Note that the specific details of LLVM installation and usage may vary based on your system configuration and the version of LLVM available through Homebrew. It's always a good idea to consult the documentation and resources specific to your development environment for accurate installation instructions and troubleshooting guidance. 12 | ``` 13 | 14 | So to building the wasm binary follow these steps: 15 | 16 | ``` 17 | brew install llvm 18 | ``` 19 | 20 | then 21 | 22 | ``` 23 | LLVM_PATH=$(brew --prefix llvm) 24 | export AR="${LLVM_PATH}/bin/llvm-ar" 25 | export CC="${LLVM_PATH}/bin/clang" 26 | make build 27 | ``` -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please ensure that your Pull Request is linked to an issue, 4 | and that the issue is tagged with the appropriate labels (e.g. bug, enhancement, etc.). This will 5 | help us to keep track of the changes and discuss them. 6 | 7 | Please note we have a code of conduct, please follow it in all your interactions with the project. 8 | 9 | ## Pull Request Process 10 | 11 | Thank you for contributing to this project! Here are a few guidelines to follow: 12 | 13 | 1. Ensure that your Pull Request is linked to an issue. 14 | 2. Ensure that the issue is tagged with the appropriate labels (e.g. bug, enhancement, etc.). 15 | 3. Ensure that your Pull Request is linked to the issue. 16 | 4. Ensure you sign your commits (see below). 17 | 18 | After you submit your Pull Request, we will review it and discuss it with you. If we have any 19 | questions or comments, we will add them to the Pull Request. If we approve your Pull Request, we 20 | will merge it. If we do not approve your Pull Request, we will close it. 21 | 22 | ### Signing your commits 23 | 24 | To sign your commits, just add the `-s` flag when you commit. This will add a `Signed-off-by` line to your commit message. For example: 25 | 26 | ```bash 27 | git commit -s -m "This is my commit message" 28 | ``` 29 | 30 | ## Code of Conduct 31 | 32 | ### Our Pledge 33 | 34 | In the interest of fostering an open and welcoming environment, we as 35 | contributors and maintainers pledge to making participation in our project and 36 | our community a harassment-free experience for everyone, regardless of age, body 37 | size, disability, ethnicity, gender identity and expression, level of experience, 38 | nationality, personal appearance, race, religion, or sexual identity and 39 | orientation. 40 | 41 | ### Our Standards 42 | 43 | Examples of behavior that contributes to creating a positive environment 44 | include: 45 | 46 | * Using welcoming and inclusive language 47 | * Being respectful of differing viewpoints and experiences 48 | * Gracefully accepting constructive criticism 49 | * Focusing on what is best for the community 50 | * Showing empathy towards other community members 51 | 52 | Examples of unacceptable behavior by participants include: 53 | 54 | * The use of sexualized language or imagery and unwelcome sexual attention or 55 | advances 56 | * Trolling, insulting/derogatory comments, and personal or political attacks 57 | * Public or private harassment 58 | * Publishing others' private information, such as a physical or electronic 59 | address, without explicit permission 60 | * Other conduct which could reasonably be considered inappropriate in a 61 | professional setting 62 | 63 | ### Our Responsibilities 64 | 65 | Project maintainers are responsible for clarifying the standards of acceptable 66 | behavior and are expected to take appropriate and fair corrective action in 67 | response to any instances of unacceptable behavior. 68 | 69 | Project maintainers have the right and responsibility to remove, edit, or 70 | reject comments, commits, code, wiki edits, issues, and other contributions 71 | that are not aligned to this Code of Conduct, or to ban temporarily or 72 | permanently any contributor for other behaviors that they deem inappropriate, 73 | threatening, offensive, or harmful. 74 | 75 | ### Scope 76 | 77 | This Code of Conduct applies both within project spaces and in public spaces 78 | when an individual is representing the project or its community. Examples of 79 | representing a project or community include using an official project e-mail 80 | address, posting via an official social media account, or acting as an appointed 81 | representative at an online or offline event. Representation of a project may be 82 | further defined and clarified by project maintainers. 83 | 84 | ### Enforcement 85 | 86 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 87 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 88 | complaints will be reviewed and investigated and will result in a response that 89 | is deemed necessary and appropriate to the circumstances. The project team is 90 | obligated to maintain confidentiality with regard to the reporter of an incident. 91 | Further details of specific enforcement policies may be posted separately. 92 | 93 | Project maintainers who do not follow or enforce the Code of Conduct in good 94 | faith may face temporary or permanent repercussions as determined by other 95 | members of the project's leadership. 96 | 97 | ### Attribution 98 | 99 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 100 | available at [http://contributor-covenant.org/version/1/4][version] 101 | 102 | [homepage]: http://contributor-covenant.org 103 | [version]: http://contributor-covenant.org/version/1/4/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PROJECT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) 2 | 3 | .PHONY: build dependencies wasm go-test rust-test go-dependencies rust-dependencies 4 | 5 | rust-dependencies: 6 | cd lib && cargo build 7 | 8 | go-dependencies: 9 | cd $(PROJECT_DIR) && go get -d -v ./... 10 | 11 | dependencies: rust-dependencies go-dependencies 12 | 13 | go-test: wasm go-dependencies 14 | cd $(PROJECT_DIR) && go test ./... 15 | 16 | rust-test: rust-dependencies 17 | cd $(PROJECT_DIR)/lib && cargo test 18 | 19 | wasm: 20 | cd $(PROJECT_DIR)/lib && cargo build --target wasm32-unknown-unknown --release 21 | mkdir -p $(PROJECT_DIR)/static 22 | cp $(PROJECT_DIR)/lib/target/wasm32-unknown-unknown/release/cedarwasm.wasm $(PROJECT_DIR)/static/cedar.wasm 23 | 24 | build: dependencies wasm 25 | 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cedar Go 2 | [![Go Report Card](https://goreportcard.com/badge/github.com/Joffref/cedar)](https://goreportcard.com/report/github.com/Joffref/cedar) 3 | [![GoDoc](https://godoc.org/github.com/Joffref/cedar?status.svg)](https://godoc.org/github.com/Joffref/cedar) 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE) 5 | 6 | A Go binding for the [Cedar project](https://www.cedarpolicy.com/en/) using [Wasm](https://webassembly.org/) to run the 7 | Cedar engine in a Go project with near zero overhead. 8 | 9 | ![Logo](assets/images/logo.png) 10 | 11 | 12 | ## Installation 13 | 14 | ```bash 15 | go get github.com/Joffref/cedar 16 | ``` 17 | 18 | ## Usage 19 | 20 | The following example shows how to use the Cedar engine to evaluate a policy inside your Go code. 21 | 22 | ```go 23 | package main 24 | 25 | import ( 26 | "context" 27 | "fmt" 28 | "github.com/Joffref/cedar" 29 | ) 30 | 31 | const policies = ` 32 | permit( 33 | principal == User::"alice", 34 | action == Action::"update", 35 | resource == Photo::"VacationPhoto94.jpg" 36 | ); 37 | ` 38 | 39 | const entities = `[]` 40 | 41 | func main() { 42 | engine, err := cedar.NewCedarEngine(context.Background()) 43 | if err != nil { 44 | panic(err) 45 | } 46 | defer engine.Close(context.Background()) 47 | err = engine.SetEntitiesFromJson(context.Background(), entities) 48 | if err != nil { 49 | panic(err) 50 | } 51 | err = engine.SetPolicies(context.Background(), policies) 52 | if err != nil { 53 | panic(err) 54 | } 55 | res, err := engine.Eval(context.Background(), cedar.EvalRequest{ 56 | Principal: "User::\"alice\"", 57 | Action: "Action::\"update\"", 58 | Resource: "Photo::\"VacationPhoto94.jpg\"", 59 | Context: "{}", // Don't forget to set the context to an empty JSON object if you don't need it. 60 | }) 61 | if err != nil { 62 | panic(err) 63 | } 64 | fmt.Println(res) 65 | } 66 | ``` 67 | 68 | ## TODO 69 | 70 | - [ ] Add more tests and examples. 71 | - [ ] Add a benchmark between the Go and the Rust version. 72 | - [ ] Support policy templates. 73 | - [ ] Support Partial Evaluation. 74 | - [ ] Add validation of the policy, the entities and the EvalRequest before sending them to the engine. 75 | - ... 76 | 77 | ## Contributing 78 | 79 | Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests. 80 | 81 | ## License 82 | 83 | This project is licensed under the Apache License v2.0 - see the [LICENSE](LICENSE) file for details. 84 | 85 | ## Misc 86 | 87 | This section contains some information about the project. 88 | 89 | ### Why this binding? 90 | 91 | The [Cedar project](https://www.cedarpolicy.com/en/) is a great project but it only provides a Rust binding. 92 | I wanted to use it in a Go project so I decided to create this binding to embed the Cedar engine in a Go project. 93 | Another solution would have been to call Cedar through a REST API but I wanted to avoid the overhead of the network. 94 | 95 | ### Why Wasm? 96 | 97 | The main reason is to avoid using [CGO](https://golang.org/cmd/cgo/) for performance reasons. 98 | Thanks to Wasm, we can call the Cedar engine directly from Go without using CGO and with near native performance. 99 | 100 | For more information about the considerations that led to this choice, I recommend watching 101 | this video : [GopherCon 2022: Takeshi Yoneda - CGO-less Foreign Function Interface with WebAssembly](https://www.youtube.com/watch?v=HcRSe4Y-1Fc). 102 | 103 | ### Why not using the FFI interface provided by the Cedar project? 104 | 105 | The FFI interface provided by the Cedar project initializes the policy and the entities store during the call to the `eval` function. 106 | This means that if you want to evaluate multiple requests, you will have to initialize the policy and the entities store for each request. 107 | This is not optimal if you want to evaluate a lot of requests. 108 | 109 | This binding initializes the policy and the entities store only once and then evaluates the requests without having to reinitialize the policy and the entities store. 110 | 111 | ### Cedar affiliation 112 | 113 | This project is not affiliated with the Cedar project, thus it is not an official binding. 114 | -------------------------------------------------------------------------------- /api.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import "github.com/tetratelabs/wazero/api" 4 | 5 | type function string 6 | 7 | const ( 8 | allocate function = "allocate" 9 | deallocate function = "deallocate" 10 | setEntities function = "set_entities" 11 | setPolicies function = "set_policies" 12 | isAuthorizedString function = "is_authorized_string" 13 | isAuthorizedJSON function = "is_authorized_json" 14 | ) 15 | 16 | // exportFuncs returns a map of exported functions from the wasm module. 17 | func exportFuncs(module api.Module) map[string]api.Function { 18 | exportedFuncs := make(map[string]api.Function) 19 | exportedFuncs[string(isAuthorizedString)] = module.ExportedFunction(string(isAuthorizedString)) 20 | exportedFuncs[string(isAuthorizedJSON)] = module.ExportedFunction(string(isAuthorizedJSON)) 21 | exportedFuncs[string(setEntities)] = module.ExportedFunction(string(setEntities)) 22 | exportedFuncs[string(setPolicies)] = module.ExportedFunction(string(setPolicies)) 23 | // allocate and deallocate help us manage memory in the wasm module. 24 | exportedFuncs[string(allocate)] = module.ExportedFunction(string(allocate)) 25 | exportedFuncs[string(deallocate)] = module.ExportedFunction(string(deallocate)) 26 | return exportedFuncs 27 | } 28 | -------------------------------------------------------------------------------- /api_test.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import ( 4 | "context" 5 | "github.com/tetratelabs/wazero" 6 | "github.com/tetratelabs/wazero/api" 7 | "testing" 8 | ) 9 | 10 | func Test_Allocation(t *testing.T) { 11 | r := wazero.NewRuntime(context.Background()) 12 | module, err := r.Instantiate(context.Background(), cedarWasm) 13 | if err != nil { 14 | t.Fatal(err) 15 | } 16 | t.Run("two concurrent allocation must return different ptr", func(t *testing.T) { 17 | twoConcurrentAllocationMustReturnDifferentPtr(t, module) 18 | }) 19 | t.Run("a huge allocation must return an error", func(t *testing.T) { 20 | aHugeAllocationMustReturnAPtr(t, module) 21 | }) 22 | } 23 | 24 | // aHugeAllocationMustReturnAPtr tests that a huge allocation mustn't return an error. 25 | // As we use Wasm to run the Engine, we need to ensure that even if the user tries to allocate a huge amount of memory, 26 | // memory will be allocated without crashing the process. 27 | func aHugeAllocationMustReturnAPtr(t *testing.T, module api.Module) { 28 | exportedFuncs := exportFuncs(module) 29 | entitiesSize := uint64(1000000000) // 1GB allocation as we allocate u8 (1 byte) * size inside runtime. 30 | entitiesPtr, err := exportedFuncs[string(allocate)].Call(context.Background(), entitiesSize) 31 | if err != nil { 32 | t.Fatal(err) 33 | } 34 | _, err = exportedFuncs[string(deallocate)].Call(context.Background(), entitiesPtr[0], entitiesSize) 35 | if err != nil { 36 | t.Fatal("expected an error") 37 | } 38 | } 39 | 40 | func twoConcurrentAllocationMustReturnDifferentPtr(t *testing.T, module api.Module) { 41 | exportedFuncs := exportFuncs(module) 42 | entitiesSize := uint64(10) 43 | entitiesPtr1, err := exportedFuncs[string(allocate)].Call(context.Background(), entitiesSize) 44 | if err != nil { 45 | t.Fatal(err) 46 | } 47 | entitiesPtr2, err := exportedFuncs[string(allocate)].Call(context.Background(), entitiesSize) 48 | if err != nil { 49 | t.Fatal(err) 50 | } 51 | if entitiesPtr1[0] == entitiesPtr2[0] { 52 | t.Fatal("expected different pointers") 53 | } 54 | _, err = exportedFuncs[string(deallocate)].Call(context.Background(), entitiesPtr1[0], entitiesSize) 55 | if err != nil { 56 | t.Fatal(err) 57 | } 58 | _, err = exportedFuncs[string(deallocate)].Call(context.Background(), entitiesPtr2[0], entitiesSize) 59 | if err != nil { 60 | t.Fatal(err) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /assets/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Joffref/cedar/1f16a62a81c1e013a601d0804a9ad87829337f92/assets/images/logo.png -------------------------------------------------------------------------------- /engine.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import ( 4 | "context" 5 | _ "embed" 6 | "encoding/json" 7 | "fmt" 8 | "github.com/tetratelabs/wazero" 9 | "github.com/tetratelabs/wazero/api" 10 | ) 11 | 12 | //go:embed static/cedar.wasm 13 | var cedarWasm []byte 14 | 15 | // CedarEngine is an instance of the cedar wasm engine. 16 | type CedarEngine struct { 17 | runtime wazero.Runtime 18 | module api.Module 19 | exportedFuncs map[string]api.Function 20 | } 21 | 22 | // NewCedarEngine creates a new instance of the cedar wasm engine. 23 | // This is blocking and may take a while to complete. Ensure you do not call this from a hot path. 24 | func NewCedarEngine(ctx context.Context) (*CedarEngine, error) { 25 | r := wazero.NewRuntime(ctx) 26 | module, err := r.Instantiate(ctx, cedarWasm) 27 | if err != nil { 28 | return nil, err 29 | } 30 | return &CedarEngine{ 31 | runtime: r, 32 | module: module, 33 | exportedFuncs: exportFuncs(module), 34 | }, nil 35 | } 36 | 37 | // SetEntitiesFromJson sets the entities in the engine from a json string. 38 | // See https://docs.cedarpolicy.com/syntax-entity.html for more information. 39 | func (c *CedarEngine) SetEntitiesFromJson(ctx context.Context, entities string) error { 40 | entitiesSize := uint64(len(entities)) 41 | entitiesPtr, err := c.exportedFuncs[string(allocate)].Call(ctx, entitiesSize) 42 | if err != nil { 43 | return err 44 | } 45 | defer c.exportedFuncs[string(deallocate)].Call(ctx, entitiesPtr[0], entitiesSize) 46 | ok := c.module.Memory().WriteString(uint32(entitiesPtr[0]), entities) 47 | if !ok { 48 | return fmt.Errorf("failed to write entities to memory") 49 | } 50 | _, err = c.exportedFuncs[string(setEntities)].Call(ctx, entitiesPtr[0], entitiesSize) 51 | return err 52 | } 53 | 54 | // SetPolicies sets the policies in the engine from a string. 55 | // See https://docs.cedarpolicy.com/syntax-policy.htmle for more information. 56 | func (c *CedarEngine) SetPolicies(ctx context.Context, policies string) error { 57 | policiesSize := uint64(len(policies)) 58 | policiesPtr, err := c.exportedFuncs[string(allocate)].Call(ctx, policiesSize) 59 | if err != nil { 60 | return err 61 | } 62 | defer c.exportedFuncs[string(deallocate)].Call(ctx, policiesPtr[0], policiesSize) 63 | ok := c.module.Memory().WriteString(uint32(policiesPtr[0]), policies) 64 | if !ok { 65 | return fmt.Errorf("failed to write policies to memory") 66 | } 67 | _, err = c.exportedFuncs[string(setPolicies)].Call(ctx, policiesPtr[0], policiesSize) 68 | return err 69 | } 70 | 71 | // Eval evaluates the request against the policies and entities in the engine. 72 | // See EvalRequest for more information. 73 | func (c *CedarEngine) Eval(ctx context.Context, req EvalRequest) (EvalResult, error) { 74 | evalPtr, err := c.writeEvalRequestInMemory(ctx, req) 75 | if err != nil { 76 | return "", err 77 | } 78 | defer c.deallocateEvalRequestInMemory(ctx, evalPtr, req) 79 | resPtr, err := c.exportedFuncs[string(isAuthorizedString)].Call( 80 | ctx, 81 | evalPtr, 82 | uint64(len(req.Principal)), 83 | evalPtr+uint64(len(req.Principal)), 84 | uint64(len(req.Action)), 85 | evalPtr+uint64(len(req.Principal))+uint64(len(req.Action)), 86 | uint64(len(req.Resource)), 87 | evalPtr+uint64(len(req.Principal))+uint64(len(req.Action))+uint64(len(req.Resource)), 88 | uint64(len(req.Context)), 89 | ) 90 | if err != nil { 91 | return "", err 92 | } 93 | decision, err := c.readDecisionFromMemory(ctx, resPtr[0]) 94 | return EvalResult(decision), nil 95 | } 96 | 97 | // EvalWithResponse evaluates the request against the policies and entities in the engine. 98 | // Returns the result as a json string. 99 | func (c *CedarEngine) EvalWithResponse(ctx context.Context, req EvalRequest) (EvalResponse, error) { 100 | evalPtr, err := c.writeEvalRequestInMemory(ctx, req) 101 | if err != nil { 102 | return EvalResponse{}, err 103 | } 104 | defer c.deallocateEvalRequestInMemory(ctx, evalPtr, req) 105 | resPtr, err := c.exportedFuncs[string(isAuthorizedJSON)].Call( 106 | ctx, 107 | evalPtr, 108 | uint64(len(req.Principal)), 109 | evalPtr+uint64(len(req.Principal)), 110 | uint64(len(req.Action)), 111 | evalPtr+uint64(len(req.Principal))+uint64(len(req.Action)), 112 | uint64(len(req.Resource)), 113 | evalPtr+uint64(len(req.Principal))+uint64(len(req.Action))+uint64(len(req.Resource)), 114 | uint64(len(req.Context)), 115 | ) 116 | if err != nil { 117 | return EvalResponse{}, err 118 | } 119 | decision, err := c.readDecisionFromMemory(ctx, resPtr[0]) 120 | var evalResponse EvalResponse 121 | err = json.Unmarshal(decision, &evalResponse) 122 | if err != nil { 123 | return EvalResponse{}, err 124 | } 125 | return evalResponse, nil 126 | } 127 | 128 | // IsAuthorized evaluates the request against the policies and entities in the engine and returns true if the request is authorized. 129 | // It is a convenience method that is equivalent to calling Eval and checking the result. 130 | // See Eval for more information. 131 | func (c *CedarEngine) IsAuthorized(ctx context.Context, req EvalRequest) (bool, error) { 132 | res, err := c.Eval(ctx, req) 133 | if err != nil { 134 | return false, err 135 | } 136 | return res.IsPermit(), nil 137 | } 138 | 139 | // Close closes the engine and cleanup the wasm runtime. 140 | // Ensure you call this when you are done with the engine to free up resources used by the engine. 141 | func (c *CedarEngine) Close(ctx context.Context) error { 142 | return c.runtime.Close(ctx) 143 | } 144 | -------------------------------------------------------------------------------- /engine_test.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | ) 7 | 8 | func TestCedarEngine_IsAuthorized(t *testing.T) { 9 | policy := ` 10 | permit( 11 | principal == User::"alice", 12 | action == Action::"update", 13 | resource == Photo::"VacationPhoto94.jpg" 14 | ); 15 | ` 16 | engine, err := NewCedarEngine(context.TODO()) 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | defer engine.Close(context.Background()) 21 | err = engine.SetEntitiesFromJson(context.Background(), "[]") 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | err = engine.SetPolicies(context.Background(), policy) 26 | if err != nil { 27 | t.Fatal(err) 28 | } 29 | t.Run("is authorized must return allow", func(t *testing.T) { 30 | isAuthorizedMustReturnAllow(t, engine, "User::\"alice\"", "Action::\"update\"", "Photo::\"VacationPhoto94.jpg\"") 31 | }) 32 | t.Run("is authorized must return deny", func(t *testing.T) { 33 | isAuthorizedMustReturnDeny(t, engine, "User::\"alice\"", "Action::\"update\"", "Photo::\"VacationPhoto95.jpg\"") 34 | }) 35 | } 36 | func isAuthorizedMustReturnAllow(t *testing.T, engine *CedarEngine, principal, action, resource string) { 37 | res, err := engine.IsAuthorized(context.Background(), EvalRequest{ 38 | Principal: principal, 39 | Action: action, 40 | Resource: resource, 41 | Context: "{}", 42 | }) 43 | if err != nil { 44 | t.Fatal(err) 45 | } 46 | if !res { 47 | t.Fatal("expected Allow") 48 | } 49 | } 50 | 51 | func isAuthorizedMustReturnDeny(t *testing.T, engine *CedarEngine, principal, action, resource string) { 52 | res, err := engine.IsAuthorized(context.Background(), EvalRequest{ 53 | Principal: principal, 54 | Action: action, 55 | Resource: resource, 56 | Context: "{}", 57 | }) 58 | if err != nil { 59 | t.Fatal(err) 60 | } 61 | if res { 62 | t.Fatal("expected Deny") 63 | } 64 | } 65 | 66 | func TestCedarEngine_EvalWithResponse(t *testing.T) { 67 | policy := ` 68 | permit( 69 | principal == User::"alice", 70 | action == Action::"update", 71 | resource == Photo::"VacationPhoto94.jpg" 72 | ); 73 | ` 74 | engine, err := NewCedarEngine(context.Background()) 75 | if err != nil { 76 | t.Fatal(err) 77 | } 78 | defer engine.Close(context.Background()) 79 | err = engine.SetEntitiesFromJson(context.Background(), "[]") 80 | if err != nil { 81 | t.Fatal(err) 82 | } 83 | err = engine.SetPolicies(context.Background(), policy) 84 | if err != nil { 85 | t.Fatal(err) 86 | } 87 | t.Run("eval with response must return allow", func(t *testing.T) { 88 | evalJSONMustReturnAllow(t, engine, "User::\"alice\"", "Action::\"update\"", "Photo::\"VacationPhoto94.jpg\"") 89 | }) 90 | t.Run("eval with response must return deny", func(t *testing.T) { 91 | evalJSONMustReturnDeny(t, engine, "User::\"alice\"", "Action::\"update\"", "Photo::\"VacationPhoto95.jpg\"") 92 | }) 93 | } 94 | 95 | func evalJSONMustReturnAllow(t *testing.T, engine *CedarEngine, principal, action, resource string) { 96 | res, err := engine.EvalWithResponse(context.Background(), EvalRequest{ 97 | Principal: principal, 98 | Action: action, 99 | Resource: resource, 100 | Context: "{}", 101 | }) 102 | if err != nil { 103 | t.Fatal(err) 104 | } 105 | if res.Decision != "Allow" { 106 | t.Fatal("expected Allow") 107 | } 108 | if res.Diagnostics.Reason[0] != "policy0" { // First policy as it is the only one. Cedar engine fixes the policy name to policy if not provided. 109 | t.Fatal("expected policy0 to be the reason for the decision") 110 | } 111 | if len(res.Diagnostics.Errors) != 0 { 112 | t.Fatal("expected no errors") 113 | } 114 | } 115 | 116 | func evalJSONMustReturnDeny(t *testing.T, engine *CedarEngine, principal, action, resource string) { 117 | res, err := engine.EvalWithResponse(context.Background(), EvalRequest{ 118 | Principal: principal, 119 | Action: action, 120 | Resource: resource, 121 | Context: "{}", 122 | }) 123 | if err != nil { 124 | t.Fatal(err) 125 | } 126 | if res.Decision != "Deny" { 127 | t.Fatal("expected Deny") 128 | } 129 | if len(res.Diagnostics.Reason) != 0 { 130 | t.Fatal("expected no reason for the decision") 131 | } 132 | if len(res.Diagnostics.Errors) != 0 { 133 | t.Fatal("expected no errors") 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /eval.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | // EvalRequest is the request object for the Eval function. 4 | // Instantion should look like this: 5 | // 6 | // res, err := engine.Eval(context.Background(), cedar.EvalRequest{ 7 | // Principal: "User::\"alice\"", 8 | // Action: "Action::\"update\"", 9 | // Resource: "Photo::\"VacationPhoto94.jpg\"", 10 | // Context: "{}", 11 | // }) 12 | // 13 | // Do not forget to add a context to the eval call in a json format and escape the quotes. 14 | // For more information, see https://www.cedarpolicy.com/en/tutorial/abac-pt1 15 | type EvalRequest struct { 16 | // Who is making the request. This is a string in the form of "User::\"alice\"". 17 | Principal string `json:"principal"` 18 | // What action is being requested. This is a string in the form of "Action::\"update\"". 19 | Action string `json:"action"` 20 | // What resource is being requested. This is a string in the form of "Photo::\"VacationPhoto94.jpg\"". 21 | Resource string `json:"resource"` 22 | // Context is a json string that can be used to pass additional information to the policy engine 23 | // for use in policy evaluation. 24 | // For more information, see https://www.cedarpolicy.com/en/tutorial/context 25 | Context string `json:"context"` 26 | } 27 | 28 | // EvalResponse is the response issued by the Eval function when in JSON Eval mode. 29 | type EvalResponse struct { 30 | // Decision is the result of the policy evaluation. 31 | Decision EvalResult `json:"decision"` 32 | // Diagnostics is the diagnostic information returned by the policy engine when an evaluation is made. 33 | Diagnostics Diagnostic `json:"diagnostics"` 34 | } 35 | 36 | // Diagnostic represents the diagnostic information returned by the policy engine when an evaluation is made. 37 | type Diagnostic struct { 38 | // Reason is the list of policies that caused the decision. 39 | Reason []string `json:"reason"` 40 | // Errors is the list of errors that occurred during evaluation. 41 | Errors []string `json:"errors"` 42 | } 43 | 44 | // EvalResult is the response object for the Eval function. 45 | type EvalResult string 46 | 47 | const ( 48 | EvalResultPermit EvalResult = "Allow" 49 | EvalResultDeny EvalResult = "Deny" 50 | ) 51 | 52 | func (e EvalResult) String() string { 53 | return string(e) 54 | } 55 | 56 | func (e EvalResult) IsPermit() bool { 57 | return e == EvalResultPermit 58 | } 59 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Joffref/cedar 2 | 3 | go 1.20 4 | 5 | require github.com/tetratelabs/wazero v1.1.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/tetratelabs/wazero v1.1.0 h1:EByoAhC+QcYpwSZJSs/aV0uokxPwBgKxfiokSUwAknQ= 2 | github.com/tetratelabs/wazero v1.1.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= 3 | -------------------------------------------------------------------------------- /helper.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | ) 7 | 8 | // writeEvalRequestInMemory writes the eval request to the wasm memory. 9 | func (c *CedarEngine) writeEvalRequestInMemory(ctx context.Context, req EvalRequest) (uint64, error) { 10 | evalSize := uint64(len(req.Principal) + len(req.Action) + len(req.Resource) + len(req.Context)) 11 | evalPtr, err := c.exportedFuncs[string(allocate)].Call(ctx, evalSize) 12 | if err != nil { 13 | return 0, err 14 | } 15 | ok := c.module.Memory().WriteString(uint32(evalPtr[0]), req.Principal) 16 | if !ok { 17 | return 0, fmt.Errorf("failed to write principal to memory") 18 | } 19 | offset := uint32(0) 20 | offset += uint32(len(req.Principal)) 21 | ok = c.module.Memory().WriteString(uint32(evalPtr[0])+offset, req.Action) 22 | if !ok { 23 | return 0, fmt.Errorf("failed to write action to memory") 24 | } 25 | offset += uint32(len(req.Action)) 26 | ok = c.module.Memory().WriteString(uint32(evalPtr[0])+offset, req.Resource) 27 | if !ok { 28 | return 0, fmt.Errorf("failed to write resource to memory") 29 | } 30 | offset += uint32(len(req.Resource)) 31 | ok = c.module.Memory().WriteString(uint32(evalPtr[0])+offset, req.Context) 32 | if !ok { 33 | return 0, fmt.Errorf("failed to write context to memory") 34 | } 35 | return evalPtr[0], nil 36 | } 37 | 38 | // deallocateEvalRequestInMemory deallocates the eval request from the wasm memory. 39 | func (c *CedarEngine) deallocateEvalRequestInMemory(ctx context.Context, ptr uint64, req EvalRequest) error { 40 | length := uint64(len(req.Principal) + len(req.Action) + len(req.Resource) + len(req.Context)) 41 | _, err := c.exportedFuncs[string(deallocate)].Call(ctx, ptr, length) 42 | return err 43 | } 44 | 45 | // readDecisionFromMemory reads the decision from the wasm memory. 46 | func (c *CedarEngine) readDecisionFromMemory(ctx context.Context, ptr uint64) ([]byte, error) { 47 | decisionPtr := uint32(ptr >> 32) 48 | decisionSize := uint32(ptr) 49 | defer c.exportedFuncs[string(deallocate)].Call(ctx, uint64(decisionPtr), uint64(decisionSize)) 50 | decision, ok := c.module.Memory().Read(decisionPtr, decisionSize) 51 | if !ok { 52 | return []byte{}, fmt.Errorf("failed to read decision from memory") 53 | } 54 | return decision, nil 55 | } 56 | -------------------------------------------------------------------------------- /lib/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | Cargo.lock 3 | 4 | target/ 5 | 6 | # Don't check in the local rustup toolchain override. 7 | /rust-toolchain.toml 8 | 9 | # Don't check in the local metadata file. 10 | .DS_Store 11 | .idea 12 | 13 | # Don't check in the Emacs temp files 14 | *~ 15 | 16 | # Don't check in test framework files 17 | .attach_pid* 18 | 19 | # Don't check IntelliJ module files 20 | *.iml 21 | 22 | libhello.a 23 | libhello.so -------------------------------------------------------------------------------- /lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "cedarwasm" 4 | description = "Cedar Policy exported to WebAssembly for use in go" 5 | edition = "2021" 6 | version = "1.0.0" 7 | 8 | [dependencies] 9 | cedar-policy = { version = "2.0.0" } 10 | wee_alloc = "0.4.5" 11 | once_cell = "1.17.1" 12 | serde_json = "1.0.96" 13 | 14 | [lib] 15 | crate_type = ["cdylib"] 16 | 17 | [profile.release] 18 | opt-level = 2 19 | lto = true 20 | codegen-units = 1 21 | -------------------------------------------------------------------------------- /lib/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /lib/src/interface.rs: -------------------------------------------------------------------------------- 1 | extern crate alloc; 2 | extern crate core; 3 | extern crate wee_alloc; 4 | extern crate serde_json; 5 | 6 | use cedar_policy::{PolicySet, Entities, Authorizer, EntityUid, Context, Request, Decision, Response}; 7 | 8 | use std::{slice}; 9 | use std::collections::HashMap; 10 | use std::str::FromStr; 11 | 12 | use once_cell::sync::Lazy; 13 | 14 | static mut ENGINE: Lazy= Lazy::new(|| { 15 | CedarEngine { 16 | entity_store: Entities::empty(), 17 | policy_set: PolicySet::new(), 18 | authorizer: Authorizer::new(), 19 | } 20 | }); 21 | 22 | static mut HEAP: Lazy> = Lazy::new(|| { 23 | HashMap::new() 24 | }); 25 | 26 | struct CedarEngine { 27 | entity_store: Entities, 28 | policy_set: PolicySet, 29 | authorizer: Authorizer 30 | } 31 | 32 | impl CedarEngine { 33 | fn set_entities(&mut self, entities_json: &str) { 34 | match Entities::from_json_str(entities_json, None) { 35 | Ok(entities) => { 36 | self.entity_store = entities; 37 | } 38 | Err(e) => { 39 | println!("Error adding entity: {}", e); 40 | } 41 | } 42 | } 43 | fn set_policies(&mut self, policies_str: &str) { 44 | match PolicySet::from_str(policies_str) { 45 | Ok(policies) => { 46 | self.policy_set = policies; 47 | } 48 | Err(e) => { 49 | println!("Error adding policy: {}", e); 50 | } 51 | } 52 | } 53 | fn is_authorized(&self, entity: &str, action: &str, resource: &str, context: &str) -> Response { 54 | let principal = EntityUid::from_str(entity).expect("entity parse error"); 55 | let action = EntityUid::from_str(action).expect("entity parse error"); 56 | let resource = EntityUid::from_str(resource).expect("entity parse error"); 57 | let context = Context::from_json_str(context, None).unwrap(); 58 | let query = Request::new(Some(principal), Some(action), Some(resource), context); 59 | self.authorizer.is_authorized(&query, &self.policy_set, &self.entity_store) 60 | } 61 | 62 | fn is_authorized_string(&self, entity: &str, action: &str, resource: &str, context: &str) -> String { 63 | let response = self.is_authorized(entity, action, resource, context); 64 | return if response.decision() == Decision::Allow { 65 | String::from("Allow") 66 | } else { 67 | String::from("Deny") 68 | } 69 | } 70 | fn is_authorized_json(&self, entity: &str, action: &str, resource: &str, context: &str) -> String { 71 | let response = self.is_authorized(entity, action, resource, context); 72 | return serde_json::to_string(&response).unwrap(); 73 | } 74 | } 75 | 76 | #[cfg_attr(all(target_arch = "wasm32"), export_name = "set_entities")] 77 | #[no_mangle] 78 | pub unsafe extern "C" fn _set_entities(entities_ptr: u32, entities_len: u32) { 79 | let entities = ptr_to_string(entities_ptr, entities_len); 80 | ENGINE.set_entities(&entities); 81 | } 82 | 83 | #[cfg_attr(all(target_arch = "wasm32"), export_name = "set_policies")] 84 | #[no_mangle] 85 | pub unsafe extern "C" fn _set_policies(policies_ptr: u32, policies_len: u32) { 86 | let policies = ptr_to_string(policies_ptr, policies_len); 87 | ENGINE.set_policies(&policies); 88 | } 89 | 90 | 91 | #[cfg_attr(all(target_arch = "wasm32"), export_name = "is_authorized_string")] 92 | #[no_mangle] 93 | // Returns a decision as a string (Allow/Deny) 94 | pub unsafe extern "C" fn _is_authorized_string( 95 | entity_ptr: u32, 96 | entity_len: u32, 97 | action_ptr: u32, 98 | action_len: u32, 99 | resource_ptr: u32, 100 | resource_len: u32, 101 | context_ptr: u32, 102 | context_len: u32, 103 | ) -> u64 { 104 | let entity = ptr_to_string(entity_ptr, entity_len); 105 | let action = ptr_to_string(action_ptr, action_len); 106 | let resource = ptr_to_string(resource_ptr, resource_len); 107 | let context = ptr_to_string(context_ptr, context_len); 108 | let result = ENGINE.is_authorized_string(entity.as_str(), action.as_str(), resource.as_str(), context.as_str()); 109 | let (ptr, len) = string_to_ptr(&result); 110 | std::mem::forget(result); 111 | return ((ptr as u64) << 32) | len as u64; 112 | } 113 | 114 | #[cfg_attr(all(target_arch = "wasm32"), export_name = "is_authorized_json")] 115 | #[no_mangle] 116 | // Returns decision formatted as JSON as a string 117 | pub unsafe extern "C" fn _is_authorized_json( 118 | entity_ptr: u32, 119 | entity_len: u32, 120 | action_ptr: u32, 121 | action_len: u32, 122 | resource_ptr: u32, 123 | resource_len: u32, 124 | context_ptr: u32, 125 | context_len: u32, 126 | ) -> u64 { 127 | let entity = ptr_to_string(entity_ptr, entity_len); 128 | let action = ptr_to_string(action_ptr, action_len); 129 | let resource = ptr_to_string(resource_ptr, resource_len); 130 | let context = ptr_to_string(context_ptr, context_len); 131 | let result = ENGINE.is_authorized_json(entity.as_str(), action.as_str(), resource.as_str(), context.as_str()); 132 | let (ptr, len) = string_to_ptr(&result); 133 | std::mem::forget(result); 134 | return ((ptr as u64) << 32) | len as u64; 135 | } 136 | 137 | 138 | /// Returns a string from WebAssembly compatible numeric types representing 139 | /// its pointer and length. 140 | unsafe fn ptr_to_string(ptr: u32, len: u32) -> String { 141 | let slice = slice::from_raw_parts_mut(ptr as *mut u8, len as usize); 142 | let utf8 = std::str::from_utf8_unchecked_mut(slice); 143 | return String::from(utf8); 144 | } 145 | 146 | /// Returns a pointer and size pair for the given string in a way compatible 147 | /// with WebAssembly numeric types. 148 | /// 149 | /// Note: This doesn't change the ownership of the String. To intentionally 150 | /// leak it, use [`std::mem::forget`] on the input after calling this. 151 | unsafe fn string_to_ptr(s: &String) -> (u32, u32) { 152 | return (s.as_ptr() as u32, s.len() as u32); 153 | } 154 | 155 | /// Set the global allocator to the WebAssembly optimized one. 156 | #[global_allocator] 157 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 158 | 159 | /// WebAssembly export that allocates a pointer (linear memory offset) that can 160 | /// be used for a string. 161 | /// 162 | /// This is an ownership transfer, which means the caller must call 163 | /// [`deallocate`] when finished. 164 | #[cfg_attr(all(target_arch = "wasm32"), export_name = "allocate")] 165 | #[no_mangle] 166 | pub unsafe extern "C" fn _allocate(size: u32) -> * mut u8 { 167 | allocate(size as usize) 168 | } 169 | 170 | /// Allocates size bytes and leaks the pointer where they start. 171 | unsafe fn allocate(size: usize) -> *mut u8 { 172 | // Allocate the amount of bytes needed. 173 | let vec: Vec = Vec::with_capacity(size); 174 | 175 | // into_raw leaks the memory to the caller. 176 | let ptr = vec.as_ptr() as *mut u8; 177 | 178 | // Store the boxed_vec to prevent it from being deallocated. 179 | HEAP.insert(ptr, vec.leak()); 180 | // Return the pointer to the caller. 181 | ptr 182 | } 183 | 184 | 185 | /// WebAssembly export that deallocates a pointer of the given size (linear 186 | /// memory offset, byteCount) allocated by [`allocate`]. 187 | #[cfg_attr(all(target_arch = "wasm32"), export_name = "deallocate")] 188 | #[no_mangle] 189 | pub unsafe extern "C" fn _deallocate(ptr: u32, size: u32) { 190 | deallocate(ptr as *mut u8, size as usize); 191 | } 192 | 193 | /// Retakes the pointer which allows its memory to be freed. 194 | unsafe fn deallocate(ptr: *mut u8, size: usize) { 195 | // Remove the boxed_vec from the map so it can be deallocated. 196 | HEAP.remove(&ptr).expect("Pointer not found in heap map"); 197 | let _ = Vec::from_raw_parts(ptr, size, size); 198 | let _ = *ptr; // explicitly drop the pointer 199 | } 200 | 201 | #[cfg(test)] 202 | mod test { 203 | use super::*; 204 | 205 | #[test] 206 | fn set_policies() { 207 | let mut engine = CedarEngine{ 208 | authorizer: Authorizer::new(), 209 | entity_store: Entities::empty(), 210 | policy_set: PolicySet::new(), 211 | }; 212 | let policies = "permit(principal, action, resource); permit(principal, action, resource);"; 213 | engine.set_policies(policies); 214 | let mut counter = 0; 215 | for _policy in engine.policy_set.policies() { 216 | counter += 1; 217 | } 218 | assert_eq!(counter, 2); 219 | } 220 | #[test] 221 | fn set_entities() { 222 | let mut engine = CedarEngine{ 223 | authorizer: Authorizer::new(), 224 | entity_store: Entities::empty(), 225 | policy_set: PolicySet::new(), 226 | }; 227 | let entities_json = r#"[ 228 | { 229 | "uid": { 230 | "type": "User", 231 | "id": "Bob" 232 | }, 233 | "attrs": {}, 234 | "parents": [ 235 | { 236 | "type": "Role", 237 | "id": "vacationPhotoJudges" 238 | }, 239 | { 240 | "type": "Role", 241 | "id": "juniorPhotographerJudges" 242 | } 243 | ] 244 | }, 245 | { 246 | "uid": { 247 | "type": "Role", 248 | "id": "vacationPhotoJudges" 249 | }, 250 | "attrs": {}, 251 | "parents": [] 252 | }, 253 | { 254 | "uid": { 255 | "type": "Role", 256 | "id": "juniorPhotographerJudges" 257 | }, 258 | "attrs": {}, 259 | "parents": [] 260 | } 261 | ]"#; 262 | engine.set_entities(entities_json); 263 | let mut counter = 0; 264 | for _entity in engine.entity_store.iter() { 265 | counter += 1; 266 | } 267 | assert_eq!(counter, 3); 268 | } 269 | 270 | #[test] 271 | fn evaluate_string_response() { 272 | let mut engine = CedarEngine{ 273 | authorizer: Authorizer::new(), 274 | entity_store: Entities::empty(), 275 | policy_set: PolicySet::new(), 276 | }; 277 | let policies = "permit(principal, action, resource); permit(principal, action, resource);"; 278 | engine.set_policies(policies); 279 | let entities = "[]"; 280 | engine.set_entities(entities); 281 | let result = engine.is_authorized_string("User::\"alice\"", "Action::\"update\"", "Photo::\"VacationPhoto94.jpg\"", "{}"); 282 | assert_eq!(result, "Allow"); 283 | } 284 | 285 | #[test] 286 | fn evaluate() { 287 | let mut engine = CedarEngine{ 288 | authorizer: Authorizer::new(), 289 | entity_store: Entities::empty(), 290 | policy_set: PolicySet::new(), 291 | }; 292 | let policies = "permit(principal, action, resource); permit(principal, action, resource);"; 293 | engine.set_policies(policies); 294 | let entities = "[]"; 295 | engine.set_entities(entities); 296 | let result = engine.is_authorized("User::\"alice\"", "Action::\"update\"", "Photo::\"VacationPhoto94.jpg\"", "{}"); 297 | assert_eq!(result.decision(), Decision::Allow); 298 | } 299 | 300 | #[test] 301 | fn allocate_deallocate() { 302 | unsafe { 303 | let ptr = allocate(10); 304 | assert_eq!(HEAP.contains_key(&ptr), true); 305 | deallocate(ptr, 10); 306 | assert_eq!(HEAP.contains_key(&ptr), false); 307 | let ptr = allocate(10); 308 | assert_eq!(HEAP.contains_key(&ptr), true); 309 | let ptr2 = allocate(10); 310 | assert_eq!(HEAP.contains_key(&ptr), true); 311 | assert_ne!(ptr as u8, ptr2 as u8); 312 | assert_eq!(HEAP.len(), 2); 313 | deallocate(ptr, 10); 314 | assert_eq!(HEAP.contains_key(&ptr), false); 315 | assert_eq!(HEAP.len(), 1); 316 | deallocate(ptr2, 10); 317 | assert_eq!(HEAP.contains_key(&ptr2), false); 318 | assert_eq!(HEAP.len(), 0); 319 | } 320 | } 321 | } 322 | -------------------------------------------------------------------------------- /lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | mod interface; 18 | 19 | pub use interface::*; 20 | -------------------------------------------------------------------------------- /static/cedar.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Joffref/cedar/1f16a62a81c1e013a601d0804a9ad87829337f92/static/cedar.wasm --------------------------------------------------------------------------------