Skip to content

fix(atelet): validate RPC inputs that become host filesystem paths - #206

Merged
Dmitry Berkovich (dberkov) merged 6 commits into
agent-substrate:mainfrom
fkautz:fix/atelet-validate-rpc-path-inputs
Jun 10, 2026
Merged

Dmitry Berkovich (dberkov) merged 6 commits into
agent-substrate:mainfrom
fkautz:fix/atelet-validate-rpc-path-inputs

Conversation

@fkautz

@fkautz Frederick F. Kautz IV (fkautz) commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #202

atelet's gRPC server runs on an unauthenticated hostPort
(manifests/ate-install/atelet.yaml), so its Run/Restore/Checkpoint
RPCs must treat every request field as untrusted. Several of those fields
are turned into host filesystem paths and then deleted, created, written,
or executed, none of them validated first. A caller that can reach the
port can smuggle a path separator or .. through them and make atelet
operate outside the intended actor tree.

Unvalidated inputs (each an independent escape route)

  • actor_template_namespace / name / id are concatenated by
    ateompath.ActorPath into the per-actor dir that resetActorDirs runs
    os.RemoveAll / os.MkdirAll on.
  • target_ateom_uid builds the netns path (/run/netns/ateom:<uid>)
    and the ateom control socket (.../ateoms/<uid>/ateom.sock).
  • spec.containers[].name becomes an OCI bundle path component
    (os.RemoveAll / MkdirAll / config.json write).
  • runsc.sha256_hash builds static-files/runsc-<hash>. The cache-hit
    os.Stat early return hands that path to ateom to execute before the
    existing hex check runs, so an escaped path could execute an arbitrary
    on-disk binary as the sandbox runtime.

Where the validators live

The field rules are exported from internal/resources
(ValidateActorRef, ValidateAteomUID, ValidateContainerNames,
ValidateRunscHash, ValidateSnapshotURIPrefix), alongside the existing
ValidateActorID. Every one of these values originates upstream in
user-supplied API/CRD data (the runsc hash and snapshot location come from
the ActorTemplate spec), so the API server and controller can apply the
same rules at admission time instead of failing at actor-activation time.
ValidateContainerNames takes names rather than the atelet proto so
resources stays proto-free. Unifying ValidateActorID with
ValidateActorRef is deferred: it changes ate-api-server's client-facing
error responses.

The per-RPC glue stays in cmd/atelet: each of Run/Checkpoint/Restore
calls its own typed validator (validateRunRequest etc.) as the first
statement at the boundary, before any path is constructed.

What is validated

  • namespace and actor ID as DNS-1123 labels, template as a DNS-1123
    subdomain, matching how these are named; additionally the combined
    <ns>:<tmpl>:<id> path component is capped at 255 bytes, since
    individually valid DNS names can join to 381 bytes, over common
    filesystems' filename limit;
  • target_ateom_uid as a DNS-1123 label (pod UIDs are UUIDs, which
    qualify);
  • each container name as a DNS-1123 label, additionally rejecting the
    reserved name pause (collides with the sandbox-infra bundle and races
    its concurrent writer) and duplicate names (same bundle path, mutual
    corruption);
  • runsc.sha256_hash as exactly 64 hex chars, checked in fetchRunsc
    before the path is built and before the cache-hit early return;
  • snapshot_uri_prefix (Checkpoint/Restore) as a parseable URI naming a
    bucket, with query/fragment/userinfo rejected: object names are appended
    by concatenation and the storage layer re-parses using only host and
    path, so those components would silently redirect the upload/download to
    a different object. The scheme is deliberately not restricted; that is
    storage-backend policy.

Validation failures return codes.InvalidArgument with the reason.
Previously the interceptor surfaced them as codes.Internal with the
message masked as "internal server error".

DNS-1123 is a deliberate fit. These values already are Kubernetes names,
so every legitimate value passes, while the charset forbids /, . (for
labels), and .., which is exactly what enables traversal. For a
cooperating caller the change is behavior-neutral: inputs newly rejected
previously failed later or misbehaved silently.

Testing

  • Table tests for each validator in internal/resources, targeting the
    exported functions (valid values, separators, .., empty, case, length,
    the label-vs-subdomain distinction, the combined-length cap, the
    pause/duplicate rules, and the URI component rejections).

  • Per-request validator tests in cmd/atelet pin which rules each RPC
    enforces, one table per validator.

  • TestRPCBoundariesReject exercises Run/Checkpoint/Restore directly
    and asserts a traversal value is rejected with InvalidArgument, which
    guards against future removal or reordering of the validation call.

  • TestFetchRunscRejectsBadHash plants a real cache file at the path an
    invalid hash resolves to and asserts fetchRunsc still errors. It passes
    with the current code and fails if validation is moved after the
    os.Stat early return, so it proves the ordering rather than just that
    validation runs.

  • Tests pass

  • No documentation changes needed

