Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mutability changes to Cadence documentation #172

Merged
merged 6 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 31 additions & 18 deletions docs/cadence/language/access-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,16 +341,17 @@ resource OuterResource {

With this pattern, we can store a `SubResource` on an `OuterResource` value,
and create different ways to access that nested resource depending on the entitlement one posseses.
Somoneone with only an unauthorized reference to `OuterResource` can only call the `getPubRef` function,
Someone with only an unauthorized reference to `OuterResource` can only call the `getPubRef` function,
and thus can only get an unauthorized reference to `SubResource` that lets them call `foo`.
However, someone with a `OuterEntitlement`-authorized refererence to the `OuterResource` can call the `getEntitledRef` function,
However, someone with a `OuterEntitlement`-authorized reference to the `OuterResource` can call the `getEntitledRef` function,
giving them a `SubEntitlement`-authorized reference to `SubResource` that allows them to call `bar`.

This pattern is functional, but it is unfortunate that we are forced to "duplicate" the accessors to `SubResource`,
duplicating the code and storing two functions on the object,
essentially creating two different views to the same object that are stored as different functions.
To avoid necessitating this duplication, we add support to the language for "entitlement mappings",
a way to declare statically how entitlements are propagated from parents to child objects in a nesting hierarchy.
a way to declare statically how entitlements are propagated from parents to child objects in a nesting hierarchy.

So, the above example could be equivalently written as:

```cadence
Expand All @@ -369,13 +370,9 @@ resource SubResource {
}

resource OuterResource {
access(self) let childResource: @SubResource

// by referering to `Map` here, we declare that the entitlements we receive when accessing the `getRef` function on this resource
// will depend on the entitlements we possess to the resource during the access.
SupunS marked this conversation as resolved.
Show resolved Hide resolved
access(Map) fun getRef(): auth(Map) &SubResource {
return &self.childResource as auth(Map) &SubResource
}
// by referering to `Map` here, we declare that the entitlements we receive when accessing the `childResource` field
// on this resource will depend on the entitlements we possess to the resource during the access.
access(Map) let childResource: @SubResource
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Has documentation already been added/changed for entitlement mappings explaining how they work with resource-typed fields?

Copy link
Member Author

@SupunS SupunS Aug 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not specifically add about resource typed fields, since this section already describes how entitlement mappings pass down the entitlements in general. Also, the newly added Field and Index Access (in reference.md) section describes how references and entitlements are received when accessing fields through a reference.

If we want to have a more granular/in-depth explanation on how entitlement mappings behave on each different use case (functions, references, and container-typed field) separately, then I guess that also makes sense and would be good to have it too. But probably unrelated to this change, so maybe we could do it in a separate PR?


init(r: @SubResource) {
self.childResource = r
Expand All @@ -384,21 +381,20 @@ resource OuterResource {

// given some value `r` of type `@OuterResource`
let pubRef = &r as &OuterResource
let pubSubRef = pubRef.getRef() // has type `&SubResource`
let pubSubRef = pubRef.childResource // has type `&SubResource`

let entitledRef = &r as auth(OuterEntitlement) &OuterResource
let entitledSubRef = entitledRef.getRef() // `OuterEntitlement` is defined to map to `SubEntitlement`, so this access yields a value of type `auth(SubEntitlement) &SubResource`
let entitledSubRef = entitledRef.childResource // `OuterEntitlement` is defined to map to `SubEntitlement`, so this access yields a value of type `auth(SubEntitlement) &SubResource`
Entitlement

// `r` is an owned value, and is thus considered "fully-entitled" to `OuterResource`,
// so this access yields a value authorized to the entire image of `Map`, in this case `SubEntitlement`
let alsoEntitledSubRef = r.getRef()
let alsoEntitledSubRef = r.childResource
```

{/* TODO: Update once mappings can be used on regular composite fields */}

Entitlement mappings may be used either in accessor functions (as in the example above), or in fields whose types are references. Note that this latter
usage will necessarily make the type of the composite non-storage, since it will have a reference field.
Entitlement mappings may be used either in accessor functions (as in the example above), or in fields whose types are
either references, or containers (structs/resources, dictionaries and arrays).
Note that having a reference field will necessarily make the type of the composite non-storage.

{/* TODO: once the Account type refactor is complete and the documentation updated, let's link here to the Account type page as an example of more complex entitlement mappings */}
Entitlement mappings need not be 1:1; it is valid to define a mapping where multiple inputs map to the same output, or where one input maps to multiple outputs.
Expand All @@ -414,4 +410,21 @@ entitlement mapping M {
}
```

attempting to map `(A | D)` through `M` will fail, since `A` should map to `(B, C)` and `D` should map to `E`, but these two outputs cannot be combined into a disjunctive set.
attempting to map `(A | D)` through `M` will fail, since `A` should map to `(B, C)` and `D` should map to `E`, but these two outputs cannot be combined into a disjunctive set.

### Built-in Mutability Entitlements

A prominent use-case of entitlements is to control access to object based on mutability.
For example, in a struct/resource/contract, the author would want to control the access to certain fields to be read-only,
and while some fields to be mutable, etc.

In order to support this, Cadence hase built-in set of entitlements that can be used to access control base on mutability.
- `Insert`
- `Remove`
- `Mutate`

These are primarily used by built-in array and dictionary functions, but are also usable by any user to control access
in their own composite type definitions.

While Cadence does not support entitlement composition or inheritance, the `Mutate` entitlement is intended to be used
as an equivalent form to the conjunction of `{Insert, Remove}` entitlements.
173 changes: 135 additions & 38 deletions docs/cadence/language/references.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ counterRef.increment()
counterRef.count // is `43`
```

References can be freely upcasted and downcasted, and are covariant in their referenced type.
So, for example, for some struct `S`, `&S` is a subtype of `&AnyStruct`, but not of `&Int`.
References can be freely upcasted and downcasted, and are covariant in their referenced type.
So, for example, for some struct `S`, `&S` is a subtype of `&AnyStruct`, but not of `&Int`.

```cadence
// Create an reference to the counter,
Expand All @@ -117,7 +117,7 @@ countRef.count // is `43`
countRef.increment()

// We can conditionally downcast `countRef` to a `Counter` if it has
// that type at runtime.
// that type at runtime.
//
let counterRef2: &Counter = countRef as? &Counter
counterRef2.increment()
Expand All @@ -128,18 +128,18 @@ Instead, consider [storing a capability and borrowing it](capability-based-acces

## Authorized References

By default, references are **unauthorized**.
By default, references are **unauthorized**.
However, they may also be **authorized** to a set of [entitlements](./access-control.md#entitlements)

Authorized references have the `auth` modifier,
Authorized references have the `auth` modifier,
along with the set of entitlements to which they are authorized. The full syntax is:
`auth(E, F, G) &T` for a reference authorized to `E`, `F` and `G`,
or `auth(E | F | G) &T` for a refernece authorized to `E`, `F`, **or** `G`.
or `auth(E | F | G) &T` for a refernece authorized to `E`, `F`, **or** `G`.
Authorized references are subtypes of unauthorized references.

Entitlements can only be given to references when they are created,
and references to a value can only be created by the owner of the value.
When creating a reference, that reference can be given any set of entitlements the value owner wishes to add.
Entitlements can only be given to references when they are created,
and references to a value can only be created by the owner of the value.
When creating a reference, that reference can be given any set of entitlements the value owner wishes to add.

Possessing an entitlement allows a reference to have access to functions and fields on its referenced type
that require that entitlement. E.g, if we extended the `HasCount` interface with a function:
Expand All @@ -149,11 +149,11 @@ entitlement Reset

resource interface HasCount {
count: Int
access(Reset) fun resetCount()
access(Reset) fun resetCount()
}
```

Then an unauthorized reference of type `&{HasCount}` would be unable to call `resetCount`.
Then an unauthorized reference of type `&{HasCount}` would be unable to call `resetCount`.
However, we can create a reference that can, like so:


Expand All @@ -164,44 +164,44 @@ let authCountRef: auth(Reset) &{HasCount} = &counter
authCountRef.resetCount()
```

It is important to note that while references are covariant (and downcastable) with respect to their reference type,
the authorization portion of the reference can never be downcast.
In fact, the only way to "add" entitlements to a reference is to do so at the time of its creation, like in the example above.
A reference will never have any more entitlements than the set with which it was created,
and the set of entitlements on a reference at runtime will always match the set expressed in its static type.
It is important to note that while references are covariant (and downcastable) with respect to their reference type,
the authorization portion of the reference can never be downcast.
In fact, the only way to "add" entitlements to a reference is to do so at the time of its creation, like in the example above.
A reference will never have any more entitlements than the set with which it was created,
and the set of entitlements on a reference at runtime will always match the set expressed in its static type.
One implication of this is that upcasting an authorized reference actually changes its runtime type:

```
let authCountRef: auth(Reset) &{HasCount} = &counter
let unauthCountRef = authCountRef as &{HasCount}
let authCountRef2 = unauthCountRef as? auth(Reset) &{HasCount}
let authCountRef2 = unauthCountRef as? auth(Reset) &{HasCount}

// Invalid: `authCountRef2` is `nil`, as the upcast of `authCountRef` cleared the
// `Reset` entitlement from the reference, meaning that it cannot be regained on downcasting.
// Invalid: `authCountRef2` is `nil`, as the upcast of `authCountRef` cleared the
// `Reset` entitlement from the reference, meaning that it cannot be regained on downcasting.
authCountRef2.resetCount()
```

The benefit of this is that there is never any "surprising" behavior with regards to entitlements,
every reference value is transparent about what it is capable of at runtime.
The benefit of this is that there is never any "surprising" behavior with regards to entitlements,
every reference value is transparent about what it is capable of at runtime.

While entitlement sets on references cannot be downcast, they can be upcast, or used in places expecting supertypes,
and have special subtyping rules based on whether they are `|` or `,`-separated sets.
and have special subtyping rules based on whether they are `|` or `,`-separated sets.

In general, an entitlement set `{Us}` is a subtype of an entitlement set `{Vs}` when `{Us}` has more entitlements
in it than `{Vs}`, and when both are `,`-separated (as they will be in most cases), this is the rule exactly:
In general, an entitlement set `{Us}` is a subtype of an entitlement set `{Vs}` when `{Us}` has more entitlements
in it than `{Vs}`, and when both are `,`-separated (as they will be in most cases), this is the rule exactly:
`{Us}` is a subset of `{Vs}` when it is a superset of `{Vs}`.

Conversely, if both are `|`-separated, the rule is reversed:
`{Us}` is a subset of `{Vs}` when it is a subset of `{Vs}`.
It may be helpful to think of this as saying that `{Us}` is more specific than `{Vs}` in this case;
`{Vs}` expresses a set of entitlements that the reference **might** possess,
`{Us}` is a subset of `{Vs}` when it is a subset of `{Vs}`.
It may be helpful to think of this as saying that `{Us}` is more specific than `{Vs}` in this case;
`{Vs}` expresses a set of entitlements that the reference **might** possess,
while `{Us}` is expressing a more specific set of potential entitlements.

Lastly, if `{Us}` is `,`-separated while `{Vs}` is `|`-separated,
then `{Us}` is a subset of `{Vs}` when any of the `Us` also appears in `{Vs}`.
To see why, consider again that `{Vs}` expresses a set of entitlements that the reference **might** possess,
and as long as at least one of these entitlements is in `{Us}` (which is a set of entitlements that we **know** the reference has),
then the description provided by `{Vs}` is correct.
Lastly, if `{Us}` is `,`-separated while `{Vs}` is `|`-separated,
then `{Us}` is a subset of `{Vs}` when any of the `Us` also appears in `{Vs}`.
To see why, consider again that `{Vs}` expresses a set of entitlements that the reference **might** possess,
and as long as at least one of these entitlements is in `{Us}` (which is a set of entitlements that we **know** the reference has),
then the description provided by `{Vs}` is correct.

As an example to illustrate these rules:

Expand Down Expand Up @@ -235,7 +235,7 @@ eOrFRef as auth(E, F) &T
### References and Entitlement Mappings

In most situations, an [entitlement mapping](./access-control.md#entitlement-mappings) is valid in the `auth` portion of a reference type.
However, in certain specific circumstances in the definition of a field or function on a composite type, an entitlement mapping may be used in an `auth` modifier.
However, in certain specific circumstances in the definition of a field or function on a composite type, an entitlement mapping may be used in an `auth` modifier.

When a field is defined with an entitlement mapping:

Expand All @@ -250,7 +250,7 @@ resource interface I {

Here, the `M` in `auth(M) &T` indicates that the entitlements that the reference produced by an `iRef.foo` access will have
are determined by the entitlements to `I` that `iRef` has, for some `iRef` value that is a reference to `{I}`. Conceptually,
it creates a correspondence between the "output" reference's type and the "input" access modifier.
it creates a correspondence between the "output" reference's type and the "input" access modifier.

When an accessor function is defined with an entitlement mapping:

Expand All @@ -268,11 +268,108 @@ resource I {
```

The `M` in the `auth(M) &T` of the function's return type annotation indicates the same thing as in the field case.
However, in this example `M` is also used in a reference type within the body of the function.
Inside the body of function with entitlement-mapped access,
the name of the entitlement mapping may be used as a stand-in for the output entitlements of the map.
However, in this example `M` is also used in a reference type within the body of the function.
Inside the body of function with entitlement-mapped access,
the name of the entitlement mapping may be used as a stand-in for the output entitlements of the map.

## Reference validity
## Field and Index Access

References to container types (structs/resources, dictionaries and arrays) can be used to access (read/write) fields
or elements of the container.

When a field/index is read through a reference, it will return:
- A reference, if the field / value at index is also container-typed.
- Or, the concrete value, if the value is a primitive type.

For example, consider the below `Collection` resource which has two fields: one (id) is String-typed,
and the other (ownedNFTs) is dictionary-typed.

```cadence
resource Collection {

// Primitive-typed field
access(all) var id: String

// Dictionary typed field
access(all) var ownedNFTs: @{UInt64: NFT}
}
```

Thus,

```cadence
var collectionRef: &Collection = ...

// `collectionRef.ownedNFTs` would return a reference of type `&{UInt64: NFT}`.
var ownedNFTsRef: &{UInt64: NFT} = collectionRef.ownedNFTs

// Whereas, `collectionRef.id` would return the value, since it is a primitive type.
var id: String = collectionRef.id
```

Similarly, accessing an element of an array/dictionary will return a reference.

```cadence
// Index-access to an array reference would return a reference to the element.
var resourceArrayRef: &[AnyResource] = ...
var elementRef: &AnyResource = collectionArrayRef[2]

// Whereas, if the array is of a primitive type, it will return the concrete value.
var intArrayRef: &[Int] = ...
var element: Int = intArrayRef[2]
```

```cadence
// Index-access to a dictionary reference would return a reference to the value.
var resourceDictionaryRef: &{String: AnyResource} = ...
var valueRef: &AnyResource? = resourceDictionaryRef["two"]

// Whereas, if the dictionary values are of a primitive type, it will return the concrete value.
var intDictionaryRef: &{String: Int} = ...
var value: Int? = intDictionaryRef["two"]
```

It is also important to note that, in the above examples, the returned references have no entitlements.
i.e: they are non-auth references.

To get entitled references for struct/resource fields, they must be defined with [entitlement mappings](./access-control.md#entitlement-mappings).
However, accessing a value at an index/key of an array/dictionary reference would always return a non-auth reference.

### Index Assignment

Assigning to an index of an array or a dictionary reference is an entitled-operation.
In other words, the assignment operator for arrays/dictionaries would also have the `Mutate` and `Insert`
[built-in entitlements](./access-control.md#built-in-mutability-entitlements).

Think of assignment as a built-in function with `Mutate` or `(Insert, Remove)` entitlements. e.g:

```cadence
access(Mutate | (Insert, Remove)) set(keyOrIndex, value) { ... }
SupunS marked this conversation as resolved.
Show resolved Hide resolved
```

Note that the syntax for having nested entitlements in access modifiers like `(Mutate | (Insert, Remove))`
is not currently supported, but this is for illustration purpose only.

Thus,

```cadence
var arrayRef = &array as &[String]
arrayRef[2] = "John" // Static Error: updating via a read-only reference

var mutableArrayRef = &array as auth(Mutate) &[String]
mutableArrayRef[2] = "John" // OK

var insertableArrayRef = &array as auth(Insert) &[String]
insertableArrayRef[2] = "John" // Static Error: doesn't have the required entitlement

var removableArrayRef = &array as auth(Remove) &[String]
removableArrayRef[2] = "John" // Static Error: doesn't have the required entitlement

var insertableAndRemovableArrayRef = &array as auth(Insert, Remove) &[String]
insertableAndRemovableArrayRef[2] = "John" // OK
```

## Reference Validity

Ephemeral references stay valid throughout the course of the program.
However, **references to resources** can become invalid during the execution of a program,
Expand Down
Loading