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
6 changes: 6 additions & 0 deletions changelog.d/438.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
- Every resource now uses the same 120-character name limit (#438). Providers,
connections, outputs, env mappings, agent teams, access teams, API tokens, worker
profiles and worker tokens used to accept names of any length; a portable import is
checked the same way, and renaming a provider to an empty name is refused instead of
stored. An encoded NUL (`%00`) in a path or query string returns 422 instead of a 500
storage error.
42 changes: 41 additions & 1 deletion crates/orbit-api/src/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,38 @@ where
}
}

/// Refuse a request whose path or query string contains an encoded NUL (`%00`).
/// PostgreSQL text cannot store one, so `?q=%00` or a `%00` in a slug used to reach the
/// store and fail with a 500 storage error (#438).
pub async fn reject_nul_in_uri(
request: Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use axum::response::IntoResponse;
let uri = request.uri();
let field = if has_encoded_nul(uri.path()) {
Some("path")
} else if uri.query().is_some_and(has_encoded_nul) {
Some("query")
} else {
None
};
if let Some(field) = field {
return ApiError::validation(vec![ValidationIssue::new(
field,
"text must not contain NUL characters (%00)",
)])
.into_response();
}
next.run(request).await
}

/// `%00` is the only encoding of NUL in a URI; a literal NUL byte cannot reach a handler.
/// `%2500` (an encoded "%" followed by "00") is not a NUL.
fn has_encoded_nul(text: &str) -> bool {
text.contains("%00")
}