atelet builds host filesystem paths from several Run/Restore/Checkpoint
request fields without validating them. Because atelet listens on an
insecure hostPort (bypassing the API server), any reachable caller could
smuggle a path separator or ".." through these fields and make atelet
read/RemoveAll/write outside the intended actor tree, collide bundles, or
execute an arbitrary binary.

Validate every path-constructing input at the three RPC boundaries (and,
for the runsc hash, at its single choke point) before any path is built:

- namespace / template / actor ID are concatenated by ateompath.ActorPath
  into a dir on which atelet runs os.RemoveAll/os.MkdirAll; validate as
  DNS-1123 names (template as a subdomain, the other two as labels).
- target_ateom_uid builds the netns path (/run/netns/ateom:<uid>) and the
  ateom control socket (.../ateoms/<uid>/ateom.sock); validate as a
  DNS-1123 label (pod UIDs are UUIDs, which qualify).
- container names become OCI bundle path components; validate each as a
  DNS-1123 label, reject the reserved "pause" name (collides with the
  sandbox-infra bundle and races its concurrent writer), and reject
  duplicates (same bundle path, mutual corruption).
- runsc.sha256_hash builds static-files/runsc-<hash>; a cache-hit os.Stat
  early-returns that path for ateom to execute before the existing hex
  check runs. Validate it as 64 hex chars before constructing the path.

Each validator has a unit test. TestRPCBoundariesReject drives Run,
Checkpoint, and Restore to confirm the validation runs before their
dependencies. TestFetchRunscRejectsBadHash plants a cache file at an
invalid hash's resolved path to prove the hash is validated before the
cache-hit early return, not merely at some point.

