Privacy

The Policy option in the schema allows configuring privacy policy for queries and mutations of entities in the database.

gopher-privacy

The main advantage of the privacy layer is that, you write the privacy policy once (in the schema), and it is always evaluated. No matter where queries and mutations are performed in your codebase, it will always go through the privacy layer.

In this tutorial, we will start by going over the basic terms we use in the framework, continue with a section for configuring the policy feature to your project, and finish with a few examples.

Basic Terms

Policy

The ent.Policy interface contains two methods: EvalQuery and EvalMutation. The first defines the read-policy, and the second defines the write-policy. A policy contains zero or more privacy rules (see below). These rules are evaluated in the same order they are declared in the schema.

If all rules are evaluated without returning an error, the evaluation finishes successfully, and the executed operation gets access to the target nodes.

privacy-rules

However, if one of the evaluated rules returns an error or a privacy.Deny decision (see below), the executed operation returns an error, and it is cancelled.

privacy-deny

Privacy Rules

Each policy (mutation or query) includes one or more privacy rules. The function signature for these rules is as follows:

  1. // EvalQuery defines the a read-policy rule.
  2. func(Policy) EvalQuery(context.Context, Query) error
  3. // EvalMutation defines the a write-policy rule.
  4. func(Policy) EvalMutation(context.Context, Mutation) error

Privacy Decisions

There are three types of decision that can help you control the privacy rules evaluation.

  • privacy.Allow - If returned from a privacy rule, the evaluation stops (next rules will be skipped), and the executed operation (query or mutation) gets access to the target nodes.
  • privacy.Deny - If returned from a privacy rule, the evaluation stops (next rules will be skipped), and the executed operation is cancelled. This equivalent to returning any error.
  • privacy.Skip - Skip the current rule, and jump to the next privacy rule. This equivalent to returning a nil error.

privacy-allow

Now that we’ve covered the basic terms, let’s start writing some code.

Configuration

In order to enable the privacy option in your code generation, enable the privacy feature with one of two options:

  • CLI
  • Go

If you are using the default go generate config, add --feature privacy option to the ent/generate.go file as follows:

ent/generate.go

  1. package ent
  2. //go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature privacy ./schema

It is recommended to add the schema/snapshot feature-flag along with the privacy flag to enhance the development experience, for example:

  1. //go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature privacy,schema/snapshot ./schema

If you are using the configuration from the GraphQL documentation, add the feature flag as follows:

  1. // +build ignore
  2. package main
  3. import (
  4. "log"
  5. "entgo.io/ent/entc"
  6. "entgo.io/ent/entc/gen"
  7. )
  8. func main() {
  9. opts := []entc.Option{
  10. entc.FeatureNames("privacy"),
  11. }
  12. if err := entc.Generate("./schema", &gen.Config{}, opts...); err != nil {
  13. log.Fatalf("running ent codegen: %v", err)
  14. }
  15. }

It is recommended to add the schema/snapshot feature-flag along with the privacy flag to enhance the development experience, for example:

  1. opts := []entc.Option{
  2. - entc.FeatureNames("privacy"),
  3. + entc.FeatureNames("privacy", "schema/snapshot"),
  4. }

Privacy Policy Registration

Privacy - 图5info

You should notice that similar to schema hooks, if you use the Policy option in your schema, you MUST add the following import in the main package, because a circular import is possible between the schema package, and the generated ent package:

  1. import _ "<project>/ent/runtime"

Examples

Admin Only

We start with a simple example of an application that lets any user read any data, and accepts mutations only from users with admin role. We will create 2 additional packages for the purpose of the examples:

  • rule - for holding the different privacy rules in our schema.
  • viewer - for getting and setting the user/viewer who’s executing the operation. In this simple example, it can be either a normal user or an admin.

After running the code-generation (with the feature-flag for privacy), we add the Policy method with 2 generated policy rules.

examples/privacyadmin/ent/schema/user.go

  1. package schema
  2. import (
  3. "entgo.io/ent"
  4. "entgo.io/ent/examples/privacyadmin/ent/privacy"
  5. )
  6. // User holds the schema definition for the User entity.
  7. type User struct {
  8. ent.Schema
  9. }
  10. // Policy defines the privacy policy of the User.
  11. func (User) Policy() ent.Policy {
  12. return privacy.Policy{
  13. Mutation: privacy.MutationPolicy{
  14. // Deny if not set otherwise.
  15. privacy.AlwaysDenyRule(),
  16. },
  17. Query: privacy.QueryPolicy{
  18. // Allow any viewer to read anything.
  19. privacy.AlwaysAllowRule(),
  20. },
  21. }
  22. }

