Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,9 @@ third-party connectors; the built-in connectors are not trait objects.
`services/worker/src/<name>.rs` using the connection config and leased credential.
3. Check URL-typed config fields in `validate_connection_urls` and, when a probe exists,
`probe_connection` (`crates/orbit-api/src/handlers/catalog.rs`); use
`orbit_security::guarded_client` for every HTTP call.
`orbit_security::guarded_client_with_policy` with `state.outbound` (the API's outbound
policy) for every HTTP call, so tests can inject a policy instead of setting environment
variables.
4. Store credentials only as encrypted `secret_ref` handles.
5. Enforce capability allowlists and autonomy in the platform (the broker), not in the client.
6. Add mock/webhook tests in `crates/orbit-api/tests`; never commit real credentials.
Expand Down
4 changes: 4 additions & 0 deletions changelog.d/445.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- The API reads the outbound network policy (`ORBIT_OUTBOUND_*`) once at startup and keeps
it in its state, and the integration tests inject a policy and a licence instead of
changing process environment variables, so a test that allows loopback can no longer
loosen the outbound guard for other tests (#445).
7 changes: 5 additions & 2 deletions crates/orbit-api/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,14 +358,17 @@ impl WorkSourceConnection {
.to_string(),
other => anyhow::bail!("unsupported work source provider '{other}'"),
};
orbit_security::check_outbound_url(&base_url, &orbit_security::OutboundPolicy::from_env())
orbit_security::check_outbound_url(&base_url, &state.outbound)
.await
.map_err(|error| anyhow::anyhow!("work source baseUrl refused: {error}"))?;
Ok(Self {
config: connection.config.clone(),
base_url,
token,
client: orbit_security::guarded_client(std::time::Duration::from_secs(20)),
client: orbit_security::guarded_client_with_policy(
std::time::Duration::from_secs(20),
state.outbound.clone(),
),
})
}
}
Expand Down
57 changes: 36 additions & 21 deletions crates/orbit-api/src/handlers/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,13 @@ pub async fn probe_provider(
.map(|value| value.expose().to_string()),
None => None,
};
let result = probe_endpoint(kind, &provider.config, credential.as_deref()).await;
let result = probe_endpoint(
kind,
&provider.config,
credential.as_deref(),
&state.outbound,
)
.await;
state.metrics.provider_probe(kind.as_str(), result.ok);

