Skip to content

Commit

Permalink
Builtins emit default values in JSON results (#507)
Browse files Browse the repository at this point in the history
The `ds.checks` builtin returns an array of `CheckResponse` messages.
Each element has a boolean `check` field indicating the outcome of one check.
However, because `false` is the default value for `bool` the marshaled JSON
object doesn't include the `check` field at all when it is false.

Dealing with missing fields is difficult in Rego (I couldn't figure it out).
The code below takes a resource context of the form:
```json
{
  "object_type": "",
  "checks": [
    {"object_id": "", "relation": ""}
  ]
}
```

It computes an array of results of the form:
```json
[
  {"object_id": "", "relation": "", "allowed": true/false}
]
```

If default values are omitted from the returned results, the array
will only include checks that evaluated to true.

```rego
raw := ds.checks({
  "default": {
    "object_type": input.resource.object_type,
    "subject_type": "user",
    "subject_id": input.user.id
  },
  "checks": checks
})

results := x {
  x := [
    {"object_id": check.object_id, "relation": check.relation, "allowed": result.check } |
    check := checks[i]
    result = raw[i]
  ]
}
```

This commit adds `EmitDefaultValues: true` to the `protojson.MarshalOptions` used by the
builtins to marshal rpc responses to JSON.
  • Loading branch information
ronenh authored Dec 3, 2024
1 parent 75f41df commit 7627ee2
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions builtins/edge/ds/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ func helpMsg(fnName string, msg proto.Message) (*ast.Term, error) {
// ProtoToBuf, marshal proto message to buffer.
func ProtoToBuf(w io.Writer, msg proto.Message) error {
b, err := protojson.MarshalOptions{
Multiline: false,
Indent: "",
AllowPartial: false,
UseProtoNames: true,
UseEnumNumbers: false,
EmitUnpopulated: false,
Multiline: false,
Indent: "",
AllowPartial: false,
UseProtoNames: true,
UseEnumNumbers: false,
EmitUnpopulated: false,
EmitDefaultValues: true,
}.Marshal(msg)
if err != nil {
return err
Expand Down

0 comments on commit 7627ee2

Please sign in to comment.