We defined a policy that rejects any mutation and accepts any query. However, as mentioned above, in this example, we accept mutations only from viewers with admin role. Let’s create 2 privacy rules to enforce this:

examples/privacyadmin/rule/rule.go

  1. package rule
  2. import (
  3. "context"
  4. "entgo.io/ent/examples/privacyadmin/ent/privacy"
  5. "entgo.io/ent/examples/privacyadmin/viewer"
  6. )
  7. // DenyIfNoViewer is a rule that returns Deny decision if the viewer is
  8. // missing in the context.
  9. func DenyIfNoViewer() privacy.QueryMutationRule {
  10. return privacy.ContextQueryMutationRule(func(ctx context.Context) error {
  11. view := viewer.FromContext(ctx)
  12. if view == nil {
  13. return privacy.Denyf("viewer-context is missing")
  14. }
  15. // Skip to the next privacy rule (equivalent to returning nil).
  16. return privacy.Skip
  17. })
  18. }
  19. // AllowIfAdmin is a rule that returns Allow decision if the viewer is admin.
  20. func AllowIfAdmin() privacy.QueryMutationRule {
  21. return privacy.ContextQueryMutationRule(func(ctx context.Context) error {
  22. view := viewer.FromContext(ctx)
  23. if view.Admin() {
  24. return privacy.Allow
  25. }
  26. // Skip to the next privacy rule (equivalent to returning nil).
  27. return privacy.Skip
  28. })
  29. }

As you can see, the first rule DenyIfNoViewer, makes sure every operation has a viewer in its context, otherwise, the operation rejected. The second rule AllowIfAdmin, accepts any operation from viewer with admin role. Let’s add them to the schema, and run the code-generation:

examples/privacyadmin/ent/schema/user.go

  1. // Policy defines the privacy policy of the User.
  2. func (User) Policy() ent.Policy {
  3. return privacy.Policy{
  4. Mutation: privacy.MutationPolicy{
  5. rule.DenyIfNoViewer(),
  6. rule.AllowIfAdmin(),
  7. privacy.AlwaysDenyRule(),
  8. },
  9. Query: privacy.QueryPolicy{
  10. privacy.AlwaysAllowRule(),
  11. },
  12. }
  13. }

Since we define the DenyIfNoViewer first, it will be executed before all other rules, and accessing the viewer.Viewer object is safe in the AllowIfAdmin rule.

After adding the rules above and running the code-generation, we expect the privacy-layer logic to be applied on ent.Client operations.

examples/privacyadmin/example_test.go

  1. func Do(ctx context.Context, client *ent.Client) error {
  2. // Expect operation to fail, because viewer-context
  3. // is missing (first mutation rule check).
  4. if err := client.User.Create().Exec(ctx); !errors.Is(err, privacy.Deny) {
  5. return fmt.Errorf("expect operation to fail, but got %w", err)
  6. }
  7. // Apply the same operation with "Admin" role.
  8. admin := viewer.NewContext(ctx, viewer.UserViewer{Role: viewer.Admin})
  9. if err := client.User.Create().Exec(admin); err != nil {
  10. return fmt.Errorf("expect operation to pass, but got %w", err)
  11. }
  12. // Apply the same operation with "ViewOnly" role.
  13. viewOnly := viewer.NewContext(ctx, viewer.UserViewer{Role: viewer.View})
  14. if err := client.User.Create().Exec(viewOnly); !errors.Is(err, privacy.Deny) {
  15. return fmt.Errorf("expect operation to fail, but got %w", err)
  16. }
  17. // Allow all viewers to query users.
  18. for _, ctx := range []context.Context{ctx, viewOnly, admin} {
  19. // Operation should pass for all viewers.
  20. count := client.User.Query().CountX(ctx)
  21. fmt.Println(count)
  22. }
  23. return nil
  24. }

Decision Context

Sometimes, we want to bind a specific privacy decision to the context.Context. In cases like this, we can use the privacy.DecisionContext function to create a new context with a privacy decision attached to it.

