Tutorial: Show Each User Only What Their Labels Allow
In this tutorial you build a connector from the Kamiwaza SDK's OpenSearch example, load the small set of company documents it ships with into an OpenSearch, and attach two content policy constraints to it. Four users then ask Kaizen the same questions, and each gets an answer built only from the paragraphs their attributes allow.
The sample has six documents: a quarterly business review, a security incident review, a brief on a large customer account, an engineering reorg, a leave of absence and next year's roadmap. Each paragraph carries a label: how sensitive it is, and for some, which groups of people may read it.
You end with:
-
A data source, "Company documents", whose connector labels every paragraph with a
sensitivitylevel (internal,confidentialorrestricted, lowest first) and a list ofaccess_tags. -
Two constraints on it: one drops a paragraph whose level is above the user's, the other drops a paragraph with a tag the user doesn't hold.
-
Four users with these attributes:
User sensitivityaccess_tagsnew-employeeinternalnone account-executiveconfidentialsalessecurity-engineerconfidentialsecuritygeneral-counselrestrictedlegal,finance
The policy runs in Kamiwaza, not in the connector. The connector only labels what it returns. Policy explains the model; this page walks through it once, end to end.
Before you start
You need:
-
A Kamiwaza administrator account, and
kubectlaccess to the cluster and to the namespace Kamiwaza is installed in. This page useskamiwaza. -
curlandjq. -
Kaizen deployed, with a chat model selected in Admin area → Models, and a Kaizen administrator.
-
For building the connector: Python 3.12, Docker, a registry the cluster pulls from, and the Kamiwaza SDK 1.4.1 or later. Earlier SDKs don't carry the examples' sample data and policy files. Install it in a virtual environment:
python3.12 -m venv ~/kzenv && source ~/kzenv/bin/activatepip install 'kamiwaza-sdk[connector]>=1.4.1'In a new terminal, run
source ~/kzenv/bin/activateagain before usingkz-ext. -
Optional: the OPA CLI, 1.0 or later, to run the templates' tests.
Set up kapi
The commands on this page call Kamiwaza's API through kapi, a small shell
function. It wraps curl: it takes an HTTP method and an API path, adds your
Kamiwaza address and an administrator's token, and passes any other arguments
to curl. kapi GET /authz/policies/health is
curl -X GET https://<YOUR_KAMIWAZA_DOMAIN>/api/authz/policies/health with
the token added.
The commands work in both bash and zsh. Run them all in one terminal: later steps use the functions and variables that earlier steps define.
If your Kamiwaza uses a certificate your machine doesn't trust, point curl at
its CA file first. Your administrator can give you the CA file. If Kamiwaza
uses a self-signed certificate, you can save it yourself, after checking with
your administrator that it's the right one, and use "$PWD/kamiwaza-ca.crt"
(the full path, so it still works from another directory) as the CA file:
openssl s_client -connect <YOUR_KAMIWAZA_DOMAIN>:443 -servername <YOUR_KAMIWAZA_DOMAIN> </dev/null \
| openssl x509 > kamiwaza-ca.crt
export CURL_CA_BUNDLE="$PWD/kamiwaza-ca.crt"
Define token_for, which asks for a user's password and prints a token for
that user, and get an administrator's token with it. Use your administrator's
username in place of admin:
export KAMIWAZA_URL=https://<YOUR_KAMIWAZA_DOMAIN>
token_for() {
local password
printf 'password for %s: ' "$1" >&2; read -rs password; echo >&2
printf '%s' "$password" | curl -sS -X POST "$KAMIWAZA_URL/api/auth/token" \
-d grant_type=password --data-urlencode "username=$1" --data-urlencode "password@-" \
| jq -r '.access_token // empty'
}
TOKEN=$(token_for admin)
[ -n "$TOKEN" ] && echo "token ok" || echo "token failed"
Then define kapi, and need, which the steps use to check what Kamiwaza
answered. need <file> <field> prints a field of the JSON response saved in a
file; when the field isn't there, it prints FAILED and the whole response,
and fails:
kapi() {
local verb=$1 route=$2
shift 2
curl -sS -X "$verb" "$KAMIWAZA_URL/api$route" -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' "$@"
}
need() {
jq -er "$2 // empty" "$1" 2>/dev/null && return 0
echo "FAILED. The response was:" >&2; cat "$1" >&2; echo >&2
return 1
}
kapi GET /auth/pats -o /dev/null -w '%{http_code}\n'
The last command prints 200 when the token works. When a step prints
FAILED, fix what the response names before you go on: the later steps
depend on it.
The token lasts four hours; run TOKEN=$(token_for admin) again when calls
start returning 401. Steps 5 and 9 use token_for to sign in as the four
users too.
Step 1: Turn on content policy
Content policy is off by default. This tutorial uses the OPA the chart installs. Connect Your OPA covers it in full, and how to use an OPA you run instead.
Install the OPA with policy still off, so it loads the policy bundle before
Kamiwaza depends on it. Add this under core: in your values file, and upgrade
with the same command and values file you installed with:
core:
authz:
contentPolicy:
enabled: false
localOpa:
enabled: true
Check that the OPA has loaded the bundle:
kapi GET /authz/policies/status \
| jq '{latest_revision, instances: [.instances[] | {opa_version, bundles: (.bundles | map_values({active_revision, state}))}]}'
Check: one instance is listed, and both its bundles are effective.
Then set enabled: true, upgrade again, and check that Kamiwaza is enforcing:
kapi GET /authz/policies/health | jq '{enabled, reachable, bundle_loaded, enforcing, active_revision, latest_revision}'
{
"enabled": true,
"reachable": true,
"bundle_loaded": true,
"enforcing": true,
"active_revision": 2,
"latest_revision": 2
}
Check: the four flags are true, and active_revision equals
latest_revision. Your revision numbers will differ.
Step 2: Create the connector project and build its image
In an empty directory, create the project from the SDK's OpenSearch example:
mkdir company-docs && cd company-docs
kz-ext create --type connector --example opensearch --name company-docs
Besides the connector, the project has two folders this tutorial uses:
sample/documents.ndjson the company documents: one OpenSearch document per paragraph
sample/mapping.json the index's field types
sample/load.sh creates the index and loads the documents (step 3)
policy/constraints/level.json
policy/constraints/tags.json
policy/templates/level_ceiling/
policy/templates/needs_matching_attribute/
The two templates come from the Kamiwaza SDK, not from this page. The SDK
ships them in kamiwaza_extensions/examples/policies/, and kz-ext create
copies the ones the example's constraints use into policy/templates/. Each
folder holds the Rego (template.rego), its tests, its parameters schema and a
README that explains its parameters.
Each paragraph in the sample starts with a label prefix: its level, (I)
for internal, (C) for confidential or (R) for restricted, then any tags in
brackets. Here is the account brief, one document per paragraph, with its
document id:
account-brief::p1 (I) Bramblewood Freight is our largest logistics customer and has been live since 2023.
account-brief::p2 (C)[sales] The Bramblewood renewal is worth $2.4M a year. Don't go below a 15% discount.
account-brief::p3 (R)[legal] Bramblewood sent us a notice of breach over the September outage. Don't discuss liability with them; send any questions to legal.
The connector's src/labels.py reads the prefix into two fields on every
search result and fetch: sensitivity and access_tags. Kamiwaza reads them
to apply policy and leaves them out of the result the user gets. The prefix
itself stays in the paragraph's text. Two of the
sample's 19 paragraphs have no readable label on purpose: roadmap-2027::p4
has no prefix, and engineering-reorg::p4 starts with (X), a level that
doesn't exist.
Test the templates, if you have the OPA CLI, and check the project:
opa test policy/templates/
kz-ext validate
PASS: 39/39
kz-ext validate ends with Validation passed and one warning, that
release/product.yaml is a scaffold stub. That is expected for a new project;
the file matters only when you publish a release of the connector.
Build the image and push it to a registry the cluster pulls from. Kamiwaza runs the connector in the cluster from the image's address in that registry, so an image pushed where only your machine can reach it never starts. Use your registry's name, and give every build a new tag:
docker build --load -t registry.example.com/kamiwaza/company-docs-connector:0.1.0 .
docker push registry.example.com/kamiwaza/company-docs-connector:0.1.0
--load also keeps the image in your local image store, where step 4 runs it
to read the connector's manifest.
Run Your Own Connector, route B
covers registries, including one your machine reaches at another address than
the cluster, and Build a Connector Image
building without internet access and for another platform.
Step 3: Start OpenSearch and load the sample documents
The connector reads from an OpenSearch, and Kamiwaza runs the connector in the
cluster, so the OpenSearch must be one the cluster can reach. For this
tutorial, run a single-node OpenSearch, with its security plugin off, in its
own namespace. Save this as opensearch.yaml:
apiVersion: v1
kind: Namespace
metadata:
name: docs-opensearch
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: opensearch
namespace: docs-opensearch
spec:
replicas: 1
selector: {matchLabels: {app: opensearch}}
template:
metadata:
labels: {app: opensearch}
spec:
containers:
- name: opensearch
image: opensearchproject/opensearch:2.19.1
env:
- {name: discovery.type, value: single-node}
- {name: DISABLE_SECURITY_PLUGIN, value: "true"}
- {name: DISABLE_INSTALL_DEMO_CONFIG, value: "true"}
- {name: OPENSEARCH_JAVA_OPTS, value: "-Xms512m -Xmx512m"}
ports: [{containerPort: 9200}]
resources:
requests: {cpu: 250m, memory: 512Mi}
limits: {memory: 1536Mi}
readinessProbe:
httpGet: {path: /_cluster/health, port: 9200}
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: opensearch
namespace: docs-opensearch
spec:
selector: {app: opensearch}
ports: [{name: http, port: 9200, targetPort: 9200}]
Start it:
kubectl apply -f opensearch.yaml
kubectl -n docs-opensearch rollout status deploy/opensearch --timeout=300s
The OpenSearch starts empty. The project's sample/load.sh fills it: it
deletes the company-docs index if it exists, creates it with the field types
in sample/mapping.json, and bulk-loads the 19 documents in
sample/documents.ndjson. It takes the OpenSearch's address as its argument, so
reach the OpenSearch from your machine through a port-forward, and run it from
the project's folder:
kubectl -n docs-opensearch port-forward svc/opensearch 29200:9200 >/dev/null &
PF_PID=$!
sleep 3
if kill -0 "$PF_PID" 2>/dev/null; then
sample/load.sh http://localhost:29200
curl -s localhost:29200/company-docs/_count | jq .count
else
echo "port-forward failed: is port 29200 already in use? Stop what holds it, then run this block again."
fi
loaded company-docs into http://localhost:29200
19
Look at what you loaded, one line per paragraph:
curl -s 'localhost:29200/company-docs/_search?size=50&sort=doc_id,paragraph' \
| jq -r '.hits.hits[]._source | "\(.doc_id)::p\(.paragraph) [\(.team)] \(.body[0:70])"'
kill "$PF_PID"
account-brief::p1 [sales] (I) Bramblewood Freight is our largest logistics customer and has been
account-brief::p2 [sales] (C)[sales] The Bramblewood renewal is worth $2.4M a year. Don't go bel
account-brief::p3 [sales] (R)[legal] Bramblewood sent us a notice of breach over the September o
engineering-reorg::p1 [engineering] (I) The Platform and Infrastructure teams merge into one team on 1 Mar
engineering-reorg::p2 [engineering] (C)[hr] Two managers move to individual-contributor roles. The change
engineering-reorg::p3 [engineering] (R)[hr][legal] Four roles are being eliminated. Severance terms are be
engineering-reorg::p4 [engineering] (X) Team leads will hold one-to-ones with everyone affected in the wee
leave-case::p1 [people] (I) A support team lead is on leave until March. The rest of the team
leave-case::p2 [people] (R)[hr] The leave is for a medical condition. Accommodations for their
q3-business-review::p1 [finance] (I) In the third quarter our customer count grew 18%, and we launched
q3-business-review::p2 [finance] (C)[finance] Third quarter revenue was $41.2M, 4% under plan, with a g
q3-business-review::p3 [finance] (R)[finance][legal] This quarter we made a non-binding offer to acquir
roadmap-2027::p1 [product] (I) The mobile app and single sign-on improvements ship in Q1.
roadmap-2027::p2 [product] (C) Usage-based pricing launches in April. It has not been announced y
roadmap-2027::p3 [product] (R)[legal] A distribution partnership is under negotiation and covered
roadmap-2027::p4 [product] Ideas for later in the year are collected on the roadmap board.
security-incident-review::p1 [security] (I) In October a misconfigured storage bucket was publicly exposed for
security-incident-review::p2 [security] (C)[security] The bucket held data exports for 212 customers. Two of t
security-incident-review::p3 [security] (R)[legal] Counsel advises that regulators in three regions must be no
team is the team that owns the page; the connector offers it as a search
filter. It plays no part in policy: only the prefix does.
The index lives in the pod only. If the pod restarts, run the port-forward and
sample/load.sh again.
This OpenSearch has no users or TLS, so it is only for trying the example. For
a real cluster, give the connection a read-only OpenSearch user, as the
project's README.md shows.
Step 4: Register the connector and create the data source
These are the steps of Run Your Own Connector, with this connector's values. Run the image you built, and read its manifest:
IMAGE_REGISTRY=registry.example.com
IMAGE_REPOSITORY=kamiwaza/company-docs-connector
IMAGE_TAG=0.1.0
IMAGE="$IMAGE_REGISTRY/$IMAGE_REPOSITORY:$IMAGE_TAG"
docker run -d --name connector-manifest -p 127.0.0.1:18080:8080 "$IMAGE"
for i in $(seq 1 30); do curl -sf 127.0.0.1:18080/manifest > manifest.json && break; sleep 2; done
CONNECTOR_TYPE=$(jq -r '.connector_type // empty' manifest.json 2>/dev/null)
if [ -n "$CONNECTOR_TYPE" ]; then echo "connector type $CONNECTOR_TYPE"
else echo "FAILED: no manifest. The connector's log:"; docker logs connector-manifest; fi
docker rm -f connector-manifest
Check: it prints connector type company-docs. If it prints FAILED
instead, the connector's log says why it didn't start; fix that and run the
block again.
Register the type:
jq --arg r "$IMAGE_REGISTRY" --arg p "$IMAGE_REPOSITORY" --arg t "$IMAGE_TAG" \
'{manifest: (.deployment += {image_registry: $r, image_repository: $p, image_tag: $t}), version: $t}' \
manifest.json \
| kapi PUT "/connectors/catalog/$CONNECTOR_TYPE" -d @- > register.json
need register.json .connector_type
It prints company-docs.
Create the data source and its connection. The endpoint is the OpenSearch service from step 3. With that OpenSearch, the username and password are required by the connector but ignored by OpenSearch:
kapi POST /catalog/containers/ \
-d '{"name": "Company documents", "platform": "kamiwaza-connector"}' > source.json
DATA_SOURCE=$(need source.json strings) && echo "$DATA_SOURCE"
DS_ENC=$(jq -rn --arg ds "$DATA_SOURCE" '$ds|@uri')
jq -n --arg ds "$DATA_SOURCE" --arg type "$CONNECTOR_TYPE" \
'{name: "Company documents", connector_type: $type, container_urn: $ds,
config: {endpoint: "http://opensearch.docs-opensearch.svc:9200", indexes: "company-docs",
search_fields: "title^2,body", username: "docs-reader", password: "change-me"}}' \
| kapi POST /connectors/ -d @- > connection.json
CONNECTION=$(need connection.json .id) && echo "connection $CONNECTION"
for i in $(seq 1 30); do
STATUS=$(kapi GET "/connectors/$CONNECTION" | jq -r .status)
echo "$STATUS"; [ "$STATUS" = ready ] || [ "$STATUS" = degraded ] && break; sleep 10
done
kapi POST "/connectors/$CONNECTION/verify" \
| jq -c '{status, connection_status, checks: [.checks[] | {label, status}]}'
{"status":"success","connection_status":"connected","checks":[{"label":"Read the allowed indexes","status":"success"},{"label":"Search","status":"success"},{"label":"Query","status":"success"}]}
Step 5: Create the users and give them attributes
Content policy sees a user's declared attributes. Declare the two the constraints read:
kapi PUT /cluster/attribute-schema/sensitivity -d '{"type": "string"}' | jq -c '{name, type, state}'
kapi PUT /cluster/attribute-schema/access_tags -d '{"type": "string[]"}' | jq -c '{name, type, state}'
{"name":"sensitivity","type":"string","state":"declared"}
{"name":"access_tags","type":"string[]","state":"declared"}
Declaring an attribute adds it to Keycloak's user profile and to the user's token. Create the four users, each with an email address; Kaizen needs one:
for user in new-employee account-executive security-engineer general-counsel; do
printf 'password for %s: ' "$user"; read -rs PASSWORD; echo
jq -n --arg u "$user" --arg p "$PASSWORD" \
'{username: $u, email: ($u + "@example.com"), password: $p, roles: ["user"]}' \
| kapi POST /auth/users/local -d @- -o /dev/null -w "$user %{http_code}\n"
done
unset PASSWORD
Each prints 201. Then set each user's attributes with
PUT /authz/subjects/<username>. set_user takes a username, a level and a
comma-separated list of tags, which may be empty. A list value becomes an
attribute with several values:
set_user() {
jq -cn --arg l "$2" --arg t "$3" \
'{attributes: {sensitivity: [$l], access_tags: ($t | split(",") | map(select(length > 0)))}}' \
| kapi PUT "/authz/subjects/$1" -d @- | jq -c '{username, attributes}'
}
set_user new-employee internal ""
set_user account-executive confidential sales
set_user security-engineer confidential security
set_user general-counsel restricted legal,finance
{"username":"new-employee","attributes":{"sensitivity":"internal"}}
{"username":"account-executive","attributes":{"access_tags":"sales","sensitivity":"confidential"}}
{"username":"security-engineer","attributes":{"access_tags":"security","sensitivity":"confidential"}}
{"username":"general-counsel","attributes":{"access_tags":["legal","finance"],"sensitivity":"restricted"}}
The response shows an attribute with one value as a plain string; it is still the list policy reads.
Check: sign in as one of the users, and see what Kamiwaza forwards to policy:
USER_TOKEN=$(token_for account-executive)
curl -sS -o /dev/null -D - "$KAMIWAZA_URL/api/auth/forward/validate" \
-H "Authorization: Bearer $USER_TOKEN" | grep -i '^x-user-attributes:'
For account-executive, the header includes
"access_tags":["sales"] and "sensitivity":"confidential". A user's attributes
reach their token at their next sign-in.
Step 6: Share the data source
A new data source is shared with no one. Share it with a group of the four users, as in Run Your Own Connector, step 3:
kapi POST /authz/groups/ -d '{"name": "docs-readers"}' > group.json
GROUP=$(need group.json .id) && echo "group $GROUP"
for user in new-employee account-executive security-engineer general-counsel; do
kapi POST "/authz/groups/$GROUP/members" -o /dev/null -w "$user %{http_code}\n" \
-d "$(jq -n --arg u "$user" '{user_id: $u}')"
done
kapi POST /authz/resources/container/grants -o /dev/null -w "grant %{http_code}\n" \
-d "$(jq -n --arg ds "$DATA_SOURCE" --arg g "$GROUP" \
'{object_id: $ds, subject: {namespace: "group", id: $g}, relation: "viewer"}')"
kapi GET "/authz/resources/container/grants?object_id=$DS_ENC" \
| jq -r '.[] | "\(.relation) \(.subject.namespace):\(.subject.id)"'
Check: the grants are you as owner and viewer group:<the group's ID>.
Sharing decides who may use the data source at all. The constraints below decide which of its records each of those users gets back.
Step 7: Upload the two templates
A template is a Rego module that defines a kind of rule. This step uploads the
two the SDK example ships, level_ceiling and needs_matching_attribute, from
the project's policy/templates/ (step 2). Read each one's README.md there
for what it does and the parameters it takes. Upload each one as a
draft, wait for your OPA to compile it, try it on sample records, and publish
it. Three functions do the uploading, waiting and publishing, here and in
step 8:
wait_draft <draft id>waits until your OPA has compiled the draft, and prints the draft's id andcompiled. A draft that doesn't compile printsFAILEDwith the compiler's error.upload_template <name> <change note>uploadspolicy/templates/<name>/as a draft, and waits for it. It setsDRAFTto the draft's id.promote <draft id>publishes the draft, and prints the policy revision it made.
From the project's folder:
wait_draft() {
local i state
for i in $(seq 1 24); do
kapi GET "/authz/policies/drafts/$1" > draft-state.json
state=$(jq -r .status draft-state.json 2>/dev/null)
[ "$state" = pending ] || break
sleep 5
done
[ "$state" = compiled ] && echo "$1 compiled" && return 0
echo "FAILED. The draft:" >&2; cat draft-state.json >&2; echo >&2
return 1
}
upload_template() {
jq -n --rawfile rego "policy/templates/$1/template.rego" \
--slurpfile schema "policy/templates/$1/parameters.schema.json" --arg note "$2" \
'{rego: $rego, parameters_schema: $schema[0], change_note: $note}' \
| kapi POST "/authz/policies/templates/$1/drafts" -d @- > draft.json
DRAFT=$(need draft.json .draft_id) && wait_draft "$DRAFT"
}
promote() {
local revision
kapi POST "/authz/policies/drafts/$1/promote" -d '{}' > promote.json
revision=$(need promote.json .revision) && echo "published, revision $revision"
}
Start with level_ceiling:
upload_template level_ceiling "Drop records above the user level"
When it prints the draft's id and compiled, try it as a user whose level is confidential,
on an internal record, a restricted one, and one with no level:
kapi POST "/authz/policies/drafts/$DRAFT/dry-run" -d '{
"parameters": {"levels": ["internal", "confidential", "restricted"],
"record_field": "sensitivity", "attribute": "sensitivity",
"unknown_level": "drop"},
"records": [{"id": 1, "sensitivity": "internal"}, {"id": 2, "sensitivity": "restricted"}, {"id": 3}],
"subject_attributes": {"sensitivity": "confidential"}
}' | jq -c .decision.drop
[{"constraint":"dry-run","index":1,"reason":"level_above_user"},{"constraint":"dry-run","index":2,"reason":"level_missing"}]
Records count from 0, so the restricted record and the one without a level
are dropped. Publish the template:
promote "$DRAFT"
Do the same for needs_matching_attribute, with its own change note and
sample:
upload_template needs_matching_attribute "Drop records whose values the user does not hold"
kapi POST "/authz/policies/drafts/$DRAFT/dry-run" -d '{
"parameters": {"record_field": "access_tags", "attribute": "access_tags"},
"records": [{"id": 1, "access_tags": ["legal"]}, {"id": 2, "access_tags": ["legal", "hr"]}, {"id": 3}],
"subject_attributes": {"access_tags": ["legal"]}
}' | jq -c .decision.drop
[{"constraint":"dry-run","index":1,"reason":"attribute_not_held"}]
The user holds legal but not hr, so record 1 is dropped. Record 2,
with no tags, is kept: this template only narrows records that name a tag. The
level template is what hides records nobody labeled. Publish it:
promote "$DRAFT"
Each template's README.md lists its parameters and drop reasons.
Step 8: Attach the constraints
To see for yourself what every user gets before policy filters anything, the first row of the table in step 9, run step 9's commands now, before you attach the constraints, and come back.
A constraint applies a template to data sources, with the template's
parameters. The example's policy/constraints/level.json:
{
"template": "level_ceiling",
"parameters": {
"levels": ["internal", "confidential", "restricted"],
"record_field": "sensitivity",
"attribute": "sensitivity",
"unknown_level": "drop"
},
"match": {"resources": ["DATA_SOURCE_URN"]},
"enforcement_action": "deny"
}
publish_constraint <name> <file> <data source URN> drafts a constraint from
a file with the URN in match, waits for it to compile, and publishes it.
Publish both, from the project's folder:
publish_constraint() {
jq --arg ds "$3" '.match.resources = [$ds]' "$2" \
| kapi POST "/authz/policies/constraints/$1/drafts" -d @- > draft.json
DRAFT=$(need draft.json .draft_id) && wait_draft "$DRAFT" && promote "$DRAFT"
}
publish_constraint company-docs-level policy/constraints/level.json "$DATA_SOURCE" &&
publish_constraint company-docs-tags policy/constraints/tags.json "$DATA_SOURCE"
kapi GET /authz/policies/health | jq -c '{enforcing, active_revision, latest_revision}'
Check: active_revision equals latest_revision. Until the OPA has loaded
a change, usually within seconds, calls to the data source are refused rather
than answered unfiltered.
Step 9: Check what each user gets
Make the calls Kaizen's tool makes, through Kamiwaza's API, as each user. G
is the Global workroom's ID. Each function takes a user's token:
search_as <token> <text>searches, and prints the ids it gets back.all_as <token>searches with a filter that matches every page, and prints how many paragraphs it gets back.query_as <token> <SQL>sends a SQL query, and prints the rows.fetch_as <token> <id>fetches one paragraph by its id, and prints the HTTP status.
G=ffffffff-ffff-ffff-ffff-ffffffffffff
SURFACES="$KAMIWAZA_URL/api/connectors/surfaces/workrooms/$G/$CONNECTION"
call_as() {
curl -sS -X POST "$SURFACES/$2" -H "Authorization: Bearer $1" \
-H 'Content-Type: application/json' -d "$3"
}
search_as() {
call_as "$1" search "$(jq -n --arg q "$2" '{surface: "documents", query: $q, page_size: 50}')" \
| jq -r '.items | map(.id | sub("company-docs/"; "")) | sort | join(" ")'
}
all_as() {
call_as "$1" search '{"surface": "documents", "page_size": 50, "filters": [{"field": "team",
"op": "in", "value": ["finance", "security", "sales", "engineering", "people", "product"]}]}' \
| jq -r '"all paragraphs: \(.items | length)"'
}
query_as() {
call_as "$1" query "$(jq -n --arg q "$2" '{surface: "documents", query: $q}')" | jq -c '.rows'
}
fetch_as() {
curl -sS "$SURFACES/content/$(jq -rn --arg id "company-docs/$2" '$id|@uri')?surface=documents" \
-H "Authorization: Bearer $1" -o fetch.json -w "fetch $2: %{http_code}\n"
}
Run them as each user. Each user's password is asked for once:
for user in new-employee account-executive security-engineer general-counsel; do
USER_TOKEN=$(token_for "$user")
echo "== $user"
for TEXT in quarter "security incident" Bramblewood; do search_as "$USER_TOKEN" "$TEXT"; done
all_as "$USER_TOKEN"
query_as "$USER_TOKEN" "SELECT team, COUNT(*) AS paragraphs FROM company-docs GROUP BY team"
fetch_as "$USER_TOKEN" leave-case::p2
done
With the constraints attached, new-employee gets:
password for new-employee:
== new-employee
q3-business-review::p1
security-incident-review::p1
account-brief::p1
all paragraphs: 6
[]
fetch leave-case::p2: 403
To see what an administrator gets, run the same calls with your own token,
"$TOKEN", in place of "$USER_TOKEN":
for TEXT in quarter "security incident" Bramblewood; do search_as "$TOKEN" "$TEXT"; done
all_as "$TOKEN"
What each user got. The first row is the same calls before step 8:
| User | "quarter" | "security incident" | "Bramblewood" | All paragraphs |
|---|---|---|---|---|
| Before the constraints, anyone | q3-business-review::p1 p2 p3 | security-incident-review::p1 p2 p3 | account-brief::p1 p2 p3 | 19 |
new-employee | p1 | p1 | p1 | 6 |
account-executive | p1 | p1 | p1 p2 | 8 |
security-engineer | p1 | p1 p2 | p1 | 8 |
general-counsel | p1 p2 p3 | p1 p3 | p1 p3 | 12 |
admin, with no attributes | p1 | p1 | p1 | 6 |
new-employeegets only the(I)paragraph that opens each page.account-executivealso gets the renewal terms,account-brief::p2(confidential,sales).security-engineerinstead gets the affected customers and leaked keys,security-incident-review::p2(confidential,security). Neither gets the other's paragraph: their level is the same, their tags differ.general-counselisrestrictedand gets the revenue figures, the acquisition offer, the regulators' deadline and the notice of breach. They still don't getsecurity-incident-review::p2oraccount-brief::p2: a high level doesn't stand in for a tag they don't hold.- Nobody here holds
hr, so nobody gets the reorg's personnel details or the medical reason inleave-case::p2, whatever their level. roadmap-2027::p4andengineering-reorg::p4have no readable label, so they are dropped for everyone.- A user without the attribute ranks at the lowest level. An administrator is not exempt: policy filters on attributes, not roles.
Fetching one paragraph by id goes through the same policy. A paragraph the user
can't see, such as leave-case::p2 for any of these users, returns 403, and
fetch.json holds:
{"detail":"Content policy doesn't allow this item to be returned."}
Queries return nothing. The connector also answers SQL, but its query rows
carry no labels: a row's columns are whatever the SQL produced, so
'internal' AS sensitivity could choose its own label, and a subquery or a
window function (MAX(body) OVER (PARTITION BY doc_id)) could put a restricted
paragraph's text in a row whose own paragraph is internal. The connector
removes any sensitivity or access_tags column from query rows and adds
none, so the level constraint drops every query row, for every user. Before the
constraints, the GROUP BY query in the loop returns
[["engineering",4],["finance",3],["people",2],["product",4],["sales",3],["security",3]];
with them, [], even for general-counsel. Labels must come from data the
connector read itself, never from the caller's SQL; search reads them from each
paragraph's text. The connector's query description tells the agent to search
instead when a content policy is attached.
Step 10: Ask the same questions in Kaizen
Open Kaizen from App Garden with Open, or go to the address in App Garden's Primary Route column, and sign in.
A Kaizen administrator selects their name at the bottom left, then Admin area → Connectors, and turns on Tools for "Company documents". RAG stays off; tools need no embedding model.
Then each user, in their own browser session, selects New session, then the + button in the message box. In the Add to chat menu, they select Connectors. Connectors start checked, so uncheck every connector except "Company documents", and ask:
How did we do last quarter? What happened with the October security incident? And where are we with Bramblewood Freight? Search the Company documents connector and cite the paragraph ids.
Kaizen's connector tool calls the connector as the signed-in user, so content policy filters every result before the model sees it. Each answer can draw only on that user's row in the table in step 9. Step 11's audit shows the calls under the user's name.
What each user's answer draws on:
new-employee: the opening paragraph of each page and nothing more.account-executive: those, plus the Bramblewood renewal value and discount floor fromaccount-brief::p2.security-engineer: the opening paragraphs, plus the 212 affected customers and the rotated API keys fromsecurity-incident-review::p2.general-counsel: the revenue and margin, the acquisition offer, the regulators' 72-hour deadline and the notice of breach, but neither of the twop2paragraphs above.
Nobody is told about the reorg's personnel changes or the reason for the leave of absence.
The sample numbers its paragraphs, so someone who gets p1 and p3 can tell
that a p2 exists. Policy withholds a record's content, not how its ids are
made; real data can use ids that don't count.
Step 11: Read the audit
Kamiwaza records an audit event for each connector call and for each constraint that dropped records, with the template's reason. They go to your OpenTelemetry collector, and to the API's log. Kamiwaza may run more than one API pod, and each logs only the calls it served, so read every pod's log:
for pod in $(kubectl -n kamiwaza get pods -l app.kubernetes.io/name=core-api -o name); do
kubectl -n kamiwaza logs "$pod" -c core-api --since=1h
done \
| grep '"Audit: kamiwaza.audit.' | grep 'Company documents' \
| jq -r '.timestamp[11:19] as $t | .attributes
| select(.["otel.event.name"] == "kamiwaza.audit.sensitive_data.access"
or .["kamiwaza.policy.decision.action"] != null)
| [$t, (.["otel.event.name"] | sub("kamiwaza.audit."; "")), .["user.name"],
(.["kamiwaza.connector.verb"] // "-"), (.["kamiwaza.audit.policy.id"] // "-"),
(.["kamiwaza.audit.decision.reason"] // "-"),
("dropped=" + ((.["kamiwaza.policy.record.dropped_count"] // "-") | tostring)),
("rows=" + ((.["db.response.returned_rows"] // "-") | tostring))]
| @tsv' \
| sort
For new-employee's search over all paragraphs:
07:29:36 authorization.decision new-employee search company-docs-level level_above_user dropped=11 rows=-
07:29:36 authorization.decision new-employee search company-docs-level level_missing dropped=2 rows=-
07:29:36 authorization.decision new-employee search company-docs-tags attribute_not_held dropped=10 rows=-
07:29:36 sensitive_data.access new-employee search - - dropped=13 rows=6
Each authorization.decision names the constraint, the reason and how many
records it dropped for that reason. A record two constraints drop counts under
each, so the reasons add up to more than the call's total. The
sensitive_data.access event has the call's total: 13 dropped, 6 returned.
Paragraph text and search arguments are never audited.
The API's log is a quick check only: a pod's log is lost when the pod restarts. For a lasting record, read the events from your OpenTelemetry collector.
Step 12: Detach the constraints and compare
Detaching a constraint from a data source stops it applying there. The constraint and its history stay stored:
for NAME in company-docs-level company-docs-tags; do
jq -n --arg ds "$DATA_SOURCE" '{resource: $ds}' \
| kapi POST "/authz/policies/constraints/$NAME/detach" -d @- \
| jq -r '"detached \(.constraint.name) (version \(.constraint.version))"'
done
Check: run the searches from step 9 again. Every user, and admin, gets
all 19 paragraphs, all three paragraphs for each search, and the aggregate
query's six rows. The incident
log, if you set it up below, stays filtered: its own constraints are still
attached.
Attach them again with attach and the same body:
for NAME in company-docs-level company-docs-tags; do
jq -n --arg ds "$DATA_SOURCE" '{resource: $ds}' \
| kapi POST "/authz/policies/constraints/$NAME/attach" -d @- \
| jq -r '"attached \(.constraint.name) (version \(.constraint.version))"'
done
The same constraints on the SQLite example
The SDK's SQLite example carries the same labels as columns in its sample table of incidents, instead of a prefix the connector reads. Its constraints are the same two files, so the same two templates apply unchanged:
cd .. && mkdir incident-log && cd incident-log
kz-ext create --type connector --example sqlite --name incident-log
diff policy/constraints/level.json ../company-docs/policy/constraints/level.json && echo same
diff policy/constraints/tags.json ../company-docs/policy/constraints/tags.json && echo same
Build it and push it to the same registry as in step 2:
docker build --load -t registry.example.com/kamiwaza/incident-log-connector:0.1.0 .
docker push registry.example.com/kamiwaza/incident-log-connector:0.1.0
Register it as in step 4. The commands below use their own variable names,
starting with IL_, so the company documents' DATA_SOURCE and CONNECTION
stay as they are:
IL_REGISTRY=registry.example.com
IL_REPOSITORY=kamiwaza/incident-log-connector
IL_TAG=0.1.0
docker run -d --name connector-manifest -p 127.0.0.1:18080:8080 "$IL_REGISTRY/$IL_REPOSITORY:$IL_TAG"
for i in $(seq 1 30); do curl -sf 127.0.0.1:18080/manifest > manifest.json && break; sleep 2; done
IL_TYPE=$(jq -r '.connector_type // empty' manifest.json 2>/dev/null)
if [ -n "$IL_TYPE" ]; then echo "connector type $IL_TYPE"
else echo "FAILED: no manifest. The connector's log:"; docker logs connector-manifest; fi
docker rm -f connector-manifest
jq --arg r "$IL_REGISTRY" --arg p "$IL_REPOSITORY" --arg t "$IL_TAG" \
'{manifest: (.deployment += {image_registry: $r, image_repository: $p, image_tag: $t}), version: $t}' \
manifest.json \
| kapi PUT "/connectors/catalog/$IL_TYPE" -d @- > register.json
need register.json .connector_type
It prints connector type incident-log, then incident-log.
Create its data source and connection, and share the data source with the
group from step 6. It needs no settings and no outside source: with
database_path empty, as in the project's connection.example.json, it
serves the sample database built into its image:
kapi POST /catalog/containers/ \
-d '{"name": "Incident log", "platform": "kamiwaza-connector"}' > source.json
IL_SOURCE=$(need source.json strings) && echo "$IL_SOURCE"
jq -n --arg ds "$IL_SOURCE" --arg type "$IL_TYPE" \
'{name: "Incident log", connector_type: $type, container_urn: $ds, config: {database_path: ""}}' \
| kapi POST /connectors/ -d @- > connection.json
IL_CONNECTION=$(need connection.json .id) && echo "connection $IL_CONNECTION"
for i in $(seq 1 30); do
STATUS=$(kapi GET "/connectors/$IL_CONNECTION" | jq -r .status)
echo "$STATUS"; [ "$STATUS" = ready ] || [ "$STATUS" = degraded ] && break; sleep 10
done
kapi POST /authz/resources/container/grants -o /dev/null -w "grant %{http_code}\n" \
-d "$(jq -n --arg ds "$IL_SOURCE" --arg g "$GROUP" \
'{object_id: $ds, subject: {namespace: "group", id: $g}, relation: "viewer"}')"
Check: the status reaches ready, and the grant prints 201.
Attach its constraints, under their own names, with publish_constraint from
step 8:
publish_constraint incidents-level policy/constraints/level.json "$IL_SOURCE" &&
publish_constraint incidents-tags policy/constraints/tags.json "$IL_SOURCE"
Its surface is named records. Search it for every incident, of any
severity, as each user:
for user in new-employee account-executive security-engineer general-counsel; do
USER_TOKEN=$(token_for "$user")
curl -sS -X POST "$KAMIWAZA_URL/api/connectors/surfaces/workrooms/$G/$IL_CONNECTION/search" \
-H "Authorization: Bearer $USER_TOKEN" -H 'Content-Type: application/json' \
-d '{"surface": "records", "page_size": 50, "filters": [{"field": "severity", "op": "in", "value": ["critical", "high", "medium", "low"]}]}' \
| jq -c --arg u "$user" '{user: $u, incidents: [.items[]?.id | sub("incident-"; "")]}'
done
It returns these incidents:
| User | Incidents |
|---|---|
| Before the constraints, anyone | 1, 2, 3, 4, 5 |
new-employee | 2 |
account-executive | 2, 5 |
security-engineer | 2, 5 |
general-counsel | 1, 2, 3, 5 |
Incident 4 has no labels, so nobody gets it.
This example's query returns no rows to anyone once the level constraint is
attached, not even general-counsel. The labels are ordinary table columns, so
SQL can write its own (SELECT title, 'internal' AS sensitivity FROM incidents), and the connector can't tell a real label column from one the SQL
made up. It removes sensitivity and access_tags from every query row
instead, and policy drops a row without a level, the same as the OpenSearch
example's query rows in step 9. A constraint applies only to the data sources in
its match: until these were attached, the incident log answered every user in
full while the company documents were filtered.
Mapping this to your own rules
The templates don't know what the levels and tags mean. The constraints' parameters say that, so the same two templates fit other rules:
- Levels are any ordered tiers: data sensitivity classes, clearance
levels, customer data tiers. Put yours in
levels, lowest first, and give each user one of them. - Tags are any keys a user must hold every one of: need-to-know
compartments, projects, deal teams, or the care team allowed to see a
patient's records. A record lists the tags it needs; a user who lacks any of
them doesn't get it, whatever their level.
leave-case::p2shows this: it holds health information, andgeneral-counseldoesn't see it. - Names are parameters too. If your records call the field
classificationand spell levels differently, setrecord_fieldand addaliasesinlevel.json; if users carry their compartments in another attribute, setattributeintags.json.
Only the constraint files change. Publish them again with a new draft, as in step 8.
Things to know
| What you see | Why |
|---|---|
| A query returns no rows, but a search finds records | Query rows never carry labels, so the level constraint drops them. Use search. |
A user sees only internal records | The user has no sensitivity attribute, or a value not in levels, or hasn't signed in since you set it. Check x-user-attributes as in step 5. |
| Records nobody labeled appear | The level constraint isn't attached, or it has record_default set. needs_matching_attribute alone keeps records without tags. |
| A search finds nothing you loaded | The OpenSearch pod restarted and lost the index. Load it again as in step 3. |
To write a template of your own, see Write a Template.
In Rego, not f(g(x)) is undefined, not true, when g(x) is undefined, so a
"drop if missing" rule written that way never fires. Write each "is it there"
test as its own rule, negate that rule, and test the missing case, as the two
templates here do.
Clean up
Clean-up detaches the constraints and removes what the tutorial created around them. It keeps the templates and the constraints, on purpose:
- Retiring is permanent. A retired template or constraint keeps its name
for good: nothing by that name can be published again. Templates are shared
by the whole cluster, so retiring
level_ceilingwould also take it away from everyone else's constraints. A constraint attached to no data source applies nowhere, so leaving it costs nothing. - Deleting a user doesn't free the username. The user's sign-in account stays in Keycloak, so a user with the same name can't be created again. Disable the test users instead, or leave them.
The commands look everything up by name, so they work in a new terminal too:
set KAMIWAZA_URL and TOKEN, and define kapi, as in
Set up kapi. remove_source <connection name> <constraint prefix> detaches the prefix's two constraints from the connection's data
source, then deletes the connection and the data source. Run it for the
incident log too if you set it up; otherwise it prints that there is no such
connection:
remove_source() {
local conn ds constraint
conn=$(kapi GET /connectors/ | jq -r --arg n "$1" '.items[] | select(.name == $n) | .id')
ds=$(kapi GET /connectors/ | jq -r --arg n "$1" '.items[] | select(.name == $n) | .container_urn')
[ -n "$conn" ] || { echo "no connection named $1"; return 0; }
for constraint in "$2-level" "$2-tags"; do
jq -n --arg ds "$ds" '{resource: $ds, change_note: "tutorial clean-up"}' \
| kapi POST "/authz/policies/constraints/$constraint/detach" -d @- \
-o /dev/null -w "detach $constraint %{http_code}\n"
done
kapi DELETE "/connectors/$conn" -o /dev/null -w "delete connection %{http_code}\n"
kapi DELETE "/catalog/containers/$(jq -rn --arg ds "$ds" '$ds|@uri')" \
-o /dev/null -w "delete data source %{http_code}\n"
}
remove_source "Company documents" company-docs
remove_source "Incident log" incidents
Each detach prints 200, and each delete 204. Then delete the group, with
?cascade=grants to remove what it was granted too (without it, the delete
answers 409), disable the four users, and delete the OpenSearch namespace:
GROUP=$(kapi GET /authz/groups/ | jq -r '.[] | select(.name == "docs-readers") | .id')
kapi DELETE "/authz/groups/$GROUP?cascade=grants" -o /dev/null -w 'delete group %{http_code}\n'
for user in new-employee account-executive security-engineer general-counsel; do
user_id=$(kapi GET /auth/users/ | jq -r --arg u "$user" '.[] | select(.username == $u) | .id')
kapi PUT "/auth/users/$user_id" -d '{"active": false}' -o /dev/null -w "disable $user %{http_code}\n"
done
kubectl delete namespace docs-opensearch
The connector types stay registered, and the sensitivity and access_tags
attributes stay declared.
To run the tutorial again:
-
Enable the users:
for user in new-employee account-executive security-engineer general-counsel; douser_id=$(kapi GET /auth/users/ | jq -r --arg u "$user" '.[] | select(.username == $u) | .id')kapi PUT "/auth/users/$user_id" -d '{"active": true}' -o /dev/null -w "enable $user %{http_code}\n"done -
Go back to the project folder (
cd ../company-docsif you're inincident-log) and skip step 2: the project and image already exist. -
Run steps 3 and 4 again: clean-up deleted the OpenSearch and the data source.
-
In step 5, skip creating the users; they already exist and keep their attributes. Creating them again answers
400("belongs to another Kamiwaza user"). -
Run steps 6 to 9, including step 9's first block, which points the functions at the new connection. Steps 7 and 8 publish new versions of the same templates and constraints, and step 8 attaches the constraints to the new data source.
-
In step 10, turn on Tools for the new "Company documents" connection.
Next steps
- Restrict a Data Source: the templates Kamiwaza ships, and how to change a constraint.
- Write a Template: your own kind of rule.
- Connector Contract: what a connector returns, including the fields policy reads.