Skip to content

Commit bc7b4d9

Browse files
EC2 Default Userclaude
andcommitted
Secret ATTACH options: HKDF subkey, versioned blob, uniform refusal
Brings the encrypted delivery of secret ATTACH options in line with the cross-SDK spec (SPEC-secret-options.md): - The AEAD key is HKDF-SHA256(root, salt empty, info "vgi.attach_secret_options.v1"), never the configured / sealing / host key itself (SecretOptionsKey, RFC 5869 vector tested). - The blob is version(0x01) || nonce || ciphertext || tag; AAD still binds it to the attach uuid. - A blob that does not open (other deployment, host key file deleted or rotated, moved blob) is the uniform "attach_opaque_data not recognized" refusal (INVALID_ARGUMENT / opaque_data_not_recognized) instead of secrets reading as absent. secretsAvailable() now only marks the framework-less AttachOptions.fromAttachId view. - Host-local key: the temp-dir fallback is $TMPDIR, else java.io.tmpdir, plus vgi-<user>; size / ownership / permission refusals name the file and VGI_SIGNING_KEY / VGI_ATTACH_SECRET_KEY_FILE. - AttachOptions.open(attachId): producers and exchanges keep only the attach id in their state and re-open the options (secret ones included) while producing, so no secret value is ever stored in function state. - txfix: state partitioned by a digest of the token, whoami() re-opens the options at produce time and reports token_in_attach_data. - Tests: concurrent key-file creation agrees, wrong-size key refused, HKDF subkey (root does not open the blob), version byte, uniform refusal on bind / begin / attachOptionsOf, secret absent from the inner bytes on HTTP, AttachOptions.open on stdio and HTTP. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent bc0bddc commit bc7b4d9

12 files changed

Lines changed: 331 additions & 88 deletions

File tree

‎docs/writable-tables-and-transactions.md‎

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,22 +22,38 @@ attach's `attach_opaque_data`, so a process that never served the `ATTACH` (a po
2222
the subprocess transport, another HTTP replica) sees them too. Keep no per-attach state in
2323
process memory.
2424

25-
**Secret options** (`AttachOptionSpec.asSecret()`) never appear in plaintext in that value
26-
(`vgi-opaque-data-sealing.md` rule 5). The framework encrypts them (ChaCha20-Poly1305, bound to
27-
the attach) with:
28-
29-
1. the configured key (`Worker.signingKey`, `Worker.opaqueDataKey` or `VGI_SIGNING_KEY`), else
30-
2. over HTTP, the per-process sealing key (multi-replica deployments configure a key anyway), else
31-
3. on stdio / unix sockets, a per-user key file shared by the host's worker processes:
32-
`$XDG_RUNTIME_DIR/vgi/attach-secret-options.key`, else
33-
`<java.io.tmpdir>/vgi-<user>/attach-secret-options.key` (directory `0700`, file `0600`,
34-
both owned by the user; `VGI_ATTACH_SECRET_KEY_FILE` names another file). It is created on
35-
the first attach that gives a secret option a value.
36-
37-
A process holding a different key sees secret options as absent and
38-
`AttachOptions.secretsAvailable()` is false. `AttachOptions.fromAttachId(attachId)` decodes the
39-
non-secret options from a plain attach id without the framework (secrets are never visible
40-
that way). `AttachOptions.toString()` redacts secret values.
25+
**Secret options** (`AttachOptionSpec.asSecret()`) reach functions and hooks this way too; it
26+
is the standard mechanism, and catalog code never puts a secret into its own attach bytes or keeps
27+
it server-side. They never appear in plaintext in the attach value, on any transport and in the
28+
opened (inner) bytes on HTTP (`vgi-opaque-data-sealing.md` rule 5). The framework encrypts them:
29+
30+
- **AEAD:** ChaCha20-Poly1305, blob `version(0x01) || nonce || ciphertext || tag`, AAD
31+
`"vgi.attach_secret_options.v1" 0x00 || attach uuid` (a blob moved into another attach does not
32+
open).
33+
- **Key:** `HKDF-SHA256(ikm = root, salt = empty, info = "vgi.attach_secret_options.v1", L = 32)`;
34+
the root itself is never the AEAD key. The root is, in order:
35+
1. the configured key (`Worker.signingKey`, `Worker.opaqueDataKey` or `VGI_SIGNING_KEY`), else
36+
2. over HTTP, the per-process sealing key (multi-replica deployments configure a key anyway), else
37+
3. on stdio / unix sockets / launch pools, the **host-local key**, shared with the workers of
38+
every VGI SDK on the host: `$VGI_ATTACH_SECRET_KEY_FILE` if set, else
39+
`$XDG_RUNTIME_DIR/vgi/attach-secret-options.key` if that directory exists, else
40+
`<per-user temp dir>/vgi-<user>/attach-secret-options.key` (`$TMPDIR`, else
41+
`java.io.tmpdir`; on macOS the per-user `/var/folders/...`). 32 raw random bytes; directory
42+
`0700`, file `0600`, both owned by the user, refused otherwise; created atomically (temp file,
43+
then hard link) so concurrent first starts agree; never overwritten; read only when a secret
44+
option actually has a value.
45+
- **Failure:** an attach whose blob does not open under this worker's key (another deployment, a
46+
host key file deleted or rotated mid-session, a moved blob) is refused with the uniform
47+
`attach_opaque_data not recognized` error (`INVALID_ARGUMENT`, `opaque_data_not_recognized`);
48+
the client re-ATTACHes. A secret option given a value when no key can be obtained fails the
49+
`ATTACH` with a message naming `VGI_SIGNING_KEY` / `VGI_ATTACH_SECRET_KEY_FILE`.
50+
- Secret values are never logged. `AttachOptions.toString()` redacts them, and
51+
`AttachOptions.fromAttachId(attachId)` (a decode without the framework) never sees them
52+
(`secretsAvailable()` is then false).
53+
- **Keep secrets out of function state.** A producer or exchange that needs a secret while
54+
producing rows stores `params.attachId()` in its state and calls `AttachOptions.open(attachId)`
55+
when it needs the values; it never stores the secret (state travels to the client, sealed, on
56+
HTTP).
4157

