Skip to content

Commit b10d21d

Browse files
test(features): use testkit's typed profiles and match the stronger refresh test
Build the refresh-handle and readiness profiles with testkit::Profile and the probe policy with policy::allow, and create every provider with install_provider. The stable-placeholder and token-exchange profiles stay YAML because Profile has no stable_placeholder or token_grant setter. The legacy refresh-handle test now waits for the probe after each rotation, sends the token as Bearer and as Basic x-access-token, and after reconfiguring rotates again, waits for a new process to succeed and checks the old handle stays revoked. Do the same here. Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
1 parent 54041ef commit b10d21d

6 files changed

Lines changed: 130 additions & 102 deletions

File tree

‎tests/suites/features/Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tests/suites/features/provider-refresh/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ path = "tests/refresh_handles.rs"
1717
harness = false
1818

1919
[dependencies]
20+
base64 = "0.22"
2021
host-server-support = { path = "../../../support/host-server" }
2122
openshell-testkit = { path = "../../../testkit/testkit" }
23+
prost-types = "0.14"
2224
serde_json = "1"

‎tests/suites/features/provider-refresh/tests/refresh_handles.rs‎

Lines changed: 100 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,13 @@
1111
use std::sync::{Arc, Mutex, PoisonError};
1212
use std::time::Duration;
1313

14+
use base64::Engine as _;
15+
use base64::engine::general_purpose::STANDARD as BASE64;
1416
use host_server_support::{HttpRecorder, Request, Response, TEST_HOST};
1517
use serde_json::json;
16-
use testkit::{Context, PYTHON_BINARIES, Poll, Result, Sandbox, policy, poll_until};
18+
use testkit::policy::{self, Access, Endpoint as _};
19+
use testkit::sdk::raw::proto;
20+
use testkit::{Context, Credential, PYTHON_BINARIES, Poll, Profile, Result, Sandbox, poll_until};
1721

1822
fn main() -> std::process::ExitCode {
1923
testkit::main()
@@ -49,11 +53,12 @@ done"#,
4953
)
5054
}
5155

52-
/// A shell command that requests `resource_url` with the credential from the
53-
/// environment as a bearer token, and fails unless the resource accepts it.
56+
/// A shell command that requests `resource_url` twice with the credential
57+
/// from the environment, as a bearer token and as the password of HTTP Basic
58+
/// `x-access-token`, and fails unless the resource accepts both.
5459
fn probe(resource_url: &str) -> String {
5560
format!(
56-
r#"python3 -c 'import os, urllib.request; urllib.request.urlopen(urllib.request.Request("{resource_url}", headers={{"Authorization": "Bearer " + os.environ["{TOKEN_ENV}"]}}), timeout=5).read()'"#
61+
r#"python3 -c 'import os, base64, urllib.request; token = os.environ["{TOKEN_ENV}"]; auths = ["Bearer " + token, "Basic " + base64.b64encode(("x-access-token:" + token).encode()).decode()]; [urllib.request.urlopen(urllib.request.Request("{resource_url}", headers={{"Authorization": auth}}), timeout=5).read() for auth in auths]'"#
5762
)
5863
}
5964

