Share a resource with relationships
Model owner, editor and viewer of a document as relationships, with folders that pass access down.
What it shows
- Two namespaces define the rules. An owner of a document is also an editor, and an editor is also a viewer. A viewer of a folder is a viewer of each document in it.
- Four relationship tuples say who is related to what. Maya owns a report, Noah edits it, and Priya may view the folder of the report.
- Your backend asks about a relation before it returns the document. LumoAuth follows the rules, so Priya may view the report with no tuple of her own for it.
expandlists everyone who can view the report, for a "Shared with" dialog.
Before you start
- An API key with the scope
authz:check. Create it in the portal: open API keys, under Applications & developer tools. The person who creates the key must hold the permissionpolicies.view. - Check that your plan includes fine-grained authorization in the plans matrix. Without it, every check answers "denied".
- Two namespaces and four tuples. You create them in the portal:
- In the sidebar, under Access control, open Relationships, and click Create namespace.
- Enter
folderas the Namespace name. Open Schema JSON, replace its text with the schema of the folder below, and click Create namespace. - Create the namespace
documentin the same way, with the schema of the document. - Open the Tuples tab and click Add relationship. Fill in the first row of the table below, and click Add tuple. Leave User relation empty.
- Add the other three rows in the same way.
The schema of the folder:
{
"relations": {
"owner": { "_this": { "relation": "owner" } },
"viewer": {
"union": [
{ "computed_userset": { "relation": "owner" } },
{ "_this": { "relation": "viewer" } }
]
}
}
}
The schema of the document. The last rule of viewer reads the parent tuple of the document, and takes the viewers of that folder:
{
"relations": {
"parent": { "_this": { "relation": "parent" } },
"owner": { "_this": { "relation": "owner" } },
"editor": {
"union": [
{ "computed_userset": { "relation": "owner" } },
{ "_this": { "relation": "editor" } }
]
},
"viewer": {
"union": [
{ "computed_userset": { "relation": "editor" } },
{ "_this": { "relation": "viewer" } },
{ "tuple_to_userset": { "tupleset": { "relation": "parent" }, "computed_userset": { "relation": "viewer" } } }
]
}
}
}
The four tuples:
| Object namespace | Object ID | Relation | User namespace | User ID |
|---|---|---|---|---|
document | q4-report | owner | user | maya |
document | q4-report | editor | user | noah |
document | q4-report | parent | folder | finance |
folder | finance | viewer | user | priya |
The names maya, noah and priya keep the example short. In your app, use the ID of the LumoAuth user: the sub claim of the token.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scope authz:check. |
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The curl version prints the JSON answers of the same six requests.
- Node.js
- Python
- Go
- PHP
- Java
- C#
- curl
authorization/share-with-relationships/js/share.mjs
// Ask LumoAuth who is related to a document, and list everyone who can view it.
//
// node authorization/share-with-relationships/js/share.mjs
import { LumoAuthBackend } from '@lumoauth/backend';
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.LUMOAUTH_API_KEY,
});
const document = 'document:q4-report';
for (const [subject, relation] of [
['user:maya', 'editor'], // Maya is the owner. An owner is also an editor.
['user:noah', 'viewer'], // Noah is an editor. An editor is also a viewer.
['user:noah', 'owner'],
['user:priya', 'viewer'], // Priya is a viewer of the folder of the document.
['user:priya', 'editor'],
]) {
const allowed = await lumo.zanzibar.check({ object: document, relation, subject });
console.log(`${subject} ${relation} of ${document} -> ${allowed ? 'allowed' : 'denied'}`);
}
// The answer of expand is a tree. Its leaves hold the subjects.
const subjects = (node) => [...(node.subjects ?? []), ...(node.children ?? []).flatMap(subjects)];
const tree = await lumo.zanzibar.expand({ object: document, relation: 'viewer' });
console.log(`can view ${document}: ${[...new Set(subjects(tree))].join(', ')}`);
node authorization/share-with-relationships/js/share.mjs
authorization/share-with-relationships/python/share.py
"""Ask LumoAuth who is related to a document, and list everyone who can view it.
python authorization/share-with-relationships/python/share.py
"""
from lumoauth import LumoAuth
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
lumo = LumoAuth()
document = "document:q4-report"
for subject, relation in (
("user:maya", "editor"), # Maya is the owner. An owner is also an editor.
("user:noah", "viewer"), # Noah is an editor. An editor is also a viewer.
("user:noah", "owner"),
("user:priya", "viewer"), # Priya is a viewer of the folder of the document.
("user:priya", "editor"),
):
allowed = lumo.zanzibar.check(document, relation, subject)
print(f"{subject} {relation} of {document} -> {'allowed' if allowed else 'denied'}")
def subjects(node):
"""The answer of expand is a tree. Its leaves hold the subjects."""
found = list(node.get("subjects") or [])
for child in node.get("children") or []:
found += subjects(child)
return found
tree = lumo.zanzibar.expand(document, "viewer")
print(f"can view {document}: {', '.join(dict.fromkeys(subjects(tree)))}")
python authorization/share-with-relationships/python/share.py
authorization/share-with-relationships/go/main.go
// Ask LumoAuth who is related to a document, and list everyone who can view it.
//
// go run ./authorization/share-with-relationships/go
package main
import (
"context"
"fmt"
"log"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
// The answer of expand is a tree. Its leaves hold the subjects.
func subjects(node lumoauth.ZanzibarUsersetNode, found []string) []string {
for _, subject := range node.Subjects {
known := false
for _, other := range found {
known = known || other == subject
}
if !known {
found = append(found, subject)
}
}
for _, child := range node.Children {
found = subjects(child, found)
}
return found
}
func main() {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
client, err := lumoauth.New()
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
document := "document:q4-report"
for _, question := range [][2]string{
{"user:maya", "editor"}, // Maya is the owner. An owner is also an editor.
{"user:noah", "viewer"}, // Noah is an editor. An editor is also a viewer.
{"user:noah", "owner"},
{"user:priya", "viewer"}, // Priya is a viewer of the folder of the document.
{"user:priya", "editor"},
} {
subject, relation := question[0], question[1]
allowed, err := client.Zanzibar.Check(ctx, document, relation, subject)
if err != nil {
log.Fatal(err)
}
answer := "denied"
if allowed {
answer = "allowed"
}
fmt.Printf("%s %s of %s -> %s\n", subject, relation, document, answer)
}
tree, err := client.Zanzibar.Expand(ctx, document, "viewer")
if err != nil {
log.Fatal(err)
}
fmt.Printf("can view %s: %s\n", document, strings.Join(subjects(*tree, nil), ", "))
}
go run ./authorization/share-with-relationships/go
authorization/share-with-relationships/php/share.php
<?php
// Ask LumoAuth who is related to a document, and list everyone who can view it.
//
// php authorization/share-with-relationships/php/share.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\LumoAuth;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
$lumo = new LumoAuth();
$document = 'document:q4-report';
foreach ([
['user:maya', 'editor'], // Maya is the owner. An owner is also an editor.
['user:noah', 'viewer'], // Noah is an editor. An editor is also a viewer.
['user:noah', 'owner'],
['user:priya', 'viewer'], // Priya is a viewer of the folder of the document.
['user:priya', 'editor'],
] as [$subject, $relation]) {
$allowed = $lumo->zanzibar->check($document, $relation, $subject);
printf("%s %s of %s -> %s\n", $subject, $relation, $document, $allowed ? 'allowed' : 'denied');
}
// The answer of expand is a tree. Its leaves hold the subjects.
function subjects(array $node): array
{
$found = $node['subjects'] ?? [];
foreach ($node['children'] ?? [] as $child) {
$found = array_merge($found, subjects($child));
}
return $found;
}
$tree = $lumo->zanzibar->expand($document, 'viewer');
printf("can view %s: %s\n", $document, implode(', ', array_unique(subjects($tree))));
php authorization/share-with-relationships/php/share.php
authorization/share-with-relationships/java/ShareDocument.java
// Ask LumoAuth who is related to a document, and list everyone who can view it.
//
// java -cp "java/lib/*" authorization/share-with-relationships/java/ShareDocument.java
import io.lumoauth.LumoAuth;
import io.lumoauth.model.ZanzibarUsersetNode;
public class ShareDocument {
public static void main(String[] args) {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
LumoAuth lumo = LumoAuth.fromEnvironment();
String document = "document:q4-report";
String[][] questions = {
{"user:maya", "editor"}, // Maya is the owner. An owner is also an editor.
{"user:noah", "viewer"}, // Noah is an editor. An editor is also a viewer.
{"user:noah", "owner"},
{"user:priya", "viewer"}, // Priya is a viewer of the folder of the document.
{"user:priya", "editor"},
};
for (String[] question : questions) {
String subject = question[0];
String relation = question[1];
boolean allowed = lumo.zanzibar().check(document, relation, subject);
System.out.printf("%s %s of %s -> %s%n", subject, relation, document, allowed ? "allowed" : "denied");
}
// The answer of expand is a tree. allSubjects() collects the subjects of its leaves.
ZanzibarUsersetNode tree = lumo.zanzibar().expand(document, "viewer");
System.out.printf("can view %s: %s%n", document, String.join(", ", tree.allSubjects()));
}
}
java -cp "java/lib/*" authorization/share-with-relationships/java/ShareDocument.java
authorization/share-with-relationships/csharp/ShareDocument.cs
#:package LumoAuth@1.7.0
#:property PublishAot=false
// Ask LumoAuth who is related to a document, and list everyone who can view it.
//
// dotnet run authorization/share-with-relationships/csharp/ShareDocument.cs
using LumoAuth;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
var lumo = LumoAuthClient.FromEnvironment();
var document = "document:q4-report";
foreach (var (subject, relation) in new[]
{
("user:maya", "editor"), // Maya is the owner. An owner is also an editor.
("user:noah", "viewer"), // Noah is an editor. An editor is also a viewer.
("user:noah", "owner"),
("user:priya", "viewer"), // Priya is a viewer of the folder of the document.
("user:priya", "editor"),
})
{
var allowed = await lumo.Zanzibar.CheckAsync(document, relation, subject);
Console.WriteLine($"{subject} {relation} of {document} -> {(allowed ? "allowed" : "denied")}");
}
// The answer of expand is a tree. AllSubjects() collects the subjects of its leaves.
var tree = await lumo.Zanzibar.ExpandAsync(document, "viewer");
Console.WriteLine($"can view {document}: {string.Join(", ", tree.AllSubjects())}");
dotnet run authorization/share-with-relationships/csharp/ShareDocument.cs
authorization/share-with-relationships/http/share.sh
#!/bin/sh
# Ask LumoAuth who is related to a document, and list everyone who can view it,
# with curl.
#
# sh authorization/share-with-relationships/http/share.sh
set -eu
ZANZIBAR="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/zanzibar"
DOCUMENT="document:q4-report"
# Maya is the owner, Noah is an editor, and Priya is a viewer of the folder.
for QUESTION in "user:maya editor" "user:noah viewer" "user:noah owner" "user:priya viewer" "user:priya editor"; do
SUBJECT="${QUESTION% *}"
RELATION="${QUESTION#* }"
# This endpoint names the subject "user".
curl --silent --show-error "$ZANZIBAR/check" \
--header "X-API-Key: $LUMOAUTH_API_KEY" \
--header "Content-Type: application/json" \
--data "{\"object\": \"$DOCUMENT\", \"relation\": \"$RELATION\", \"user\": \"$SUBJECT\"}"
echo
done
# The answer is a tree. Its leaves hold the subjects.
curl --silent --show-error "$ZANZIBAR/expand" \
--header "X-API-Key: $LUMOAUTH_API_KEY" \
--header "Content-Type: application/json" \
--data "{\"object\": \"$DOCUMENT\", \"relation\": \"viewer\"}"
echo
sh authorization/share-with-relationships/http/share.sh
Check the result
Output
user:maya editor of document:q4-report -> allowed
user:noah viewer of document:q4-report -> allowed
user:noah owner of document:q4-report -> denied
user:priya viewer of document:q4-report -> allowed
user:priya editor of document:q4-report -> denied
can view document:q4-report: user:maya, user:noah, user:priya
- Share the folder with one more person: add the tuple
folder:finance#viewer@user:omarin the portal, and run the program again. The last line now namesuser:omartoo. - The Tester tab of the Relationships page answers the same questions in the portal. It also shows the rule that gave the answer.
Limits
- LumoAuth has no API for writing a tuple or a namespace. You write them in the portal, so your app cannot add a tuple when a person clicks "Share".
- There is no operation that lists the objects of a person, such as "every document that Priya can view". Ask about each object.
- A namespace cannot exclude subjects, as in "every viewer except blocked users".
expandlists a userset such asteam:finance#memberas it is. It does not list the members of the team.- When the subject is a LumoAuth user who is blocked or deleted, the answer is "denied", whatever the tuples say.
- An API key may ask about any subject. A signed-in person who asks with an access token may ask only about themselves, unless they hold the permission
authz.check.