examples/privacyadmin/example_test.go

  1. func Do(ctx context.Context, client *ent.Client) error {
  2. // Bind a privacy decision to the context (bypass all other rules).
  3. allow := privacy.DecisionContext(ctx, privacy.Allow)
  4. if err := client.User.Create().Exec(allow); err != nil {
  5. return fmt.Errorf("expect operation to pass, but got %w", err)
  6. }
  7. return nil
  8. }

The full example exists in GitHub.

Multi Tenancy

In this example, we’re going to create a schema with 3 entity types - Tenant, User and Group. The helper packages viewer and rule (as mentioned above) also exist in this example to help us structure the application.

tenant-example

Let’s start building this application piece by piece. We begin by creating 3 different schemas (see the full code here), and since we want to share some logic between them, we create another mixed-in schema and add it to all other schemas as follows:

examples/privacytenant/ent/schema/mixin.go

  1. // BaseMixin for all schemas in the graph.
  2. type BaseMixin struct {
  3. mixin.Schema
  4. }
  5. // Policy defines the privacy policy of the BaseMixin.
  6. func (BaseMixin) Policy() ent.Policy {
  7. return privacy.Policy{
  8. Query: privacy.QueryPolicy{
  9. // Deny any query operation in case
  10. // there is no "viewer context".
  11. rule.DenyIfNoViewer(),
  12. // Allow admins to query any information.
  13. rule.AllowIfAdmin(),
  14. },
  15. Mutation: privacy.MutationPolicy{
  16. // Deny any mutation operation in case
  17. // there is no "viewer context".
  18. rule.DenyIfNoViewer(),
  19. },
  20. }
  21. }

examples/privacytenant/ent/schema/tenant.go

  1. // Mixin of the Tenant schema.
  2. func (Tenant) Mixin() []ent.Mixin {
  3. return []ent.Mixin{
  4. BaseMixin{},
  5. }
  6. }

As explained in the first example, the DenyIfNoViewer privacy rule, denies the operation if the context.Context does not contain the viewer.Viewer information.

Similar to the previous example, we want to add a constraint that only admin users can create tenants (and deny otherwise). We do it by copying the AllowIfAdmin rule from above, and adding it to the Policy of the Tenant schema:

examples/privacytenant/ent/schema/tenant.go

  1. // Policy defines the privacy policy of the User.
  2. func (Tenant) Policy() ent.Policy {
  3. return privacy.Policy{
  4. Mutation: privacy.MutationPolicy{
  5. // For Tenant type, we only allow admin users to mutate
  6. // the tenant information and deny otherwise.
  7. rule.AllowIfAdmin(),
  8. privacy.AlwaysDenyRule(),
  9. },
  10. }
  11. }

Then, we expect the following code to run successfully:

examples/privacytenant/example_test.go

  1. func Example_CreateTenants(ctx context.Context, client *ent.Client) {
  2. // Expect operation to fail in case viewer-context is missing.
  3. // First mutation privacy policy rule defined in BaseMixin.
  4. if err := client.Tenant.Create().Exec(ctx); !errors.Is(err, privacy.Deny) {
  5. log.Fatal("expect tenant creation to fail, but got:", err)
  6. }
  7. // Expect operation to fail in case the ent.User in the viewer-context
  8. // is not an admin user. Privacy policy defined in the Tenant schema.
  9. viewCtx := viewer.NewContext(ctx, viewer.UserViewer{Role: viewer.View})
  10. if err := client.Tenant.Create().Exec(viewCtx); !errors.Is(err, privacy.Deny) {
  11. log.Fatal("expect tenant creation to fail, but got:", err)
  12. }
  13. // Operations should pass successfully as the user in the viewer-context
  14. // is an admin user. First mutation privacy policy in Tenant schema.
  15. adminCtx := viewer.NewContext(ctx, viewer.UserViewer{Role: viewer.Admin})
  16. hub, err := client.Tenant.Create().SetName("GitHub").Save(adminCtx)
  17. if err != nil {
  18. log.Fatal("expect tenant creation to pass, but got:", err)
  19. }
  20. fmt.Println(hub)
  21. lab, err := client.Tenant.Create().SetName("GitLab").Save(adminCtx)
  22. if err != nil {
  23. log.Fatal("expect tenant creation to pass, but got:", err)
  24. }
  25. fmt.Println(lab)
  26. // Output:
  27. // Tenant(id=1, name=GitHub)
  28. // Tenant(id=2, name=GitLab)
  29. }

We continue by adding the rest of the edges in our data-model (see image above), and since both User and Group have an edge to the Tenant schema, we create a shared mixed-in schema named TenantMixin for this:

examples/privacytenant/ent/schema/mixin.go

  1. // TenantMixin for embedding the tenant info in different schemas.
  2. type TenantMixin struct {
  3. mixin.Schema
  4. }
  5. // Fields for all schemas that embed TenantMixin.
  6. func (TenantMixin) Fields() []ent.Field {
  7. return []ent.Field{
  8. field.Int("tenant_id").
  9. Immutable(),
  10. }
  11. }
  12. // Edges for all schemas that embed TenantMixin.
  13. func (TenantMixin) Edges() []ent.Edge {
  14. return []ent.Edge{
  15. edge.To("tenant", Tenant.Type).
  16. Field("tenant_id").
  17. Unique().
  18. Required().
  19. Immutable(),
  20. }
  21. }

Filter Rules

Next, we may want to enforce a rule that will limit viewers to only query groups and users that are connected to the tenant they belong to. For use cases like this, Ent has an additional type of privacy rule named Filter. We can use Filter rules to filter out entities based on the identity of the viewer. Unlike the rules we previously discussed, Filter rules can limit the scope of the queries a viewer can make, in addition to returning privacy decisions.

Privacy - 图7Note

The privacy filtering option needs to be enabled using the entql feature-flag (see instructions above).

examples/privacytenant/rule/rule.go

  1. // FilterTenantRule is a query/mutation rule that filters out entities that are not in the tenant.
  2. func FilterTenantRule() privacy.QueryMutationRule {
  3. // TenantsFilter is an interface to wrap WhereHasTenantWith()
  4. // predicate that is used by both `Group` and `User` schemas.
  5. type TenantsFilter interface {
  6. WhereTenantID(entql.IntP)
  7. }
  8. return privacy.FilterFunc(func(ctx context.Context, f privacy.Filter) error {
  9. view := viewer.FromContext(ctx)
  10. tid, ok := view.Tenant()
  11. if !ok {
  12. return privacy.Denyf("missing tenant information in viewer")
  13. }
  14. tf, ok := f.(TenantsFilter)
  15. if !ok {
  16. return privacy.Denyf("unexpected filter type %T", f)
  17. }
  18. // Make sure that a tenant reads only entities that have an edge to it.
  19. tf.WhereTenantID(entql.IntEQ(tid))
  20. // Skip to the next privacy rule (equivalent to return nil).
  21. return privacy.Skip
  22. })
  23. }

After creating the FilterTenantRule privacy rule, we add it to the TenantMixin to make sure all schemas that use this mixin, will also have this privacy rule.

examples/privacytenant/ent/schema/mixin.go

  1. // Policy for all schemas that embed TenantMixin.
  2. func (TenantMixin) Policy() ent.Policy {
  3. return rule.FilterTenantRule()
  4. }

Then, after running the code-generation, we expect the privacy-rules to take effect on the client operations.