@@ -68,9 +73,8 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes(
6873
) -> testkit::Result {
6974
let issuer = Issuer::start().await?;
7075
let provider = cx.name("refresh");
71-
let profile = profile(&provider, issuer.port());
72-
let provider_type = cx.import_profile(&profile).await?;
73-
cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, BOOTSTRAP_TOKEN)])
76+
let profile = profile(&provider, issuer.port()).to_yaml()?;
77+
cx.install_provider(&provider, &profile, &[(TOKEN_ENV, BOOTSTRAP_TOKEN)])
7478
.await?;
7579
let refresh = cx.provider_refresh(&provider, TOKEN_ENV);
7680
let configure = async || {
@@ -90,7 +94,7 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes(
9094
.sandbox("rfh")
9195
.image(testkit::python_image())
9296
.providers([provider.as_str()])
93-
.policy(probe_policy(issuer.port())?)
97+
.policy(probe_policy(issuer.port()))
9498
.command(["sh", "-c", &main_process(&resource_url)])
9599
.create_ready()
96100
.await?;
@@ -104,14 +108,14 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes(
104108

105109
for _ in 0..ROTATIONS {
106110
refresh.rotate().await?.success()?;
111+
wait_for_probe(
112+
&sandbox,
113+
"ok",
114+
"the long-running process to use the latest rotated token",
115+
)
116+
.await
117+
.map_err(|error| error.context(format!("issuer saw {}", issuer.summary())))?;
107118
}
108-
wait_for_probe(
109-
&sandbox,
110-
"ok",
111-
"the long-running process to use the latest rotated token",
112-
)
113-
.await
114-
.map_err(|error| error.context(format!("issuer saw {}", issuer.summary())))?;
115119

116120
configure().await?;
117121
wait_for_probe(
@@ -121,10 +125,31 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes(
121125
)
122126
.await?;
123127

124-
sandbox
125-
.exec(["sh", "-c", &probe(&resource_url)])
126-
.await?
127-
.success()?;
128+
refresh.rotate().await?.success()?;
129+
poll_until(
130+
"a new process to reach the resource after reconfiguring",
131+
PROBE_TIMEOUT,
132+
Duration::from_millis(500),
133+
async || {
134+
let fresh = sandbox.exec(["sh", "-c", &probe(&resource_url)]).await?;
135+
Ok(if fresh.exit_code == 0 {
136+
Poll::Ready(())
137+
} else {
138+
Poll::Pending(format!(
139+
"the probe exited {}: {}",
140+
fresh.exit_code,
141+
fresh.stderr.trim()
142+
))
143+
})
144+
},
145+
)
146+
.await
147+
.map_err(|error| error.context(format!("issuer saw {}", issuer.summary())))?;
148+
let old = trigger_probe(&sandbox).await?;
149+
testkit::ensure!(
150+
old == "failed",
151+
"the long-running process's revoked handle worked again after a new token was issued: {old:?}"
152+
);
128153
Ok(())
129154
}
130155

@@ -164,7 +189,8 @@ async fn wait_for_probe(sandbox: &Sandbox, expected: &str, what: &str) -> Result
164189

165190
/// An OAuth issuer and the resource it guards. Each `POST /token` issues a
166191
/// new token and invalidates the last. `GET /probe` answers `204` to the
167-
/// current token and `401` to anything else.
192+
/// current token, as a bearer token or as the password of HTTP Basic
193+
/// `x-access-token`, and `401` to anything else.
168194
struct Issuer {
169195
server: HttpRecorder,
170196
}
@@ -185,8 +211,14 @@ impl Issuer {
185211
}))
186212
}
187213
("GET", "/probe")
188-
if request.header("authorization").as_deref()
189-
== Some(&format!("Bearer {}", state.1)) =>
214+
if request.header("authorization").is_some_and(|auth| {
215+
auth == format!("Bearer {}", state.1)
216+
|| auth
217+
== format!(
218+
"Basic {}",
219+
BASE64.encode(format!("x-access-token:{}", state.1))
220+
)
221+
}) =>
190222
{
191223
Response::new(204)
192224
}
@@ -215,49 +247,52 @@ impl Issuer {
215247

216248
/// A profile whose credential refreshes with OAuth client credentials from
217249
/// the issuer on `port`, and is bound to the resource on the same port.
218-
fn profile(id: &str, port: u16) -> String {
219-
let binaries = PYTHON_BINARIES
220-
.iter()
221-
.map(|binary| format!("\"{binary}\""))
222-
.collect::<Vec<_>>()
223-
.join(", ");
224-
format!(
225-
"id: {id}
226-
display_name: Provider refresh handle test
227-
category: other
228-
credentials:
229-
- name: access_token
230-
env_vars: [{TOKEN_ENV}]
231-
required: true
232-
auth_style: bearer
233-
header_name: authorization
234-
refresh:
235-
strategy: oauth2_client_credentials
236-
token_url: http://127.0.0.1:{port}/token
237-
refresh_before_seconds: 30
238-
max_lifetime_seconds: 300
239-
material:
240-
- name: client_id
241-
required: true
242-
- name: client_secret
243-
required: true
244-
secret: true
245-
endpoints:
246-
- {{host: {TEST_HOST}, port: {port}, path: /probe, protocol: rest, access: full, enforcement: enforce}}
247-
binaries: [{binaries}]
248-
"
249-
)
250+
fn profile(id: &str, port: u16) -> Profile {
251+
let material = |name: &str, secret: bool| proto::ProviderCredentialRefreshMaterial {
252+
name: name.to_string(),
253+
required: true,
254+
secret,
255+
..proto::ProviderCredentialRefreshMaterial::default()
256+
};
257+
let seconds = |seconds| Some(prost_types::Duration { seconds, nanos: 0 });
258+
Profile::new(id)
259+
.display_name("Provider refresh handle test")
260+
.credential(
261+
Credential::new("access_token")
262+
.env_var(TOKEN_ENV)
263+
.required()
264+
.auth_style("bearer")
265+
.header_name("authorization")
266+
.refresh(proto::ProviderCredentialRefresh {
267+
strategy: proto::ProviderCredentialRefreshStrategy::Oauth2ClientCredentials
268+
as i32,
269+
token_url: format!("http://127.0.0.1:{port}/token"),
270+
refresh_before: seconds(30),
271+
max_lifetime: seconds(300),
272+
material: vec![
273+
material("client_id", false),
274+
material("client_secret", true),
275+
],
276+
..proto::ProviderCredentialRefresh::default()
277+
}),
278+
)
279+
.endpoint(TEST_HOST, port, |ep| {
280+
ep.rest(Access::Full).enforce().path("/probe");
281+
})
282+
.binaries(PYTHON_BINARIES.iter().copied())
250283
}
251284

252-
fn probe_policy(port: u16) -> Result<testkit::sdk::raw::proto::SandboxPolicy> {
253-
policy::base_with(&format!(
254-
"network_policies:
255-
refresh_probe:
256-
name: refresh_probe
257-
endpoints:
258-
- {{host: {TEST_HOST}, port: {port}, path: /probe, protocol: rest, access: full, enforcement: enforce}}
259-
binaries: {binaries}
260-
",
261-
binaries = policy::binaries_yaml(PYTHON_BINARIES),
262-
))
285+
fn probe_policy(port: u16) -> proto::SandboxPolicy {
286+
let mut policy = policy::base();
287+
policy::allow(
288+
&mut policy,
289+
"refresh_probe",
290+
TEST_HOST,
291+
port,
292+
PYTHON_BINARIES,
293+
)
294+
.rest(Access::Full)
295+
.enforce()
296+
.path("/probe");
297+
policy
263298
}

‎tests/suites/features/provider-rotation/tests/readiness.rs‎

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ use provider_rotation::{
2222
probe, probe_disallowed_binary,
2323
};
2424
use serde_json::{Value, json};
25-
use testkit::{CliChild, Context, Error, PYTHON_BINARIES, Result, Sandbox};
25+
use testkit::policy::{Access, Endpoint as _};
26+
use testkit::{CliChild, Context, Error, PYTHON_BINARIES, Profile, Result, Sandbox};
2627

2728
fn main() -> std::process::ExitCode {
2829
testkit::main()
@@ -106,10 +107,8 @@ async fn acknowledged_changes_reach_fresh_clients_and_detach_revokes_retained_re
106107
let keys = keys();
107108
let backends = Backends::start(Credential::Bearer, &keys).await?;
108109
let provider = cx.name("ready");
109-
let provider_type = cx
110-
.import_profile(&profile(&provider, backends.port()))
111-
.await?;
112-
cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, &keys[0])])
110+
let profile = profile(&provider, backends.port())?;
111+
cx.install_provider(&provider, &profile, &[(TOKEN_ENV, &keys[0])])
113112
.await?;
114113
let sandbox = cx
115114
.sandbox("ready")
@@ -282,16 +281,21 @@ async fn acknowledged_changes_reach_fresh_clients_and_detach_revokes_retained_re
282281
}
283282

