Skip to content

fix(apk): stop repository key IDs from escaping key paths and URLs - #2698

Merged
konradzapalowicz merged 2 commits into
chainguard-dev:mainfrom
konradzapalowicz:push-nltsuxlztzms
Nov 25, 2026
Merged

konradzapalowicz merged 2 commits into
chainguard-dev:mainfrom
konradzapalowicz:push-nltsuxlztzms

Conversation

@konradzapalowicz

Copy link
Copy Markdown
Contributor

A repository that supports key discovery serves its signing keys as a JWKS. Each key's kid is chosen by the repository, and DiscoverKeys turns it into the key file name (<kid>.rsa.pub). Until now the kid was not checked, so a kid containing a path separator or .. let apko install-keys write a key outside /etc/apk/keys. The same kid also went unescaped into the key URL that apko lock records, so characters such as ?, # or % changed which resource that URL named.

DiscoverKeys now rejects the whole key set when any kid contains /, \ or .., before a file name is built from it. Because the check sits in discovery, every caller is protected. The lockfile key URL now path-escapes the key ID as a single segment. Keys with ordinary identifiers are discovered, installed and locked exactly as before.

What changed

JWKS from repository
   │  {"kid": "../evil", ...}
   ▼
DiscoverKeys  (pkg/apk/apk/implementation.go)
   for each key:
     kid == ""                       → error (existing)
     kid has / or \ or ".."          → error: invalid "kid" "../evil": must not contain path separators or ".."
     keyName = kid + ".rsa.pub"        (whole set rejected → nil keys)
   │
   ├─► install-keys          filepath.Join("/etc/apk/keys", ID)   ← can no longer escape
   ├─► InitRuntimeOnlyKeys → WriteRuntimeKeys                     (already guarded; untouched)
   ├─► fetchChainguardKeys → in-memory keyring
   └─► lock: discoverKeysForLock
         keyURL := repoBase + "/" + url.PathEscape(key.ID)
              "rsa-test.rsa.pub"  → unchanged
              "a?b#c%2f.rsa.pub"  → "a%3Fb%23c%252f.rsa.pub"  (one path segment, not query/fragment)
--- a/pkg/apk/apk/implementation.go
+++ b/pkg/apk/apk/implementation.go
@@ func DiscoverKeys
 		if key.KeyID == "" {
 			return nil, fmt.Errorf(`key missing "kid"`)
 		}
+		// The repository chooses the kid and it becomes a file name, so it must
+		// not be able to name a path outside the keys directory.
+		if strings.ContainsAny(key.KeyID, `/\`) || strings.Contains(key.KeyID, "..") {
+			return nil, fmt.Errorf(`invalid "kid" %q: must not contain path separators or ".."`, key.KeyID)
+		}
 		keyName := key.KeyID + ".rsa.pub"
--- a/internal/cli/lock.go
+++ b/internal/cli/lock.go
@@ func discoverKeysForLock
-			// For each JWKS key, emit a URL: repository + "/" + KeyID
+			// For each JWKS key, emit a URL: repository + "/" + path-escaped KeyID
 			repoBase := strings.TrimSuffix(repo, "/")
 			for _, key := range keys {
-				keyURL := repoBase + "/" + key.ID
+				keyURL := repoBase + "/" + url.PathEscape(key.ID)
File Change
pkg/apk/apk/implementation.go +5: inline kid check in DiscoverKeys
pkg/apk/apk/implementation_test.go +55: TestDiscoverKeysRejectsUnsafeKeyIDs (6 reject rows, 1 accept row)
internal/cli/lock.go +3 −2: net/url import, url.PathEscape, comment
internal/cli/lock_security_test.go +56: TestDiscoverKeysForLockEscapesKeyIDInURL

Testing

  • go build ./...
  • go test ./pkg/apk/apk/ ./internal/cli/
  • golangci-lint run ./pkg/apk/apk/... ./internal/cli/... (0 issues)
  • Both new tests fail when their fix is removed.

🤖 Generated with Claude Code

A repository chooses each JWKS "kid", and DiscoverKeys turns it into the
key file name. A kid containing a path separator or ".." let install-keys
write outside /etc/apk/keys. DiscoverKeys now rejects the whole key set
before building a name from such a kid, which protects every caller.
discoverKeysForLock built each key URL as repository + "/" + key ID. A
repository-chosen kid containing "?", "#" or "%" changed which resource
the URL named. The key ID is now escaped as a single path segment, which
leaves ordinary key IDs unchanged.

@tomgeorge tomgeorge left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. The kid check closes the path escape for every caller, and the lockfile URL now treats the key ID as one path segment.

What I verified

  • DiscoverKeys rejects the whole set before building a file name when any kid contains /, \ or .. (pkg/apk/apk/implementation.go:1533). With those excluded, kid + ".rsa.pub" is a single plain file name, so filepath.Join("/etc/apk/keys", key.ID) in internal/cli/install-keys.go:44 can't leave the directory.
  • All three discovery callers go through that check: install-keys, InitRuntimeOnlyKeys (implementation.go:460, which WriteRuntimeKeys guards a second time at :492), and fetchChainguardKeys via (*APK).DiscoverKeys. The singleflight cache in front of it caches the result, not the raw JWKS, so a cached result was validated too.
  • url.PathEscape(key.ID) in internal/cli/lock.go:383 leaves IDs like rsa-test.rsa.pub unchanged, so existing lockfiles don't churn. url.Parse of the escaped URL gives back the literal ID as the last path segment, which is the file name discovery would have used. TestDiscoverKeysForLockEscapesKeyIDInURL covers both points.
  • TestDiscoverKeysRejectsUnsafeKeyIDs covers a bad kid both before and after a good one and checks that no keys come back. It also checks that ordinary names, including one with a single dot, still pass.
  • At 050cf6d, CodeQL and the other checks pass.

Security

  • untrusted-input: cleared. A repository-chosen kid is validated at implementation.go:1533 before it reaches a file path or URL.
  • crypto (trusted key installation): cleared. A malformed kid now fails discovery instead of planting a key outside the keyring directory. Not checked by a second agent.

@konradzapalowicz
konradzapalowicz merged commit aff5632 into chainguard-dev:main Nov 25, 2026
8 checks passed
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.

3 participants