|
1 | 1 | --- |
2 | 2 | title: Identity-aware encryption |
3 | | -description: Use LockContext in @cipherstash/stack to tie encryption to a user JWT so only that identity can decrypt their data, including Clerk and Next.js setup. |
| 3 | +description: Authenticate as the end user with OidcFederationStrategy and bind encryption to a JWT claim with withLockContext, so only that identity can decrypt their data. |
4 | 4 | --- |
5 | 5 |
|
6 | | -Lock encryption to a specific user by requiring a valid JWT for decryption. When a value is encrypted with a lock context, it can only be decrypted by presenting the same user's identity token. |
| 6 | +Lock encryption to a specific user, so a value can only be decrypted while the client is authenticated as the identity that encrypted it. |
7 | 7 |
|
8 | 8 | ## How it works |
9 | 9 |
|
10 | 10 | <Callout type="warn"> |
11 | 11 | Lock contexts require a Business or Enterprise workspace plan. |
12 | 12 | </Callout> |
13 | 13 |
|
| 14 | +Two pieces combine. |
| 15 | + |
| 16 | +**An auth strategy** decides who the client is when it talks to ZeroKMS. `OidcFederationStrategy` federates a signed-in user's OIDC JWT (from Supabase, Clerk, Auth0, or Okta) into a CipherStash token, so every ZeroKMS request is made as that user rather than as your service. |
| 17 | + |
| 18 | +**A lock context** names which claim from that user's JWT to bind the value to, typically `sub`. ZeroKMS resolves the claim's value from the token authenticating the request and bakes it into the data key's tag. |
| 19 | + |
| 20 | +Lock context is layered on top of the strategy: it requires `OidcFederationStrategy`, but the strategy does not require lock context. Authenticating as the user gives you a per-user audit trail; adding lock context gives you the cryptographic binding. |
| 21 | + |
14 | 22 | Lock contexts are useful for: |
15 | 23 |
|
16 | 24 | - Multi-tenant applications where each user's data must be isolated |
17 | 25 | - Compliance requirements that demand per-user encryption boundaries |
18 | 26 | - Applications where you need to prove that only authorized users accessed specific records |
19 | 27 |
|
20 | | -The flow is: |
| 28 | +## Basic usage |
21 | 29 |
|
22 | | -1. Create a `LockContext` instance. |
23 | | -2. Identify the user with their JWT. |
24 | | -3. Pass the lock context to encrypt and decrypt operations. |
| 30 | +Register your identity provider with the workspace first, on the [OIDC providers](https://dashboard.cipherstash.com/workspaces/_/oidc-providers) page in the Dashboard. The `_` in that URL resolves to whichever workspace you have selected. |
25 | 31 |
|
26 | | -## Basic usage |
| 32 | +Construct the client with `OidcFederationStrategy`. Pass a function returning the **current** provider JWT: the strategy calls it again whenever it needs to re-federate, so do not capture a token once. |
27 | 33 |
|
28 | | -```typescript filename="identity.ts" |
29 | | -import { LockContext } from "@cipherstash/stack/identity" |
| 34 | +```typescript filename="client.ts" |
| 35 | +import { Encryption, OidcFederationStrategy } from "@cipherstash/stack" |
| 36 | +import { users } from "./schema" |
30 | 37 |
|
31 | | -// 1. Create a lock context (defaults to the "sub" claim) |
32 | | -const lc = new LockContext() |
| 38 | +export const client = await Encryption({ |
| 39 | + schemas: [users], |
| 40 | + config: { |
| 41 | + authStrategy: OidcFederationStrategy.create( |
| 42 | + process.env.CS_WORKSPACE_CRN, |
| 43 | + () => getUserJwt(), |
| 44 | + ), |
| 45 | + }, |
| 46 | +}) |
| 47 | +``` |
33 | 48 |
|
34 | | -// 2. Identify the user with their JWT |
35 | | -const identifyResult = await lc.identify(userJwt) |
| 49 | +`OidcFederationStrategy` is re-exported from `@cipherstash/stack`, so a separate `@cipherstash/auth` import is not needed. |
36 | 50 |
|
37 | | -if (identifyResult.failure) { |
38 | | - throw new Error(identifyResult.failure.message) |
39 | | -} |
| 51 | +<Callout type="warn"> |
| 52 | +`OidcFederationStrategy` is the only strategy that supports lock contexts. `AccessKeyStrategy` authenticates as your service rather than as an end user, so there is no user identity for ZeroKMS to resolve the claim against. |
| 53 | +</Callout> |
40 | 54 |
|
41 | | -const lockContext = identifyResult.data |
| 55 | +Then bind operations to the user's claim. Every example below uses the `client` above: without its `authStrategy`, `.withLockContext()` has no end-user identity to bind to. |
42 | 56 |
|
43 | | -// 3. Encrypt with lock context |
| 57 | +```typescript filename="identity.ts" |
| 58 | +// Encrypt, binding the data key to the user's `sub` claim |
44 | 59 | const encrypted = await client |
45 | 60 | .encrypt("sensitive data", { column: users.email, table: users }) |
46 | | - .withLockContext(lockContext) |
| 61 | + .withLockContext({ identityClaim: ["sub"] }) |
47 | 62 |
|
48 | | -// 4. Decrypt with the same lock context |
| 63 | +// Decrypt with the same claim, as the same user |
49 | 64 | const decrypted = await client |
50 | 65 | .decrypt(encrypted.data) |
51 | | - .withLockContext(lockContext) |
| 66 | + .withLockContext({ identityClaim: ["sub"] }) |
52 | 67 | ``` |
53 | 68 |
|
| 69 | +<Callout type="warn"> |
| 70 | +`lockContext.identify(jwt)` is **deprecated**. Per-operation CTS tokens were removed in `protect-ffi` 0.25, so `identify()` no longer affects encryption: code that still calls it compiles and logs a deprecation warning, but the token it fetches is unused. Authenticate the client with `OidcFederationStrategy` and pass the claim to `.withLockContext()` instead. |
| 71 | + |
| 72 | +Constructing a `LockContext` is not deprecated, it is simply optional here. `.withLockContext()` accepts either a `LockContext` or a plain `{ identityClaim }`. |
| 73 | +</Callout> |
| 74 | + |
54 | 75 | ## Supported operations |
55 | 76 |
|
56 | 77 | Lock contexts work with all encrypt and decrypt operations: |
57 | 78 |
|
58 | 79 | ```typescript filename="identity.ts" |
59 | | -// Single operations |
60 | | -const encrypted = await client |
61 | | - .encryptModel(user, users) |
62 | | - .withLockContext(lockContext) |
| 80 | +const claim = { identityClaim: ["sub"] } |
63 | 81 |
|
64 | | -const decrypted = await client |
65 | | - .decryptModel(encryptedUser) |
66 | | - .withLockContext(lockContext) |
| 82 | +// Single operations |
| 83 | +const encrypted = await client.encryptModel(user, users).withLockContext(claim) |
| 84 | +const decrypted = await client.decryptModel(encryptedUser).withLockContext(claim) |
67 | 85 |
|
68 | 86 | // Bulk operations |
69 | 87 | const bulkEncrypted = await client |
70 | 88 | .bulkEncryptModels(userModels, users) |
71 | | - .withLockContext(lockContext) |
| 89 | + .withLockContext(claim) |
72 | 90 |
|
73 | 91 | const bulkDecrypted = await client |
74 | 92 | .bulkDecryptModels(encryptedUsers) |
75 | | - .withLockContext(lockContext) |
| 93 | + .withLockContext(claim) |
76 | 94 |
|
77 | 95 | // Query operations |
78 | 96 | const term = await client |
79 | | - .encryptQuery("user@example.com", { |
80 | | - column: users.email, |
81 | | - table: users, |
82 | | - }) |
83 | | - .withLockContext(lockContext) |
| 97 | + .encryptQuery("user@example.com", { column: users.email, table: users }) |
| 98 | + .withLockContext(claim) |
84 | 99 | ``` |
85 | 100 |
|
86 | 101 | ## Custom identity claims |
87 | 102 |
|
88 | | -Override the default context by specifying which identity claims to use: |
89 | | - |
90 | | -```typescript filename="identity.ts" |
91 | | -const lc = new LockContext({ |
92 | | - context: { |
93 | | - identityClaim: ["sub"], // this is the default |
94 | | - }, |
95 | | -}) |
96 | | -``` |
| 103 | +`identityClaim` selects which claim (or claims) of the user's JWT ZeroKMS binds to. |
97 | 104 |
|
98 | 105 | | Identity claim | Description | |
99 | 106 | |---|---| |
100 | 107 | | `sub` | The user's subject identifier | |
101 | | -| `scopes` | The user's scopes set by your IDP policy | |
| 108 | +| `scopes` | The user's scopes, set by your IdP policy | |
102 | 109 |
|
103 | | -Combine claims for identity and permissions scoping: |
| 110 | +Combine claims to scope by identity and permissions together: |
104 | 111 |
|
105 | 112 | ```typescript filename="identity.ts" |
106 | | -const lc = new LockContext({ |
107 | | - context: { |
108 | | - identityClaim: ["sub", "scopes"], |
109 | | - }, |
110 | | -}) |
111 | | -``` |
112 | | - |
113 | | -## Using with Clerk and Next.js |
114 | | - |
115 | | -Install the `@cipherstash/nextjs` package for automatic CTS token setup with [Clerk](https://clerk.com/): |
116 | | - |
117 | | -```bash cta cta-type="install" example-id="install-nextjs-identity" |
118 | | -npm install @cipherstash/nextjs |
119 | | -``` |
120 | | - |
121 | | -### Set up middleware |
122 | | - |
123 | | -In your `middleware.ts`, use `protectClerkMiddleware` to automatically generate CTS tokens for every user session: |
124 | | - |
125 | | -```typescript filename="middleware.ts" |
126 | | -import { clerkMiddleware } from "@clerk/nextjs/server" |
127 | | -import { protectClerkMiddleware } from "@cipherstash/nextjs/clerk" |
128 | | - |
129 | | -export default clerkMiddleware(async (auth, req) => { |
130 | | - return protectClerkMiddleware(auth, req) |
131 | | -}) |
| 113 | +await client |
| 114 | + .encrypt("sensitive data", { column: users.email, table: users }) |
| 115 | + .withLockContext({ identityClaim: ["sub", "scopes"] }) |
132 | 116 | ``` |
133 | 117 |
|
134 | | -### Retrieve the CTS token |
135 | | - |
136 | | -Use `getCtsToken` to get the CTS token for the current user: |
137 | | - |
138 | | -```typescript filename="page.tsx" |
139 | | -import { getCtsToken } from "@cipherstash/nextjs" |
140 | | - |
141 | | -export default async function Page() { |
142 | | - const ctsToken = await getCtsToken() |
| 118 | +The same claim must be supplied to decrypt. A value encrypted under `["sub"]` will not decrypt under `["sub", "scopes"]`. |
143 | 119 |
|
144 | | - if (!ctsToken.success) { |
145 | | - // handle error |
146 | | - } |
| 120 | +## Using with Clerk and Next.js |
147 | 121 |
|
148 | | - // ctsToken is ready to use |
| 122 | +Clerk is an OIDC provider like any other: hand `OidcFederationStrategy` a function that returns the current Clerk session token. |
| 123 | + |
| 124 | +```typescript filename="client.ts" |
| 125 | +import { auth } from "@clerk/nextjs/server" |
| 126 | +import { Encryption, OidcFederationStrategy } from "@cipherstash/stack" |
| 127 | +import { users } from "./schema" |
| 128 | + |
| 129 | +export async function getClient() { |
| 130 | + return Encryption({ |
| 131 | + schemas: [users], |
| 132 | + config: { |
| 133 | + authStrategy: OidcFederationStrategy.create( |
| 134 | + process.env.CS_WORKSPACE_CRN, |
| 135 | + async () => { |
| 136 | + const { getToken } = await auth() |
| 137 | + return await getToken() |
| 138 | + }, |
| 139 | + ), |
| 140 | + }, |
| 141 | + }) |
149 | 142 | } |
150 | 143 | ``` |
151 | 144 |
|
152 | | -### Create a LockContext with an existing CTS token |
153 | | - |
154 | | -Since the CTS token is already available from the middleware, construct the `LockContext` directly. The CTS token has the shape `{ accessToken: string, expiry: number }`. Passing it directly avoids a second round-trip to CTS. |
155 | | - |
156 | | -```typescript filename="page.tsx" |
157 | | -import { LockContext } from "@cipherstash/stack/identity" |
158 | | -import { getCtsToken } from "@cipherstash/nextjs" |
159 | | - |
160 | | -export default async function Page() { |
161 | | - const ctsToken = await getCtsToken() |
162 | | - |
163 | | - if (!ctsToken.success) { |
164 | | - // handle error |
165 | | - } |
166 | | - |
167 | | - const lockContext = new LockContext({ ctsToken }) |
| 145 | +Because the callback is re-invoked on every re-federation, it picks up a refreshed Clerk token automatically. |
168 | 146 |
|
169 | | - // Use lockContext with encrypt/decrypt operations |
170 | | -} |
171 | | -``` |
172 | | - |
173 | | -`getCtsToken` returns `{ success: true, ctsToken: CtsToken }` on success or `{ success: false, error: string }` on failure. |
| 147 | +<Callout type="info"> |
| 148 | +The `@cipherstash/nextjs` package (`protectClerkMiddleware`, `getCtsToken`) belongs to the earlier CTS-token flow, in which a token was fetched per request and handed to `new LockContext({ ctsToken })`. Encryption operations no longer consume a CTS token, so that middleware is not required for identity-aware encryption. |
| 149 | +</Callout> |
174 | 150 |
|
175 | 151 | ## Error handling |
176 | 152 |
|
177 | | -The `identify` method returns a `Result` type: |
| 153 | +Encryption operations return a `Result`. |
178 | 154 |
|
179 | 155 | ```typescript filename="identity.ts" |
180 | | -const result = await lc.identify(userJwt) |
| 156 | +const result = await client |
| 157 | + .encrypt("sensitive data", { column: users.email, table: users }) |
| 158 | + .withLockContext({ identityClaim: ["sub"] }) |
181 | 159 |
|
182 | 160 | if (result.failure) { |
183 | | - // result.failure.type is 'CtsTokenError' |
184 | | - console.error("CTS token exchange failed:", result.failure.message) |
| 161 | + console.error("Encryption failed:", result.failure.message) |
185 | 162 | } |
186 | 163 | ``` |
187 | 164 |
|
188 | 165 | Common failure scenarios: |
189 | 166 |
|
190 | | -| Scenario | Error type | Description | |
191 | | -|---|---|---| |
192 | | -| Invalid JWT | `CtsTokenError` | The JWT token was rejected by CTS | |
193 | | -| Network failure | `CtsTokenError` | Could not reach the CTS endpoint | |
194 | | -| Missing workspace | Runtime error | `CS_WORKSPACE_CRN` is not configured | |
195 | | -| Expired CTS token | `LockContextError` | The CTS token has expired. Call `identify` again | |
| 167 | +| Scenario | Description | |
| 168 | +|---|---| |
| 169 | +| Invalid or expired provider JWT | Federation is rejected. The callback should return a live token, not one captured earlier | |
| 170 | +| Provider not registered | The OIDC provider has not been added to the workspace | |
| 171 | +| Network failure | The CipherStash API could not be reached | |
| 172 | +| Missing workspace | `CS_WORKSPACE_CRN` is not configured | |
| 173 | +| Claim mismatch on decrypt | The value was encrypted under a different `identityClaim`, or as a different user | |
| 174 | + |
| 175 | +See [Error handling](/stack/reference/error-handling) for the full set of error types. |
0 commit comments