Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "runtime-agent-instance",
crate_name = "codex_runtime_agent_instance",
)

View File

@@ -0,0 +1,39 @@
[package]
name = "codex-runtime-agent-instance"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
doctest = false
[lints]
workspace = true
[dependencies]
base64 = { workspace = true }
codex-agent-identity = { workspace = true }
codex-api = { workspace = true }
codex-features = { workspace = true }
codex-http-client = { workspace = true }
codex-login = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-redacted-string = { workspace = true }
ed25519-dalek = { workspace = true }
http = { workspace = true }
rand = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["fs", "rt", "sync"] }
url = { workspace = true }
uuid = { workspace = true, features = ["serde", "v4"] }
zeroize = { workspace = true }
[dev-dependencies]
bytes = { workspace = true }
futures = { workspace = true }
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,29 @@
//! Actor and host information returned by composite registration, without another hydration call.
use crate::ActorInfo;
use crate::AgentHostAuthorization;
pub struct AuthenticatedActor {
pub(crate) info: ActorInfo,
}
impl AuthenticatedActor {
pub fn info(&self) -> &ActorInfo {
&self.info
}
}
pub struct AgentHost {
pub(crate) id: String,
pub(crate) authorization: AgentHostAuthorization,
}
impl AgentHost {
pub fn id(&self) -> &str {
&self.id
}
pub fn authorization(&self) -> &AgentHostAuthorization {
&self.authorization
}
}

View File

@@ -0,0 +1,215 @@
//! Apply runtime auth from the selected request credentials. No credential-only fallback is allowed.
use crate::ActorInfo;
use crate::RegistrationError;
use crate::RuntimeAgentInstance;
use crate::RuntimeAuthBinding;
use crate::RuntimeAuthError;
use codex_api::AuthError;
use codex_api::AuthHeaderTelemetry;
use codex_api::AuthHeadersFuture;
use codex_api::AuthProvider;
use codex_features::RuntimeAuthMode;
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
use codex_http_client::HttpClientFactory;
use codex_login::AuthChangeState;
use codex_login::AuthOwner;
use codex_login::CodexAuth;
use http::HeaderMap;
use http::HeaderValue;
use http::StatusCode;
use http::header::AUTHORIZATION;
use std::sync::Arc;
const AGENT_ASSERTION: &str = "x-openai-agent-assertion";
/// Request-scoped credentials and transport selected with their matching runtime.
#[derive(Clone)]
pub struct RuntimeAuth {
pub(crate) runtime: Arc<RuntimeAgentInstance>,
pub(crate) auth: CodexAuth,
pub(crate) http_client_factory: HttpClientFactory,
pub(crate) change_state: AuthChangeState,
pub(crate) owner: AuthOwner,
pub(crate) binding: Arc<RuntimeAuthBinding>,
}
impl std::fmt::Debug for RuntimeAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeAuth")
.field("runtime", &self.runtime)
.field("auth_mode", &self.auth.api_auth_mode())
.field("change_state", &self.change_state)
.finish_non_exhaustive()
}
}
/// Request-scoped provider: retries sign fresh assertions from the same selected runtime/credential.
struct RuntimeRequestAuth {
auth: RuntimeAuth,
mode: RuntimeAuthMode,
}
impl RuntimeAuth {
pub fn runtime(&self) -> &Arc<RuntimeAgentInstance> {
&self.runtime
}
pub fn auth(&self) -> &CodexAuth {
&self.auth
}
pub fn http_client_factory(&self) -> &HttpClientFactory {
&self.http_client_factory
}
pub fn change_state(&self) -> AuthChangeState {
self.change_state
}
pub fn auth_owner(&self) -> &AuthOwner {
&self.owner
}
pub fn binding(&self) -> &Arc<RuntimeAuthBinding> {
&self.binding
}
/// Preserve the caller's transport settings and restrictions while binding requests to
/// this credential's account. Independent managed policies must not replace each other.
pub fn bind_http_client_factory(
&self,
factory: HttpClientFactory,
) -> Result<HttpClientFactory, AuthError> {
let account_policy = self.http_client_factory().network_policy();
let policy = factory
.network_policy()
.clone()
.with_account_binding(account_policy)
.ok_or_else(|| {
AuthError::Build(
"runtime credentials and transport must share the application network policy"
.to_string(),
)
})?;
Ok(factory
.with_network_policy(policy)
.with_sensitive_header_protection())
}
/// Use this selection for a request and its retries; select auth again for the next request.
pub fn into_auth_provider(self, mode: RuntimeAuthMode) -> codex_api::SharedAuthProvider {
Arc::new(RuntimeRequestAuth { auth: self, mode })
}
fn auth_headers(&self, mode: RuntimeAuthMode) -> Result<HeaderMap, AuthError> {
let assertion = self
.runtime()
.assertion()
.map_err(|_| AuthError::Build("failed to sign runtime assertion".to_string()))?;
let mut headers = HeaderMap::new();
match mode {
RuntimeAuthMode::DualHeader => {
let token = self.auth().get_token().map_err(|_| {
AuthError::Build("runtime actor credential is unavailable".to_string())
})?;
headers.insert(AUTHORIZATION, secret_header(&format!("Bearer {token}"))?);
headers.insert(AGENT_ASSERTION, secret_header(assertion.as_str())?);
}
RuntimeAuthMode::AssertionOnly => {
headers.insert(
AUTHORIZATION,
secret_header(&format!("AgentAssertion {}", assertion.as_str()))?,
);
}
}
if let ActorInfo::Chatgpt { account_id, .. } = self.runtime().actor().info() {
headers.insert(
CHATGPT_ACCOUNT_ID_HEADER,
HeaderValue::from_str(account_id)
.map_err(|_| AuthError::Build("invalid runtime account header".to_string()))?,
);
}
if self.auth().is_fedramp_account() {
headers.insert("x-openai-fedramp", HeaderValue::from_static("true"));
}
Ok(headers)
}
}
impl AuthProvider for RuntimeRequestAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
headers.extend(self.auth.auth_headers(self.mode)?);
Ok(())
}
fn auth_header_telemetry(&self) -> Result<AuthHeaderTelemetry, AuthError> {
Ok(AuthHeaderTelemetry {
attached: true,
name: Some("authorization"),
})
}
fn apply_auth_headers(&self, headers: HeaderMap) -> AuthHeadersFuture<'_> {
Box::pin(async move {
Ok(replace_auth_headers(
headers,
self.auth.auth_headers(self.mode)?,
))
})
}
}
fn secret_header(value: &str) -> Result<HeaderValue, AuthError> {
let mut header = HeaderValue::from_str(value)
.map_err(|_| AuthError::Build("invalid runtime authentication header".to_string()))?;
header.set_sensitive(true);
Ok(header)
}
impl From<RuntimeAuthError> for AuthError {
fn from(error: RuntimeAuthError) -> Self {
let transient = match &error {
RuntimeAuthError::Policy(denied)
| RuntimeAuthError::Registration(RegistrationError::Policy(denied)) => {
return Self::Policy(*denied);
}
RuntimeAuthError::Registration(RegistrationError::Transport) => true,
RuntimeAuthError::Registration(RegistrationError::Rejected { status, .. }) => {
status.is_server_error() || *status == StatusCode::TOO_MANY_REQUESTS
}
RuntimeAuthError::Unavailable
| RuntimeAuthError::Unsupported
| RuntimeAuthError::UnsupportedResourceSelection
| RuntimeAuthError::InvalidResourceSelection(_)
| RuntimeAuthError::Changed
| RuntimeAuthError::RefreshFailed
| RuntimeAuthError::RefreshTokenFailed(_)
| RuntimeAuthError::Task(_)
| RuntimeAuthError::KeyGeneration
| RuntimeAuthError::Registration(
RegistrationError::InvalidEndpoint
| RegistrationError::InvalidRequest
| RegistrationError::InvalidResponse,
) => false,
};
if transient {
Self::Transient(error.to_string())
} else {
Self::Build(error.to_string())
}
}
}
fn replace_auth_headers(mut headers: HeaderMap, auth: HeaderMap) -> HeaderMap {
for name in [
AUTHORIZATION.as_str(),
AGENT_ASSERTION,
CHATGPT_ACCOUNT_ID_HEADER,
"x-openai-fedramp",
] {
headers.remove(name);
}
headers.extend(auth);
headers
}