284283
/// A profile with one bearer credential bound to the server on `port`.
285-
fn profile(id: &str, port: u16) -> String {
286-
json!({
287-
"id": id, "display_name": "Provider readiness test", "category": "other",
288-
"credentials": [{"name": "synthetic", "env_vars": [TOKEN_ENV], "required": true,
289-
"auth_style": "bearer", "header_name": "authorization"}],
290-
"endpoints": [{"host": TEST_HOST, "port": port, "path": "/v1/**", "protocol": "rest",
291-
"access": "full", "enforcement": "enforce"}],
292-
"binaries": PYTHON_BINARIES,
293-
})
294-
.to_string()
284+
fn profile(id: &str, port: u16) -> Result<String> {
285+
Profile::new(id)
286+
.display_name("Provider readiness test")
287+
.credential(
288+
testkit::Credential::new("synthetic")
289+
.env_var(TOKEN_ENV)
290+
.required()
291+
.auth_style("bearer")
292+
.header_name("authorization"),
293+
)
294+
.endpoint(TEST_HOST, port, |ep| {
295+
ep.rest(Access::Full).enforce().path("/v1/**");
296+
})
297+
.binaries(PYTHON_BINARIES.iter().copied())
298+
.to_yaml()
295299
}
296300

297301
fn pid(response: &Value) -> Result<u64> {

‎tests/suites/features/provider-rotation/tests/stable_placeholders.rs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,8 @@ async fn assertion_rotation(cx: &Context, stable: bool) -> Result {
138138
let backends = Backends::start(Credential::Assertion, &keys).await?;
139139
let suffix = if stable { "stbl" } else { "ordn" };
140140
let provider = cx.name(suffix);
141-
let provider_type = cx
142-
.import_profile(&profile(&provider, backends.port(), stable))
143-
.await?;
144-
cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, &keys[0])])
141+
let profile = profile(&provider, backends.port(), stable);
142+
cx.install_provider(&provider, &profile, &[(TOKEN_ENV, &keys[0])])
145143
.await?;
146144
let config = json!({"key": TOKEN_ENV, "header": ASSERTION_HEADER, "payload": tool_call(),
147145
"host": TEST_HOST, "other_host": backends.other_host(), "port": backends.port(),

‎tests/suites/features/provider-token-exchange/tests/token_exchange.rs‎

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -70,17 +70,9 @@ async fn independent_grants_across_sandboxes(cx: &mut Context) -> testkit::Resul
7070
let mut sandboxes = Vec::new();
7171
for instance in ["a", "b"] {
7272
let provider = cx.name(&format!("grants-{instance}"));
73-
let profile_type = cx
74-
.import_profile(&grants_profile(
75-
&provider,
76-
token_port,
77-
identity_port,
78-
target_port,
79-
instance,
80-
))
81-
.await?;
73+
let profile = grants_profile(&provider, token_port, identity_port, target_port, instance);
8274
let subject = format!("{USER_SUBJECT_TOKEN}-{instance}");
83-
cx.create_provider(&provider, &profile_type, &[(SUBJECT_TOKEN_ENV, &subject)])
75+
cx.install_provider(&provider, &profile, &[(SUBJECT_TOKEN_ENV, &subject)])
8476
.await?;
8577
sandboxes.push(
8678
cx.sandbox(&format!("pte{instance}"))
@@ -175,15 +167,10 @@ async fn routes_recover_and_select_a_b_a_on_one_connection(cx: &mut Context) ->
175167
let mut providers = Vec::new();
176168
for route in ["a", "b"] {
177169
let provider = cx.name(&format!("route-{route}"));
178-
let profile_type = cx
179-
.import_profile(&route_profile(&provider, token_port, target_port, route))
170+
let profile = route_profile(&provider, token_port, target_port, route);
171+
let stored = format!("stored-{route}");
172+
cx.install_provider(&provider, &profile, &[(SUBJECT_TOKEN_ENV, &stored)])
180173
.await?;
181-
cx.create_provider(
182-
&provider,
183-
&profile_type,
184-
&[(SUBJECT_TOKEN_ENV, &format!("stored-{route}"))],
185-
)
186-
.await?;
187174
providers.push(provider);
188175
}
189176
let sandbox = cx

0 commit comments

Comments
 (0)