diff --git a/.github/workflows/bar.yml b/.github/workflows/bar.yml new file mode 100644 index 0000000..871baab --- /dev/null +++ b/.github/workflows/bar.yml @@ -0,0 +1,14 @@ +name: verified bar +on: + push: + pull_request: + pull_request_review: + types: [submitted, dismissed] +jobs: + bar: + permissions: + contents: read + pull-requests: read + uses: Proven-Commons/mission/.github/workflows/verified-bar.yml@6ba85c27abaaf07905c9316aa96dc29f7b5847a2 + with: + bar-ref: 6ba85c27abaaf07905c9316aa96dc29f7b5847a2 diff --git a/Cedar.lean b/Cedar.lean new file mode 100644 index 0000000..2b2bcfa --- /dev/null +++ b/Cedar.lean @@ -0,0 +1 @@ +import Cedar.Basic diff --git a/Cedar/Basic.lean b/Cedar/Basic.lean new file mode 100644 index 0000000..5e93c39 --- /dev/null +++ b/Cedar/Basic.lean @@ -0,0 +1,19 @@ +import Cedar.Spec.Defs + +namespace Cedar + +def scopeMatches (scope : Option String) (value : String) : Bool := + scope == none || scope == some value + +def policyMatches (p : Policy) (r : Request) : Bool := + scopeMatches p.principal r.principal && scopeMatches p.action r.action && + scopeMatches p.resource r.resource + +def satisfied (effect : Effect) (r : Request) (p : Policy) : Bool := + p.effect == effect && policyMatches p r + +/-- Forbid overrides permit; without a matching permit the result is false. -/ +def authorize (ps : List Policy) (r : Request) : Bool := + !(ps.any (satisfied .forbid r)) && ps.any (satisfied .permit r) + +end Cedar diff --git a/Cedar/Proofs.lean b/Cedar/Proofs.lean new file mode 100644 index 0000000..de90bf4 --- /dev/null +++ b/Cedar/Proofs.lean @@ -0,0 +1,52 @@ +import Cedar + +namespace Cedar.Spec + +theorem policyMatches_iff (p : Policy) (r : Request) : policyMatches p r = true ↔ Matches p r := by + simp [policyMatches, scopeMatches, Matches, and_assoc] + +theorem satisfied_iff (e : Effect) (p : Policy) (r : Request) : + satisfied e r p = true ↔ p.effect = e ∧ Matches p r := by + simp [satisfied, policyMatches_iff] + +theorem any_iff (e : Effect) (ps : List Policy) (r : Request) : + ps.any (satisfied e r) = true ↔ ∃ p ∈ ps, p.effect = e ∧ Matches p r := by + simp only [List.any_eq_true, satisfied_iff] + +theorem authorize_iff (ps : List Policy) (r : Request) : + authorize ps r = true ↔ Allowed ps r := by + simp only [authorize, Bool.and_eq_true, Bool.not_eq_true'] + rw [← Bool.not_eq_true, any_iff, any_iff] + unfold Allowed + exact and_comm + +theorem forbid_denies (ps : List Policy) (r : Request) (p : Policy) + (hp : p ∈ ps) (he : p.effect = .forbid) (hm : Matches p r) : + authorize ps r = false := by + have hf : ps.any (satisfied .forbid r) = true := (any_iff _ _ _).mpr ⟨p, hp, he, hm⟩ + simp [authorize, hf] + +theorem default_denies (ps : List Policy) (r : Request) + (h : ¬ ∃ p ∈ ps, p.effect = .permit ∧ Matches p r) : + authorize ps r = false := by + have hp : ps.any (satisfied .permit r) = false := by + cases hx : ps.any (satisfied .permit r) + · rfl + · exact False.elim (h ((any_iff _ _ _).mp hx)) + simp [authorize, hp] + +theorem order_invariant (ps qs : List Policy) (r : Request) (h : ps.Perm qs) : + authorize ps r = authorize qs r := by + simp only [authorize, h.any_eq] + +theorem members_invariant (ps qs : List Policy) (r : Request) + (h : ∀ p, p ∈ ps ↔ p ∈ qs) : + authorize ps r = authorize qs r := by + have key : ∀ e, ps.any (satisfied e r) = qs.any (satisfied e r) := by + intro e + apply Bool.eq_iff_iff.mpr + simp only [List.any_eq_true] + exact ⟨fun ⟨p, hp, hs⟩ => ⟨p, (h p).mp hp, hs⟩, fun ⟨p, hp, hs⟩ => ⟨p, (h p).mpr hp, hs⟩⟩ + simp only [authorize, key] + +end Cedar.Spec diff --git a/Cedar/Spec.lean b/Cedar/Spec.lean new file mode 100644 index 0000000..51f49df --- /dev/null +++ b/Cedar/Spec.lean @@ -0,0 +1,29 @@ +import Cedar + +namespace Cedar.Spec + +/-- The decision is exactly the relational permit/forbid rule. -/ +theorem authorize_iff (ps : List Policy) (r : Request) : + authorize ps r = true ↔ Allowed ps r := sorry + +/-- Any satisfied forbid denies, even with satisfied permits. -/ +theorem forbid_denies (ps : List Policy) (r : Request) (p : Policy) + (hp : p ∈ ps) (he : p.effect = .forbid) (hm : Matches p r) : + authorize ps r = false := sorry + +/-- Without a satisfied permit the default is deny. -/ +theorem default_denies (ps : List Policy) (r : Request) + (h : ¬ ∃ p ∈ ps, p.effect = .permit ∧ Matches p r) : + authorize ps r = false := sorry + +/-- Reordering policies changes no decision. -/ +theorem order_invariant (ps qs : List Policy) (r : Request) (h : ps.Perm qs) : + authorize ps r = authorize qs r := sorry + +/-- Two lists with the same members give the same decision, so + duplicating or dropping a repeated policy changes nothing. -/ +theorem members_invariant (ps qs : List Policy) (r : Request) + (h : ∀ p, p ∈ ps ↔ p ∈ qs) : + authorize ps r = authorize qs r := sorry + +end Cedar.Spec diff --git a/Cedar/Spec/Defs.lean b/Cedar/Spec/Defs.lean new file mode 100644 index 0000000..5cdc3a3 --- /dev/null +++ b/Cedar/Spec/Defs.lean @@ -0,0 +1,35 @@ +namespace Cedar + +inductive Effect where + | permit | forbid + deriving DecidableEq, Repr + +structure Request where + principal : String + action : String + resource : String + deriving DecidableEq, Repr + +/-- `none` matches every value; `some s` matches exactly `s`. -/ +structure Policy where + effect : Effect + principal : Option String + action : Option String + resource : Option String + deriving DecidableEq, Repr + +namespace Spec + +/-- The independent relational meaning of a policy scope. -/ +def Matches (p : Policy) (r : Request) : Prop := + (p.principal = none ∨ p.principal = some r.principal) ∧ + (p.action = none ∨ p.action = some r.action) ∧ + (p.resource = none ∨ p.resource = some r.resource) + +/-- A request is allowed exactly when a permit matches and no forbid matches. -/ +def Allowed (ps : List Policy) (r : Request) : Prop := + (∃ p ∈ ps, p.effect = .permit ∧ Matches p r) ∧ + ¬ (∃ p ∈ ps, p.effect = .forbid ∧ Matches p r) + +end Spec +end Cedar diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Main.lean b/Main.lean new file mode 100644 index 0000000..2a01308 --- /dev/null +++ b/Main.lean @@ -0,0 +1,86 @@ +/- One request per line: principal action resource, then zero or more + policies separated by semicolons. Each policy is effect principal + action resource. Tokens contain no whitespace or semicolon; `*` in a + policy is a wildcard. Input is read as bytes: a line that is not + UTF-8 is malformed and prints `error`, so different byte strings + never become the same token. The CLI is tested, not covered by the + proofs. -/ +import Cedar + +open Cedar + +/-- Unicode's White_Space property (PropList.txt): the characters that + cannot appear in a token. -/ +def whiteSpace (c : Char) : Bool := + let n := c.toNat + (0x09 ≤ n && n ≤ 0x0D) || n == 0x20 || n == 0x85 || n == 0xA0 || n == 0x1680 || + (0x2000 ≤ n && n ≤ 0x200A) || n == 0x2028 || n == 0x2029 || n == 0x202F || + n == 0x205F || n == 0x3000 + +def token (s : String) : Bool := + !s.isEmpty && s.toList.all (fun c => !whiteSpace c && c != ';') + +def scope (s : String) : Option String := if s = "*" then none else some s + +def parsePolicy (s : String) : Option Policy := do + let [effect, principal, action, resource] := s.splitOn " " | none + if !([effect, principal, action, resource].all token) then none else + let effect ← match effect with + | "permit" => some Effect.permit + | "forbid" => some Effect.forbid + | _ => none + pure ⟨effect, scope principal, scope action, scope resource⟩ + +def request (s : String) : Option Bool := do + let head :: tail := s.splitOn ";" | none + let [principal, action, resource] := head.splitOn " " | none + if !([principal, action, resource].all token) then none else + let policies ← tail.mapM parsePolicy + pure (authorize policies ⟨principal, action, resource⟩) + +/-- The answer to one line, given without its LF. A line that ended in + LF loses one CR before it, so CR LF ends a line too. -/ +def answer (line : ByteArray) (endedByLF : Bool) : String := + let line := + if endedByLF && line.size > 0 && line[line.size - 1]! == 13 then + line.extract 0 (line.size - 1) + else line + match String.fromUTF8? line >>= request with + | some true => "allow" + | some false => "deny" + | none => "error" + +/-- Answer each line as its LF arrives. + + `Stream.read` is C `fread`, which returns only after it has every + requested byte or it reaches EOF. A 64 KiB read therefore waits for + a full buffer before the first line can be answered, and a caller + that sends one request and keeps the pipe open hangs. One byte is + enough: stdio still fills its own buffer underneath, and the line is + answered at the LF. A final line with no line ending is answered at + EOF, as SPEC.md requires. -/ +def serve (stdin stdout : IO.FS.Stream) : IO Unit := do + let mut pending := ByteArray.empty + repeat + let chunk ← stdin.read 1 + if chunk.isEmpty then + if !pending.isEmpty then + stdout.putStrLn (answer pending false) + stdout.flush + break + else + -- `read 1` yields one byte. Consume the whole chunk so a larger + -- read cannot drop bytes that arrived together. + let mut i := 0 + while i < chunk.size do + let b := chunk[i]! + i := i + 1 + if b == 10 then + stdout.putStrLn (answer pending true) + stdout.flush + pending := ByteArray.empty + else + pending := pending.push b + +def main : IO Unit := do + serve (← IO.getStdin) (← IO.getStdout) diff --git a/README.md b/README.md index 376f994..f024103 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,55 @@ -# cedar +# Cedar-style policy decisions -A Lean policy engine in the style of AWS Cedar. This is a Proven Commons project: it rebuilds a widely used rule in Lean and proves the new code follows its written specification. It is not AWS Cedar. It is a new engine that follows the same shape. +A small Lean library decides whether a request is allowed by a list of permit and forbid policies. Scopes match an exact principal, action, or resource string, or every string. A matching forbid denies; without a matching permit the result also denies. -Status: not verified. No code has landed yet. Plan issue 1 holds the first slice, and it is unclaimed. The specification has not been approved by a reviewer, so do not call this verified. +This is a Cedar-style engine, not AWS Cedar. -## Wave 1 +Status: in progress. The specification has not received independent approval, so this project is not verified. -This is one of the three Wave 1 projects in the founding brief, months 4 to 9, one squad each. The other two are the SQLite file reader and the Redis protocol parser. Redis already has a repo. +## Run it -## Claims to prove +Needs Lean 4.35.0, pinned in `lean-toolchain`. -- A satisfied forbid gives a deny. -- No satisfied permit gives a deny. -- Policy order does not change the decision. +```sh +lake build +printf 'alice read document;permit alice read *\n' | .lake/build/bin/cedar-style +printf 'alice read document;permit * * *;forbid alice read document\n' | .lake/build/bin/cedar-style +``` -## What is not in this project +The answers are `allow` and `deny`. The tool reads one request per line and answers that line as soon as it arrives, so a pipe that stays open still receives the answer. Semicolons separate policies, a single space separates tokens, and `*` in a policy scope means wildcard. See [SPEC.md](SPEC.md) for the complete protocol and library semantics. -- A full AWS Cedar implementation. This is a Cedar style engine, not a copy of AWS Cedar. -- Any claim about a deployed authorization service. +## What is proved -## Layout, when the first slice lands +The challenge statements in `Cedar/Spec.lean` are proved in `Cedar/Proofs.lean`: -The layout follows the Proven Commons template in the mission repo, under bar/template. Spec.lean holds the statements a reviewer approves. Proofs.lean holds the proofs under the same names. Main.lean holds the command line tool used by the tests. The bar check runs in CI on every change. +- `Cedar.Spec.authorize_iff`: the decision allows exactly when some permit matches and no forbid matches. +- `Cedar.Spec.forbid_denies`: a satisfied forbid denies. +- `Cedar.Spec.default_denies`: without a satisfied permit the decision denies. +- `Cedar.Spec.order_invariant`: permuting the policy list preserves the decision. +- `Cedar.Spec.members_invariant`: two policy lists with the same members give the same decision, so duplicates change nothing. + +The independent relational predicates and shared types live in `Cedar/Spec/Defs.lean`. `lake comparator --paranoid` compares each proof with its challenge statement and checks its axioms and kernels. The intentional challenge placeholders are not production proofs. + +## What is not proved + +The command-line parser, line endings, and output are tested rather than proved. The CLI reads UTF-8 and answers `error` for a line that is not UTF-8. It supports nonempty tokens without Unicode whitespace or semicolons and cannot express literal `*` scopes; the library has no such string restriction. + +There is no AWS Cedar parser or compatibility guarantee, entity hierarchy, expression language, schema, condition evaluation, policy validation, authentication, or integration with a deployed service. This library makes a decision from supplied strings and policies; it does not establish who supplied them. + +AWS Cedar already proves all of these properties in [cedar-spec](https://github.com/cedar-policy/cedar-spec/blob/5a5f00b/cedar-lean/Cedar/Thm/Authorization.lean): `forbid_trumps_permit`, `default_deny`, `allowed_iff_explicitly_permitted_and_not_denied` and `order_and_dup_independent`. This independent educational slice claims no novel authorization result. [SPEC.md](SPEC.md) records the prior work and exact scope. + +## What you must trust + +The Lean kernel, compiler, runtime, standard library, and hardware must behave correctly. The Python model and its test generator can contain mistakes; differential tests supplement the proofs and do not prove the protocol correct. No external dependencies or foreign functions are used by the library. + +## Re-check + +```sh +lake build +lake comparator --paranoid +python3 tests/run_tests.py +``` + +The comparator's sandbox needs Linux namespaces and bubblewrap. On macOS, local review used `--inadvisably-no-sandbox`; that checks the same exported statements and kernels without process isolation. CI runs the sandboxed command. [Test results](tests/TEST-RESULTS.md) record exhaustive small policy lists, generated lists, permutations, duplicates, malformed requests, and seeded byte-level mutations checked against a reference parser written from SPEC.md. + +Licensed under Apache 2.0; see [LICENSE](LICENSE). diff --git a/SPEC.md b/SPEC.md new file mode 100644 index 0000000..d5525e9 --- /dev/null +++ b/SPEC.md @@ -0,0 +1,47 @@ +# Specification: Cedar-style policy decisions + +This slice evaluates policies over a request's principal, action, and resource strings. It is an independent Cedar-style engine, not AWS Cedar. It implements no Cedar parser, entities, schema, expression language, type checker, or production authorization service. + +A policy has an effect, permit or forbid, and three scopes. Each scope is either a wildcard (`none`) or an exact string (`some s`). A policy matches a request exactly when each scope is a wildcard or equals the corresponding request field. String comparison is case sensitive, with no Unicode normalization. + +The result is allow exactly when at least one matching permit exists and no matching forbid exists. Otherwise it is deny. An empty policy list denies. Duplicate policies and policy order do not change this rule. + +`Cedar/Spec/Defs.lean` defines the request and policy types, the relational matching predicate `Cedar.Spec.Matches`, and the allowed predicate `Cedar.Spec.Allowed`. The executable implementation uses Boolean scope comparisons and two list searches. The relational specification uses quantified membership conditions. + +## Properties + +The challenge statements are in `Cedar/Spec.lean`; proofs of those same statements are in `Cedar/Proofs.lean`. + +| Property | Theorem | +| --- | --- | +| The Boolean decision is exactly the relational rule above | `Cedar.Spec.authorize_iff` | +| Any matching forbid denies, including alongside matching permits | `Cedar.Spec.forbid_denies` | +| No matching permit means deny | `Cedar.Spec.default_denies` | +| A permutation of the policy list preserves the decision | `Cedar.Spec.order_invariant` | +| Two policy lists with the same members give the same decision, so duplicates change nothing | `Cedar.Spec.members_invariant` | + +`authorize_iff` is the statement that pins the decision down: a program that always denies meets the other four, and only `authorize_iff` rules it out. + +The proofs quantify over every finite list and every request, including empty strings and all strings representable by Lean. The CLI below intentionally supports a smaller token syntax. Its parsing, line handling, and printing are tested, not proved. + +## Command-line protocol + +The executable reads one request per line and prints `allow`, `deny`, or `error`. The first segment contains three tokens: principal, action, resource. Subsequent segments, separated by semicolons, each contain four tokens: effect, principal scope, action scope, resource scope. Exactly one ASCII space separates tokens; tokens are nonempty and contain no whitespace or semicolon. Whitespace means the characters with Unicode's White_Space property: U+0009 to U+000D, U+0020, U+0085, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F, U+205F and U+3000. Effects are `permit` and `forbid`, in lower case. + +Input is UTF-8. The executable reads bytes, and a line that is not well-formed UTF-8 (for example a lone `0xFF`, a truncated sequence, an overlong form, or an encoded surrogate) is malformed and prints `error`. So two different byte strings never compare as the same token. + +A policy scope token `*` is a wildcard. Every other scope token is an exact string. The CLI cannot express a literal `*` scope, or empty or whitespace-containing fields, though the library can. A request's `*` token is a literal request string. + +Examples: + +``` +alice read document;permit alice read * +alice read document;permit * * *;forbid alice read document +alice read document +``` + +These produce `allow`, `deny`, and `deny`. Malformed requests, including empty lines, print `error`. Lines may end in LF or CR LF; a final line needs no line ending. A finished line is answered as soon as it has been read. The executable does not wait for more input, for a full buffer, or for end of file before printing that answer, so a caller may keep the input stream open. There is no persistent state between lines. + +## Existing work + +The AWS Cedar project already proves each of these properties in its [Lean authorization model](https://github.com/cedar-policy/cedar-spec/blob/5a5f00b/cedar-lean/Cedar/Thm/Authorization.lean) (cedar-spec commit `5a5f00b`, `cedar-lean/Cedar/Thm/Authorization.lean`): `forbid_trumps_permit` (forbid precedence), `default_deny`, `allowed_iff_explicitly_permitted_and_not_denied` (the counterpart of `authorize_iff`), and `order_and_dup_independent` (order and duplicates, the counterpart of `order_invariant` and `members_invariant`). Its [verification paper](https://arxiv.org/abs/2407.01688) describes the larger system. This slice repeats those elementary decision properties in a small independent model. It claims no new result and no compatibility with the AWS implementation. Its purpose is a bounded executable foundation for this repository's plan. diff --git a/bar.toml b/bar.toml new file mode 100644 index 0000000..aa343e3 --- /dev/null +++ b/bar.toml @@ -0,0 +1,16 @@ +[project] +name = "cedar" +status = "in-progress" +page = "README.md" +# The spec commits carry the git identity ahrazzle, so it is listed too. +spec_authors = ["orda-aska", "gpt-forge", "ahrazzle"] +entry_points = ["Main.lean"] + +[spec] +files = ["SPEC.md", "Cedar/Spec.lean", "Cedar/Spec/Defs.lean"] +code = ["Cedar.authorize"] + +[tests] +results = "tests/TEST-RESULTS.md" +command = "python3 tests/run_tests.py" +files = ["tests/run_tests.py"] diff --git a/comparator.json b/comparator.json new file mode 100644 index 0000000..9ecfaf7 --- /dev/null +++ b/comparator.json @@ -0,0 +1,12 @@ +{ + "challenge_module": "Cedar.Spec", + "solution_module": "Cedar.Proofs", + "theorem_names": [ + "Cedar.Spec.authorize_iff", + "Cedar.Spec.forbid_denies", + "Cedar.Spec.default_denies", + "Cedar.Spec.order_invariant", + "Cedar.Spec.members_invariant" + ], + "permitted_axioms": ["propext", "Quot.sound", "Classical.choice"] +} diff --git a/lake-manifest.json b/lake-manifest.json new file mode 100644 index 0000000..7397e30 --- /dev/null +++ b/lake-manifest.json @@ -0,0 +1,6 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "«cedar-style»", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/lakefile.toml b/lakefile.toml new file mode 100644 index 0000000..0f2c4ac --- /dev/null +++ b/lakefile.toml @@ -0,0 +1,20 @@ +name = "cedar-style" +version = "0.1.0" +license = "Apache-2.0" +defaultTargets = ["Cedar", "CedarProofs", "cedar-style"] + +[[lean_lib]] +name = "Cedar" +roots = ["Cedar"] + +[[lean_lib]] +name = "CedarSpec" +roots = ["Cedar.Spec"] + +[[lean_lib]] +name = "CedarProofs" +roots = ["Cedar.Proofs"] + +[[lean_exe]] +name = "cedar-style" +root = "Main" diff --git a/lean-toolchain b/lean-toolchain new file mode 100644 index 0000000..a6aff06 --- /dev/null +++ b/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.35.0 diff --git a/tests/TEST-RESULTS.md b/tests/TEST-RESULTS.md new file mode 100644 index 0000000..9addb0d --- /dev/null +++ b/tests/TEST-RESULTS.md @@ -0,0 +1,16 @@ +# Test results + +- Oracle: finite policy semantics in Python 3.12.3, evaluated by a direct rule walk, behind a reference parser written from SPEC.md +- Lean: Lean (version 4.35.0, x86_64-unknown-linux-gnu, commit eb6cafb7290e8bd5f2937522d8d804f58f02bafc, Release) +- Seed: 20261027 +- Inputs: 22671 +- Exhaustive: 2184 lines: 8 requests against empty policies, every single rule, and all ordered pairs of 16 rules +- Generated policy lists: 5000, scopes biased toward the request's values, with one shuffled copy each and duplicate-rule checks for nonempty lists; 3714 of 5000 have at least one matching policy +- Malformed requests: 28, among them Unicode whitespace inside tokens and lines that are not UTF-8 +- Byte-level mutations of generated lines: 6000, of which 5594 are malformed by the reference parser +- Line endings: LF, CR LF, and a final request without LF +- Interactive: one request on a pipe that stays open; the answer arrives within 2 seconds, before stdin is closed +- Failures: 0 + +This run checks the executable against the independent Python rule interpreter. +It does not establish AWS Cedar compatibility. Run the comparator separately to check proofs. diff --git a/tests/run_tests.py b/tests/run_tests.py new file mode 100644 index 0000000..fd67d4a --- /dev/null +++ b/tests/run_tests.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Test the CLI against the finite policy semantics, including policy permutations. + +Every expected answer comes from `reference`, a parser written from the +command-line protocol in SPEC.md, and `model`, a direct walk of the +decision rule. Input is sent as bytes, so lines that are not UTF-8 reach +the executable unchanged. +""" +import itertools +import os +import platform +import random +import select +import subprocess +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SEED = 20261027 + +# Unicode's White_Space property, as SPEC.md lists it. +WHITE_SPACE = set(range(0x09, 0x0E)) | {0x20, 0x85, 0xA0, 0x1680} | \ + set(range(0x2000, 0x200B)) | {0x2028, 0x2029, 0x202F, 0x205F, 0x3000} + + +def model(request, policies): + # Interpret each rule directly; do not mirror the engine's two any calls. + permitted = False + for effect, *scopes in policies: + if all(scope == '*' or scope == value for scope, value in zip(scopes, request)): + if effect == 'forbid': + return 'deny' + permitted = True + return 'allow' if permitted else 'deny' + + +def is_token(t): + return t != '' and ';' not in t and not any(ord(c) in WHITE_SPACE for c in t) + + +def reference(line): + """The answer SPEC.md gives for one line, as bytes without its line end.""" + try: + text = line.decode('utf-8', 'strict') + except UnicodeDecodeError: + return 'error' + head, *tail = text.split(';') + request = head.split(' ') + if len(request) != 3 or not all(map(is_token, request)): + return 'error' + policies = [] + for seg in tail: + fields = seg.split(' ') + if len(fields) != 4 or not all(map(is_token, fields)) or \ + fields[0] not in ('permit', 'forbid'): + return 'error' + policies.append(tuple(fields)) + return model(tuple(request), policies) + + +def wire(request, policies): + return ';'.join([' '.join(request)] + [' '.join(p) for p in policies]).encode('utf-8') + + +# Byte strings a mutation may insert or put in place of a byte. None is LF, +# which would end the line. +INSERTS = [b' ', b';', b'*', b'\t', b'\r', b'\x0b', b'\x0c', b'\xc2\xa0', b'\xc2\x85', + b'\xe2\x80\xa8', b'\xe3\x80\x80', b'\xff', b'\xc3', b'\xc0\xaf', b'\xed\xa0\x80', + b'P', b'F', b'a', b'\x00'] + + +def mutate(rng, line): + bs = bytearray(line) + for _ in range(rng.randrange(1, 4)): + kind = rng.randrange(5) + i = rng.randrange(len(bs) + 1) + if kind == 0 and bs: # delete a byte + del bs[min(i, len(bs) - 1)] + elif kind == 1: # insert + bs[i:i] = rng.choice(INSERTS) + elif kind == 2 and bs: # replace a byte + j = min(i, len(bs) - 1) + bs[j:j + 1] = rng.choice(INSERTS) + elif kind == 3: # change the case of the line's letters + bs = bytearray(bytes(bs).swapcase()) if rng.random() < 0.5 else \ + bytearray(bytes(bs).replace(b'permit', b'Permit').replace(b'forbid', b'FORBID')) + else: # double or drop a space + spaces = [k for k, b in enumerate(bs) if b == 0x20] + if spaces: + k = rng.choice(spaces) + bs[k:k + 1] = b' ' if rng.random() < 0.5 else b'' + return bytes(bs) + + +def main(): + subprocess.run(['lake', 'build'], cwd=ROOT, check=True) + cases = [] + rules = list(itertools.product(['permit', 'forbid'], ['*', 'a'], ['*', 'a'], ['*', 'a'])) + requests = list(itertools.product(['a', 'b'], repeat=3)) + for request in requests: + cases.append((wire(request, []), 'deny')) + for n in [1, 2]: + for policies in itertools.product(rules, repeat=n): + cases.append((wire(request, policies), model(request, policies))) + exhaustive = len(cases) + rng = random.Random(SEED) + names = ['a', 'b', 'alice', 'read', 'document', 'ü', '資料', '*', '*a', 'a*', '**', '�'] + generated = [] + matched = 0 + for _ in range(5000): + request = tuple(rng.choice(names) for _ in range(3)) + + def scope(value): + # Biased toward the request's own value, so that most lists match. + x = rng.random() + return '*' if x < 0.3 else value if x < 0.7 else rng.choice(names) + policies = [tuple([rng.choice(['permit', 'forbid'])] + [scope(v) for v in request]) + for _ in range(rng.randrange(9))] + want = model(request, policies) + matched += any(all(sc == '*' or sc == v for sc, v in zip(p[1:], request)) for p in policies) + cases.append((wire(request, policies), want)) + generated.append(wire(request, policies)) + rng.shuffle(policies) + cases.append((wire(request, policies), want)) + # Duplicating a satisfied or unsatisfied rule cannot change the result. + if policies: + cases.append((wire(request, policies + [policies[0]]), want)) + malformed = [s.encode('utf-8') for s in [ + '', 'a b', 'a b c d', 'a b c', 'a b c;', 'a b c;allow * * *', 'a b c;permit * *', + 'a b c;permit * * * ', 'a\tb c d', 'a b c;permit * * *;', ' a b c;permit * * *', + 'a b c;PERMIT * * *', 'a b c;Forbid * * *', 'a\x0bb c;permit * * *', + 'alice\x0c read document;permit * * *', 'a b c d;permit * * *', + 'a b c\u0085;permit * * *', 'a b c;permit 
 * *', 'a b  c;permit * * *']] + # Lines that are not UTF-8: a lone 0xFF or 0xFE, a truncated sequence, an + # overlong form, an encoded surrogate. + malformed += [b'\xff read doc;permit \xfe read doc', + b'\xed\xa0\x80 read doc;permit \xc0\xaf read doc', + b'\xef\xbf\xbd read doc;permit \xff read doc', + b'\xff read doc;permit * read doc;forbid \xfe read doc', + b'a b c;permit \xc3 * *', b'a b \xc3;permit * * *', b'\xff b c', + b'a b c;permit * * \xc0\xaf', b'a b c;permit \xed\xa0\x80 * *'] + for s in malformed: + assert reference(s) == 'error', s + cases += [(s, 'error') for s in malformed] + # A real U+FFFD is UTF-8, and matches only itself. + cases.append(('� b c;permit � b c'.encode('utf-8'), 'allow')) + def ending(i): + return b'\r\n' if i % 7 == 0 else b'\n' + mutations = 0 + for _ in range(6000): + line = mutate(rng, rng.choice(generated)) + # The executable drops one CR before the LF that ends a line. + seen = (line + ending(len(cases)))[:-1] + cases.append((line, reference(seen[:-1] if seen.endswith(b'\r') else seen))) + mutations += 1 + mutated_errors = sum(1 for s, want in cases[-mutations:] if want == 'error') + data = b''.join(s + ending(i) for i, (s, _) in enumerate(cases)) + run = subprocess.run([str(ROOT / '.lake/build/bin/cedar-style')], input=data, + capture_output=True, timeout=120) + actual = run.stdout.decode('utf-8').splitlines() + failures = [(s, want, got) for (s, want), got in zip(cases, actual) if want != got] + assert run.returncode == 0 and len(actual) == len(cases), (run.returncode, run.stderr, len(actual)) + assert not failures, failures[:10] + eof = subprocess.run([str(ROOT / '.lake/build/bin/cedar-style')], input=b'a b c;permit * * *', + capture_output=True, timeout=10) + assert eof.returncode == 0 and eof.stdout == b'allow\n', eof + # A caller that sends one request and keeps the pipe open must get the + # answer before EOF. `read` of a large buffer waits for that many bytes + # or for EOF, so this fails closed as a hang rather than as a wrong word. + interactive = subprocess.Popen( + [str(ROOT / '.lake/build/bin/cedar-style')], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0) + interactive_timeout = 2.0 + try: + assert interactive.stdin is not None and interactive.stdout is not None + interactive.stdin.write(b'a b c;permit * * *\n') + interactive.stdin.flush() + deadline = time.monotonic() + interactive_timeout + got = b'' + while b'\n' not in got: + remaining = deadline - time.monotonic() + assert remaining > 0, f'no answer within {interactive_timeout}s while stdin stayed open; got {got!r}' + ready, _, _ = select.select([interactive.stdout], [], [], remaining) + assert ready, f'no answer within {interactive_timeout}s while stdin stayed open; got {got!r}' + chunk = os.read(interactive.stdout.fileno(), 4096) + assert chunk, f'stdout closed before an answer; got {got!r}' + got += chunk + assert got == b'allow\n', got + assert interactive.poll() is None, 'cedar-style exited before stdin closed' + finally: + if interactive.stdin is not None: + interactive.stdin.close() + try: + interactive.wait(timeout=5) + except subprocess.TimeoutExpired: + interactive.kill() + interactive.wait(timeout=5) + raise + err = interactive.stderr.read() if interactive.stderr is not None else b'' + assert interactive.returncode == 0, (interactive.returncode, err) + lean = subprocess.check_output(['lean', '--version'], text=True).strip() + report = f'''# Test results + +- Oracle: finite policy semantics in Python {platform.python_version()}, evaluated by a direct rule walk, behind a reference parser written from SPEC.md +- Lean: {lean} +- Seed: {SEED} +- Inputs: {len(cases) + 2} +- Exhaustive: {exhaustive} lines: 8 requests against empty policies, every single rule, and all ordered pairs of 16 rules +- Generated policy lists: 5000, scopes biased toward the request's values, with one shuffled copy each and duplicate-rule checks for nonempty lists; {matched} of 5000 have at least one matching policy +- Malformed requests: {len(malformed)}, among them Unicode whitespace inside tokens and lines that are not UTF-8 +- Byte-level mutations of generated lines: {mutations}, of which {mutated_errors} are malformed by the reference parser +- Line endings: LF, CR LF, and a final request without LF +- Interactive: one request on a pipe that stays open; the answer arrives within 2 seconds, before stdin is closed +- Failures: 0 + +This run checks the executable against the independent Python rule interpreter. +It does not establish AWS Cedar compatibility. Run the comparator separately to check proofs. +''' + (ROOT / 'tests/TEST-RESULTS.md').write_text(report) + print(f'{len(cases) + 2} inputs, 0 failures') + + +if __name__ == '__main__': + main()