Skip to content

Commit 84092fe

Browse files
rustyconoverclaude
andcommitted
fix: request secrets declared as plain type strings; add secret-lookup fixtures
Meta.required_secrets kept only SecretLookupEntry and dict entries and dropped everything else without a word, so `required_secrets = ["llm"]` declared nothing: the client was never asked to resolve the secret and the function ran without credentials. Entries may now be a bare type string, SecretLookupEntry, Secret or dict; any other entry, an empty type, or a non-list value raises at metadata resolution. Secret() annotations were merged into the requirements deduplicated by type alone, so a second annotation of an already-declared type with a different scope or name was dropped. They now dedup on (type, name, scope). The example worker gains the five functions of the shared secret-lookup conformance contract (vgi docs/secret_lookup_fixtures.md): secret_value_by_type, secret_value_by_name, secret_value_for_scope, secret_value_required and secret_types_seen, exercised by test/sql/integration/secret/secret_lookup_*.test. ci/run-integration.sh opts in with VGI_SECRET_LOOKUP_FIXTURES=1. By-type lookup itself (an unnamed __default_<type> secret) was already fixed in 0b993d2; the new unit tests pin it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4cd34c2 commit 84092fe

6 files changed

Lines changed: 645 additions & 12 deletions

File tree

‎ci/run-integration.sh‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,10 @@ export VGI_SIMPLE_WRITABLE_WORKER="${LAUNCH_PREFIX}${SIMPLE_WRITABLE}"
235235
# database:// installs and directly executes this package, even when the main
236236
# lane talks to an already-running HTTP worker.
237237
export VGI_DATABASE_PACKAGE_WORKER="$WORKER"
238+
# The example worker implements the secret-lookup conformance fixtures
239+
# (vgi docs/secret_lookup_fixtures.md), so opt in to secret/secret_lookup_*.test
240+
# on every lane.
241+
export VGI_SECRET_LOOKUP_FIXTURES=1
238242

239243
case "$TRANSPORT" in
240244
stdio)

‎docs/protocol/vgi-secrets.md‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ A worker asks in one of two ways.
3131
**Statically.** Function metadata lists lookups in `required_secrets`. The client resolves them
3232
before the first bind, so they are in the first bind request.
3333

34+
In vgi-python, `Meta.required_secrets` is a list whose entries may be a bare secret-type string
35+
(`"s3"`, the simplest form), a `SecretLookupEntry`, a `Secret`, or a dict with a `secret_type` key.
36+
`Secret()` annotations on `on_bind`/`compute` parameters are added to the list, one entry per
37+
distinct `(type, name, scope)`. Any other entry, an empty type, or a value that is not a list raises
38+
at metadata resolution: a requirement the SDK cannot read is one the client is never asked to
39+
resolve.
40+
3441
**Dynamically.** A bind may need a lookup it can only compute from its arguments, such as the bucket
3542
in a path argument. The worker answers the bind with a *secret-scope request*: a `BindResponse`
3643
whose `lookup_secret_types` list is non-empty. `lookup_scopes` and `lookup_names` are parallel
@@ -122,10 +129,22 @@ SDKs expose these as selectors on the resolved-secrets object.
122129
| C# | `SecretArgCodec.AllOfType` | `SecretArgCodec.ForScopeOfType` |
123130
| TypeScript | `secretsOfType` | `secretForScopeOfType` |
124131

125-
## 6. History
132+
## 6. Conformance
133+
134+
The shared integration suite checks this contract against every SDK's example worker in
135+
`test/sql/integration/secret/secret_lookup_*.test` (vgi repo). The fixture functions those files
136+
call are specified in the vgi repo's `docs/secret_lookup_fixtures.md`; vgi-python implements them
137+
in `vgi/_test_fixtures/secret_lookup.py`.
138+
139+
## 7. History
126140