examples/privacytenant/example_test.go

  1. func Example_TenantView(ctx context.Context, client *ent.Client) {
  2. // Operations should pass successfully as the user in the viewer-context
  3. // is an admin user. First mutation privacy policy in Tenant schema.
  4. adminCtx := viewer.NewContext(ctx, viewer.UserViewer{Role: viewer.Admin})
  5. hub := client.Tenant.Create().SetName("GitHub").SaveX(adminCtx)
  6. lab := client.Tenant.Create().SetName("GitLab").SaveX(adminCtx)
  7. // Create 2 tenant-specific viewer contexts.
  8. hubView := viewer.NewContext(ctx, viewer.UserViewer{T: hub})
  9. labView := viewer.NewContext(ctx, viewer.UserViewer{T: lab})
  10. // Create 2 users in each tenant.
  11. hubUsers := client.User.CreateBulk(
  12. client.User.Create().SetName("a8m").SetTenant(hub),
  13. client.User.Create().SetName("nati").SetTenant(hub),
  14. ).SaveX(hubView)
  15. fmt.Println(hubUsers)
  16. labUsers := client.User.CreateBulk(
  17. client.User.Create().SetName("foo").SetTenant(lab),
  18. client.User.Create().SetName("bar").SetTenant(lab),
  19. ).SaveX(labView)
  20. fmt.Println(labUsers)
  21. // Query users should fail in case viewer-context is missing.
  22. if _, err := client.User.Query().Count(ctx); !errors.Is(err, privacy.Deny) {
  23. log.Fatal("expect user query to fail, but got:", err)
  24. }
  25. // Ensure each tenant can see only its users.
  26. // First and only rule in TenantMixin.
  27. fmt.Println(client.User.Query().Select(user.FieldName).StringsX(hubView))
  28. fmt.Println(client.User.Query().CountX(hubView))
  29. fmt.Println(client.User.Query().Select(user.FieldName).StringsX(labView))
  30. fmt.Println(client.User.Query().CountX(labView))
  31. // Expect admin users to see everything. First
  32. // query privacy policy defined in BaseMixin.
  33. fmt.Println(client.User.Query().CountX(adminCtx)) // 4
  34. // Update operation with specific tenant-view should update
  35. // only the tenant in the viewer-context.
  36. client.User.Update().SetFoods([]string{"pizza"}).SaveX(hubView)
  37. fmt.Println(client.User.Query().AllX(hubView))
  38. fmt.Println(client.User.Query().AllX(labView))
  39. // Delete operation with specific tenant-view should delete
  40. // only the tenant in the viewer-context.
  41. client.User.Delete().ExecX(labView)
  42. fmt.Println(
  43. client.User.Query().CountX(hubView), // 2
  44. client.User.Query().CountX(labView), // 0
  45. )
  46. // DeleteOne with wrong viewer-context is nop.
  47. client.User.DeleteOne(hubUsers[0]).ExecX(labView)
  48. fmt.Println(client.User.Query().CountX(hubView)) // 2
  49. // Unlike queries, admin users are not allowed to mutate tenant specific data.
  50. if err := client.User.DeleteOne(hubUsers[0]).Exec(adminCtx); !errors.Is(err, privacy.Deny) {
  51. log.Fatal("expect user deletion to fail, but got:", err)
  52. }
  53. // Output:
  54. // [User(id=1, tenant_id=1, name=a8m, foods=[]) User(id=2, tenant_id=1, name=nati, foods=[])]
  55. // [User(id=3, tenant_id=2, name=foo, foods=[]) User(id=4, tenant_id=2, name=bar, foods=[])]
  56. // [a8m nati]
  57. // 2
  58. // [foo bar]
  59. // 2
  60. // 4
  61. // [User(id=1, tenant_id=1, name=a8m, foods=[pizza]) User(id=2, tenant_id=1, name=nati, foods=[pizza])]
  62. // [User(id=3, tenant_id=2, name=foo, foods=[]) User(id=4, tenant_id=2, name=bar, foods=[])]
  63. // 2 0
  64. // 2
  65. }

We finish our example with another privacy-rule named DenyMismatchedTenants on the Group schema. The DenyMismatchedTenants rule rejects group creation if the associated users do not belong to the same tenant as the group.

examples/privacytenant/rule/rule.go

  1. // DenyMismatchedTenants is a rule that runs only on create operations and returns a deny
  2. // decision if the operation tries to add users to groups that are not in the same tenant.
  3. func DenyMismatchedTenants() privacy.MutationRule {
  4. return privacy.GroupMutationRuleFunc(func(ctx context.Context, m *ent.GroupMutation) error {
  5. tid, exists := m.TenantID()
  6. if !exists {
  7. return privacy.Denyf("missing tenant information in mutation")
  8. }
  9. users := m.UsersIDs()
  10. // If there are no users in the mutation, skip this rule-check.
  11. if len(users) == 0 {
  12. return privacy.Skip
  13. }
  14. // Query the tenant-ids of all attached users. Expect all users to be connected to the same tenant
  15. // as the group. Note, we use privacy.DecisionContext to skip the FilterTenantRule defined above.
  16. ids, err := m.Client().User.Query().Where(user.IDIn(users...)).Select(user.FieldTenantID).Ints(privacy.DecisionContext(ctx, privacy.Allow))
  17. if err != nil {
  18. return privacy.Denyf("querying the tenant-ids %v", err)
  19. }
  20. if len(ids) != len(users) {
  21. return privacy.Denyf("one the attached users is not connected to a tenant %v", err)
  22. }
  23. for _, id := range ids {
  24. if id != tid {
  25. return privacy.Denyf("mismatch tenant-ids for group/users %d != %d", tid, id)
  26. }
  27. }
  28. // Skip to the next privacy rule (equivalent to return nil).
  29. return privacy.Skip
  30. })
  31. }

We add this rule to the Group schema and run code-generation.