View File

@@ -0,0 +1,414 @@
//! Register and refresh a runtime within one selected credential source.
use crate::AgentHostAuthorization;
use crate::AuthenticatedActorAuthorization;
use crate::PlatformResourceSelection;
use crate::RegistrationError;
use crate::RuntimeAgentInstance;
use crate::RuntimeAuth;
use crate::RuntimeRegistration;
use crate::RuntimeRegistrationClient;
use crate::RuntimeRegistrationMetadata;
use codex_agent_identity::ChatGptEnvironment;
use codex_http_client::HttpClientFactory;
use codex_http_client::NetworkPolicyDenied;
use codex_login::AuthChangeState;
use codex_login::AuthManager;
use codex_login::AuthOwner;
use codex_login::CodexAuth;
use codex_login::RefreshTokenError;
use codex_login::auth::RefreshTokenFailedError;
use http::StatusCode;
use std::sync::Arc;
use tokio::sync::Mutex;
use url::Url;
/// A selected credential source and its registration state, retained across request preparation.
pub struct RuntimeAuthBinding {
pub(crate) credentials: Arc<AuthManager>,
pub(crate) registration: RegistrationTarget,
pub(crate) metadata: RuntimeRegistrationMetadata,
state: Mutex<Option<CachedRuntime>>,
}
#[derive(Clone)]
pub(crate) enum RegistrationTarget {
Explicit {
host: AgentHostAuthorization,
url: Url,
},
ChatGpt {
installation_id: String,
base_url: String,
},
}
impl RegistrationTarget {
fn host(&self) -> Result<AgentHostAuthorization, RegistrationError> {
match self {
Self::Explicit { host, .. } => Ok(host.clone()),
Self::ChatGpt {
installation_id, ..
} => Ok(AgentHostAuthorization::InstallationId {
installation_id: installation_id
.parse()
.map_err(|_| RegistrationError::InvalidRequest)?,
}),
}
}
fn url(&self) -> Result<Url, RegistrationError> {
match self {
Self::Explicit { url, .. } => Ok(url.clone()),
Self::ChatGpt { base_url, .. } => {
let url = match ChatGptEnvironment::from_chatgpt_base_url(base_url)
.map_err(|_| RegistrationError::InvalidEndpoint)?
{
ChatGptEnvironment::Production => crate::DEFAULT_REGISTRATION_URL,
ChatGptEnvironment::Staging => "https://auth.api.openai.org/agent/register",
};
url.parse().map_err(|_| RegistrationError::InvalidEndpoint)
}
}
}
}
struct CachedRuntime {
source_generation: u64,
selection: PlatformResourceSelection,
state: RuntimeState,
}
enum RuntimeState {
Pending { registration: RuntimeRegistration },
Ready { runtime: Arc<RuntimeAgentInstance> },
Denied { error: RegistrationError },
}
impl std::fmt::Debug for RuntimeAuthBinding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeAuthBinding").finish_non_exhaustive()
}
}
impl RuntimeAuthBinding {
pub(crate) fn new(
credentials: Arc<AuthManager>,
registration: RegistrationTarget,
metadata: RuntimeRegistrationMetadata,
) -> Self {
Self {
credentials,
registration,
metadata,
state: Mutex::new(None),
}
}
pub(crate) fn uses_credentials(&self, credentials: &Arc<AuthManager>) -> bool {
Arc::ptr_eq(&self.credentials, credentials)
}
pub fn auth_owner(&self) -> AuthOwner {
self.credentials.auth_owner()
}
pub fn registration_url(&self) -> Result<Url, RegistrationError> {
self.registration.url()
}
pub async fn auth(self: &Arc<Self>) -> Result<RuntimeAuth, RuntimeAuthError> {
self.auth_with_selection(&PlatformResourceSelection::default())
.await
}
/// Select auth and a runtime for the requested organization and project.
pub async fn auth_with_selection(
self: &Arc<Self>,
selection: &PlatformResourceSelection,
) -> Result<RuntimeAuth, RuntimeAuthError> {
self.select_auth(selection, /*expected_source*/ None).await
}
#[expect(
clippy::await_holding_invalid_type,
reason = "runtime initialization serializes registration and refresh for one credential source"
)]
async fn select_auth(
self: &Arc<Self>,
selection: &PlatformResourceSelection,
expected_source: Option<u64>,
) -> Result<RuntimeAuth, RuntimeAuthError> {
// This initializer's lock can span IO. No AuthManager lock is held across registration.
let mut state = self.state.lock().await;
self.check_source(expected_source)?;
let (auth, http_client_factory) = self
.credentials
.auth_with_http_client_factory()
.await
.ok_or(RuntimeAuthError::Unavailable)?;
let mut recovery = self.credentials.unauthorized_recovery();
let mut result = self
.auth_once(
&mut state,
auth,
http_client_factory,
selection,
expected_source,
)
.await;
while matches!(
&result,
Err(RuntimeAuthError::Registration(
RegistrationError::Rejected {
status: StatusCode::UNAUTHORIZED,
..
}
))
) && recovery.has_next()
{
self.check_source(expected_source)?;
recovery.next().await.map_err(|error| match error {
RefreshTokenError::Policy(denied) => RuntimeAuthError::Policy(denied),
RefreshTokenError::Permanent(error) => RuntimeAuthError::RefreshTokenFailed(error),
RefreshTokenError::Transient(_) => RuntimeAuthError::RefreshFailed,
})?;
let (auth, http_client_factory) = self
.credentials
.auth_with_http_client_factory()
.await
.ok_or(RuntimeAuthError::Unavailable)?;
result = self
.auth_once(
&mut state,
auth,
http_client_factory,
selection,
expected_source,
)
.await;
}
result
}
async fn auth_once(
self: &Arc<Self>,
state: &mut Option<CachedRuntime>,
auth: CodexAuth,
http_client_factory: HttpClientFactory,
selection: &PlatformResourceSelection,
expected_source: Option<u64>,
) -> Result<RuntimeAuth, RuntimeAuthError> {
let actor_auth = actor_authorization(&auth, selection)?;
let http_client_factory = http_client_factory.with_sensitive_header_protection();
let change_state = self.auth_state(&auth)?;
self.check_source(expected_source)?;
// Registered runtimes can serve different projects. Pending and denied
// registrations retain their original scope and idempotency key.
if state.as_ref().is_some_and(|cached| {
cached.source_generation != change_state.source_generation
|| cached.selection.organization_id != selection.organization_id
|| (!matches!(cached.state, RuntimeState::Ready { .. })
&& cached.selection != *selection)
}) {
*state = None;
}
let cached = match state {
Some(cached) => cached,
None => state.insert(CachedRuntime {
source_generation: change_state.source_generation,
selection: selection.clone(),
state: RuntimeState::Pending {
registration: RuntimeRegistration::new(
actor_auth.clone(),
self.registration.host()?,
self.metadata.clone(),
)
.map_err(|_| RuntimeAuthError::KeyGeneration)?,
},
}),
};
let runtime_state = &mut cached.state;
let registration = match runtime_state {
RuntimeState::Ready { runtime } => {
return self.selected_auth(
runtime.clone(),
auth,
http_client_factory,
change_state,
);
}
RuntimeState::Denied { error } => return Err(error.clone().into()),
RuntimeState::Pending { registration } => {
registration.request.actor_auth = actor_auth;
registration
}
};
let client =
RuntimeRegistrationClient::new(http_client_factory.clone(), self.registration.url()?)?;
let result = client.register(registration).await;
if self.auth_state(&auth)?.source_generation != change_state.source_generation {
// A late response must not publish an old identity after a credential switch.
*state = None;
return Err(RuntimeAuthError::Changed);
}
match result {
Ok(info) => {
let runtime = Arc::new(registration.finish(info));
*runtime_state = RuntimeState::Ready {
runtime: runtime.clone(),
};
self.selected_auth(runtime, auth, http_client_factory, change_state)
}
Err(
error @ RegistrationError::Rejected {
status: StatusCode::FORBIDDEN,
..
},
) => {
*runtime_state = RuntimeState::Denied {
error: error.clone(),
};
Err(error.into())
}
Err(error) => Err(error.into()),
}
}
fn selected_auth(
self: &Arc<Self>,
runtime: Arc<RuntimeAgentInstance>,
auth: CodexAuth,
http_client_factory: HttpClientFactory,
change_state: AuthChangeState,
) -> Result<RuntimeAuth, RuntimeAuthError> {
let owner = self
.credentials
.auth_owner_for(&auth)
.ok_or(RuntimeAuthError::Changed)?;
Ok(RuntimeAuth {
runtime,
auth,
http_client_factory,
change_state,
owner,
binding: Arc::clone(self),
})
}
/// Resolve auth for work whose routing, cache key, or payload uses a captured credential.
/// A same-source refresh is allowed; a different source must not take over that work.
/// This binds credential identity, not when the caller captured it. Restoring the exact
/// same credential can select a new runtime after logout; a different source cannot.
pub async fn auth_for(
self: &Arc<Self>,
expected: &CodexAuth,
selection: &PlatformResourceSelection,
) -> Result<RuntimeAuth, RuntimeAuthError> {
let source = self
.credentials
.auth_change_state_for(expected)
.ok_or(RuntimeAuthError::Changed)?;
self.auth_for_source(source.source_generation, selection)
.await
}
/// Select another request within a reusable client's original credential source.
pub async fn auth_for_source(
self: &Arc<Self>,
source_generation: u64,
selection: &PlatformResourceSelection,
) -> Result<RuntimeAuth, RuntimeAuthError> {
self.select_auth(selection, Some(source_generation)).await
}
fn check_source(&self, expected: Option<u64>) -> Result<(), RuntimeAuthError> {
if expected.is_some_and(|expected| {
self.credentials
.auth_change_state_receiver()
.borrow()
.source_generation
!= expected
}) {
return Err(RuntimeAuthError::Changed);
}
Ok(())
}
fn auth_state(&self, auth: &CodexAuth) -> Result<AuthChangeState, RuntimeAuthError> {
let state = self
.credentials
.auth_change_state_for(auth)
.ok_or(RuntimeAuthError::Changed)?;
if let Some(error) = self.credentials.refresh_failure_for_auth(auth) {
return Err(RuntimeAuthError::RefreshTokenFailed(error));
}
Ok(state)
}
}
fn actor_authorization(
auth: &CodexAuth,
selection: &PlatformResourceSelection,
) -> Result<AuthenticatedActorAuthorization, RuntimeAuthError> {
if !matches!(auth, CodexAuth::ApiKey(_)) && selection != &PlatformResourceSelection::default() {
return Err(RuntimeAuthError::UnsupportedResourceSelection);
}
let credential = auth
.get_token()
.map_err(|_| RuntimeAuthError::Unsupported)?
.into();
Ok(match auth {
CodexAuth::ApiKey(_) => AuthenticatedActorAuthorization::PlatformApiKey {
credential,
selection: selection.clone(),
},
CodexAuth::Chatgpt(_) | CodexAuth::ChatgptAuthTokens(_) => {
AuthenticatedActorAuthorization::Oauth { credential }
}
CodexAuth::PersonalAccessToken(_) => {
AuthenticatedActorAuthorization::PersonalAccessToken { credential }
}
CodexAuth::Headers(_)
| CodexAuth::AgentIdentity(_)
| CodexAuth::BedrockApiKey(_)
| CodexAuth::BedrockAccessKeys(_) => return Err(RuntimeAuthError::Unsupported),
})
}
#[derive(Debug, thiserror::Error)]
pub enum RuntimeAuthError {
#[error("runtime registration requires an actor credential")]
Unavailable,
#[error(
"this credential cannot register a runtime; sign in again with a supported OpenAI credential"
)]
Unsupported,
#[error("organization and project selection requires an OpenAI API key")]
UnsupportedResourceSelection,
#[error("invalid {0} resource selector")]
InvalidResourceSelection(&'static str),
#[error("credentials changed during runtime registration; try again")]
Changed,
#[error("runtime registration could not refresh actor credentials")]
RefreshFailed,
#[error(transparent)]
RefreshTokenFailed(#[from] RefreshTokenFailedError),
#[error("runtime auth task failed: {0}")]
Task(#[from] tokio::task::JoinError),
#[error("failed to generate runtime signing key")]
KeyGeneration,
#[error(transparent)]
Policy(#[from] NetworkPolicyDenied),
#[error(transparent)]
Registration(RegistrationError),
}
impl From<RegistrationError> for RuntimeAuthError {
fn from(error: RegistrationError) -> Self {
match error {
RegistrationError::Policy(denied) => Self::Policy(denied),
error => Self::Registration(error),
}
}
}

View File

@@ -0,0 +1,88 @@
//! Wire types for one-call runtime registration. Credentials are inputs, not identity claims.
use codex_utils_redacted_string::RedactedString;
use serde::Deserialize;
use serde::Serialize;
use uuid::Uuid;
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthenticatedActorAuthorization {
Oauth {
credential: RedactedString,
},
PersonalAccessToken {
credential: RedactedString,
},
PlatformApiKey {
credential: RedactedString,
#[serde(flatten)]
selection: PlatformResourceSelection,
},
}
/// API resource selectors to authenticate, not claims about the resulting actor.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
pub struct PlatformResourceSelection {
#[serde(skip_serializing_if = "Option::is_none")]
pub organization_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub project_id: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentHostAuthorization {
// An installation ID is tracking metadata, not proof of device ownership.
InstallationId { installation_id: Uuid },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RuntimeRole {
Orchestrator,
Executor,
OrchestratorAndExecutor,
}
#[derive(Clone, Debug, Serialize)]
pub struct RuntimeRegistrationMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub harness: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub harness_version: Option<String>,
pub role: RuntimeRole,
}
#[derive(Clone, Debug, Serialize)]
pub struct RuntimeRegistrationRequest {
pub actor_auth: AuthenticatedActorAuthorization,
pub agent_host_auth: AgentHostAuthorization,
pub public_key: String,
pub metadata: RuntimeRegistrationMetadata,
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
pub struct RuntimeRegistrationResponse {
pub runtime_agent_instance_id: String,
pub agent_host_id: String,
pub actor: ActorInfo,
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ActorInfo {
Chatgpt {
user_id: String,
account_id: String,
},
Platform {
user_id: String,
organization_id: String,
project_id: Option<String>,
},
}
#[cfg(test)]
#[path = "bootstrap_tests.rs"]
mod tests;

View File

@@ -0,0 +1,98 @@
//! Registration wire compatibility for each supported actor entry point.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn registration_serializes_the_supported_actor_authorizations() {
let installation_id = "00000000-0000-4000-8000-000000000001";
for (authorization, expected) in [
(
AuthenticatedActorAuthorization::Oauth {
credential: "secret".into(),
},
json!({"type": "oauth", "credential": "secret"}),
),
(
AuthenticatedActorAuthorization::PersonalAccessToken {
credential: "secret".into(),
},
json!({"type": "personal_access_token", "credential": "secret"}),
),
(
AuthenticatedActorAuthorization::PlatformApiKey {
selection: Default::default(),
credential: "secret".into(),
},
json!({"type": "platform_api_key", "credential": "secret"}),
),
] {
let request = RuntimeRegistrationRequest {
actor_auth: authorization,
agent_host_auth: AgentHostAuthorization::InstallationId {
installation_id: installation_id.parse().unwrap(),
},
public_key: "ssh-ed25519 public-key".into(),
metadata: RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: Some("0.0.0".into()),
role: RuntimeRole::OrchestratorAndExecutor,
},
};
assert!(!format!("{request:?}").contains("secret"));
assert_eq!(
serde_json::to_value(request).unwrap(),
json!({
"actor_auth": expected,
"agent_host_auth": {"type": "installation_id", "installation_id": installation_id},
"public_key": "ssh-ed25519 public-key",
"metadata": {"harness": "codex", "harness_version": "0.0.0", "role": "orchestrator_and_executor"},
})
);
}
}
#[test]
fn registration_decodes_composite_actor_contexts() {
for (actor, expected) in [
(
json!({"kind": "chatgpt", "user_id": "user", "account_id": "account"}),
ActorInfo::Chatgpt {
user_id: "user".into(),
account_id: "account".into(),
},
),
(
json!({"kind": "platform", "user_id": "user", "organization_id": "org", "project_id": "project"}),
ActorInfo::Platform {
user_id: "user".into(),
organization_id: "org".into(),
project_id: Some("project".into()),
},
),
] {
let response: RuntimeRegistrationResponse = serde_json::from_value(json!({
"runtime_agent_instance_id": "runtime", "agent_host_id": "host", "actor": actor,
}))
.unwrap();
assert_eq!(
response,
RuntimeRegistrationResponse {
runtime_agent_instance_id: "runtime".into(),
agent_host_id: "host".into(),
actor: expected,
}
);
}
assert!(
serde_json::from_value::<RuntimeRegistrationResponse>(
json!({"runtime_agent_instance_id": "runtime"})
)
.is_err()
);
assert!(
serde_json::from_value::<ActorInfo>(json!({"kind": "platform", "user_id": "user"}))
.is_err()
);
}

View File

@@ -0,0 +1,187 @@
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Result;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use codex_utils_absolute_path::AbsolutePathBuf;
use tokio::fs;
use uuid::Uuid;
const INSTALLATION_ID_FILENAME: &str = "installation_id";
pub async fn resolve_installation_id(codex_home: &AbsolutePathBuf) -> Result<String> {
let path = codex_home.join(INSTALLATION_ID_FILENAME);
fs::create_dir_all(codex_home).await?;
tokio::task::spawn_blocking(move || {
let mut options = OpenOptions::new();
options.read(true).write(true).create(true);
#[cfg(unix)]
{
options.mode(0o644);
}
let mut file = options.open(&path)?;
file.lock_shared()?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
if Uuid::parse_str(contents.trim()).is_err() {
// Another process can initialize the ID while we switch locks. Read it again
// under the exclusive lock before deciding whether to create a new one.
file.unlock()?;
file.lock()?;
file.seek(SeekFrom::Start(0))?;
contents.clear();
file.read_to_string(&mut contents)?;
}
#[cfg(unix)]
{
let metadata = file.metadata()?;
let current_mode = metadata.permissions().mode() & 0o777;
if current_mode != 0o644 {
let mut permissions = metadata.permissions();
permissions.set_mode(0o644);
file.set_permissions(permissions)?;
}
}
let trimmed = contents.trim();
if !trimmed.is_empty()
&& let Ok(existing) = Uuid::parse_str(trimmed)
{
return Ok(existing.to_string());
}
let installation_id = Uuid::new_v4().to_string();
file.set_len(0)?;
file.seek(SeekFrom::Start(0))?;
file.write_all(installation_id.as_bytes())?;
file.flush()?;
file.sync_all()?;
Ok(installation_id)
})
.await?
}
#[cfg(test)]
mod tests {
use super::INSTALLATION_ID_FILENAME;
use super::resolve_installation_id;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use uuid::Uuid;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
#[tokio::test]
async fn resolve_installation_id_generates_and_persists_uuid() {
let codex_home = TempDir::new().expect("create temp dir");
let codex_home_abs = AbsolutePathBuf::from_absolute_path(codex_home.path())
.expect("absolute temporary directory");
let persisted_path = codex_home.path().join(INSTALLATION_ID_FILENAME);
let installation_id = resolve_installation_id(&codex_home_abs)
.await
.expect("resolve installation id");
assert_eq!(
std::fs::read_to_string(&persisted_path).expect("read persisted installation id"),
installation_id
);
assert!(Uuid::parse_str(&installation_id).is_ok());
#[cfg(unix)]
{
let mode = std::fs::metadata(&persisted_path)
.expect("read installation id metadata")
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o644);
}
}
#[tokio::test]
async fn resolve_installation_id_reuses_existing_uuid() {
let codex_home = TempDir::new().expect("create temp dir");
let codex_home_abs = AbsolutePathBuf::from_absolute_path(codex_home.path())
.expect("absolute temporary directory");
let existing = Uuid::new_v4().to_string().to_uppercase();
std::fs::write(
codex_home.path().join(INSTALLATION_ID_FILENAME),
existing.clone(),
)
.expect("write installation id");
#[cfg(unix)]
let reader = {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(codex_home.path().join(INSTALLATION_ID_FILENAME))
.expect("open existing ID");
file.set_permissions(std::fs::Permissions::from_mode(0o600))
.expect("set existing permissions");
file.lock_shared().expect("share existing ID");
file
};
let resolved = tokio::time::timeout(
std::time::Duration::from_secs(1),
resolve_installation_id(&codex_home_abs),
)
.await
.expect("valid ID readers must not serialize")
.expect("resolve installation id");
assert_eq!(
resolved,
Uuid::parse_str(existing.as_str())
.expect("parse existing installation id")
.to_string()
);
#[cfg(unix)]
assert_eq!(
reader
.metadata()
.expect("read installation id metadata")
.permissions()
.mode()
& 0o777,
0o644
);
}
#[tokio::test]
async fn resolve_installation_id_rewrites_invalid_file_contents() {
let codex_home = TempDir::new().expect("create temp dir");
let codex_home_abs = AbsolutePathBuf::from_absolute_path(codex_home.path())
.expect("absolute temporary directory");
std::fs::write(
codex_home.path().join(INSTALLATION_ID_FILENAME),
"not-a-uuid",
)
.expect("write invalid installation id");
let resolved = resolve_installation_id(&codex_home_abs)
.await
.expect("resolve installation id");
assert!(Uuid::parse_str(&resolved).is_ok());
assert_eq!(
std::fs::read_to_string(codex_home.path().join(INSTALLATION_ID_FILENAME))
.expect("read rewritten installation id"),
resolved
);
}
}

View File

@@ -0,0 +1,37 @@
//! Ephemeral OpenAI runtimes: composite registration and per-request assertions.
mod actor;
mod auth;
mod binding;
mod bootstrap;
mod installation_id;
mod manager;
mod registration;
mod runtime;
pub use actor::AgentHost;
pub use actor::AuthenticatedActor;
pub use bootstrap::ActorInfo;
pub use bootstrap::AgentHostAuthorization;
pub use bootstrap::AuthenticatedActorAuthorization;
pub use bootstrap::PlatformResourceSelection;
pub use bootstrap::RuntimeRegistrationMetadata;
pub use bootstrap::RuntimeRegistrationRequest;
pub use bootstrap::RuntimeRegistrationResponse;
pub use bootstrap::RuntimeRole;
pub use codex_http_client::is_openai_api_url;
pub use auth::RuntimeAuth;
pub use binding::RuntimeAuthBinding;
pub use binding::RuntimeAuthError;
pub use installation_id::resolve_installation_id;
pub use manager::RuntimeAuthManager;
pub use registration::DEFAULT_REGISTRATION_URL;
pub use registration::RegistrationError;
pub use registration::RegistrationErrorCode;
pub use registration::RuntimeRegistrationClient;
pub use runtime::RuntimeAgentInstance;
pub use runtime::RuntimeRegistration;
/// Harness-owned lazy runtime, shared before any request requires registration.
pub type RuntimeAuthSlot = std::sync::Arc<std::sync::OnceLock<std::sync::Arc<RuntimeAuthManager>>>;

View File

@@ -0,0 +1,198 @@
//! Bind credential sources to shared runtime registrations.
use crate::AgentHostAuthorization;
use crate::PlatformResourceSelection;
use crate::RegistrationError;
use crate::RuntimeAuth;
use crate::RuntimeAuthBinding;
use crate::RuntimeAuthError;
use crate::RuntimeRegistrationMetadata;
use crate::binding::RegistrationTarget;
use codex_login::AuthManager;
use codex_login::AuthRuntimeConfig;
use codex_login::CodexAuth;
use std::sync::Arc;
use url::Url;
/// Shares registration state across requests using the same credential source and context.
pub struct RuntimeAuthManager {
login: Arc<RuntimeAuthBinding>,
registrations: std::sync::Mutex<Vec<CredentialRegistration>>,
}
enum CredentialRegistration {
Provider(Arc<RuntimeAuthBinding>),
ApiKey(Arc<RuntimeAuthBinding>),
}
impl std::fmt::Debug for RuntimeAuthManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeAuthManager").finish_non_exhaustive()
}
}
impl RuntimeAuthManager {
pub fn uses_credentials(&self, credentials: &Arc<AuthManager>) -> bool {
self.login.uses_credentials(credentials)
}
pub fn new(
credentials: Arc<AuthManager>,
host: AgentHostAuthorization,
metadata: RuntimeRegistrationMetadata,
registration_url: Url,
) -> Self {
Self::from_registration(
credentials,
RegistrationTarget::Explicit {
host,
url: registration_url,
},
metadata,
)
}
/// Resolve the ChatGPT registration origin only when a first-party request needs a runtime.
pub fn for_chatgpt(
credentials: Arc<AuthManager>,
installation_id: String,
base_url: String,
metadata: RuntimeRegistrationMetadata,
) -> Self {
Self::from_registration(
credentials,
RegistrationTarget::ChatGpt {
installation_id,
base_url,
},
metadata,
)
}
fn from_registration(
credentials: Arc<AuthManager>,
registration: RegistrationTarget,
metadata: RuntimeRegistrationMetadata,
) -> Self {
Self {
login: Arc::new(RuntimeAuthBinding::new(credentials, registration, metadata)),
registrations: std::sync::Mutex::new(Vec::new()),
}
}
/// Construct a Codex runtime owner without registering it or generating its key.
pub fn for_codex(
credentials: Arc<AuthManager>,
chatgpt_base_url: &str,
installation_id: &str,
) -> Self {
Self::for_chatgpt(
credentials,
installation_id.to_owned(),
chatgpt_base_url.to_owned(),
RuntimeRegistrationMetadata {
harness: Some("codex".to_string()),
harness_version: Some(env!("CARGO_PKG_VERSION").to_string()),
role: crate::RuntimeRole::Orchestrator,
},
)
}
pub fn registration_url(&self) -> Result<Url, RegistrationError> {
self.login.registration_url()
}
pub async fn auth(&self) -> Result<RuntimeAuth, RuntimeAuthError> {
self.login.auth().await
}
pub async fn auth_with_selection(
&self,
selection: &PlatformResourceSelection,
) -> Result<RuntimeAuth, RuntimeAuthError> {
self.login.auth_with_selection(selection).await
}
pub async fn auth_for(
&self,
expected: &CodexAuth,
selection: &PlatformResourceSelection,
) -> Result<RuntimeAuth, RuntimeAuthError> {
self.login.auth_for(expected, selection).await
}
pub async fn auth_for_source(
&self,
source_generation: u64,
selection: &PlatformResourceSelection,
) -> Result<RuntimeAuth, RuntimeAuthError> {
self.login
.auth_for_source(source_generation, selection)
.await
}
/// Bind a login or command-backed credential without changing its refresh lifecycle.
pub fn bind(&self, credentials: Arc<AuthManager>) -> Arc<RuntimeAuthBinding> {
if self.login.uses_credentials(&credentials) {
return Arc::clone(&self.login);
}
let mut registrations = self
.registrations
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(binding) = registrations.iter().find_map(|entry| match entry {
CredentialRegistration::Provider(binding) if binding.uses_credentials(&credentials) => {
Some(binding)
}
_ => None,
}) {
return Arc::clone(binding);
}
let binding = Arc::new(RuntimeAuthBinding::new(
credentials,
self.login.registration.clone(),
self.login.metadata.clone(),
));
registrations.push(CredentialRegistration::Provider(Arc::clone(&binding)));
binding
}
/// An explicit key is independent of login storage and command output, even when bytes match.
pub fn bind_api_key(
&self,
api_key: &str,
runtime: &AuthRuntimeConfig,
) -> Arc<RuntimeAuthBinding> {
let mut registrations = self
.registrations
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(binding) = registrations.iter().find_map(|entry| match entry {
CredentialRegistration::ApiKey(binding)
if binding
.credentials
.auth_cached()
.as_ref()
.and_then(CodexAuth::api_key)
== Some(api_key)
&& binding.credentials.runtime_config() == *runtime =>
{
Some(binding)
}
_ => None,
}) {
return Arc::clone(binding);
}
let binding = Arc::new(RuntimeAuthBinding::new(
AuthManager::from_api_key(api_key, runtime.clone()),
self.login.registration.clone(),
self.login.metadata.clone(),
));
registrations.push(CredentialRegistration::ApiKey(Arc::clone(&binding)));
binding
}
}
#[cfg(test)]
#[path = "manager_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,157 @@
//! Direct composite bootstrap. Credentials are sent only in the body, never through redirects.
use crate::RuntimeRegistration;
use crate::RuntimeRegistrationResponse;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::HttpError;
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
use http::StatusCode;
use serde::Deserialize;
use std::time::Duration;
use url::Url;
pub const DEFAULT_REGISTRATION_URL: &str = "https://auth.openai.com/agent/register";
const MAX_BODY_BYTES: usize = 64 * 1024;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
/// Makes one bounded attempt. Callers reuse the pending registration when retrying.
pub struct RuntimeRegistrationClient {
http: RouteAwareClientPool,
url: Url,
}
impl RuntimeRegistrationClient {
pub fn new(factory: HttpClientFactory, url: Url) -> Result<Self, RegistrationError> {
let loopback = url.host_str().is_some_and(|host| {
host == "localhost"
|| host == "[::1]"
|| host
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback())
});
if !(url.scheme() == "https" || (url.scheme() == "http" && loopback))
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(RegistrationError::InvalidEndpoint);
}
Ok(Self {
http: RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_redirects_or_request_logging(
factory,
ClientRouteClass::Auth,
),
url,
})
}
pub async fn register(
&self,
registration: &RuntimeRegistration,
) -> Result<RuntimeRegistrationResponse, RegistrationError> {
let body = serde_json::to_vec(&registration.request)
.map_err(|_| RegistrationError::InvalidRequest)?;
if body.len() > MAX_BODY_BYTES {
return Err(RegistrationError::InvalidRequest);
}
let mut response = self
.http
.post(self.url.as_str())
.header("Content-Type", "application/json")
.header(
"Idempotency-Key",
registration.initialization_id.to_string(),
)
.timeout(REQUEST_TIMEOUT)
.body(body)
.send()
.await
.map_err(|error| match error {
RouteAwareRequestError::Policy(denied) => RegistrationError::Policy(denied),
_ => RegistrationError::Transport,
})?;
let status = response.status();
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|error| match error {
HttpError::Policy(denied) => RegistrationError::Policy(denied),
_ => RegistrationError::Transport,
})? {
if chunk.len() > MAX_BODY_BYTES - body.len() {
return Err(RegistrationError::InvalidResponse);
}
body.extend_from_slice(&chunk);
}
if status != StatusCode::OK {
let code = serde_json::from_slice::<ErrorEnvelope>(&body)
.ok()
.map(|e| e.error.code);
return Err(RegistrationError::Rejected { status, code });
}
let info: crate::RuntimeRegistrationResponse =
serde_json::from_slice(&body).map_err(|_| RegistrationError::InvalidResponse)?;
if info.runtime_agent_instance_id.is_empty() || info.agent_host_id.is_empty() {
return Err(RegistrationError::InvalidResponse);
}
Ok(info)
}
}
/// Errors intentionally omit raw transport details and server messages, which can contain secrets.
#[derive(Clone, Debug, thiserror::Error)]
pub enum RegistrationError {
#[error(
"runtime registration requires a secure endpoint without credentials or query parameters"
)]
InvalidEndpoint,
#[error("invalid runtime registration request")]
InvalidRequest,
#[error(transparent)]
Policy(#[from] NetworkPolicyDenied),
#[error("runtime registration transport failed")]
Transport,
#[error("invalid runtime registration response")]
InvalidResponse,
#[error("runtime registration rejected ({status}, {code:?})")]
Rejected {
status: StatusCode,
code: Option<RegistrationErrorCode>,
},
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RegistrationErrorCode {
TokenExpired,
RuntimeActorInvalid,
RuntimeInstanceRevoked,
RuntimeActorSourceInactive,
RuntimeInputInvalid,
RuntimeIdempotencyKeyInvalid,
RuntimeActorConflict,
RuntimeHostConflict,
RuntimeRegistrationConflict,
RuntimeInputTooLarge,
RuntimeRateLimited,
RuntimeVerificationUnavailable,
NotFound,
#[serde(other)]
Unknown,
}
#[derive(Deserialize)]
struct ErrorEnvelope {
error: ErrorDetail,
}
#[derive(Deserialize)]
struct ErrorDetail {
code: RegistrationErrorCode,
}
#[cfg(test)]
#[path = "registration_tests.rs"]
mod tests;

View File

@@ -0,0 +1,272 @@
//! Exercise bootstrap and signing through a real HTTP server without changing process auth.
use super::*;
use crate::AgentHostAuthorization;
use crate::AuthenticatedActorAuthorization;
use crate::RuntimeAgentInstance;
use crate::RuntimeRegistrationMetadata;
use crate::RuntimeRole;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_http_client::DestinationPolicy;
use codex_http_client::NetworkPolicyController;
use codex_http_client::OutboundProxyPolicy;
use ed25519_dalek::Signature;
use ed25519_dalek::VerifyingKey;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use uuid::Uuid;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn pending() -> RuntimeRegistration {
RuntimeRegistration::new(
AuthenticatedActorAuthorization::PlatformApiKey {
selection: Default::default(),
credential: "actor-secret".into(),
},
AgentHostAuthorization::InstallationId {
installation_id: Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: Some("1.0.0".into()),
role: RuntimeRole::OrchestratorAndExecutor,
},
)
.unwrap()
}
fn client(server: &MockServer) -> RuntimeRegistrationClient {
let registration_url = Url::parse(DEFAULT_REGISTRATION_URL).unwrap();
let endpoint = Url::parse(&server.uri())
.unwrap()
.join(registration_url.path())
.unwrap();
RuntimeRegistrationClient::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
endpoint,
)
.unwrap()
}
fn registered() -> Value {
json!({
"runtime_agent_instance_id": "agent-instance-test",
"agent_host_id": "host-test",
"actor": {
"kind": "platform",
"user_id": "user-test",
"organization_id": "org-test",
"project_id": "proj-test"
}
})
}
#[tokio::test]
async fn registration_retries_keep_the_key_and_sign_fresh_assertions() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(registered()))
.expect(2)
.mount(&server)
.await;
let pending = pending();
let client = client(&server);
let info = client.register(&pending).await.unwrap();
let retry_info = client.register(&pending).await.unwrap();
assert_eq!(info, retry_info);
let runtime = pending.finish(info);
let retry = pending.finish(retry_info);
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].body, requests[1].body);
for request in &requests {
assert!(!request.headers.contains_key("authorization"));
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
assert_eq!(
request.headers["idempotency-key"],
pending.initialization_id.to_string()
);
}
let request: Value = requests[0].body_json().unwrap();
assert_eq!(request, serde_json::to_value(&pending.request).unwrap());
let key = STANDARD
.decode(
request["public_key"]
.as_str()
.unwrap()
.split_once(' ')
.unwrap()
.1,
)
.unwrap();
let key = VerifyingKey::from_bytes(key[19..].try_into().unwrap()).unwrap();
let before = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let first = verify_assertion(&runtime, &key);
let second = verify_assertion(&retry, &key);
let after = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
assert_ne!(first["id"], second["id"]);
for payload in [first, second] {
assert!(Uuid::parse_str(payload["id"].as_str().unwrap()).is_ok());
assert!((before..=after).contains(&payload["iat"].as_u64().unwrap()));
assert_eq!(
payload,
json!({
"version": 1, "runtime_agent_instance": "agent-instance-test",
"iat": payload["iat"], "id": payload["id"]
})
);
}
}
fn verify_assertion(runtime: &RuntimeAgentInstance, key: &VerifyingKey) -> Value {
let assertion = runtime.assertion().unwrap();
let parts: Vec<_> = assertion.split('.').collect();
assert_eq!(parts.len(), 4);
assert_eq!(parts[0], "1");
assert!(!assertion.contains('='));
let protected: Value =
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[1]).unwrap()).unwrap();
assert_eq!(
protected,
json!({"alg": "EdDSA", "typ": "openai-agent-assertion+jws"})
);
let signature = Signature::from_slice(&URL_SAFE_NO_PAD.decode(parts[3]).unwrap()).unwrap();
key.verify_strict(format!("{}.{}", parts[1], parts[2]).as_bytes(), &signature)
.unwrap();
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[2]).unwrap()).unwrap()
}
#[test]
fn new_initializations_use_new_keys_and_retry_ids() {
let first = pending();
let second = pending();
assert_ne!(first.initialization_id, second.initialization_id);
assert_ne!(first.request.public_key, second.request.public_key);
}
#[tokio::test]
async fn rejected_registration_preserves_only_status_and_known_error_codes() {
for (status, code, expected) in [
(401, "token_expired", RegistrationErrorCode::TokenExpired),
(
403,
"runtime_instance_revoked",
RegistrationErrorCode::RuntimeInstanceRevoked,
),
(500, "secret-from-server", RegistrationErrorCode::Unknown),
] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"error": {"code": code, "message": "secret-from-server"}
})))
.expect(1)
.mount(&server)
.await;
let error = client(&server).register(&pending()).await.unwrap_err();
assert!(!format!("{error} {error:?}").contains("secret-from-server"));
assert!(
matches!(error, RegistrationError::Rejected { status: actual, code: Some(actual_code) }
if actual.as_u16() == status && actual_code == expected)
);
}
}
#[tokio::test]
async fn registration_preserves_policy_revocation() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(registered()))
.expect(1)
.mount(&server)
.await;
let controller = NetworkPolicyController::default();
let policy = controller.policy();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
let client = RuntimeRegistrationClient::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone().for_current_account()),
format!("{}/agent/register", server.uri()).parse().unwrap(),
)
.unwrap();
let pending = pending();
client.register(&pending).await.unwrap();
policy.invalidate();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
assert!(matches!(
client.register(&pending).await,
Err(RegistrationError::Policy(NetworkPolicyDenied::Revoked))
));
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}
#[tokio::test]
async fn registration_rejects_incomplete_or_oversized_responses() {
for body in [
json!({"runtime_agent_instance_id": "old-response"}).to_string(),
"x".repeat(MAX_BODY_BYTES + 1),
] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200).set_body_string(body))
.expect(1)
.mount(&server)
.await;
assert!(matches!(
client(&server).register(&pending()).await,
Err(RegistrationError::InvalidResponse)
));
}
}
#[tokio::test]
async fn registration_never_forwards_credentials_through_a_redirect() {
let server = MockServer::start().await;
let destination = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(307).insert_header("Location", destination.uri()))
.expect(1)
.mount(&server)
.await;
assert!(matches!(
client(&server).register(&pending()).await,
Err(RegistrationError::Rejected {
status: StatusCode::TEMPORARY_REDIRECT,
..
})
));
assert!(destination.received_requests().await.unwrap().is_empty());
}
#[test]
fn registration_rejects_unsafe_endpoints() {
for endpoint in [
"http://auth.example.com/register",
"https://user:secret@auth.example.com/register",
"https://auth.example.com/register?token=secret",
] {
assert!(matches!(
RuntimeRegistrationClient::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
endpoint.parse().unwrap(),
),
Err(RegistrationError::InvalidEndpoint)
));
}
}

