Repository navigation
fix(atelet): validate RPC inputs that become host filesystem paths - #206
Conversation
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
| // 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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
done in 936ee6b, unrolled into three plain if blocks.
| 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') |
There was a problem hiding this comment.
nit: have you considered to use regex instead?
There was a problem hiding this comment.
went with hex.DecodeString instead (936ee6b). it's the same decoder the digest comparison in fetchRunsc already uses.
| } | ||
|
|
||
| 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 { |
There was a problem hiding this comment.
nit: could you please write validation method per request type, like validateRunRequest(). Each request has non common parameters that needs to be validated.
There was a problem hiding this comment.
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.
| @@ -0,0 +1,236 @@ | |||
| // Copyright 2026 Google LLC | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
could you please create an issue so we can track it.
There was a problem hiding this comment.
There was a problem hiding this comment.
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.
| if err := validateActorRequest(req.GetActorTemplateNamespace(), req.GetActorTemplateName(), req.GetActorId(), req.GetTargetAteomUid(), req.GetSpec()); err != nil { | ||
| return err | ||
| } | ||
| return validateSnapshotURIPrefix(req.GetSnapshotUriPrefix()) |
There was a problem hiding this comment.
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()
There was a problem hiding this comment.
done in 2cc5021, both validateCheckpointRequest and validateRestoreRequest.
| // 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) { |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| t.Errorf("validateRunRequest with valid fields: %v", err) | ||
| } | ||
|
|
||
| if err := validateCheckpointRequest(&ateletpb.CheckpointRequest{ |
There was a problem hiding this comment.
could you please use "could you please use tests := []struct {}" style for testing multiple test cases
There was a problem hiding this comment.
done in 2cc5021, same shape across all three: a tests := []struct table where each row mutates one field of a shared valid-request builder.
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.
8c64c7b
into
agent-substrate:main
Fixes #202
atelet's gRPC server runs on an unauthenticated hostPort
(
manifests/ate-install/atelet.yaml), so itsRun/Restore/CheckpointRPCs 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 ateletoperate outside the intended actor tree.
Unvalidated inputs (each an independent escape route)
actor_template_namespace/name/idare concatenated byateompath.ActorPathinto the per-actor dir thatresetActorDirsrunsos.RemoveAll/os.MkdirAllon.target_ateom_uidbuilds the netns path (/run/netns/ateom:<uid>)and the ateom control socket (
.../ateoms/<uid>/ateom.sock).spec.containers[].namebecomes an OCI bundle path component(
os.RemoveAll/MkdirAll/config.jsonwrite).runsc.sha256_hashbuildsstatic-files/runsc-<hash>. The cache-hitos.Statearly return hands that path to ateom to execute before theexisting 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 existingValidateActorID. Every one of these values originates upstream inuser-supplied API/CRD data (the runsc hash and snapshot location come from
the
ActorTemplatespec), so the API server and controller can apply thesame rules at admission time instead of failing at actor-activation time.
ValidateContainerNamestakes names rather than the atelet proto soresourcesstays proto-free. UnifyingValidateActorIDwithValidateActorRefis deferred: it changes ate-api-server's client-facingerror responses.
The per-RPC glue stays in
cmd/atelet: each ofRun/Checkpoint/Restorecalls its own typed validator (
validateRunRequestetc.) as the firststatement at the boundary, before any path is constructed.
What is validated
subdomain, matching how these are named; additionally the combined
<ns>:<tmpl>:<id>path component is capped at 255 bytes, sinceindividually valid DNS names can join to 381 bytes, over common
filesystems' filename limit;
target_ateom_uidas a DNS-1123 label (pod UIDs are UUIDs, whichqualify);
reserved name
pause(collides with the sandbox-infra bundle and racesits concurrent writer) and duplicate names (same bundle path, mutual
corruption);
runsc.sha256_hashas exactly 64 hex chars, checked infetchRunscbefore the path is built and before the cache-hit early return;
snapshot_uri_prefix(Checkpoint/Restore) as a parseable URI naming abucket, 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.InvalidArgumentwith the reason.Previously the interceptor surfaced them as
codes.Internalwith themessage 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
/,.(forlabels), and
.., which is exactly what enables traversal. For acooperating 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 theexported 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/ateletpin which rules each RPCenforces, one table per validator.
TestRPCBoundariesRejectexercisesRun/Checkpoint/Restoredirectlyand asserts a traversal value is rejected with
InvalidArgument, whichguards against future removal or reordering of the validation call.
TestFetchRunscRejectsBadHashplants a real cache file at the path aninvalid hash resolves to and asserts
fetchRunscstill errors. It passeswith the current code and fails if validation is moved after the
os.Statearly return, so it proves the ordering rather than just thatvalidation runs.
Tests pass
No documentation changes needed