127141
vgi-python's bind-time `SecretsAccessor` used to expect dynamically requested secrets in columns
128142
named `secret_0`, `secret_1`, … with the lookup's type, name and scope in Arrow field metadata. No
129143
client sends that layout, so `params.secrets.get(type, name=…)` and `get(type, scope=…)` returned
130144
`None` on the second bind although the secret was in the batch. The accessor now reads the layout
131145
in §4, and `secret_0` is an ordinary secret name.
146+
147+
`Meta.required_secrets` used to keep only `SecretLookupEntry` and dict entries and silently drop
148+
everything else, so `required_secrets = ["llm"]` declared nothing and the function never received
149+
the secret. Annotation-derived requirements were also deduplicated by type alone, so a second
150+
`Secret("s3", scope=...)` of an already-declared type was dropped. Both now behave as §2 describes.

‎tests/test_secret_requirements.py‎

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
"""Secret requirement declarations and by-type secret lookup.
2+
3+
Two ways a function used to end up without its credentials:
4+
5+
* ``Meta.required_secrets = ["llm"]`` — a plain type string was silently
6+
dropped, so the client was never asked to resolve the secret.
7+
* looking a secret up by TYPE as if the type were the batch's column name — the
8+
client keys each column by the secret's unique NAME (``__default_<type>`` for
9+
an unnamed secret), so only a secret named after its type matched.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
from dataclasses import dataclass
15+
from typing import Annotated, Any
16+
17+
import pyarrow as pa
18+
import pytest
19+
20+
from vgi.arguments import Arg, Secret, SecretLookupEntry
21+
from vgi.invocation import BindResponse
22+
from vgi.metadata import _coerce_required_secrets, resolve_metadata
23+
from vgi.table_function import BindParams, ResolvedSecrets, SecretsAccessor, TableFunctionGenerator
24+
25+
26+
@dataclass(slots=True, frozen=True)
27+
class _Args:
28+
count: Annotated[int, Arg(0, doc="Count")] = 1
29+
30+
31+
def _table_function(required_secrets: Any) -> type[TableFunctionGenerator[_Args]]:
32+
class _Func(TableFunctionGenerator[_Args]):
33+
class Meta:
34+
pass
35+
36+
@classmethod
37+
def on_bind(cls, params: BindParams[_Args]) -> BindResponse:
38+
return BindResponse(output_schema=pa.schema([pa.field("x", pa.int64())]))
39+
40+
@classmethod
41+
def process(cls, params: Any, state: Any, out: Any) -> None: ...
42+
43+
_Func.Meta.required_secrets = required_secrets # type: ignore[attr-defined]
44+
return _Func
45+
46+
47+
class TestCoerceRequiredSecrets:
48+
"""Every accepted declaration form becomes a lookup; anything else is an error."""
49+
50+
def test_bare_type_string(self) -> None:
51+
"""A bare type string becomes a type-only lookup."""
52+
assert _coerce_required_secrets("F", ["llm"]) == [SecretLookupEntry(secret_type="llm")]
53+
54+
def test_all_forms_in_order(self) -> None:
55+
"""Every supported form is converted, preserving declaration order."""
56+
entries = _coerce_required_secrets(
57+
"F",
58+
[
59+
"a",
60+
SecretLookupEntry(secret_type="b", scope="s3://x/"),
61+
Secret("c", name="n"),
62+
{"secret_type": "d", "scope": "gs://y/"},
63+
],
64+
)
65+
assert entries == [
66+
SecretLookupEntry(secret_type="a"),
67+
SecretLookupEntry(secret_type="b", scope="s3://x/"),
68+
SecretLookupEntry(secret_type="c", secret_name="n"),
69+
SecretLookupEntry(secret_type="d", scope="gs://y/"),
70+
]
71+
72+
def test_tuple_and_none(self) -> None:
73+
"""A tuple is accepted and None means no requirements."""
74+
assert _coerce_required_secrets("F", ("a",)) == [SecretLookupEntry(secret_type="a")]
75+
assert _coerce_required_secrets("F", None) == []
76+
77+
@pytest.mark.parametrize("raw", ["llm", SecretLookupEntry(secret_type="llm"), {"secret_type": "llm"}, 7])
78+
def test_non_list_container_rejected(self, raw: Any) -> None:
79+
"""A non-list value is rejected instead of iterated."""
80+
# A bare string would otherwise iterate as one requirement per character.
81+
with pytest.raises(TypeError, match="must be a list"):
82+
_coerce_required_secrets("F", raw)
83+
84+
@pytest.mark.parametrize("entry", [7, ("llm",), b"llm", object()])
85+
def test_unknown_entry_rejected(self, entry: Any) -> None:
86+
"""An entry of an unsupported type raises instead of being dropped."""
87+
with pytest.raises(TypeError, match=r"required_secrets\[0\]"):
88+
_coerce_required_secrets("F", [entry])
89+
90+
def test_dict_without_type_rejected(self) -> None:
91+
"""A dict entry must name its secret type."""
92+
with pytest.raises(TypeError, match="secret_type"):
93+
_coerce_required_secrets("F", [{"scope": "s3://x/"}])
94+
95+
@pytest.mark.parametrize("entry", ["", SecretLookupEntry(secret_type=""), {"secret_type": ""}])
96+
def test_empty_type_rejected(self, entry: Any) -> None:
97+
"""An empty secret type is rejected."""
98+
# The client skips an entry with an empty type, so it would never resolve.
99+
with pytest.raises(ValueError, match="empty secret_type"):
100+
_coerce_required_secrets("F", [entry])
101+
102+
103+
class TestRequiredSecretsMetadata:
104+
"""``Meta.required_secrets`` reaches the function metadata the client reads."""
105+
106+
def test_string_entry_is_requested(self) -> None:
107+
"""A bare string in Meta.required_secrets reaches the metadata."""
108+
resolve_metadata.cache_clear()
109+
meta = _table_function(["llm"]).get_metadata()
110+
assert meta.required_secrets == [SecretLookupEntry(secret_type="llm")]
111+
112+
def test_unrecognised_entry_fails_loudly(self) -> None:
113+
"""An unreadable entry fails metadata resolution."""
114+
resolve_metadata.cache_clear()
115+
with pytest.raises(TypeError, match="required_secrets"):
116+
_table_function([42]).get_metadata()
117+
118+
def test_conformance_fixture_declares_bare_string(self) -> None:
119+
"""The conformance fixtures declare their requirements as the contract says."""
120+
resolve_metadata.cache_clear()
121+
from vgi._test_fixtures.secret_lookup import SecretTypesSeenFunction, SecretValueByTypeFunction
122+
123+
assert SecretValueByTypeFunction.get_metadata().required_secrets == [
124+
SecretLookupEntry(secret_type="vgi_example")
125+
]
126+
assert SecretTypesSeenFunction.get_metadata().required_secrets == [
127+
SecretLookupEntry(secret_type="vgi_example"),
128+
SecretLookupEntry(secret_type="s3", scope="s3://vgi-conformance/"),
129+
]
130+
131+
def test_same_type_annotations_with_different_scopes_are_both_requested(self) -> None:
132+
"""Same-type annotations with different scopes are all requested."""
133+
resolve_metadata.cache_clear()
134+
135+
class _Func(TableFunctionGenerator[_Args]):
136+
class Meta:
137+
required_secrets = ["s3"]
138+
139+
@classmethod
140+
def on_bind(
141+
cls,
142+
params: BindParams[_Args],
143+
*,
144+
a: Annotated[dict[str, Any] | None, Secret("s3", scope="s3://a/")] = None,
145+
b: Annotated[dict[str, Any] | None, Secret("s3", scope="s3://b/")] = None,
146+
again: Annotated[dict[str, Any] | None, Secret("s3")] = None,
147+
) -> BindResponse:
148+
return BindResponse(output_schema=pa.schema([pa.field("x", pa.int64())]))
149+
150+
@classmethod
151+
def process(cls, params: Any, state: Any, out: Any) -> None: ...
152+
153+
lookups = {(e.secret_type, e.secret_name, e.scope) for e in _Func.get_metadata().required_secrets}
154+
assert lookups == {("s3", None, None), ("s3", None, "s3://a/"), ("s3", None, "s3://b/")}
155+
# The unscoped annotation duplicates the Meta entry and is not repeated.
156+
assert len(_Func.get_metadata().required_secrets) == 3
157+
158+
159+
def _secrets_batch(columns: dict[str, dict[str, str]]) -> pa.RecordBatch:
160+
"""A secrets batch as the DuckDB extension builds it: one struct column per secret NAME."""
161+
arrays = [pa.array([fields], type=pa.struct([(k, pa.string()) for k in fields])) for fields in columns.values()]
162+
return pa.RecordBatch.from_arrays(arrays, names=list(columns))
163+
164+
165+
class TestLookupByType:
166+
"""A by-type lookup matches each secret's ``type`` field, not its column name."""
167+
168+
def test_unnamed_default_secret_found_by_type(self) -> None:
169+
"""An unnamed secret (column __default_<type>) is found by type."""
170+
batch = _secrets_batch(
171+
{"__default_brave": {"type": "brave", "name": "__default_brave", "scope": "", "api_key": "k"}}
172+
)
173+
accessor = SecretsAccessor(batch)
174+
secret = accessor.get("brave")
175+
assert secret is not None
176+
assert secret["api_key"].as_py() == "k"
177+
assert accessor.all_resolved # no needless two-phase request
178+
assert accessor.to_dict().lookup("brave") is secret
179+
180+
def test_secret_named_unlike_its_type_found_by_type(self) -> None:
181+
"""A secret named unlike its type is found by type."""
182+
batch = _secrets_batch({"prod_creds": {"type": "brave", "name": "prod_creds", "scope": "", "api_key": "p"}})
183+
secret = SecretsAccessor(batch).get("brave", required=True)
184+
assert secret is not None
185+
assert secret["api_key"].as_py() == "p"
186+
187+
def test_by_type_prefers_unscoped(self) -> None:
188+
"""A by-type lookup prefers the unscoped secret of that type."""
189+
secrets = ResolvedSecrets(
190+
{
191+
"a_scoped": {"type": "s3", "scope": "s3://a/", "k": "scoped"},
192+
"z_unscoped": {"type": "s3", "scope": "", "k": "unscoped"},
193+
}
194+
)
195+
found = secrets.lookup("s3")
196+
assert found is not None
197+
assert found["k"] == "unscoped"
198+
199+
def test_name_lookup_checks_type(self) -> None:
200+
"""A by-name lookup also checks the secret's type."""
201+
secrets = ResolvedSecrets({"creds": {"type": "gcs", "scope": "", "k": "g"}})
202+
assert secrets.lookup("s3", name="creds") is None
203+
found = secrets.lookup("gcs", name="creds")
204+
assert found is not None
205+
assert found["k"] == "g"
206+
207+
def test_missing_type_is_none_then_required_error_on_retry(self) -> None:
208+
"""A missing secret is requested, then reported as missing on the retry."""
209+
batch = _secrets_batch({"other": {"type": "gcs", "name": "other", "scope": "", "k": "g"}})
210+
first = SecretsAccessor(batch)
211+
assert first.get("brave") is None
212+
assert first.pending_lookups == [SecretLookupEntry(secret_type="brave")]
213+
retry = SecretsAccessor(batch, is_retry=True)
214+
with pytest.raises(ValueError, match="Required secret 'brave' not found"):
215+
retry.get("brave", required=True)

0 commit comments

Comments
 (0)