|
| 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