// Persist discovered models so agent/worker selectors can use them without a manual
Expand Down Expand Up @@ -392,7 +398,7 @@ pub async fn probe_unsaved(
return Err(ApiError::validation(report.issues));
}
// Never persist or log the credential used for this probe.
let result = probe_endpoint(kind, &config, body.credential.as_deref()).await;
let result = probe_endpoint(kind, &config, body.credential.as_deref(), &state.outbound).await;
state.metrics.provider_probe(kind.as_str(), result.ok);
Ok(Json(result))
}
Expand All @@ -401,6 +407,7 @@ async fn probe_endpoint(
kind: ProviderKind,
config: &serde_json::Value,
credential: Option<&str>,
policy: &orbit_security::OutboundPolicy,
) -> ProviderProbeResponse {
let base_url = match config.get("baseUrl").and_then(|v| v.as_str()) {
Some(value) if !value.is_empty() => value,
Expand Down Expand Up @@ -428,17 +435,18 @@ async fn probe_endpoint(
};
}
let url = format!("{}/models", base_url.trim_end_matches('/'));
if let Err(error) =
orbit_security::check_outbound_url(&url, &orbit_security::OutboundPolicy::from_env()).await
{
if let Err(error) = orbit_security::check_outbound_url(&url, policy).await {
return ProviderProbeResponse {
ok: false,
latency_ms: 0,
models: vec![],
error: Some(format!("endpoint refused ({})", error.category())),
};
}
let client = orbit_security::guarded_client(std::time::Duration::from_secs(10));
let client = orbit_security::guarded_client_with_policy(
std::time::Duration::from_secs(10),
policy.clone(),
);
let mut request = client.get(&url);
if let Some(credential) = credential {
request = if kind == ProviderKind::Anthropic {
Expand Down Expand Up @@ -532,12 +540,15 @@ fn sanitize_provider_config(config: &mut serde_json::Value) {
const CONNECTION_URL_FIELDS: [&str; 4] = ["baseUrl", "cloneBaseUrl", "url", "apiServer"];

/// Validate URL-typed connection config fields against the outbound policy
/// (`ORBIT_OUTBOUND_ALLOW_PRIVATE` / `ORBIT_OUTBOUND_ALLOWED_HOSTS`) and the Kubernetes
/// namespace fields (`defaultNamespace`, `namespaces`), which are spliced into request
/// paths (#391); errors are 422s on the offending field name. A kubeconfig credential's
/// own `server` is checked when the Kubernetes client connects.
pub(crate) async fn validate_connection_config(config: &serde_json::Value) -> Result<(), ApiError> {
let policy = orbit_security::OutboundPolicy::from_env();
/// (`ORBIT_OUTBOUND_ALLOW_PRIVATE` / `ORBIT_OUTBOUND_ALLOWED_HOSTS`, read once into
/// `AppState::outbound`) and the Kubernetes namespace fields (`defaultNamespace`,
/// `namespaces`), which are spliced into request paths (#391); errors are 422s on the
/// offending field name. A kubeconfig credential's own `server` is checked when the
/// Kubernetes client connects.
pub(crate) async fn validate_connection_config(
config: &serde_json::Value,
policy: &orbit_security::OutboundPolicy,
) -> Result<(), ApiError> {
let mut issues = Vec::new();
for field in CONNECTION_URL_FIELDS {
let Some(value) = config.get(field).and_then(|v| v.as_str()) else {
Expand All @@ -547,7 +558,7 @@ pub(crate) async fn validate_connection_config(config: &serde_json::Value) -> Re
if value.is_empty() {
continue;
}
if let Err(error) = orbit_security::check_outbound_url(value, &policy).await {
if let Err(error) = orbit_security::check_outbound_url(value, policy).await {
issues.push(orbit_domain::ValidationIssue::new(field, error.to_string()));
}
}
Expand Down Expand Up @@ -609,7 +620,7 @@ pub async fn create_connection(
.get_connector_by_slug(auth.org_id, &body.connector_slug)
.await?
.ok_or_else(|| ApiError::not_found(format!("connector '{}'", body.connector_slug)))?;
validate_connection_config(&body.config).await?;
validate_connection_config(&body.config, &state.outbound).await?;

let secret_ref = if let Some(credential) = &body.credential {
if credential.trim().is_empty() {
Expand Down Expand Up @@ -697,7 +708,7 @@ pub async fn update_connection(
&existing.visibility,
)?;
if let Some(config) = &body.config {
validate_connection_config(config).await?;
validate_connection_config(config, &state.outbound).await?;
// A stored credential must never follow an edited endpoint (#321), the same rule
// providers follow: changing a URL field requires the credential for it.
if existing.credential_ref.is_some() && body.credential.is_none() {
Expand Down Expand Up @@ -883,6 +894,7 @@ pub async fn test_connection(
&row.connector_slug,
&row.connection.config,
credential.as_deref(),
&state.outbound,
)
.await
else {
Expand Down Expand Up @@ -920,6 +932,7 @@ async fn probe_connection(
slug: &str,
config: &serde_json::Value,
credential: Option<&str>,
policy: &orbit_security::OutboundPolicy,
) -> Option<(bool, Option<u16>, String)> {
Some(match slug {
// The mock connector talks to nothing; a stored connection is always usable.
Expand All @@ -929,13 +942,13 @@ async fn probe_connection(
"Mock connector needs no external service".into(),
),
"gitlab" | "github" | "webhook" | "kubernetes" => {
probe_supported_connection(slug, config, credential).await
probe_supported_connection(slug, config, credential, policy).await
}
"s3" => {
let result = async {
let (config, credentials) =
orbit_s3::S3Config::from_connection(config, credential)?;
let client = orbit_s3::S3Client::new(config, credentials)?;
let client = orbit_s3::S3Client::with_policy(config, credentials, policy.clone())?;
match client.list_buckets().await {
Ok(buckets) => Ok(format!(
"S3 reachable; {} allowed bucket(s) visible",
Expand Down Expand Up @@ -982,8 +995,12 @@ async fn probe_supported_connection(
slug: &str,
config: &serde_json::Value,
credential: Option<&str>,
policy: &orbit_security::OutboundPolicy,
) -> (bool, Option<u16>, String) {
let client = orbit_security::guarded_client(std::time::Duration::from_secs(10));
let client = orbit_security::guarded_client_with_policy(
std::time::Duration::from_secs(10),
policy.clone(),
);
let (url, request) = match slug {
"gitlab" | "github" => {
let base = config
Expand Down Expand Up @@ -1045,9 +1062,7 @@ async fn probe_supported_connection(
);
}
};
if let Err(error) =
orbit_security::check_outbound_url(&url, &orbit_security::OutboundPolicy::from_env()).await
{
if let Err(error) = orbit_security::check_outbound_url(&url, policy).await {
return (
false,
None,
Expand Down
6 changes: 5 additions & 1 deletion crates/orbit-api/src/handlers/import_portable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,11 @@ async fn translate(
if config.is_null() {
config = json!({});
}
if let Err(error) = crate::handlers::catalog::validate_connection_config(&config).await
if let Err(error) = crate::handlers::catalog::validate_connection_config(
&config,
&resolver.state.outbound,
)
.await
{
for issue in &error.details {
found.issue(issue.path.clone(), issue.message.clone());
Expand Down
48 changes: 32 additions & 16 deletions crates/orbit-api/src/handlers/outputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,11 @@ fn credential(body: &OutputRequest, kind: OutputKind) -> Option<&str> {
.filter(|value| !value.is_empty())
}

async fn guard_credential(kind: OutputKind, value: &str) -> Result<(), ApiError> {
async fn guard_credential(
kind: OutputKind,
value: &str,
policy: &OutboundPolicy,
) -> Result<(), ApiError> {
match kind {
OutputKind::Telegram => {
// Telegram tokens are `<numeric id>:<secret>`; rejecting URL metacharacters here
Expand Down Expand Up @@ -231,7 +235,7 @@ async fn guard_credential(kind: OutputKind, value: &str) -> Result<(), ApiError>
})?;
Ok(())
}
_ => guard_webhook_url(value).await,
_ => guard_webhook_url(value, policy).await,
}
}

Expand Down Expand Up @@ -514,7 +518,7 @@ pub async fn create(
format!("{} is required", credential_field(kind)),
)])
})?;
guard_credential(kind, value).await?;
guard_credential(kind, value, &state.outbound).await?;
let config = request_config(&body)?.unwrap_or_else(|| serde_json::json!({}));
if kind == OutputKind::S3 {
orbit_s3::S3Config::for_output(&config, Some(value)).map_err(|message| {
Expand Down Expand Up @@ -597,7 +601,7 @@ pub async fn update(
})?;
}
let secret_ref = if let Some(value) = credential(&body, kind) {
guard_credential(kind, value).await?;
guard_credential(kind, value, &state.outbound).await?;
if kind == OutputKind::S3 {
orbit_s3::S3Config::for_output(&config, Some(value)).map_err(|message| {
ApiError::validation(vec![ValidationIssue::new("config", message)])
Expand Down Expand Up @@ -774,7 +778,8 @@ pub async fn send(
message,
retryable: false,
})?;
let client = orbit_s3::S3Client::new(config, credentials).map_err(|message| SendError {
let client = orbit_s3::S3Client::with_policy(config, credentials, state.outbound.clone())
.map_err(|message| SendError {
status: None,
message,
retryable: false,
Expand Down Expand Up @@ -805,7 +810,7 @@ pub async fn send(
retryable: false,
})?;
return send_telegram_with_progress(
&TelegramEndpoint::from_env(),
&TelegramEndpoint::from_env(state.outbound.clone()),
&secret,
&target,
text,
Expand All @@ -814,14 +819,17 @@ pub async fn send(
)
.await;
}
guard_webhook_url(&secret)
guard_webhook_url(&secret, &state.outbound)
.await
.map_err(|error| SendError {
status: None,
message: error.message,
retryable: false,
})?;
let client = orbit_security::guarded_client(std::time::Duration::from_secs(15));
let client = orbit_security::guarded_client_with_policy(
std::time::Duration::from_secs(15),
state.outbound.clone(),
);
let payload = if kind == OutputKind::Webhook {
serde_json::json!({
"event": execution
Expand Down Expand Up @@ -875,13 +883,15 @@ pub struct TelegramEndpoint {
}

impl TelegramEndpoint {
pub fn from_env() -> Self {
/// The Bot API base URL from `ORBIT_TELEGRAM_API_BASE_URL` (tests point it at a mock),
/// guarded by the given outbound policy.
pub fn from_env(policy: OutboundPolicy) -> Self {
let base_url = std::env::var("ORBIT_TELEGRAM_API_BASE_URL")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.unwrap_or_else(|| TELEGRAM_API_BASE_URL.to_string());
Self::new(base_url, OutboundPolicy::from_env())
Self::new(base_url, policy)
}

pub fn new(base_url: impl Into<String>, policy: OutboundPolicy) -> Self {
Expand Down Expand Up @@ -1195,8 +1205,8 @@ fn summary(execution: &ExecutionRecord) -> String {

/// Refuse webhook targets in loopback, link-local/metadata or other blocked ranges
/// (see `ORBIT_OUTBOUND_*`). Private ranges are allowed by default.
async fn guard_webhook_url(url: &str) -> Result<(), ApiError> {
orbit_security::check_outbound_url(url, &orbit_security::OutboundPolicy::from_env())
async fn guard_webhook_url(url: &str, policy: &OutboundPolicy) -> Result<(), ApiError> {
orbit_security::check_outbound_url(url, policy)
.await
.map_err(|error| {
ApiError::validation(vec![ValidationIssue::new("webhookUrl", error.to_string())])
Expand Down Expand Up @@ -1250,9 +1260,13 @@ mod tests {

#[tokio::test]
async fn telegram_tokens_cannot_alter_the_request_path() {
assert!(guard_credential(OutputKind::Telegram, "123456:ABC_def-1")
.await
.is_ok());
assert!(guard_credential(
OutputKind::Telegram,
"123456:ABC_def-1",
&OutboundPolicy::default()
)
.await
.is_ok());
for token in [
"123:abc/../../evil",
"123:abc?x=1",
Expand All @@ -1261,7 +1275,9 @@ mod tests {
":secret",
] {
assert!(
guard_credential(OutputKind::Telegram, token).await.is_err(),
guard_credential(OutputKind::Telegram, token, &OutboundPolicy::default())
.await
.is_err(),
"{token} must be rejected"
);
}
Expand Down
4 changes: 4 additions & 0 deletions crates/orbit-api/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ pub struct AppState {
pub license: LicenseHandle,
/// Cancelled on SIGTERM/SIGINT: stops background loops and ends SSE streams.
pub shutdown: tokio_util::sync::CancellationToken,
/// Outbound network policy for every request the API sends (work sources, outputs,
/// provider and connection probes). Read once from `ORBIT_OUTBOUND_*` at startup so
/// tests can inject a policy instead of changing the process environment (#445).
pub outbound: orbit_security::OutboundPolicy,
}

/// Guard held while an execution is counted and inserted. `Unrestricted` is returned when
Expand Down
7 changes: 5 additions & 2 deletions crates/orbit-api/src/team_outcomes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,15 +215,18 @@ async fn connector_for_work_source(
.to_string(),
other => anyhow::bail!("unsupported work source provider '{other}'"),
};
orbit_security::check_outbound_url(&base_url, &orbit_security::OutboundPolicy::from_env())
orbit_security::check_outbound_url(&base_url, &state.outbound)
.await
.map_err(|error| anyhow::anyhow!("work source baseUrl refused: {error}"))?;
Ok(Some(WorkSourceConnector {
source: source.clone(),
connection_config: connection.config.clone(),
base_url,
token,
client: orbit_security::guarded_client(std::time::Duration::from_secs(20)),
client: orbit_security::guarded_client_with_policy(
std::time::Duration::from_secs(20),
state.outbound.clone(),
),
}))
}

Expand Down
Loading