|
| 1 | +package examples |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/alanshaw/ucantone/ipld/datamodel" |
| 7 | + "github.com/alanshaw/ucantone/ucan/delegation/policy" |
| 8 | +) |
| 9 | + |
| 10 | +func TestParsePolicy(t *testing.T) { |
| 11 | + // Create some data to match against the policy: |
| 12 | + msg := datamodel.NewMap( |
| 13 | + datamodel.WithEntry("to", []string{"bob@example.com"}), |
| 14 | + datamodel.WithEntry("from", "alice@example.com"), |
| 15 | + datamodel.WithEntry("message", "Hello bob!"), |
| 16 | + ) |
| 17 | + |
| 18 | + // A policy is a list of statements. |
| 19 | + // See https://github.com/ucan-wg/delegation/blob/main/README.md#policy |
| 20 | + pol, err := policy.Build( |
| 21 | + policy.All(".to", policy.Like(".", "*.example.com")), |
| 22 | + policy.Equal(".from", "alice@example.com"), |
| 23 | + ) |
| 24 | + if err != nil { |
| 25 | + panic(err) |
| 26 | + } |
| 27 | + |
| 28 | + ok, err := policy.Match(pol, msg) |
| 29 | + if err != nil { |
| 30 | + panic(err) |
| 31 | + } |
| 32 | + // expect this policy to match the data |
| 33 | + if ok != true { |
| 34 | + panic("policy did not match") |
| 35 | + } |
| 36 | + |
| 37 | + // Alternatively you can parse a DAG-JSON encoded policy: |
| 38 | + pol, err = policy.Parse(`[ |
| 39 | + ["all", ".to", ["like", ".", "*@example.com"]], |
| 40 | + ["==", ".from", "alice@example.com"] |
| 41 | + ]`) |
| 42 | + if err != nil { |
| 43 | + panic(err) |
| 44 | + } |
| 45 | + |
| 46 | + ok, err = policy.Match(pol, msg) |
| 47 | + if err != nil { |
| 48 | + panic(err) |
| 49 | + } |
| 50 | + // expect this policy to match the data |
| 51 | + if ok != true { |
| 52 | + panic("policy did not match") |
| 53 | + } |
| 54 | +} |
0 commit comments