Skip to content

Commit 81a2817

Browse files
committed
fix(sdk): address client credentials review
Signed-off-by: Seth Jennings <[email protected]>
1 parent 4f283c7 commit 81a2817

8 files changed

Lines changed: 147 additions & 38 deletions

File tree

‎architecture/gateway.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -189,9 +189,10 @@ reuses them when refreshing an access token. This preserves the intended API
189189
resource selection for identity providers that bind access-token audiences to
190190
OAuth scopes.
191191

192-
SDK client-credentials providers use the same registered issuer, client ID,
193-
audience, and scope metadata but own a separate in-memory lifecycle. They repeat
194-
the grant before expiry and never persist the client secret or acquired access
192+
Python and Go SDK client-credentials providers can use the same registered
193+
issuer, client ID, audience, and scope metadata; the TypeScript provider accepts
194+
those fields explicitly. All three own a separate in-memory lifecycle, repeat
195+
the grant before expiry, and never persist the client secret or acquired access
195196
token into the CLI token cache. This keeps non-interactive SDK authentication
196197
independent from refresh-token rotation and shared disk state.
197198

‎docs/sandboxes/manage-sandboxes.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ from openshell import ClientCredentialsAuth, SandboxClient
276276
277277
auth = ClientCredentialsAuth(client_secret=lambda: load_secret())
278278
with SandboxClient.from_active_cluster(client_credentials=auth) as client:
279-
sandboxes = client.list()
279+
sandboxes = client.list(workspace="default")
280280
```
281281
282282
## Expose Long Running Services

‎python/openshell/sandbox.py‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def __init__(
191191
client_secret: str | Callable[[], str],
192192
issuer: str | None = None,
193193
client_id: str | None = None,
194-
scopes: Sequence[str] = (),
194+
scopes: Sequence[str] | None = None,
195195
audience: str | None = None,
196196
insecure: bool = False,
197197
timeout: float = 30.0,
@@ -204,7 +204,7 @@ def __init__(
204204
self._secret = client_secret
205205
self._issuer = issuer
206206
self._client_id = client_id
207-
self._scopes = tuple(scopes)
207+
self._scopes = tuple(scopes) if scopes is not None else None
208208
self._audience = audience
209209
self._insecure = insecure
210210
self._timeout = timeout
@@ -221,8 +221,10 @@ def __repr__(self) -> str:
221221
f"scopes={self._scopes!r}, audience={self._audience!r})"
222222
)
223223

224-
def _apply_gateway_metadata(self, metadata: Mapping[str, object]) -> None:
225-
"""Fill omitted public fields from registered gateway metadata."""
224+
def _apply_gateway_metadata(
225+
self, metadata: Mapping[str, object], *, insecure: bool = False
226+
) -> None:
227+
"""Fill omitted fields and apply active-gateway transport settings."""
226228
if self._issuer is None:
227229
value = metadata.get("oidc_issuer")
228230
self._issuer = value if isinstance(value, str) and value else None
@@ -232,10 +234,13 @@ def _apply_gateway_metadata(self, metadata: Mapping[str, object]) -> None:
232234
if self._audience is None:
233235
value = metadata.get("oidc_audience")
234236
self._audience = value if isinstance(value, str) and value else None
235-
if not self._scopes:
237+
if self._scopes is None:
236238
value = metadata.get("oidc_scopes")
237239
if isinstance(value, str):
238240
self._scopes = tuple(value.split())
241+
# Preserve an explicit provider-level opt-in while also honoring the
242+
# active-gateway construction flag used by the existing OIDC refresher.
243+
self._insecure = self._insecure or insecure
239244

240245
def __call__(self) -> str:
241246
if (
@@ -632,7 +637,7 @@ def from_active_cluster(
632637
raise SandboxError(
633638
f"gateway '{cluster_name}' is not configured for OIDC"
634639
)
635-
client_credentials._apply_gateway_metadata(metadata)
640+
client_credentials._apply_gateway_metadata(metadata, insecure=insecure)
636641
bearer_token = client_credentials
637642
elif metadata.get("auth_mode") == "oidc":
638643
bearer_token, bearer_close = _make_cluster_bearer_provider(

‎python/openshell/sandbox_test.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,39 @@ def handler(request: Any) -> Any:
111111
assert "conformance-secret" not in repr(auth)
112112

113113

114+
def test_client_credentials_auth_preserves_explicit_empty_scopes() -> None:
115+
import httpx
116+
117+
form: dict[str, str] = {}
118+
119+
def handler(request: Any) -> Any:
120+
if request.method == "GET":
121+
return httpx.Response(
122+
200,
123+
json={
124+
"issuer": "https://issuer.example.com",
125+
"token_endpoint": "https://issuer.example.com/token",
126+
},
127+
)
128+
form.update(
129+
__import__("urllib.parse").parse.parse_qsl(request.content.decode())
130+
)
131+
return httpx.Response(200, json={"access_token": "token", "expires_in": 120})
132+
133+
auth = ClientCredentialsAuth(
134+
issuer="https://issuer.example.com",
135+
client_id="client",
136+
client_secret="secret",
137+
scopes=(),
138+
_transport=httpx.MockTransport(handler),
139+
)
140+
auth._apply_gateway_metadata({"oidc_scopes": "sandbox:read sandbox:write"})
141+
142+
assert auth() == "token"
143+
assert auth._scopes == ()
144+
assert "scope" not in form
145+
146+
114147
@pytest.mark.parametrize(
115148
"expires_in", _client_credentials_fixture()["expiry"]["invalid_expires_in"]
116149
)
@@ -1518,12 +1551,16 @@ def test_from_active_cluster_fills_client_credentials_from_metadata(
15181551
)
15191552
metadata_path.write_text(json.dumps(metadata))
15201553
auth = ClientCredentialsAuth(client_secret="secret")
1521-
client = SandboxClient.from_active_cluster(client_credentials=auth)
1554+
client = SandboxClient.from_active_cluster(
1555+
client_credentials=auth,
1556+
insecure=True,
1557+
)
15221558
try:
15231559
assert auth._issuer == "https://issuer.example.com"
15241560
assert auth._client_id == "service-client"
15251561
assert auth._audience == "gateway"
15261562
assert auth._scopes == ("sandbox:read", "sandbox:write")
1563+
assert auth._insecure is True
15271564
finally:
15281565
client.close()
15291566

‎sdk/typescript/src/oidc.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,34 @@ describe('clientCredentials', () => {
186186
await expect(provider.getToken()).rejects.toThrow(/too large/);
187187
});
188188

189+
it('times out while reading a stalled body and retries cleanly', async () => {
190+
let issuer = '';
191+
let discoveryCalls = 0;
192+
const server = createServer((req, res) => {
193+
if (req.url === '/.well-known/openid-configuration') {
194+
discoveryCalls += 1;
195+
if (discoveryCalls === 1) {
196+
res.writeHead(200, { 'content-type': 'application/json' });
197+
res.write('{"issuer":');
198+
return;
199+
}
200+
res.end(JSON.stringify({ issuer, token_endpoint: `${issuer}/token` }));
201+
return;
202+
}
203+
res.end(JSON.stringify({ access_token: 'recovered', expires_in: 120 }));
204+
});
205+
servers.push(server);
206+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
207+
const address = server.address();
208+
if (!address || typeof address === 'string') throw new Error('missing address');
209+
issuer = `http://127.0.0.1:${address.port}`;
210+
const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret', timeoutMs: 100 });
211+
212+
await expect(provider.getToken()).rejects.toThrow(/discovery request timed out/);
213+
await expect(provider.getToken()).resolves.toBe('recovered');
214+
expect(discoveryCalls).toBe(2);
215+
});
216+
189217
it('lets one waiter cancel without canceling the shared exchange', async () => {
190218
let issuer = '';
191219
let releaseToken!: () => void;

‎sdk/typescript/src/oidc.ts‎

Lines changed: 34 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export interface ClientCredentialsOptions {
1717
clientSecret: string | (() => string | Promise<string>);
1818
scopes?: readonly string[];
1919
audience?: string;
20+
/** Timeout for each complete discovery or token response, including its body. */
2021
timeoutMs?: number;
2122
}
2223

@@ -131,12 +132,26 @@ class ClientCredentialsProvider implements OidcTokenProvider {
131132
}
132133
}
133134

134-
async #request(url: string, init: RequestInit): Promise<Response> {
135+
async #requestJson(
136+
url: string,
137+
init: RequestInit,
138+
responseKind: string,
139+
operation: string,
140+
): Promise<Record<string, unknown>> {
135141
const controller = new AbortController();
136142
const timeout = setTimeout(() => controller.abort(), this.#options.timeoutMs ?? 30_000);
137143
try {
138-
return await fetch(url, { ...init, redirect: 'manual', signal: controller.signal });
139-
} catch {
144+
const response = await fetch(url, { ...init, redirect: 'manual', signal: controller.signal });
145+
if (response.status !== 200) {
146+
await response.body?.cancel();
147+
throw new SdkError('auth', `OAuth ${operation} failed with HTTP ${response.status}`);
148+
}
149+
return await boundedJson(response, responseKind);
150+
} catch (error) {
151+
if (error instanceof SdkError) throw error;
152+
if (controller.signal.aborted) {
153+
throw new SdkError('auth', `OAuth ${operation} request timed out`);
154+
}
140155
throw new SdkError('auth', 'OAuth client credentials request failed');
141156
} finally {
142157
clearTimeout(timeout);
@@ -145,14 +160,12 @@ class ClientCredentialsProvider implements OidcTokenProvider {
145160

146161
async #exchange(): Promise<string> {
147162
if (!this.#tokenEndpoint) {
148-
const response = await this.#request(`${this.#issuer}/.well-known/openid-configuration`, {
149-
headers: { accept: 'application/json' },
150-
});
151-
if (response.status !== 200) {
152-
await response.body?.cancel();
153-
throw new SdkError('auth', `OAuth discovery failed with HTTP ${response.status}`);
154-
}
155-
const discovery = await boundedJson(response, 'discovery');
163+
const discovery = await this.#requestJson(
164+
`${this.#issuer}/.well-known/openid-configuration`,
165+
{ headers: { accept: 'application/json' } },
166+
'discovery',
167+
'discovery',
168+
);
156169
if (typeof discovery.issuer !== 'string' || withoutTrailingSlash(discovery.issuer) !== this.#issuer) {
157170
throw new SdkError('auth', 'OAuth discovery issuer mismatch');
158171
}
@@ -169,16 +182,16 @@ class ClientCredentialsProvider implements OidcTokenProvider {
169182
});
170183
if (this.#options.scopes?.length) form.set('scope', this.#options.scopes.join(' '));
171184
if (this.#options.audience) form.set('audience', this.#options.audience);
172-
const response = await this.#request(this.#tokenEndpoint, {
173-
method: 'POST',
174-
headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
175-
body: form,
176-
});
177-
if (response.status !== 200) {
178-
await response.body?.cancel();
179-
throw new SdkError('auth', `OAuth client credentials exchange failed with HTTP ${response.status}`);
180-
}
181-
const token = await boundedJson(response, 'client credentials response');
185+
const token = await this.#requestJson(
186+
this.#tokenEndpoint,
187+
{
188+
method: 'POST',
189+
headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
190+
body: form,
191+
},
192+
'client credentials response',
193+
'client credentials exchange',
194+
);
182195
if (typeof token.access_token !== 'string' || !token.access_token) {
183196
throw new SdkError('auth', 'OAuth client credentials response is missing access_token');
184197
}