4258
## Per-attach settings: `Worker.onAttach`
4359

‎vgi-example-worker/src/main/java/farm/query/vgi/example/txfix/TxFixState.java‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,11 @@ static Path dir() {
8181
return d != null && !d.isBlank() ? Path.of(d) : Path.of(System.getProperty("java.io.tmpdir"), "vgi-txfix");
8282
}
8383

84-
private static String partitionName(String token) {
84+
/**
85+
* The partition a token's state lives in: a digest, so function state and file names never
86+
* hold the secret itself.
87+
*/
88+
static String partition(String token) {
8589
try {
8690
byte[] digest = MessageDigest.getInstance("SHA-256").digest(
8791
(token == null ? "\0null" : "t:" + token).getBytes(StandardCharsets.UTF_8));
@@ -91,10 +95,9 @@ private static String partitionName(String token) {
9195
}
9296
}
9397

94-
/** Run {@code body} on the token's partition under its lock, saving whatever it changed. */
95-
static <T> T withPartition(String token, Function<Partition, T> body) {
98+
/** Run {@code body} on a partition ({@link #partition}) under its lock, saving what it changed. */
99+
static <T> T withPartition(String name, Function<Partition, T> body) {
96100
Path dir = dir();
97-
String name = partitionName(token);
98101
IN_PROCESS.lock();
99102
try {
100103
Files.createDirectories(dir);

‎vgi-example-worker/src/main/java/farm/query/vgi/example/txfix/TxFixWorker.java‎

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,17 @@ private static Schema withRowId(Schema user) {
9191
return new Schema(fields);
9292
}
9393

94+
/** Whether {@code needle} occurs in {@code haystack}: the never-plaintext check whoami reports. */
95+
static boolean contains(byte[] haystack, byte[] needle) {
96+
if (haystack == null || needle.length == 0) return false;
97+
outer:
98+
for (int i = 0; i + needle.length <= haystack.length; i++) {
99+
for (int j = 0; j < needle.length; j++) if (haystack[i + j] != needle[j]) continue outer;
100+
return true;
101+
}
102+
return false;
103+
}
104+
94105
static String hex(byte[] b) {
95106
return b == null ? null : HexFormat.of().formatHex(b);
96107
}
@@ -99,6 +110,11 @@ static String token(AttachOptions o) {
99110
return o.getString("token");
100111
}
101112

113+
/** The state partition of the attach's token (a digest; the token itself is never stored). */
114+
static String partition(AttachOptions o) {
115+
return TxFixState.partition(token(o));
116+
}
117+
102118
/** The transaction a call stages under: its id on a transactional attach, else none. */
103119
static String stagingTx(AttachOptions o, byte[] transactionId) {
104120
return o.getBoolean("transactional", false) ? hex(transactionId) : null;
@@ -179,7 +195,7 @@ static final class Hooks implements TransactionHooks {
179195
public byte[] begin(AttachContext attach) {
180196
byte[] id = new byte[16];
181197
RNG.nextBytes(id);
182-
TxFixState.withPartition(token(attach.options()), p -> {
198+
TxFixState.withPartition(partition(attach.options()), p -> {
183199
p.event("begin", hex(id), true);
184200
return null;
185201
});
@@ -189,7 +205,7 @@ public byte[] begin(AttachContext attach) {
189205
@Override
190206
public void commit(AttachContext attach, byte[] transactionId) {
191207
String tx = hex(transactionId);
192-
String refused = TxFixState.withPartition(token(attach.options()), p -> {
208+
String refused = TxFixState.withPartition(partition(attach.options()), p -> {
193209
TreeMap<Integer, TxFixState.Row> staged = p.staged.remove(tx);
194210
if (staged != null) {
195211
for (TxFixState.Row r : staged.values()) {
@@ -209,7 +225,7 @@ public void commit(AttachContext attach, byte[] transactionId) {
209225
@Override
210226
public void rollback(AttachContext attach, byte[] transactionId) {
211227
String tx = hex(transactionId);
212-
TxFixState.withPartition(token(attach.options()), p -> {
228+
TxFixState.withPartition(partition(attach.options()), p -> {
213229
p.staged.remove(tx);
214230
p.event("rollback", tx, true);
215231
return null;
@@ -271,18 +287,18 @@ static final class Reset extends RowsFunction {
271287
public TableProducerState createProducer(TableInitParams params) {
272288
ResetState s = new ResetState();
273289
s.outputSchema = params.outputSchema();
274-
s.token = token(params.attachOptions());
290+
s.partition = partition(params.attachOptions());
275291
return s;
276292
}
277293
}
278294

279295
/** {@code reset()} producer. */
280296
public static final class ResetState extends OnceState {
281-
public String token;
297+
public String partition;
282298

283299
@Override
284300
List<Map<String, Object>> rows() {
285-
TxFixState.withPartition(token, p -> {
301+
TxFixState.withPartition(partition, p -> {
286302
p.reset();
287303
return null;
288304
});
@@ -296,30 +312,34 @@ static final class WhoAmI extends RowsFunction {
296312
@Override String name0() { return "whoami"; }
297313
@Override Schema schema() {
298314
return new Schema(List.of(Schemas.nullable("token", Schemas.UTF8),
299-
Schemas.nullable("transactional", Schemas.BOOL)));
315+
Schemas.nullable("transactional", Schemas.BOOL),
316+
Schemas.nullable("token_in_attach_data", Schemas.BOOL)));
300317
}
301318
@Override String description() { return "The attach's options as the function sees them"; }
302319

303320
@Override
304321
public TableProducerState createProducer(TableInitParams params) {
305322
WhoAmIState s = new WhoAmIState();
306323
s.outputSchema = params.outputSchema();
307-
s.token = token(params.attachOptions());
308-
s.transactional = params.attachOptions().getBoolean("transactional", false);
324+
// Only the attach id is kept: the token is opened again while producing.
325+
s.attachId = params.attachId();
309326
return s;
310327
}
311328
}
312329

313-
/** {@code whoami()} producer. */
330+
/** {@code whoami()} producer: re-opens the options from the attach id; no secret in state. */
314331
public static final class WhoAmIState extends OnceState {
315-
public String token;
316-
public boolean transactional;
332+
public byte[] attachId;
317333

318334
@Override
319335
List<Map<String, Object>> rows() {
336+
AttachOptions options = AttachOptions.open(attachId);
337+
String token = token(options);
320338
Map<String, Object> row = new LinkedHashMap<>();
321339
row.put("token", token);
322-
row.put("transactional", transactional);
340+
row.put("transactional", options.getBoolean("transactional", false));
341+
row.put("token_in_attach_data",
342+
token != null && contains(attachId, token.getBytes(StandardCharsets.UTF_8)));
323343
return List.of(row);
324344
}
325345
}
@@ -367,18 +387,18 @@ static final class Events extends RowsFunction {
367387
public TableProducerState createProducer(TableInitParams params) {
368388
EventsState s = new EventsState();
369389
s.outputSchema = params.outputSchema();
370-
s.token = token(params.attachOptions());
390+
s.partition = partition(params.attachOptions());
371391
return s;
372392
}
373393
}
374394

375395
/** {@code events()} producer. */
376396
public static final class EventsState extends OnceState {
377-
public String token;
397+
public String partition;
378398

379399
@Override
380400
List<Map<String, Object>> rows() {
381-
return TxFixState.withPartition(token, p -> {
401+
return TxFixState.withPartition(partition, p -> {
382402
List<Map<String, Object>> out = new ArrayList<>();
383403
for (TxFixState.Event e : p.events) {
384404
Map<String, Object> row = new LinkedHashMap<>();
@@ -404,20 +424,20 @@ static final class ItemsScan extends RowsFunction {
404424
public TableProducerState createProducer(TableInitParams params) {
405425
ItemsState s = new ItemsState();
406426
s.outputSchema = params.outputSchema();
407-
s.token = token(params.attachOptions());
427+
s.partition = partition(params.attachOptions());
408428
s.txId = stagingTx(params.attachOptions(), params.transactionId());
409429
return s;
410430
}
411431
}
412432

413433
/** {@code items_scan()} producer: committed rows overlaid with the transaction's staged ones. */
414434
public static final class ItemsState extends OnceState {
415-
public String token;
435+
public String partition;
416436
public String txId;
417437

418438
@Override
419439
List<Map<String, Object>> rows() {
420-
return TxFixState.withPartition(token, p -> {
440+
return TxFixState.withPartition(partition, p -> {
421441
List<Map<String, Object>> out = new ArrayList<>();
422442
for (TxFixState.Row r : p.view(txId).values()) {
423443
Map<String, Object> row = r.asMap();
@@ -486,7 +506,7 @@ public BindResponse onBind(TableInOutBindParams params) {
486506
@Override
487507
public TableInOutExchangeState createExchange(TableInOutInitParams params) {
488508
UpdateState s = new UpdateState();
489-
s.token = token(params.attachOptions());
509+
s.partition = partition(params.attachOptions());
490510
s.transactional = params.attachOptions().getBoolean("transactional", false);
491511
s.txId = stagingTx(params.attachOptions(), params.transactionId());
492512
s.mode = WriteOptions.from(params.arguments()).resultMode().wireName();
@@ -496,7 +516,7 @@ public TableInOutExchangeState createExchange(TableInOutInitParams params) {
496516

497517
/** {@code items_update} exchange: validates every row, then applies or stages them. */
498518
public static final class UpdateState extends TableInOutExchangeState {
499-
public String token;
519+
public String partition;
500520
public boolean transactional;
501521
public String txId;
502522
public String mode;
@@ -508,7 +528,7 @@ public void onInputBatch(AnnotatedBatch input, OutputCollector out, CallContext
508528
if (rowids == null) throw new IllegalArgumentException("txfix: UPDATE input carries no rowid");
509529
List<Map<String, Object>> before = new ArrayList<>();
510530
List<Map<String, Object>> after = new ArrayList<>();
511-
TxFixState.withPartition(token, p -> {
531+
TxFixState.withPartition(partition, p -> {
512532
TreeMap<Integer, TxFixState.Row> current = p.view(txId);
513533
List<TxFixState.Row> updated = new ArrayList<>();
514534
for (int i = 0; i < batch.getRowCount(); i++) {

‎vgi/src/main/java/farm/query/vgi/AttachOptions.java‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,16 @@
2828
*
2929
* <p>The values travel inside the attach's {@code attach_opaque_data}, so every worker
3030
* process sees them, including one that never served the {@code ATTACH} (a pooled or
31-
* load-balanced deployment). Secret values never travel in plaintext there: the framework
32-
* encrypts them with the worker's opaque-data key ({@link Worker#signingKey(byte[])} /
33-
* {@code VGI_SIGNING_KEY}; over HTTP the per-process sealing key when none is configured;
34-
* on stdio / unix sockets without a configured key, a per-user key file shared by the
35-
* host's worker processes, see {@code docs/writable-tables-and-transactions.md}). A process that cannot open
36-
* them sees secret options as absent ({@link #secretsAvailable()} is then false).
31+
* load-balanced deployment). This is the standard way for a secret option to reach functions:
32+
* catalog code never puts a secret into its own attach bytes or keeps it server-side. Secret
33+
* values never travel in plaintext: the framework encrypts them (ChaCha20-Poly1305, bound to the
34+
* attach) with a key derived by HKDF-SHA256 from the worker's root key
35+
* ({@link Worker#signingKey(byte[])} / {@code VGI_SIGNING_KEY}; over HTTP the per-process sealing
36+
* key when none is configured; on stdio / unix sockets without a configured key, a per-user key
37+
* file shared by the host's worker processes, see {@code docs/writable-tables-and-transactions.md}).
38+
* An attach whose secrets do not open under this worker's key (another deployment, a deleted or
39+
* rotated key file) is refused with the uniform {@code attach_opaque_data not recognized} error,
40+
* and the client re-ATTACHes.
3741
*
3842
* <p>Values are plain Java objects: {@code String} for VARCHAR, {@code Boolean},
3943
* {@code Long} for every integer type, {@code Double} for floating point, {@code byte[]}
@@ -80,8 +84,7 @@ public static AttachOptions of(Map<String, ?> values, Set<String> secretNames) {
8084
*
8185
* @param values option name to value (a {@code null} value is an option set to NULL)
8286
* @param secretNames which of the names are secret (redacted by {@link #toString()})
83-
* @param secretsAvailable false when the attach carries secret options this process could
84-
* not open (they are then absent from {@code values})
87+
* @param secretsAvailable false when {@code values} lacks secret options the attach carries
8588
* @return the option set
8689
*/
8790
public static AttachOptions of(Map<String, ?> values, Set<String> secretNames, boolean secretsAvailable) {
@@ -106,6 +109,34 @@ public static AttachOptions fromAttachId(byte[] attachId) {
106109
}
107110
}
108111

112+
private static volatile java.util.function.Function<byte[], AttachOptions> resolver;
113+
114+
/**
115+
* Framework use: installs the process's resolver for {@link #open} (the worker's service
116+
* does this when it starts).
117+
*
118+
* @param r opens a plain attach id with this worker's key
119+
*/
120+
public static void installResolver(java.util.function.Function<byte[], AttachOptions> r) {
121+
resolver = r;
122+
}
123+
124+
/**
125+
* Every option value of a plain attach id, secret ones included, opened with this worker's
126+
* key: what a producer or exchange calls while producing rows, so its state keeps only the
127+
* attach id ({@code params.attachId()}) and never a secret value. Same result as the
128+
* parameters' {@code attachOptions()}.
129+
*
130+
* @param attachId the plain attach id from the function's parameters
131+
* @return the options
132+
* @throws farm.query.vgirpc.errors.StatusError {@code attach_opaque_data not recognized} when
133+
* the secret values do not open under this worker's key
134+
*/
135+
public static AttachOptions open(byte[] attachId) {
136+
var r = resolver;
137+
return r == null ? fromAttachId(attachId) : r.apply(attachId);
138+
}
139+
109140
/**
110141
* The values of a one-row option batch, keyed by column name.
111142
*
@@ -202,9 +233,9 @@ public boolean isSecret(String name) {
202233
}
203234

204235
/**
205-
* Whether this process could open the attach's secret options. False only when the attach
206-
* carries secret values this process has no key for (see the class documentation); the
207-
* secret options are then absent from this set.
236+
* Whether this view holds the attach's secret option values. Always true for the views the
237+
* framework hands functions and hooks; false only for {@link #fromAttachId} of an attach that
238+
* carries encrypted secret values (that decode cannot open them).
208239
*
209240
* @return true when every secret option of the attach is present
210241
*/

0 commit comments

Comments
 (0)