Skip to content

Commit f48205e

Browse files
authored
feat(runtime): support scoped registry credentials for managed builds (#132)
Signed-off-by: wayne <rcywjo@gmail.com>
1 parent 1cfe184 commit f48205e

7 files changed

Lines changed: 409 additions & 43 deletions

File tree

‎config/config.go‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64,17 +64,19 @@ type ManagedRuntimeConfig struct {
6464
}
6565

6666
type ManagedRuntimeProfile struct {
67-
Image string `toml:"image" json:"image"`
68-
BootstrapRoot string `toml:"bootstrap_root" json:"bootstrapRoot"`
69-
Registry string `toml:"registry" json:"registry"`
70-
RepositoryPrefix string `toml:"repository_prefix" json:"repositoryPrefix"`
71-
RegistryAuthFile string `toml:"registry_auth_file" json:"registryAuthFile"`
72-
RegistryInsecure bool `toml:"registry_insecure" json:"registryInsecure"`
73-
BuildkitEndpoint string `toml:"buildkit_endpoint" json:"buildkitEndpoint"`
74-
ProviderURL string `toml:"provider_url" json:"providerURL"`
75-
AllowedTenants []string `toml:"allowed_tenants" json:"allowedTenants"`
76-
WritableMB int `toml:"writable_mb" json:"writableMB"`
77-
MinimumRootMB int `toml:"minimum_root_mb" json:"minimumRootMB"`
67+
Image string `toml:"image" json:"image"`
68+
BootstrapRoot string `toml:"bootstrap_root" json:"bootstrapRoot"`
69+
Registry string `toml:"registry" json:"registry"`
70+
RepositoryPrefix string `toml:"repository_prefix" json:"repositoryPrefix"`
71+
RegistryAuthFile string `toml:"registry_auth_file" json:"registryAuthFile"`
72+
// SourceRegistryAuthFiles maps exact source Registry authorities to dedicated pull credential files.
73+
SourceRegistryAuthFiles map[string]string `toml:"source_registry_auth_files" json:"sourceRegistryAuthFiles,omitempty"`
74+
RegistryInsecure bool `toml:"registry_insecure" json:"registryInsecure"`
75+
BuildkitEndpoint string `toml:"buildkit_endpoint" json:"buildkitEndpoint"`
76+
ProviderURL string `toml:"provider_url" json:"providerURL"`
77+
AllowedTenants []string `toml:"allowed_tenants" json:"allowedTenants"`
78+
WritableMB int `toml:"writable_mb" json:"writableMB"`
79+
MinimumRootMB int `toml:"minimum_root_mb" json:"minimumRootMB"`
7880
}
7981

8082
// MinimumStorageMB includes the private image upper and a usable root layer.

‎doc/checkpoint-restore.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,10 @@ unlisted tenants are rejected before node state is created. Clients select only
559559
`extra_config.managedRuntimeProfile` and cannot replace reserved mounts, labels
560560
or file-backed upper configuration.
561561

562+
The optional `source_registry_auth_files` table maps an exact source Registry authority to an absolute credential file path. Sandboxd selects the publication authority from `registry_auth_file` and each explicitly configured source authority from its assigned file. Use separate pull-only credentials scoped by the source Registry to the repositories needed by this profile. New collections read the current files when generating the Buildx client configuration. Rotation applies to new collections. Existing checkpoints keep their collection and its saved configuration.
563+
564+
For both source and publishing registries, Sandboxd looks up the exact Buildx login key in the credential file. The key is the configured hostname including any port. Docker Hub uses `https://index.docker.io/v1/` for all three supported authorities (`docker.io`, `index.docker.io` and `registry-1.docker.io`). Only an absent exact key triggers lookup of normalized legacy entries. Sandboxd writes the selected credential under the Buildx key and rejects duplicate authorities that map to the same key. Selected `auth` values must use Docker's standard Base64-encoded `username:password` format. An empty or invalid exact entry fails admission before a new collection is created, even when a legacy login is available.
565+
562566
The total writable quota must cover `writable_mb` plus `minimum_root_mb` (4096 MiB when omitted or zero). For the example 4096 MiB upper, the platform advertises an 8192 MiB minimum through ADXlet node resource labels. The SDK reserves this floor and restricts placement before creating an environment; explicit undersized requests or limits fail early. Sandboxd independently rejects a smaller total quota before creating any collection state, leaving a usable root layer rather than accepting a one-MiB remainder. Regenerate node metadata from the same profile when changing geometry.
563567

564568
Fresh environments acquire different opaque image collections. Sandboxd injects

‎go.mod‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ require (
1212
github.com/containerd/ttrpc v1.2.8
1313
github.com/containerd/typeurl/v2 v2.1.1
1414
github.com/coreos/go-iptables v0.6.0
15+
github.com/docker/cli v29.0.3+incompatible
1516
github.com/gogo/protobuf v1.3.2
1617
github.com/golang/protobuf v1.5.4
1718
github.com/google/go-containerregistry v0.20.7
@@ -54,7 +55,6 @@ require (
5455
github.com/coreos/go-systemd/v22 v22.6.0 // indirect
5556
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
5657
github.com/davecgh/go-spew v1.1.1 // indirect
57-
github.com/docker/cli v29.0.3+incompatible // indirect
5858
github.com/docker/distribution v2.8.3+incompatible // indirect
5959
github.com/docker/docker-credential-helpers v0.9.3 // indirect
6060
github.com/docker/go-units v0.5.0 // indirect

‎internal/server/managed_runtime.go‎

Lines changed: 58 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"crypto/rand"
66
"crypto/sha256"
7+
"encoding/base64"
78
"encoding/hex"
89
"encoding/json"
910
"errors"
@@ -15,6 +16,7 @@ import (
1516
"strings"
1617
"time"
1718

19+
"github.com/google/go-containerregistry/pkg/authn"
1820
"github.com/google/go-containerregistry/pkg/name"
1921
runtime "github.com/inclusionAI/sandboxd/api/runtime/v1"
2022
"github.com/inclusionAI/sandboxd/config"
@@ -33,6 +35,9 @@ const managedCheckpointFile = "managed-runtime.json"
3335
var managedName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
3436
var managedID = regexp.MustCompile(`^[a-f0-9]{32}$`)
3537

38+
// These are the normalized fallbacks when the standard login key is absent.
39+
var dockerHubAuthorities = []string{name.DefaultRegistry, "docker.io", "registry-1.docker.io"}
40+
3641
type managedRecord struct {
3742
LifecycleVersion int `json:"lifecycle_version,omitempty"`
3843
CollectionID string `json:"collection_id"`
@@ -72,21 +77,62 @@ func managedProfileSelection(request *runtime.StartRequest) (string, error) {
7277
}
7378

7479
func profileFingerprint(profile config.ManagedRuntimeProfile) string {
75-
// Authorization is checked against current policy before compatibility.
76-
// Adding/reordering tenants must not invalidate another tenant's snapshot.
80+
// Access policy for fresh collections does not change the saved runtime layout.
7781
profile.AllowedTenants = nil
82+
profile.SourceRegistryAuthFiles = nil
7883
data, _ := json.Marshal(profile)
7984
value := sha256.Sum256(data)
8085
return hex.EncodeToString(value[:])
8186
}
8287

88+
func managedDockerConfigKey(host string) string {
89+
if slices.Contains(dockerHubAuthorities, host) {
90+
return authn.DefaultAuthKey
91+
}
92+
return host
93+
}
94+
8395
func managedRegistryAuth(path, host string) (string, error) {
84-
auths, err := registryauth.Load(path)
85-
if err != nil || auths[host].Auth == "" {
86-
// Do not expose file contents or credentials in admission failures.
87-
return "", fmt.Errorf("managed Registry credential is unavailable")
96+
exactKey := managedDockerConfigKey(host)
97+
fallbackKeys := []string{host}
98+
if exactKey == authn.DefaultAuthKey {
99+
fallbackKeys = dockerHubAuthorities
100+
}
101+
entry, err := registryauth.LoadEntry(path, exactKey, fallbackKeys...)
102+
auth := entry.Auth
103+
if err != nil || auth == "" {
104+
return "", errors.New("managed Registry credential is unavailable")
105+
}
106+
decoded, err := base64.StdEncoding.DecodeString(auth)
107+
username, _, ok := strings.Cut(string(decoded), ":")
108+
if err != nil || !ok || username == "" {
109+
// The Docker CLI would reject the entire config. Keep the error secret-free.
110+
return "", errors.New("managed Registry credential must be base64-encoded username:password")
111+
}
112+
return auth, nil
113+
}
114+
115+
func managedDockerAuths(profile config.ManagedRuntimeProfile) (map[string]map[string]string, error) {
116+
publishAuth, err := managedRegistryAuth(profile.RegistryAuthFile, profile.Registry)
117+
if err != nil {
118+
return nil, err
119+
}
120+
auths := map[string]map[string]string{managedDockerConfigKey(profile.Registry): {"auth": publishAuth}}
121+
for host, path := range profile.SourceRegistryAuthFiles {
122+
if _, err := name.NewRegistry(host, name.StrictValidation); err != nil || !filepath.IsAbs(path) {
123+
return nil, errors.New("invalid managed source Registry configuration")
124+
}
125+
key := managedDockerConfigKey(host)
126+
if _, exists := auths[key]; exists {
127+
return nil, fmt.Errorf("managed source Registry %q is already configured", host)
128+
}
129+
auth, err := managedRegistryAuth(path, host)
130+
if err != nil {
131+
return nil, fmt.Errorf("managed source Registry %q: %w", host, err)
132+
}
133+
auths[key] = map[string]string{"auth": auth}
88134
}
89-
return auths[host].Auth, nil
135+
return auths, nil
90136
}
91137

92138
func writePrivateJSON(path string, value any, mode os.FileMode) error {
@@ -219,6 +265,10 @@ func (h *sandboxService) prepareManagedRuntime(ctx context.Context, request *run
219265
}
220266
}
221267
} else {
268+
auths, err := managedDockerAuths(profile)
269+
if err != nil {
270+
return nil, err
271+
}
222272
var identity [16]byte
223273
var secret [32]byte
224274
if _, err := rand.Read(identity[:]); err != nil {
@@ -276,11 +326,6 @@ func (h *sandboxService) prepareManagedRuntime(ctx context.Context, request *run
276326
rollback()
277327
return nil, err
278328
}
279-
auth, err := managedRegistryAuth(profile.RegistryAuthFile, profile.Registry)
280-
if err != nil {
281-
rollback()
282-
return nil, err
283-
}
284329
profileData := map[string]any{"registry": profile.Registry, "registry_insecure": profile.RegistryInsecure, "prefix": prefix + "/" + id, "endpoint": profile.BuildkitEndpoint, "builder": "akernel-remote", "provider": profile.ProviderURL, "token_file": "/run/akernel-build/token", "plan": "/opt/akernel-images/.metadata/plan.json", "writable_mb": profile.WritableMB}
285330
if err := writePrivateJSON(filepath.Join(guest, "profile.json"), profileData, 0400); err != nil {
286331
rollback()
@@ -290,7 +335,7 @@ func (h *sandboxService) prepareManagedRuntime(ctx context.Context, request *run
290335
rollback()
291336
return nil, err
292337
}
293-
if err := writePrivateJSON(filepath.Join(guest, "docker-config.json"), map[string]any{"auths": map[string]any{profile.Registry: map[string]string{"auth": auth}}}, 0400); err != nil {
338+
if err := writePrivateJSON(filepath.Join(guest, "docker-config.json"), map[string]any{"auths": auths}, 0400); err != nil {
294339
rollback()
295340
return nil, err
296341
}

0 commit comments

Comments
 (0)