‎sdk/typescript/src/transport.test.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
// contract without a live gateway: only PEM bytes are validated, no handshake
66
// is performed.
77

8-
import { describe, expect, it } from 'vitest';
8+
import { describe, expect, it, vi } from 'vitest';
99
import { errorCode } from './errors.js';
10-
import { buildTransport } from './transport.js';
10+
import { authInterceptor, buildTransport } from './transport.js';
1111

1212
const pem = (label: string) => Buffer.from(`-----BEGIN ${label}-----\ntest\n-----END ${label}-----\n`);
1313

@@ -88,6 +88,29 @@ describe('buildTransport token exclusivity', () => {
8888
});
8989
});
9090

91+
describe('renewable bearer interceptor', () => {
92+
it('awaits the provider and attaches its current token to every request', async () => {
93+
const signal = new AbortController().signal;
94+
const getToken = vi.fn().mockResolvedValueOnce('token-1').mockResolvedValueOnce('token-2');
95+
const seen: string[] = [];
96+
const next = vi.fn(async (req: { header: Headers }) => {
97+
seen.push(req.header.get('authorization') ?? '');
98+
return {} as never;
99+
});
100+
const invoke = authInterceptor({
101+
gateway: 'https://gw.local',
102+
oidcTokenProvider: { getToken },
103+
})(next as never);
104+
105+
await invoke({ header: new Headers(), signal } as never);
106+
await invoke({ header: new Headers(), signal } as never);
107+
108+
expect(seen).toEqual(['Bearer token-1', 'Bearer token-2']);
109+
expect(getToken).toHaveBeenNthCalledWith(1, signal);
110+
expect(getToken).toHaveBeenNthCalledWith(2, signal);
111+
});
112+
});
113+
91114
describe('buildTransport plaintext auth guard', () => {
92115
it('rejects a token over http:// to a non-loopback host', () => {
93116
const fn = () => buildTransport({ gateway: 'http://gw.remote:8080', oidcToken: 'a' });

‎sdk/typescript/src/transport.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,18 @@ export interface ConnectOptions {
3737
/** Disable TLS verification (dev/debug only). */
3838
insecureSkipVerify?: boolean;
3939
/**
40-
* Permit sending an auth token (oidcToken/edgeToken) over plaintext `http://`
41-
* to a non-loopback host. Off by default: tokens over cleartext to a remote
42-
* host leak credentials on the wire. Loopback hosts are always allowed.
40+
* Permit sending an auth token (oidcToken/oidcTokenProvider/edgeToken) over
41+
* plaintext `http://` to a non-loopback host. Off by default: tokens over
42+
* cleartext to a remote host leak credentials on the wire. Loopback hosts are
43+
* always allowed.
4344
*/
4445
allowInsecureAuth?: boolean;
4546
}
4647

4748
// OIDC bearer takes precedence; otherwise attach the Cloudflare Access header +
4849
// cookie. No-op when neither token is set.
49-
function authInterceptor(opts: ConnectOptions): Interceptor {
50+
/** @internal Exported for transport contract tests; not part of the package root API. */
51+
export function authInterceptor(opts: ConnectOptions): Interceptor {
5052
return (next) => async (req) => {
5153
if (opts.oidcTokenProvider) {
5254
req.header.set('authorization', `Bearer ${await opts.oidcTokenProvider.getToken(req.signal)}`);

0 commit comments

Comments
 (0)