Fixes agent-substrate#202
Comment thread cmd/atelet/main.go Outdated
// leave a traversal window via the others. Template names are DNS-1123
// subdomains (dots allowed); namespaces and actor IDs are labels.
func validateActorRef(namespace, template, actorID string) error {
for _, f := range []struct {

@dberkov Dmitry Berkovich (dberkov) Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could you pleas rewrite it in format like
if errs := validation.IsDNS1123Label(namespace); len(errs) > 0 {
return fmt.Errorf(...)
}

it will be much easy to read the code.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in 936ee6b, unrolled into three plain if blocks.

Comment thread cmd/atelet/main.go Outdated
return fmt.Errorf("invalid runsc sha256 hash: want 64 hex chars, got %d", len(sha256Hash))
}
for _, r := range sha256Hash {
isHex := (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: have you considered to use regex instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

went with hex.DecodeString instead (936ee6b). it's the same decoder the digest comparison in fetchRunsc already uses.

Comment thread cmd/atelet/main.go Outdated
}

func (s *AteomHerder) Run(ctx context.Context, req *ateletpb.RunRequest) (*ateletpb.RunResponse, error) {
if err := validateActorRequest(req.GetActorTemplateNamespace(), req.GetActorTemplateName(), req.GetActorId(), req.GetTargetAteomUid(), req.GetSpec()); err != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could you please write validation method per request type, like validateRunRequest(). Each request has non common parameters that needs to be validated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in e81ba71. each RPC now has a typed validator (validateRunRequest / validateCheckpointRequest / validateRestoreRequest) wrapping a shared core for the common fields. the checkpoint/restore ones also validate the one non-common field, snapshot_uri_prefix: it must parse and name a bucket. deliberately not restricting the scheme since that's storage-backend policy, parseGCSURL only consumes host and path.

Comment thread cmd/atelet/main_test.go
@@ -0,0 +1,236 @@
// Copyright 2026 Google LLC

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for writing unit tests for the new functions. Ideally we not supposed to write unit tests for private methods. How complicated to write unit tests for public methods instead?
You can keep the unit tests of public method to concentrate on the params validations only in this PR, however it will be a good start for adding more unit tests later.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not a problem, my preference is to test both external and internal APIs since they are both contracts (turtles all the way down?). TestRPCBoundariesReject does test the package's publicly exported entry points (all three RPC handlers), and TestFetchRunscRejectsBadHash checks validation ordering on an internal method, but agree that it should be more exhaustive. Happy to take that on in a different PR.

One observation, we can't fully validate the happy path of the RPC without mocking the full downstream stack (object storage, actor dirs, image pulls, a live ateom), which is why there are combinatorial tables on the helpers.

While double checking this I also found we have two implementations of the actor-id rule: ate-api-server uses a regex (resources.ValidateActorID) and this PR uses k8s.io/apimachinery's DNS-1123 validators. I'll refactor this PR to move the new validators into internal/resources and export them, so they have a public contract and the table tests target it. Unifying ValidateActorID with these is better as a follow-up since it touches ate-api-server's client-facing error responses.

Thoughts on this as an approach? If it looks good I'll push that refactor shortly and open issues for the deferred work.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please create an issue so we can track it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

filed #216 for unifying ValidateActorID with the new validators and #217 for expanding test coverage at the RPC layer. the refactor from the thread above is now on the branch (34dae11): the validators live in internal/resources as exported functions and the table tests target that public contract.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ValidateActorID intentionally avoids using the apimachinery validator, because we need to expose a validation function and expose a regex for valid actor IDs, so atenet can creating DNS configuration. I think there is value in having a single authoritative definition of what an actor id is, in a single place.

…ing/hex

Review feedback from dberkov on agent-substrate#206:
- validateActorRef: replace the table-driven loop with three plain if
  blocks, matching the style of the other validators.
- validateRunscHash: replace the manual per-rune hex check with
  hex.DecodeString, the same decoder the digest comparison in fetchRunsc
  already uses.
Review feedback from dberkov on agent-substrate#206: give each RPC its own typed
validator (validateRunRequest / validateCheckpointRequest /
validateRestoreRequest) wrapping the shared common-field core, so call
sites take the request type instead of four positional strings and
request-specific rules have an obvious home.

The Checkpoint/Restore wrappers use that home for the one field Run does
not have: snapshot_uri_prefix must parse and name a bucket, so a bad
prefix fails at the RPC boundary instead of deep inside an
object-storage call. The check is deliberately scheme-agnostic; which
schemes are acceptable is storage-backend policy (parseGCSURL only
consumes host and path), and the local snapshot paths come from the
separately validated actor ref, not this URI.
Comment thread cmd/atelet/main.go Outdated
if err := validateActorRequest(req.GetActorTemplateNamespace(), req.GetActorTemplateName(), req.GetActorId(), req.GetTargetAteomUid(), req.GetSpec()); err != nil {
return err
}
return validateSnapshotURIPrefix(req.GetSnapshotUriPrefix())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit:
if err := validateSnapshotURIPrefix(req.GetSnapshotUriPrefix()); err != nil {
return err
}

return nil.

It will allow more cleaner way to add more validation later. Similar comment for validateRestoreRequest()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in 2cc5021, both validateCheckpointRequest and validateRestoreRequest.

Comment thread cmd/atelet/main_test.go Outdated
// Restore must reject a bad snapshot URI prefix even when every common field
// is valid, and Run (which has no URI field) must accept the same common
// fields.
func TestPerRequestValidators(t *testing.T) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could you please split out to independent TestXXX methods. Lets assume it will be bug in both validateRunRequest & validateCheckpointRequest.

Entire test will fail and it will not be clear enough what validation has an issue, without reading the logs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in 2cc5021. one test per request validator (TestValidateRunRequest / TestValidateCheckpointRequest / TestValidateRestoreRequest), so in your scenario the output is two distinct top-level failures, each naming its validator. the subtest name carries the broken rule.

Comment thread cmd/atelet/main_test.go Outdated
t.Errorf("validateRunRequest with valid fields: %v", err)
}

if err := validateCheckpointRequest(&ateletpb.CheckpointRequest{

@dberkov Dmitry Berkovich (dberkov) Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please use "could you please use tests := []struct {}" style for testing multiple test cases

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in 2cc5021, same shape across all three: a tests := []struct table where each row mutates one field of a shared valid-request builder.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

Review feedback from dberkov on agent-substrate#206:
- validateCheckpointRequest / validateRestoreRequest end with an explicit
  if err := validateSnapshotURIPrefix(...) block and return nil, so
  future validations append cleanly.
- The combined per-request validator test is split into one table-driven
  test per validator (TestValidateRunRequest / TestValidateCheckpointRequest /
  TestValidateRestoreRequest). A failure now names the validator in the
  top-level test name and the broken rule in the subtest name. Each table
  row mutates one field of a shared valid request builder.
Exported as ValidateActorRef / ValidateAteomUID / ValidateContainerNames /
ValidateRunscHash / ValidateSnapshotURIPrefix so the API server and
controller can apply the same rules at their boundaries, and so the
table tests target a public contract. ValidateContainerNames takes
names rather than the atelet proto to keep resources proto-free.
The RPC-boundary glue (per-request validators) stays in cmd/atelet.
Unifying resources.ValidateActorID with ValidateActorRef is deferred:
it changes ate-api-server's client-facing error responses.
- ValidateSnapshotURIPrefix rejects query, fragment, opaque, and userinfo
  components. Object names are appended to the prefix by concatenation,
  so a query or fragment would swallow the appended name when the storage
  layer re-parses the URI (it uses only host and path), silently
  redirecting the upload/download to a different object.
- ValidateActorRef caps the combined <ns>:<tmpl>:<id> path component at
  255 bytes: individually valid DNS names can join to 381 bytes, over the
  filename limit of common filesystems.
- Validation failures at the RPC boundary (and the runsc hash check) are
  wrapped as status.Error(codes.InvalidArgument, ...). The interceptor
  maps plain errors to codes.Internal and replaces the message with
  "internal server error", so callers previously saw neither the right
  code nor the reason. TestRPCBoundariesReject now asserts the code.
@dberkov
Dmitry Berkovich (dberkov) merged commit 8c64c7b into agent-substrate:main Jun 10, 2026
8 checks passed
@fkautz
Frederick F. Kautz IV (fkautz) deleted the fix/atelet-validate-rpc-path-inputs branch June 11, 2026 06:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Validate atelet RPC inputs that become host filesystem paths

3 participants