examples/privacytenant/ent/schema/group.go

  1. // Policy defines the privacy policy of the Group.
  2. func (Group) Policy() ent.Policy {
  3. return privacy.Policy{
  4. Mutation: privacy.MutationPolicy{
  5. // Limit DenyMismatchedTenants only for
  6. // Create operation
  7. privacy.OnMutationOperation(
  8. rule.DenyMismatchedTenants(),
  9. ent.OpCreate,
  10. ),
  11. },
  12. }
  13. }

Again, we expect the privacy-rules to take effect on the client operations.

examples/privacytenant/example_test.go

  1. func Example_DenyMismatchedTenants(ctx context.Context, client *ent.Client) {
  2. // Operation should pass successfully as the user in the viewer-context
  3. // is an admin user. First mutation privacy policy in Tenant schema.
  4. adminCtx := viewer.NewContext(ctx, viewer.UserViewer{Role: viewer.Admin})
  5. hub := client.Tenant.Create().SetName("GitHub").SaveX(adminCtx)
  6. lab := client.Tenant.Create().SetName("GitLab").SaveX(adminCtx)
  7. // Create 2 tenant-specific viewer contexts.
  8. hubView := viewer.NewContext(ctx, viewer.UserViewer{T: hub})
  9. labView := viewer.NewContext(ctx, viewer.UserViewer{T: lab})
  10. // Create 2 users in each tenant.
  11. hubUsers := client.User.CreateBulk(
  12. client.User.Create().SetName("a8m").SetTenant(hub),
  13. client.User.Create().SetName("nati").SetTenant(hub),
  14. ).SaveX(hubView)
  15. fmt.Println(hubUsers)
  16. labUsers := client.User.CreateBulk(
  17. client.User.Create().SetName("foo").SetTenant(lab),
  18. client.User.Create().SetName("bar").SetTenant(lab),
  19. ).SaveX(labView)
  20. fmt.Println(labUsers)
  21. // Expect operation to fail as the DenyMismatchedTenants rule makes
  22. // sure the group and the users are connected to the same tenant.
  23. if err := client.Group.Create().SetName("entgo.io").SetTenant(hub).AddUsers(labUsers...).Exec(hubView); !errors.Is(err, privacy.Deny) {
  24. log.Fatal("expect operation to fail, since labUsers are not connected to the same tenant")
  25. }
  26. if err := client.Group.Create().SetName("entgo.io").SetTenant(hub).AddUsers(hubUsers[0], labUsers[0]).Exec(hubView); !errors.Is(err, privacy.Deny) {
  27. log.Fatal("expect operation to fail, since labUsers[0] is not connected to the same tenant")
  28. }
  29. // Expect mutation to pass as all users belong to the same tenant as the group.
  30. entgo := client.Group.Create().SetName("entgo.io").SetTenant(hub).AddUsers(hubUsers...).SaveX(hubView)
  31. fmt.Println(entgo)
  32. // Output:
  33. // [User(id=1, tenant_id=1, name=a8m, foods=[]) User(id=2, tenant_id=1, name=nati, foods=[])]
  34. // [User(id=3, tenant_id=2, name=foo, foods=[]) User(id=4, tenant_id=2, name=bar, foods=[])]
  35. // Group(id=1, tenant_id=1, name=entgo.io)
  36. }

In some cases, we want to reject user operations on entities that do not belong to their tenant without loading these entities from the database (unlike the DenyMismatchedTenants example above). To achieve this, we rely on the FilterTenantRule rule to add its filtering on mutations as well, and expect operations to fail with NotFoundError in case the tenant_id column does not match the one stored in the viewer-context.

examples/privacytenant/example_test.go

  1. func Example_DenyMismatchedView(ctx context.Context, client *ent.Client) {
  2. // Continuation of the code above.
  3. // Expect operation to fail, because the FilterTenantRule rule makes sure
  4. // that tenants can update and delete only their groups.
  5. if err := entgo.Update().SetName("fail.go").Exec(labView); !ent.IsNotFound(err) {
  6. log.Fatal("expect operation to fail, since the group (entgo) is managed by a different tenant (hub), but got:", err)
  7. }
  8. // Operation should pass in case it was applied with the right viewer-context.
  9. entgo = entgo.Update().SetName("entgo").SaveX(hubView)
  10. fmt.Println(entgo)
  11. // Output:
  12. // Group(id=1, tenant_id=1, name=entgo)
  13. }

The full example exists in GitHub.

Please note that this documentation is under active development.