/// Whether a JSON text contains the escape `\u0000`. A literal NUL byte is invalid JSON
/// anyway; `\\u0000` (an escaped backslash followed by "u0000") is not a NUL.
fn contains_nul_escape(json: &[u8]) -> bool {
Expand All @@ -65,7 +97,15 @@ fn contains_nul_escape(json: &[u8]) -> bool {

#[cfg(test)]
mod tests {
use super::contains_nul_escape;
use super::{contains_nul_escape, has_encoded_nul};

#[test]
fn finds_only_encoded_nul_in_uris() {
assert!(has_encoded_nul("q=%00"));
assert!(has_encoded_nul("/api/v1/skills/a%00b"));
assert!(!has_encoded_nul("q=%2500"));
assert!(!has_encoded_nul("q=100%25&status=queued"));
}

#[test]
fn finds_only_real_nul_escapes() {
Expand Down
1 change: 1 addition & 0 deletions crates/orbit-api/src/handlers/access_teams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ fn validated(body: &TeamRequest) -> Result<(String, String), ApiError> {
if name.is_empty() {
issues.push(ValidationIssue::new("name", "name is required"));
}
issues.extend(orbit_domain::name_length_issue("name", &name));
if !is_valid_slug(&slug) {
issues.push(ValidationIssue::new(
"slug",
Expand Down
3 changes: 3 additions & 0 deletions crates/orbit-api/src/handlers/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,9 @@ pub async fn create_api_token(
orbit_domain::ValidationIssue::new("name", "token name is required"),
]));
}
if let Some(issue) = orbit_domain::name_length_issue("name", &body.name) {
return Err(ApiError::validation(vec![issue]));
}
let scopes = if body.scopes.is_empty() {
auth.permissions()
} else {
Expand Down
20 changes: 20 additions & 0 deletions crates/orbit-api/src/handlers/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ pub async fn create_provider(
orbit_domain::ValidationIssue::new("name", "provider name is required"),
]));
}
if let Some(issue) = orbit_domain::name_length_issue("name", &body.name) {
return Err(ApiError::validation(vec![issue]));
}
let mut config = body.config.clone();
sanitize_provider_config(&mut config);
let report = validate_provider_config(kind, &config);
Expand Down Expand Up @@ -199,6 +202,17 @@ pub async fn update_provider(
let kind = ProviderKind::parse(&existing.kind)
.ok_or_else(|| ApiError::internal("provider has an unknown kind"))?;

if let Some(name) = body.name.as_deref() {
// An empty name used to be stored as "" (#438).
if name.trim().is_empty() {
return Err(ApiError::validation(vec![
orbit_domain::ValidationIssue::new("name", "provider name is required"),
]));
}
if let Some(issue) = orbit_domain::name_length_issue("name", name) {
return Err(ApiError::validation(vec![issue]));
}
}
let config = match body.config {
Some(mut config) => {
sanitize_provider_config(&mut config);
Expand Down Expand Up @@ -600,6 +614,9 @@ pub async fn create_connection(
orbit_domain::ValidationIssue::new("name", "connection name is required"),
]));
}
if let Some(issue) = orbit_domain::name_length_issue("name", &body.name) {
return Err(ApiError::validation(vec![issue]));
}
let connector = state
.store
.get_connector_by_slug(auth.org_id, &body.connector_slug)
Expand Down Expand Up @@ -712,6 +729,9 @@ pub async fn update_connection(
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty());
if let Some(issue) = name.and_then(|name| orbit_domain::name_length_issue("name", name)) {
return Err(ApiError::validation(vec![issue]));
}
let mut secret_ref: Option<String> = None;
if let Some(credential) = &body.credential {
if credential.trim().is_empty() {
Expand Down
1 change: 1 addition & 0 deletions crates/orbit-api/src/handlers/env_mappings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ fn validated(body: &EnvMappingRequest) -> Result<(String, String, serde_json::Va
if name.is_empty() {
issues.push(ValidationIssue::new("name", "name is required"));
}
issues.extend(orbit_domain::name_length_issue("name", &name));
let array = body.mappings.as_array().cloned().unwrap_or_default();
if array.is_empty() {
issues.push(ValidationIssue::new(
Expand Down
12 changes: 12 additions & 0 deletions crates/orbit-api/src/handlers/import_portable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,18 @@ async fn translate(
found: &mut Findings,
) -> Option<Translated> {
let name = doc.metadata.name.trim().to_string();
// Agents, skills and tool policies check the limit in their own validators.
if matches!(
kind,
PortableKind::Provider
| PortableKind::Connection
| PortableKind::WorkerProfile
| PortableKind::AgentTeam
) {
if let Some(issue) = orbit_domain::name_length_issue("metadata.name", &name) {
found.issues.push(issue);
}
}
match kind {
PortableKind::Agent => {
let mut spec = doc.spec.clone();
Expand Down
1 change: 1 addition & 0 deletions crates/orbit-api/src/handlers/outputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ fn validated(
if name.is_empty() {
issues.push(ValidationIssue::new("name", "name is required"));
}
issues.extend(orbit_domain::name_length_issue("name", &name));
let Some(kind) = OutputKind::parse(&body.kind) else {
issues.push(ValidationIssue::new(
"kind",
Expand Down
7 changes: 5 additions & 2 deletions crates/orbit-api/src/handlers/skills.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,10 +197,13 @@ pub(crate) fn validate_skill(
"lowercase letters, digits, - or _",
));
}
if name.trim().is_empty() || name.chars().count() > 120 {
if name.trim().is_empty() || name.trim().chars().count() > orbit_domain::MAX_NAME_CHARS {
issues.push(ValidationIssue::new(
"name",
"name must be 1..=120 characters",
format!(
"name must be 1..={} characters",
orbit_domain::MAX_NAME_CHARS
),
));
}
if content.trim().is_empty() {
Expand Down
2 changes: 2 additions & 0 deletions crates/orbit-api/src/handlers/teams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,7 @@ pub async fn create_team(
if body.name.trim().is_empty() {
required.push(ValidationIssue::new("name", "name is required"));
}
required.extend(orbit_domain::name_length_issue("name", &body.name));
if body.steps.is_empty() {
required.push(ValidationIssue::new(
"steps",
Expand Down Expand Up @@ -971,6 +972,7 @@ pub(crate) async fn replace_team(
if body.name.trim().is_empty() {
required.push(ValidationIssue::new("name", "name is required"));
}
required.extend(orbit_domain::name_length_issue("name", &body.name));
if body.steps.is_empty() {
required.push(ValidationIssue::new(
"steps",
Expand Down
5 changes: 5 additions & 0 deletions crates/orbit-api/src/handlers/worker_profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,9 @@ pub async fn create_token(
None
}
};
if let Some(issue) = orbit_domain::name_length_issue("name", &body.name) {
return Err(ApiError::validation(vec![issue]));
}
let mut harnesses = body.harnesses;
if let Some(profile) = &profile {
harnesses = vec![profile.harness_kind.clone()];
Expand Down Expand Up @@ -635,6 +638,7 @@ pub async fn create_profile(
if body.name.trim().is_empty() {
issues.push(ValidationIssue::new("name", "name is required"));
}
issues.extend(orbit_domain::name_length_issue("name", &body.name));
for slug in &body.skill_slugs {
match state.store.get_skill_by_slug(auth.org_id, slug).await? {
Some(skill)
Expand Down Expand Up @@ -788,6 +792,7 @@ pub async fn update_profile(
if body.name.trim().is_empty() {
issues.push(ValidationIssue::new("name", "name is required"));
}
issues.extend(orbit_domain::name_length_issue("name", &body.name));
for slug in &body.skill_slugs {
match state.store.get_skill_by_slug(auth.org_id, slug).await? {
Some(skill)
Expand Down
1 change: 1 addition & 0 deletions crates/orbit-api/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ pub fn build_router(state: AppState) -> Router {
.merge(worker)
.merge(protected)
.fallback(crate::error::not_found_fallback)
.layer(middleware::from_fn(crate::extract::reject_nul_in_uri))
// Inside `instrument` so the request id is available to the envelope.
.layer(middleware::from_fn(crate::error::envelope_rejections))
.layer(middleware::from_fn_with_state(
Expand Down
92 changes: 92 additions & 0 deletions crates/orbit-api/tests/api_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,98 @@ async fn invalid_text_harnesses_and_archived_triggers_are_refused() {
assert_eq!(status, StatusCode::CONFLICT, "{body}");
}

/// #438: every resource family uses the same 120-character name limit (it used to be
/// 120 for agents, skills and tool policies and unlimited for the rest), and an encoded
/// NUL in a path or query string is a 422, not a 500 storage error. (Access teams need an
/// enterprise licence here; they use the same check.)
#[tokio::test]
async fn names_share_one_limit_and_nul_in_uris_is_refused() {
let Some(app) = test_app(true).await else {
return;
};
let long = "n".repeat(orbit_domain::MAX_NAME_CHARS + 1);
let cases = [
(
"/api/v1/providers",
json!({ "name": long, "kind": "harness_managed", "config": { "harness": "opencode" } }),
),
(
"/api/v1/connections",
json!({ "connectorSlug": "github", "name": long }),
),
(
"/api/v1/outputs",
json!({ "name": long, "kind": "webhook", "config": {} }),
),
(
"/api/v1/env-mappings",
json!({ "name": long, "mappings": [] }),
),
(
"/api/v1/agent-teams",
json!({ "name": long, "mode": "pipeline" }),
),
(
"/api/v1/api-tokens",
json!({ "name": long, "scopes": ["agents:read"] }),
),
("/api/v1/worker-profiles", profile_body(&long, json!({}))),
(
"/api/v1/worker-tokens",
json!({ "name": long, "harnesses": ["mock"] }),
),
];
for (path, body) in cases {
let (status, body) = send(&app.router, post(path, body)).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{path}: {body}");
let details = body["error"]["details"]
.as_array()
.cloned()
.unwrap_or_default();
assert!(
details.iter().any(|issue| issue["path"] == "name"
&& issue["message"] == "name must be at most 120 characters"),
"{path}: {body}"
);
}

// A name of exactly the limit is accepted.
let (status, created) = send(
&app.router,
post(
"/api/v1/providers",
json!({
"name": "p".repeat(orbit_domain::MAX_NAME_CHARS),
"kind": "harness_managed",
"config": { "harness": "opencode" },
}),
),
)
.await;
assert_eq!(status, StatusCode::CREATED, "{created}");
// Renames are checked too, and an empty rename is refused instead of stored as "".
let provider = format!("/api/v1/providers/{}", created["id"].as_str().unwrap());
for name in [long.as_str(), " "] {
let (status, body) =
send(&app.router, patch_json(&provider, json!({ "name": name }))).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{name:?}: {body}");
assert_eq!(body["error"]["details"][0]["path"], "name", "{body}");
}

for (uri, field) in [
("/api/v1/agents?q=%00", "query"),
("/api/v1/executions?status=%00", "query"),
("/api/v1/skills/a%00b", "path"),
] {
let (status, body) = send(&app.router, get(uri)).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{uri}: {body}");
assert_eq!(body["error"]["details"][0]["path"], field, "{uri}: {body}");
}
// An encoded "%" followed by "00" is ordinary text.
let (status, body) = send(&app.router, get("/api/v1/agents?q=%2500")).await;
assert_eq!(status, StatusCode::OK, "{body}");
}

/// #438: a token lifetime outside 1..=3650 days is refused, not turned into a token that
/// never expires.
#[tokio::test]
Expand Down
7 changes: 5 additions & 2 deletions crates/orbit-domain/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,11 @@ impl AgentDefinition {
report.push("kind", format!("unsupported kind, expected {AGENT_KIND}"));
}
let name = self.metadata.name.trim();
if name.is_empty() || name.chars().count() > 120 {
report.push("metadata.name", "name must be 1..=120 characters");
if name.is_empty() || name.chars().count() > crate::MAX_NAME_CHARS {
report.push(
"metadata.name",
format!("name must be 1..={} characters", crate::MAX_NAME_CHARS),
);
}
if self.metadata.description.chars().count() > 2000 {
report.push(
Expand Down
2 changes: 2 additions & 0 deletions crates/orbit-domain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod error;
pub mod execution;
pub mod harness_kind;
pub mod ids;
pub mod names;
pub mod pagination;
pub mod schedule;
pub mod tool_policy;
Expand All @@ -26,6 +27,7 @@ pub use error::*;
pub use execution::*;
pub use harness_kind::*;
pub use ids::*;
pub use names::{name_length_issue, MAX_NAME_CHARS};
pub use pagination::*;
pub use schedule::{next_occurrence, parse_timezone, validate_schedule, ScheduleError};
pub use tool_policy::*;
Expand Down
37 changes: 37 additions & 0 deletions crates/orbit-domain/src/names.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! Display names for stored resources (agents, skills, providers, connections, outputs,
//! teams, tokens, …) share one length limit so the API and the web forms agree (#438).

use crate::ValidationIssue;

/// The longest display name, in characters, that any resource accepts.
pub const MAX_NAME_CHARS: usize = 120;

/// A validation issue at `path` when the trimmed `name` is longer than
/// [`MAX_NAME_CHARS`]. Whether a name is required is left to the caller, whose message
/// names the resource.
pub fn name_length_issue(path: &str, name: &str) -> Option<ValidationIssue> {
(name.trim().chars().count() > MAX_NAME_CHARS).then(|| {
ValidationIssue::new(
path,
format!("name must be at most {MAX_NAME_CHARS} characters"),
)
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn names_are_limited_in_characters_after_trimming() {
assert!(name_length_issue("name", &"a".repeat(MAX_NAME_CHARS)).is_none());
assert!(
name_length_issue("name", &format!(" {} ", "a".repeat(MAX_NAME_CHARS))).is_none()
);
// Multi-byte characters count once.
assert!(name_length_issue("name", &"é".repeat(MAX_NAME_CHARS)).is_none());
let issue = name_length_issue("metadata.name", &"a".repeat(MAX_NAME_CHARS + 1)).unwrap();
assert_eq!(issue.path, "metadata.name");
assert_eq!(issue.message, "name must be at most 120 characters");
}
}
Loading