View File

@@ -0,0 +1,123 @@
//! A pending registration keeps its key and retry ID; a registered runtime signs v1 assertions.
use crate::AgentHost;
use crate::AuthenticatedActor;
use crate::RuntimeRegistrationRequest;
use crate::RuntimeRegistrationResponse;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_agent_identity::encode_ssh_ed25519_public_key;
use codex_utils_redacted_string::RedactedString;
use ed25519_dalek::Signer;
use ed25519_dalek::SigningKey;
use rand::TryRngCore;
use rand::rngs::OsRng;
use serde_json::json;
use std::fmt;
use std::io;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use uuid::Uuid;
use zeroize::Zeroizing;
/// One initialization, including retries. Neither this key nor the resulting runtime is persisted.
pub struct RuntimeRegistration {
pub(crate) initialization_id: Uuid,
pub(crate) request: RuntimeRegistrationRequest,
pub(crate) signing_key: Arc<SigningKey>,
}
impl RuntimeRegistration {
pub fn new(
actor: crate::AuthenticatedActorAuthorization,
host: crate::AgentHostAuthorization,
metadata: crate::RuntimeRegistrationMetadata,
) -> io::Result<Self> {
let mut seed = Zeroizing::new([0u8; 32]);
OsRng
.try_fill_bytes(seed.as_mut())
.map_err(|_| io::Error::other("failed to generate runtime signing key"))?;
let signing_key = SigningKey::from_bytes(&seed);
Ok(Self {
initialization_id: Uuid::new_v4(),
request: RuntimeRegistrationRequest {
actor_auth: actor,
agent_host_auth: host,
public_key: encode_ssh_ed25519_public_key(&signing_key.verifying_key()),
metadata,
},
signing_key: Arc::new(signing_key),
})
}
pub(crate) fn finish(&self, info: RuntimeRegistrationResponse) -> RuntimeAgentInstance {
RuntimeAgentInstance {
id: info.runtime_agent_instance_id,
actor: AuthenticatedActor { info: info.actor },
host: AgentHost {
id: info.agent_host_id,
authorization: self.request.agent_host_auth.clone(),
},
signing_key: self.signing_key.clone(),
}
}
}
/// A server-registered identity and its memory-only signer, shared for this runtime's lifetime.
pub struct RuntimeAgentInstance {
id: String,
pub(crate) actor: AuthenticatedActor,
host: AgentHost,
signing_key: Arc<SigningKey>,
}
impl RuntimeAgentInstance {
pub fn id(&self) -> &str {
&self.id
}
pub fn actor(&self) -> &AuthenticatedActor {
&self.actor
}
pub fn host(&self) -> &AgentHost {
&self.host
}
/// Make a fresh assertion for each request attempt or connection handshake.
pub fn assertion(&self) -> io::Result<RedactedString> {
let issued_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| io::Error::other("system clock is before the Unix epoch"))?
.as_secs();
let protected =
URL_SAFE_NO_PAD.encode(br#"{"alg":"EdDSA","typ":"openai-agent-assertion+jws"}"#);
let payload = URL_SAFE_NO_PAD.encode(
json!({
"version": 1,
"runtime_agent_instance": self.id,
"iat": issued_at,
"id": Uuid::new_v4(),
})
.to_string(),
);
let signing_input = format!("{protected}.{payload}");
let signature =
URL_SAFE_NO_PAD.encode(self.signing_key.sign(signing_input.as_bytes()).to_bytes());
// The outer version routes the assertion; it is not part of the JWS signing input.
let assertion = format!("1.{signing_input}.{signature}");
if assertion.len() > 8192 {
return Err(io::Error::other("runtime assertion exceeds the size limit"));
}
Ok(assertion.into())
}
}
impl fmt::Debug for RuntimeAgentInstance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RuntimeAgentInstance")
.field("runtime_agent_instance_id", &self.id)
.finish_non_exhaustive()
}
}