diff --git a/.github/workflows/validate-milestone.yml b/.github/workflows/validate-milestone.yml index 0b74e95c9b6e..65377b512395 100644 --- a/.github/workflows/validate-milestone.yml +++ b/.github/workflows/validate-milestone.yml @@ -1,50 +1,64 @@ name: validate-milestone +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + permissions: - contents: read - pull-requests: read + issues: read on: pull_request: - types: [opened, synchronize, milestoned, demilestoned, edited] + types: [opened, reopened, edited, synchronize, milestoned, demilestoned] jobs: validate-milestone: + if: ${{ github.repository == 'docker/cli' && github.event.pull_request.state == 'open' }} runs-on: ubuntu-26.04 timeout-minutes: 5 steps: - - name: Validate milestone matches VERSION + - name: Validate milestone matches next version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: MILESTONE: ${{ github.event.pull_request.milestone.title }} + # Pinned "[Branch status]" issue with a "json docker-versions" block + # mapping each branch to its next and last version. + BRANCH_STATUS_ISSUE: 7526 with: script: | - const files = await github.paginate(github.rest.pulls.listFiles, { + const issueNumber = Number(process.env.BRANCH_STATUS_ISSUE); + const source = `issue #${issueNumber}`; + const baseBranch = context.payload.pull_request.base.ref; + core.info(`Base branch: ${baseBranch}`); + + const {data: issue} = await github.rest.issues.get({ owner: context.repo.owner, repo: context.repo.repo, - pull_number: context.payload.pull_request.number, + issue_number: issueNumber, }); - core.info(`Modified files: ${files.map(f => f.filename).join(', ')}`); - - const touchesVersion = files.some(f => f.filename === 'VERSION'); - core.info(`Touches VERSION: ${touchesVersion}`); - - // Use the PR's version when it bumps the file, base branch otherwise. - // It's fine to trust the author in this case, it's not meant to be - // a security gate, just a helpful check for maintainers. - const ref = touchesVersion - ? context.payload.pull_request.head.sha - : context.payload.pull_request.base.ref; + const lines = (issue.body ?? '').split('\n').map(line => line.trimEnd()); + const start = lines.indexOf('```json docker-versions') + 1; + const end = lines.indexOf('```', start); + if (start === 0 || end === -1) { + core.setFailed(`Could not find a 'json docker-versions' block in ${source}`); + return; + } - core.info(`Base ref: ${ref}`); + // For example: {"master": {"next": "29.10.0", "last": "29.9.1"}} + let versions; + try { + versions = JSON.parse(lines.slice(start, end).join('\n')); + } catch (err) { + core.setFailed(`Invalid 'json docker-versions' block in ${source}: ${err.message}`); + return; + } + core.info(`Versions: ${JSON.stringify(versions)}`); - const resp = await github.rest.repos.getContent({ - owner: context.repo.owner, - repo: context.repo.repo, - path: 'VERSION', - ref, - }); - const expected = Buffer.from(resp.data.content, resp.data.encoding).toString('utf8').trim(); + const expected = versions?.[baseBranch]?.next; + if (!expected) { + core.setFailed(`Could not find the next version for branch '${baseBranch}' in ${source}`); + return; + } const milestone = process.env.MILESTONE; if (!milestone) { @@ -52,7 +66,26 @@ jobs: return; } if (milestone !== expected) { - core.setFailed(`Milestone '${milestone}' does not match VERSION '${expected}'`); + const guidance = + 'This check prevents the PR from being merged accidentally before it is appropriate ' + + 'for its milestone. If the milestone is intentional, no action is needed.'; + await core.summary + .addHeading('This PR is intentionally blocked from merging for now') + .addTable([ + [ + {data: 'Milestone', header: true}, + {data: 'Expected next version', header: true}, + ], + [milestone, expected], + ]) + .addRaw(`The expected version for the '${baseBranch}' branch comes from ${source}.`) + .addEOL() + .addRaw(guidance) + .write(); + core.setFailed( + `This PR cannot be merged yet because milestone '${milestone}' does not match ` + + `the next version '${expected}'. ${guidance}` + ); return; } core.info(`Milestone: ${milestone} ✓`); diff --git a/cli-plugins/plugin/plugin.go b/cli-plugins/plugin/plugin.go index d4dfb5ade29c..11100f8d6803 100644 --- a/cli-plugins/plugin/plugin.go +++ b/cli-plugins/plugin/plugin.go @@ -166,7 +166,11 @@ func Run(makeCmd func(command.Cli) *cobra.Command, meta metadata.Metadata, ops . if stErr.StatusCode == 0 { // FIXME(thaJeztah): this should never be used with a zero status-code. Check if we do this anywhere. stErr.StatusCode = 1 } - _, _ = fmt.Fprintln(dockerCLI.Err(), stErr) + + // Only print the message if the error has text. + if msg := stErr.Error(); msg != "" { + _, _ = fmt.Fprintln(dockerCLI.Err(), msg) + } os.Exit(stErr.StatusCode) } _, _ = fmt.Fprintln(dockerCLI.Err(), err) diff --git a/cli/command/registry.go b/cli/command/registry.go index 2e767d5b72f3..a949f8afed91 100644 --- a/cli/command/registry.go +++ b/cli/command/registry.go @@ -24,9 +24,10 @@ import ( const ( registerSuggest = "Log in with your Docker ID or email address to push and pull images from Docker Hub. " + "If you don't have a Docker ID, head over to https://hub.docker.com/ to create one." - patSuggest = "You can log in with your password or a Personal Access " + - "Token (PAT). Using a limited-scope PAT grants better security and is required " + - "for organizations using SSO. Learn more at https://docs.docker.com/go/access-tokens/" + patOrOatSuggest = "You can use a personal access token (PAT) or organization access token (OAT) instead of a password. " + + "Scoped tokens improve security; a PAT is required for password-based login with SSO. " + + "When using an OAT, use your organization name as the username. " + + "Learn more at https://docs.docker.com/go/access-tokens/" ) // authConfigKey is the key used to store credentials for Docker Hub. It is @@ -123,7 +124,7 @@ func PromptUserForCredentials(ctx context.Context, cli Streams, argUser, argPass // a token instead of a password. _, _ = fmt.Fprintln(cli.Out(), registerSuggest) if hints.Enabled() { - _, _ = fmt.Fprintln(cli.Out(), patSuggest) + _, _ = fmt.Fprintln(cli.Out(), patOrOatSuggest) _, _ = fmt.Fprintln(cli.Out()) } } @@ -167,8 +168,8 @@ func PromptUserForCredentials(ctx context.Context, cli Streams, argUser, argPass if serverAddress == authConfigKey { out := tui.NewOutput(cli.Err()) - out.PrintNote("A Personal Access Token (PAT) can be used instead.\n" + - "To create a PAT, visit " + aec.Underline.Apply("https://app.docker.com/settings") + "\n\n") + out.PrintNote("You can use a personal access token (PAT) or organization access token (OAT) instead of a password.\n" + + "Learn more at " + aec.Underline.Apply("https://docs.docker.com/go/access-tokens/") + "\n\n") } argPassword, err = prompt.ReadInput(ctx, stdIn, cli.Out(), "Password: ") diff --git a/cli/command/registry/login.go b/cli/command/registry/login.go index 2b522910d800..ac2481835a31 100644 --- a/cli/command/registry/login.go +++ b/cli/command/registry/login.go @@ -62,9 +62,9 @@ func newLoginCommand(dockerCLI command.Cli) *cobra.Command { flags := cmd.Flags() - flags.StringVarP(&opts.user, "username", "u", "", "Username") - flags.StringVarP(&opts.password, "password", "p", "", `Password or Personal Access Token (PAT), or "-" to read from stdin`) - flags.BoolVar(&opts.passwordStdin, "password-stdin", false, "Take the Password or Personal Access Token (PAT) from stdin") + flags.StringVarP(&opts.user, "username", "u", "", "Username or organization name (for OATs)") + flags.StringVarP(&opts.password, "password", "p", "", `Password or access token. Use "-" to read from stdin`) + flags.BoolVar(&opts.passwordStdin, "password-stdin", false, "Read password or access token from stdin") return cmd } diff --git a/cli/command/service/progress/progress.go b/cli/command/service/progress/progress.go index ef191fce33ac..e52fe8bdd0b8 100644 --- a/cli/command/service/progress/progress.go +++ b/cli/command/service/progress/progress.go @@ -72,7 +72,7 @@ func terminalState(state swarm.TaskState) bool { // //nolint:gocyclo func ServiceProgress(ctx context.Context, apiClient client.APIClient, serviceID string, progressWriter io.WriteCloser) error { - defer progressWriter.Close() + defer func() { _ = progressWriter.Close() }() progressOut := streamformatter.NewJSONProgressOutput(progressWriter, false) @@ -118,7 +118,7 @@ func ServiceProgress(ctx context.Context, apiClient client.APIClient, serviceID return fmt.Errorf("service update paused: %s", res.Service.UpdateStatus.Message) case swarm.UpdateStateRollbackStarted: if !rollback && res.Service.UpdateStatus.Message != "" { - progressOut.WriteProgress(progress.Progress{ + _ = progressOut.WriteProgress(progress.Progress{ ID: "rollback", Action: res.Service.UpdateStatus.Message, }) @@ -169,7 +169,7 @@ func ServiceProgress(ctx context.Context, apiClient client.APIClient, serviceID // use the presence of this field to check if the service is a job // here. if res.Service.JobStatus != nil { - progress.Message(progressOut, "", "job complete") + _ = progressOut.WriteProgress(progress.Progress{Message: "job complete"}) return nil } @@ -205,8 +205,8 @@ func ServiceProgress(ctx context.Context, apiClient client.APIClient, serviceID case <-time.After(200 * time.Millisecond): case <-sigint: if !converged { - progress.Message(progressOut, "", "Operation continuing in background.") - progress.Messagef(progressOut, "", "Use `docker service ps %s` to check progress.", serviceID) + _ = progressOut.WriteProgress(progress.Progress{Message: "Operation continuing in background."}) + _ = progressOut.WriteProgress(progress.Progress{Message: fmt.Sprintf("Use `docker service ps %s` to check progress.", serviceID)}) } return nil } @@ -255,13 +255,13 @@ func initializeUpdater(service swarm.Service, progressOut progress.Output) (prog func writeOverallProgress(progressOut progress.Output, numerator, denominator int, rollback bool) { if rollback { - progressOut.WriteProgress(progress.Progress{ + _ = progressOut.WriteProgress(progress.Progress{ ID: "overall progress", Action: fmt.Sprintf("rolling back update: %d out of %d tasks", numerator, denominator), }) return } - progressOut.WriteProgress(progress.Progress{ + _ = progressOut.WriteProgress(progress.Progress{ ID: "overall progress", Action: fmt.Sprintf("%d out of %d tasks", numerator, denominator), }) @@ -305,7 +305,10 @@ func (u *replicatedProgressUpdater) update(service swarm.Service, tasks []swarm. if replicas <= maxProgressBars { for i := uint64(1); i <= replicas; i++ { - progress.Update(u.progressOut, fmt.Sprintf("%d/%d", i, replicas), " ") + _ = u.progressOut.WriteProgress(progress.Progress{ + ID: fmt.Sprintf("%d/%d", i, replicas), + Action: " ", + }) } } u.initialized = true @@ -388,7 +391,7 @@ func (u *replicatedProgressUpdater) writeTaskProgress(task swarm.Task, mappedSlo } if task.Status.Err != "" { - u.progressOut.WriteProgress(progress.Progress{ + _ = u.progressOut.WriteProgress(progress.Progress{ ID: fmt.Sprintf("%d/%d", mappedSlot, replicas), Action: truncError(task.Status.Err), }) @@ -396,7 +399,7 @@ func (u *replicatedProgressUpdater) writeTaskProgress(task swarm.Task, mappedSlo } if !terminalState(task.DesiredState) && !terminalState(task.Status.State) { - u.progressOut.WriteProgress(progress.Progress{ + _ = u.progressOut.WriteProgress(progress.Progress{ ID: fmt.Sprintf("%d/%d", mappedSlot, replicas), Action: fmt.Sprintf("%-[1]*s", longestState, task.Status.State), Current: numberedStates[task.Status.State], @@ -427,7 +430,7 @@ func (u *globalProgressUpdater) update(_ swarm.Service, tasks []swarm.Task, acti // Two possibilities: either the orchestrator hasn't created // the tasks yet, or the service doesn't meet constraints for // any node. Either way, we wait. - u.progressOut.WriteProgress(progress.Progress{ + _ = u.progressOut.WriteProgress(progress.Progress{ ID: "overall progress", Action: "waiting for new tasks", }) @@ -505,7 +508,7 @@ func (u *globalProgressUpdater) writeTaskProgress(task swarm.Task, nodeCount int } if task.Status.Err != "" { - u.progressOut.WriteProgress(progress.Progress{ + _ = u.progressOut.WriteProgress(progress.Progress{ ID: formatter.TruncateID(task.NodeID), Action: truncError(task.Status.Err), }) @@ -513,7 +516,7 @@ func (u *globalProgressUpdater) writeTaskProgress(task swarm.Task, nodeCount int } if !terminalState(task.DesiredState) && !terminalState(task.Status.State) { - u.progressOut.WriteProgress(progress.Progress{ + _ = u.progressOut.WriteProgress(progress.Progress{ ID: formatter.TruncateID(task.NodeID), Action: fmt.Sprintf("%-[1]*s", longestState, task.Status.State), Current: numberedStates[task.Status.State], @@ -593,7 +596,7 @@ func (u *replicatedJobProgressUpdater) update(_ swarm.Service, tasks []swarm.Tas // only write out progress bars if there will be less than the maximum if u.total <= maxProgressBars { for i := 1; i <= u.total; i++ { - u.progressOut.WriteProgress(progress.Progress{ + _ = u.progressOut.WriteProgress(progress.Progress{ ID: fmt.Sprintf("%d/%d", i, u.total), Action: " ", }) diff --git a/cli/command/swarm/progress/root_rotation.go b/cli/command/swarm/progress/root_rotation.go index 54e53e55d960..ea0e069bfb69 100644 --- a/cli/command/swarm/progress/root_rotation.go +++ b/cli/command/swarm/progress/root_rotation.go @@ -37,9 +37,9 @@ func RootRotationProgress(ctx context.Context, apiClient client.APIClient, progr defer signal.Stop(sigint) // draw 2 progress bars, 1 for nodes with the correct cert, 1 for nodes with the correct trust root - progress.Update(progressOut, "desired root digest", "") - progress.Update(progressOut, certsRotatedStr, certsAction) - progress.Update(progressOut, rootsRotatedStr, rootsAction) + _ = progressOut.WriteProgress(progress.Progress{ID: "desired root digest"}) + _ = progressOut.WriteProgress(progress.Progress{ID: certsRotatedStr, Action: certsAction}) + _ = progressOut.WriteProgress(progress.Progress{ID: rootsRotatedStr, Action: rootsAction}) var done bool @@ -64,8 +64,8 @@ func RootRotationProgress(ctx context.Context, apiClient client.APIClient, progr case <-time.After(200 * time.Millisecond): case <-sigint: if !done { - progress.Message(progressOut, "", "Operation continuing in background.") - progress.Message(progressOut, "", "Use `swarmctl cluster inspect default` to check progress.") + _ = progressOut.WriteProgress(progress.Progress{Message: "Operation continuing in background."}) + _ = progressOut.WriteProgress(progress.Progress{Message: "Use `swarmctl cluster inspect default` to check progress."}) } return nil } diff --git a/cmd/docker/internal/assets/docker.ico b/cmd/docker/internal/assets/docker.ico index 1d5ab4f0a9bd..e4bc5d4291ce 100644 Binary files a/cmd/docker/internal/assets/docker.ico and b/cmd/docker/internal/assets/docker.ico differ diff --git a/docs/reference/commandline/login.md b/docs/reference/commandline/login.md index 458edd7b91b0..4603bb96d655 100644 --- a/docs/reference/commandline/login.md +++ b/docs/reference/commandline/login.md @@ -6,11 +6,11 @@ Defaults to Docker Hub if no server is specified. ### Options -| Name | Type | Default | Description | -|:---------------------------------------------|:---------|:--------|:-------------------------------------------------------------------| -| `-p`, `--password` | `string` | | Password or Personal Access Token (PAT), or `-` to read from stdin | -| [`--password-stdin`](#password-stdin) | `bool` | | Take the Password or Personal Access Token (PAT) from stdin | -| [`-u`](#username), [`--username`](#username) | `string` | | Username | +| Name | Type | Default | Description | +|:---------------------------------------------|:---------|:--------|:-----------------------------------------------------| +| `-p`, `--password` | `string` | | Password or access token. Use `-` to read from stdin | +| [`--password-stdin`](#password-stdin) | `bool` | | Read password or access token from stdin | +| [`-u`](#username), [`--username`](#username) | `string` | | Username or organization name (for OATs) | @@ -229,6 +229,26 @@ with the username `moby`. The password is entered interactively. $ docker login -u moby ``` +### Authenticate with an access token + +To authenticate to Docker Hub with a [personal access token (PAT)](https://docs.docker.com/security/access-tokens/personal-access-tokens/) +or [organization access token (OAT)](https://docs.docker.com/security/access-tokens/organization-access-tokens/), +use the token in place of a password. + +For a PAT, use your Docker ID as the username. For an OAT, use your +organization name instead. The following example authenticates using +the organization `myorg`. The token is entered interactively. + +```console +$ docker login --username myorg +``` + +To authenticate non-interactively, see [Provide a password using STDIN](#password-stdin). + +> [!NOTE] +> OATs don't support Docker Desktop sign-in or Image Access Management. +> Use web-based sign-in or a PAT instead, where supported. + ### Provide a password using STDIN (--password-stdin) To run the `docker login` command non-interactively, you can set the diff --git a/vendor.mod b/vendor.mod index 8c2ecc54343c..a1bf702a647a 100644 --- a/vendor.mod +++ b/vendor.mod @@ -89,7 +89,7 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/klauspost/compress v1.20.2 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect - github.com/moby/sys/user v0.4.1 // indirect + github.com/moby/sys/user v0.5.1 // indirect github.com/moby/sys/userns v0.2.1 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/prometheus/client_golang v1.22.0 // indirect diff --git a/vendor.sum b/vendor.sum index 5e0a24bdb5cd..f13bf3fd84ff 100644 --- a/vendor.sum +++ b/vendor.sum @@ -110,8 +110,8 @@ github.com/moby/sys/signal v0.7.1 h1:PrQxdvxcGijdo6UXXo/lU/TvHUWyPhj7UOpSo8tuvk0 github.com/moby/sys/signal v0.7.1/go.mod h1:Se1VGehYokAkrSQwL4tDzHvETwUZlnY7S5XtQ50mQp8= github.com/moby/sys/symlink v0.3.0 h1:GZX89mEZ9u53f97npBy4Rc3vJKj7JBDj/PN2I22GrNU= github.com/moby/sys/symlink v0.3.0/go.mod h1:3eNdhduHmYPcgsJtZXW1W4XUJdZGBIkttZ8xKqPUJq0= -github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0= -github.com/moby/sys/user v0.4.1/go.mod h1:E9QsW5WRe1kUAf7kW8hXKwu1uhsZEAdPLYHYSDudF4Y= +github.com/moby/sys/user v0.5.1 h1:IMM/21OvpU2icUZczWBwLMf8iBEx1bOoiCQqcy1eKu0= +github.com/moby/sys/user v0.5.1/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow= github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8= github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= diff --git a/vendor/github.com/moby/sys/user/idtools.go b/vendor/github.com/moby/sys/user/idtools.go index 595b7a927263..147815311166 100644 --- a/vendor/github.com/moby/sys/user/idtools.go +++ b/vendor/github.com/moby/sys/user/idtools.go @@ -12,37 +12,39 @@ type mkdirOptions struct { onlyNew bool } -// WithOnlyNew is an option for MkdirAllAndChown that will only change ownership and permissions -// on newly created directories. If the directory already exists, it will not be modified +// WithOnlyNew configures [MkdirAllAndChown] and [MkdirAndChown] to leave +// the requested directory unchanged if it already exists. Newly created +// directories are still assigned the requested ownership and permissions. func WithOnlyNew(o *mkdirOptions) { o.onlyNew = true } -// MkdirAllAndChown creates a directory (include any along the path) and then modifies -// ownership to the requested uid/gid. By default, if the directory already exists, this -// function will still change ownership and permissions. If WithOnlyNew is passed as an -// option, then only the newly created directories will have ownership and permissions changed. +// MkdirAllAndChown creates a directory named path, along with any necessary +// parents, and applies the requested ownership and permission bits to all +// directories it creates. +// +// If path already exists as a directory, its ownership and permission bits +// are updated unless [WithOnlyNew] is specified. Existing parent directories +// are not modified. +// +// MkdirAllAndChown is similar to [os.MkdirAll], but also applies ownership and +// reapplies the requested permission bits after creation, so the resulting +// permissions are not affected by the process umask. func MkdirAllAndChown(path string, mode os.FileMode, uid, gid int, opts ...MkdirOpt) error { - var options mkdirOptions - for _, opt := range opts { - opt(&options) - } - - return mkdirAs(path, mode, uid, gid, true, options.onlyNew) + return mkdirAs(path, mode, uid, gid, true, opts...) } -// MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid. -// By default, if the directory already exists, this function still changes ownership and permissions. -// If WithOnlyNew is passed as an option, then only the newly created directory will have ownership -// and permissions changed. -// Note that unlike os.Mkdir(), this function does not return IsExist error -// in case path already exists. +// MkdirAndChown creates a directory named path and applies the requested +// ownership and permission bits. +// +// If path already exists as a directory, its ownership and permission bits +// are updated unless [WithOnlyNew] is specified. +// +// MkdirAndChown is similar to [os.Mkdir], but returns nil if path already +// exists as a directory. The resulting permission bits are not affected by +// the process umask. func MkdirAndChown(path string, mode os.FileMode, uid, gid int, opts ...MkdirOpt) error { - var options mkdirOptions - for _, opt := range opts { - opt(&options) - } - return mkdirAs(path, mode, uid, gid, false, options.onlyNew) + return mkdirAs(path, mode, uid, gid, false, opts...) } // getRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. @@ -106,22 +108,14 @@ func (i IdentityMapping) RootPair() (int, int) { return uid, gid } -// ToHost returns the host UID and GID for the container uid, gid. -// Remapping is only performed if the ids aren't already the remapped root ids +// ToHost returns the host UID and GID for the container uid and gid. +// An empty mapping is treated as identity. func (i IdentityMapping) ToHost(uid, gid int) (int, int, error) { - var err error - ruid, rgid := i.RootPair() - - if uid != ruid { - ruid, err = toHost(uid, i.UIDMaps) - if err != nil { - return ruid, rgid, err - } - } - - if gid != rgid { - rgid, err = toHost(gid, i.GIDMaps) + ruid, err := toHost(uid, i.UIDMaps) + if err != nil { + return -1, -1, err } + rgid, err := toHost(gid, i.GIDMaps) return ruid, rgid, err } diff --git a/vendor/github.com/moby/sys/user/idtools_unix.go b/vendor/github.com/moby/sys/user/idtools_unix.go index 4e39d2446b23..929aaa07a7e9 100644 --- a/vendor/github.com/moby/sys/user/idtools_unix.go +++ b/vendor/github.com/moby/sys/user/idtools_unix.go @@ -3,6 +3,7 @@ package user import ( + "errors" "fmt" "os" "path/filepath" @@ -10,57 +11,59 @@ import ( "syscall" ) -func mkdirAs(path string, mode os.FileMode, uid, gid int, mkAll, onlyNew bool) error { +func mkdirAs(path string, mode os.FileMode, uid, gid int, mkAll bool, opts ...MkdirOpt) error { + var options mkdirOptions + for _, opt := range opts { + opt(&options) + } + path, err := filepath.Abs(path) if err != nil { return err } - stat, err := os.Stat(path) - if err == nil { + stat, statErr := os.Stat(path) + if statErr == nil { if !stat.IsDir() { return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} } - if onlyNew { + // The requested directory already exists. Leave it unchanged when only + // newly created directories should receive the requested metadata. + if options.onlyNew { return nil } - - // short-circuit -- we were called with an existing directory and chown was requested return setPermissions(path, mode, uid, gid, stat) } - // make an array containing the original path asked for, plus (for mkAll == true) - // all path components leading up to the complete path that don't exist before we MkdirAll - // so that we can chown all of them properly at the end. If onlyNew is true, we won't - // chown the full directory path if it exists - var paths []string - if os.IsNotExist(err) { - paths = append(paths, path) + // Track the requested directory and any parent directories created by + // Mkdir/MkdirAll to set their ownership and permissions afterward. + var createdDirs []string + if errors.Is(statErr, os.ErrNotExist) { + createdDirs = append(createdDirs, path) } if mkAll { - // walk back to "/" looking for directories which do not exist - // and add them to the paths array for chown after creation - dirPath := path - for { - dirPath = filepath.Dir(dirPath) - if dirPath == "/" { - break - } - if _, err = os.Stat(dirPath); os.IsNotExist(err) { - paths = append(paths, dirPath) + if errors.Is(statErr, os.ErrNotExist) { + // Walk back to "/" looking for directories which do not exist + // and add them to the paths array for chown after creation. + // Stop at the first existing directory. + for p := filepath.Dir(path); p != "/"; p = filepath.Dir(p) { + if _, err := os.Stat(p); err == nil { + break + } else if errors.Is(err, os.ErrNotExist) { + createdDirs = append(createdDirs, p) + } } } - if err = os.MkdirAll(path, mode); err != nil { + if err := os.MkdirAll(path, mode); err != nil { return err } - } else if err = os.Mkdir(path, mode); err != nil { + } else if err := os.Mkdir(path, mode); err != nil { return err } - // even if it existed, we will chown the requested path + any subpaths that - // didn't exist when we called MkdirAll - for _, pathComponent := range paths { - if err = setPermissions(pathComponent, mode, uid, gid, nil); err != nil { + // Apply the requested ownership and permissions to each newly created directory. + for _, dir := range createdDirs { + if err := setPermissions(dir, mode, uid, gid, nil); err != nil { return err } } diff --git a/vendor/github.com/moby/sys/user/idtools_windows.go b/vendor/github.com/moby/sys/user/idtools_windows.go index 9de730cafbe0..3973d5593a22 100644 --- a/vendor/github.com/moby/sys/user/idtools_windows.go +++ b/vendor/github.com/moby/sys/user/idtools_windows.go @@ -2,12 +2,25 @@ package user import ( "os" + "syscall" ) -// This is currently a wrapper around [os.MkdirAll] since currently -// permissions aren't set through this path, the identity isn't utilized. -// Ownership is handled elsewhere, but in the future could be support here -// too. -func mkdirAs(path string, _ os.FileMode, _, _ int, _, _ bool) error { - return os.MkdirAll(path, 0) +// mkdirAs creates path, optionally creating any missing parent directories. +// +// On Windows this is currently a thin wrapper around os.Mkdir and +// os.MkdirAll. Unlike the Unix implementation, ownership and permission +// bits are not applied. +func mkdirAs(path string, _ os.FileMode, _, _ int, mkAll bool, _ ...MkdirOpt) error { + if mkAll { + return os.MkdirAll(path, 0) + } + stat, err := os.Stat(path) + if err == nil { + if !stat.IsDir() { + return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} + } + return nil + } + + return os.Mkdir(path, 0) } diff --git a/vendor/github.com/moby/sys/user/lookup_unix.go b/vendor/github.com/moby/sys/user/lookup_unix.go index 4540747d28fb..570793fe211c 100644 --- a/vendor/github.com/moby/sys/user/lookup_unix.go +++ b/vendor/github.com/moby/sys/user/lookup_unix.go @@ -20,7 +20,7 @@ const ( // cannot be found (or there is no /etc/passwd file on the filesystem), then // LookupUser returns an error. func LookupUser(username string) (User, error) { - return lookupUserFunc(func(u User) bool { + return lookupUserFileFilter(unixPasswdPath, func(u User) bool { return u.Name == username }) } @@ -29,21 +29,13 @@ func LookupUser(username string) (User, error) { // be found (or there is no /etc/passwd file on the filesystem), then LookupId // returns an error. func LookupUid(uid int) (User, error) { - return lookupUserFunc(func(u User) bool { + return lookupUserFileFilter(unixPasswdPath, func(u User) bool { return u.Uid == uid }) } -func lookupUserFunc(filter func(u User) bool) (User, error) { - // Get operating system-specific passwd reader-closer. - passwd, err := GetPasswd() - if err != nil { - return User{}, err - } - defer passwd.Close() - - // Get the users. - users, err := ParsePasswdFilter(passwd, filter) +func lookupUserFileFilter(path string, filter func(u User) bool) (User, error) { + users, err := ParsePasswdFileFilter(path, filter) if err != nil { return User{}, err } @@ -61,7 +53,7 @@ func lookupUserFunc(filter func(u User) bool) (User, error) { // be found (or there is no /etc/group file on the filesystem), then LookupGroup // returns an error. func LookupGroup(groupname string) (Group, error) { - return lookupGroupFunc(func(g Group) bool { + return lookupGroupFileFilter(unixGroupPath, func(g Group) bool { return g.Name == groupname }) } @@ -70,21 +62,13 @@ func LookupGroup(groupname string) (Group, error) { // be found (or there is no /etc/group file on the filesystem), then LookupGid // returns an error. func LookupGid(gid int) (Group, error) { - return lookupGroupFunc(func(g Group) bool { + return lookupGroupFileFilter(unixGroupPath, func(g Group) bool { return g.Gid == gid }) } -func lookupGroupFunc(filter func(g Group) bool) (Group, error) { - // Get operating system-specific group reader-closer. - group, err := GetGroup() - if err != nil { - return Group{}, err - } - defer group.Close() - - // Get the users. - groups, err := ParseGroupFilter(group, filter) +func lookupGroupFileFilter(path string, filter func(g Group) bool) (Group, error) { + groups, err := ParseGroupFileFilter(path, filter) if err != nil { return Group{}, err } @@ -98,18 +82,30 @@ func lookupGroupFunc(filter func(g Group) bool) (Group, error) { return groups[0], nil } +// GetPasswdPath returns the path to the system passwd file. func GetPasswdPath() (string, error) { return unixPasswdPath, nil } +// GetPasswd opens the system passwd file for reading. +// +// Unlike the file-based parsing functions, it does not restrict the file type +// or limit the amount of data that can be read. The caller is responsible for +// closing the returned reader. func GetPasswd() (io.ReadCloser, error) { return os.Open(unixPasswdPath) } +// GetGroupPath returns the path to the system group file. func GetGroupPath() (string, error) { return unixGroupPath, nil } +// GetGroup opens the system group file for reading. +// +// Unlike the file-based parsing functions, it does not restrict the file type +// or limit the amount of data that can be read. The caller is responsible for +// closing the returned reader. func GetGroup() (io.ReadCloser, error) { return os.Open(unixGroupPath) } diff --git a/vendor/github.com/moby/sys/user/user.go b/vendor/github.com/moby/sys/user/user.go index 857711ebfd21..66b4a4b48b96 100644 --- a/vendor/github.com/moby/sys/user/user.go +++ b/vendor/github.com/moby/sys/user/user.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "os" + "slices" "strconv" "strings" ) @@ -17,9 +18,9 @@ const ( ) var ( - // ErrNoPasswdEntries is returned if no matching entries were found in /etc/group. + // ErrNoPasswdEntries is returned if no matching entries were found in /etc/passwd. ErrNoPasswdEntries = errors.New("no matching entries in passwd file") - // ErrNoGroupEntries is returned if no matching entries were found in /etc/passwd. + // ErrNoGroupEntries is returned if no matching entries were found in /etc/group. ErrNoGroupEntries = errors.New("no matching entries in group file") // ErrRange is returned if a UID or GID is outside of the valid range. ErrRange = fmt.Errorf("uids and gids must be in range %d-%d", minID, maxID) @@ -56,44 +57,67 @@ type IDMap struct { Count int64 } -func parseLine(line []byte, v ...any) { - parseParts(bytes.Split(line, []byte(":")), v...) +// parseLine parses a colon-separated record into the provided fields. +// See [parseParts] for details. +func parseLine(line []byte, v ...any) bool { + return parseParts(bytes.Split(line, []byte(":")), v...) } -func parseParts(parts [][]byte, v ...any) { - if len(parts) == 0 { - return - } - - for i, p := range parts { - // Ignore cases where we don't have enough fields to populate the arguments. - // Some configuration files like to misbehave. - if len(v) <= i { - break +// parseParts parses the provided parts into the corresponding fields, +// and reports whether the record is valid. +// +// Missing fields are treated as empty. Empty string fields are accepted, +// but missing, empty, non-numeric, or out-of-range integer fields make +// the record invalid. For *int fields (UIDs and GIDs), the valid range +// is the one checked by [validateID]. +// +// This follows the behavior of glibc's passwd and group parsers, which +// skip malformed records when reading entries. +// +// See https://sources.debian.org/src/glibc/2.42-13/nss/nss_fgetent_r.c/ +// and https://sources.debian.org/src/glibc/2.42-13/nss/fgetpwent_r.c/#L150-L165 +func parseParts(parts [][]byte, fields ...any) bool { + for i, v := range fields { + var p []byte + if i < len(parts) { + p = parts[i] } // Use the type of the argument to figure out how to parse it, scanf() style. // This is legit. - switch e := v[i].(type) { + switch e := v.(type) { case *string: *e = string(p) case *int: - // "numbers", with conversion errors ignored because of some misbehaving configuration files. - *e, _ = strconv.Atoi(string(p)) + // The only *int fields are UIDs and GIDs. + n, err := parseNumeric(string(p)) + if err != nil { + return false + } + *e = n case *int64: - *e, _ = strconv.ParseInt(string(p), 10, 64) + n, err := strconv.ParseInt(string(p), 10, 64) + if err != nil { + return false + } + *e = n case *[]string: - // Comma-separated lists. - if len(p) != 0 { - *e = strings.Split(string(p), ",") - } else { - *e = []string{} + // Comma-separated lists. Like glibc, skip leading whitespace + // (but keep trailing one), and drop empty elements. + // + // See https://sources.debian.org/src/glibc/2.42-13/nss/nss_files/files-parse.c/#L278-L291 + *e = []string{} + for s := range strings.SplitSeq(string(p), ",") { + if s = strings.TrimLeft(s, " \t\n\v\f\r"); s != "" { + *e = append(*e, s) + } } default: // Someone goof'd when writing code using this function. Scream so they can hear us. panic(fmt.Sprintf("parseLine only accepts {*string, *int, *int64, *[]string} as arguments! %#v is not a pointer!", e)) } } + return true } func ParsePasswdFile(path string) ([]User, error) { @@ -105,7 +129,7 @@ func ParsePasswd(passwd io.Reader) ([]User, error) { } func ParsePasswdFileFilter(path string, filter func(User) bool) ([]User, error) { - passwd, err := os.Open(path) + passwd, err := openUserFile(path) if err != nil { return nil, err } @@ -124,8 +148,9 @@ func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { ) for s.Scan() { + // Skip blank lines and comments, like glibc does (see ParseGroupFilter). line := bytes.TrimSpace(s.Bytes()) - if len(line) == 0 { + if len(line) == 0 || line[0] == '#' { continue } @@ -135,7 +160,10 @@ func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { // root:x:0:0:root:/root:/bin/bash // adm:x:3:4:adm:/var/adm:/bin/false p := User{} - parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell) + if !parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell) { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) @@ -194,7 +222,10 @@ func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) { // root:x:0:root // adm:x:4:root,adm,daemon p := Group{} - parseLine(line, &p.Name, &p.Pass, &p.Gid, &p.List) + if !parseLine(line, &p.Name, &p.Pass, &p.Gid, &p.List) { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) @@ -234,36 +265,50 @@ func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath return GetExecUser(userSpec, defaults, passwd, group) } -// parseNumeric parses the given UID or GID value to an integer and within -// the minID - maxID range. +// validateID checks whether a UID or GID is within the supported range, +// returning [ErrRange] if it is not. // -// While the Linux kernel allows the max UID to be MaxUint32 - 2, -// and the OCI Runtime Spec has no definition about the max UID, we require -// the UID to be <= MaxInt32. +// While the Linux kernel allows UIDs up to MaxUint32 - 2, and the OCI +// Runtime Spec does not define a maximum UID, we restrict IDs to MaxInt32 +// for compatibility with 32-bit systems and OCI runtimes. // // See https://github.com/containerd/containerd/commit/de1341c201ffb0effebbf51d00376181968c8779 -func parseNumeric(val string) (int, bool, error) { - if val == "" { - return 0, false, nil +func validateID(id int) error { + if id < minID || id > maxID { + return ErrRange } + return nil +} + +// parseNumeric parses a UID or GID as an integer within the supported range. +func parseNumeric(val string) (int, error) { id, err := strconv.Atoi(val) if err != nil { - if errors.Is(err, strconv.ErrSyntax) { - // Discard the error, because non-numeric values are expected - // when passing a username or group-name. - return 0, false, nil - } if errors.Is(err, strconv.ErrRange) { - return 0, true, ErrRange + return 0, ErrRange } - // Other errors ("invalid base", "invalid bit size"); should never - // happen with strconv.Atoi. - return 0, false, err + return 0, err } - if id < minID || id > maxID { - return 0, true, ErrRange + if err := validateID(id); err != nil { + return 0, err + } + return id, nil +} + +// parseMaybeNumeric parses a UID or GID as a numeric ID, or indicates +// that the value should be interpreted as a username or group name. +// +// Non-numeric values are expected when passing a username or group name, +// so syntax errors are ignored. The boolean indicates whether the value +// was interpreted as a numeric ID. +func parseMaybeNumeric(val string) (int, bool, error) { + id, err := parseNumeric(val) + if errors.Is(err, strconv.ErrSyntax) { + // Discard the error, because non-numeric values are expected + // when passing a username or group-name. + return 0, false, nil } - return id, true, nil + return id, true, err } // GetExecUser parses a user specification string (using the passwd and group @@ -296,51 +341,40 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) ( user := &ExecUser{ Uid: defaults.Uid, Gid: defaults.Gid, - Sgids: defaults.Sgids, + Sgids: append([]int{}, defaults.Sgids...), // Sgids slice *cannot* be nil. Home: defaults.Home, } - // Sgids slice *cannot* be nil. - if user.Sgids == nil { - user.Sgids = []int{} - } - - // Allow for userArg to have either "user" syntax, or optionally "user:group" syntax - var userArg, groupArg string - parseLine([]byte(userSpec), &userArg, &groupArg) + // Allow for userSpec to have either "user", or optionally "user:group" syntax. + usr, grp, _ := strings.Cut(userSpec, ":") - // Convert userArg and groupArg to be numeric, so we don't have to execute + // Convert usr and grp to be numeric, so we don't have to execute // Atoi *twice* for each iteration over lines. - uidArg, isUID, err := parseNumeric(userArg) + userArg, err := parseUserArg(usr) if err != nil { return nil, err } - gidArg, isGID, err := parseNumeric(groupArg) + groupArg, err := parseGroupArg(grp) if err != nil { return nil, err } // Find the matching user. users, err := ParsePasswdFilter(passwd, func(u User) bool { - if userArg == "" { + if userArg == nil { // Default to current state of the user. return u.Uid == user.Uid } - - if isUID { - // If the userArg is a valid numeric value, always treat it as a UID. - return uidArg == u.Uid - } - - return u.Name == userArg + return userArg.matches(u) }) // If we can't find the user, we have to bail. if err != nil && passwd != nil { - if userArg == "" { - userArg = strconv.Itoa(user.Uid) + name := usr + if userArg == nil { + name = strconv.Itoa(user.Uid) } - return nil, fmt.Errorf("unable to find user %s: %w", userArg, err) + return nil, fmt.Errorf("unable to find user %s: %w", name, err) } var matchedUserName string @@ -350,57 +384,42 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) ( user.Uid = users[0].Uid user.Gid = users[0].Gid user.Home = users[0].Home - } else if userArg != "" { + } else if userArg != nil { // If we can't find a user with the given username, the only other valid // option is if it's a numeric username with no associated entry in passwd. - - if !isUID { - // Not numeric. - return nil, fmt.Errorf("unable to find user %s: %w", userArg, ErrNoPasswdEntries) + if !userArg.isNumeric { + return nil, fmt.Errorf("unable to find user %s: %w", userArg.name, ErrNoPasswdEntries) } - user.Uid = uidArg + user.Uid = userArg.uid } // On to the groups. If we matched a username, we need to do this because of // the supplementary group IDs. - if groupArg != "" || matchedUserName != "" { + if groupArg != nil || matchedUserName != "" { groups, err := ParseGroupFilter(group, func(g Group) bool { // If the group argument isn't explicit, we'll just search for it. - if groupArg == "" { + if groupArg == nil { // Check if user is a member of this group. - for _, u := range g.List { - if u == matchedUserName { - return true - } - } - return false + return slices.Contains(g.List, matchedUserName) } - - if isGID { - // If the groupArg is numeric, always treat it as a GID. - return gidArg == g.Gid - } - - return g.Name == groupArg + return groupArg.matches(g) }) if err != nil && group != nil { return nil, fmt.Errorf("unable to find groups for spec %v: %w", matchedUserName, err) } // Only start modifying user.Gid if it is in explicit form. - if groupArg != "" { + if groupArg != nil { if len(groups) > 0 { // First match wins, even if there's more than one matching entry. user.Gid = groups[0].Gid } else { // If we can't find a group with the given name, the only other valid // option is if it's a numeric group name with no associated entry in group. - - if !isGID { - // Not numeric. - return nil, fmt.Errorf("unable to find group %s: %w", groupArg, ErrNoGroupEntries) + if !groupArg.isNumeric { + return nil, fmt.Errorf("unable to find group %s: %w", groupArg.name, ErrNoGroupEntries) } - user.Gid = gidArg + user.Gid = groupArg.gid } } else if len(groups) > 0 { // Supplementary group ids only make sense if in the implicit form. @@ -414,39 +433,22 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) ( return user, nil } -// groupArg is a parsed group argument for [GetAdditionalGroups]. -type groupArg struct { - name string - gid int - isNumeric bool -} - -// matches reports whether group g satisfies the argument. Numeric arguments -// are matched by GID only, others by name. -func (ag groupArg) matches(g Group) bool { - if ag.isNumeric { - return g.Gid == ag.gid - } - return g.Name == ag.name -} - // GetAdditionalGroups looks up a list of groups by name or group id // against the given /etc/group formatted data. If a group name cannot // be found, an error will be returned. If a group id cannot be found, // or the given group data is nil, the id will be returned as-is // provided it is in the legal range. func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) { - addtlGroups := make([]groupArg, len(additionalGroups)) - for i, ag := range additionalGroups { - gid, ok, err := parseNumeric(ag) + addtlGroups := make([]groupArg, 0, len(additionalGroups)) + for _, ag := range additionalGroups { + groupArg, err := parseGroupArg(ag) if err != nil { return nil, err } - addtlGroups[i] = groupArg{ - name: ag, - gid: gid, - isNumeric: ok, + if groupArg == nil { + return nil, errors.New("empty group name") } + addtlGroups = append(addtlGroups, *groupArg) } groups := []Group{} @@ -471,9 +473,6 @@ func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, err for _, g := range groups { if ag.matches(g) { // take the first matched group as correct - if g.Gid < minID || g.Gid > maxID { - return nil, ErrRange - } gidMap[g.Gid] = struct{}{} found = true break @@ -501,25 +500,46 @@ func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, err // that opens the groupPath given and gives it as an argument to // GetAdditionalGroups. func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { - var group io.Reader - - if groupFile, err := os.Open(groupPath); err == nil { - group = groupFile - defer groupFile.Close() + groupFile, err := openUserFile(groupPath) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + return GetAdditionalGroups(additionalGroups, nil) } - return GetAdditionalGroups(additionalGroups, group) + defer func() { _ = groupFile.Close() }() + + return GetAdditionalGroups(additionalGroups, groupFile) } +// maxSubID is the maximum subordinate ID (maxof(id_t) in shadow-utils). +const maxSubID = 1<<32 - 1 + +// valid reports whether s is a valid subordinate ID range. It follows the +// checks done by shadow-utils: the name must not be empty, and the range +// must fit into 32-bit IDs. +// +// See https://github.com/shadow-maint/shadow/blob/24bc15eac4dcdec9c73c59988fe030b44a98c3de/lib/subordinateio.c#L93-L127 +func (s SubID) valid() bool { + return s.Name != "" && + s.SubID >= 0 && s.SubID <= maxSubID && + s.Count >= 0 && s.Count <= min(maxSubID+1-s.SubID, maxSubID) +} + +// ParseSubIDFile parses subordinate UID/GID ranges from the specified file. func ParseSubIDFile(path string) ([]SubID, error) { return ParseSubIDFileFilter(path, nil) } +// ParseSubID parses subordinate UID/GID ranges from the provided reader. func ParseSubID(subid io.Reader) ([]SubID, error) { return ParseSubIDFilter(subid, nil) } +// ParseSubIDFileFilter parses subordinate UID/GID ranges from the specified +// file, returning only entries matching filter. A nil filter matches all entries. func ParseSubIDFileFilter(path string, filter func(SubID) bool) ([]SubID, error) { - subid, err := os.Open(path) + subid, err := openUserFile(path) if err != nil { return nil, err } @@ -527,6 +547,8 @@ func ParseSubIDFileFilter(path string, filter func(SubID) bool) ([]SubID, error) return ParseSubIDFilter(subid, filter) } +// ParseSubIDFilter parses subordinate UID/GID ranges from the provided reader, +// returning only entries matching filter. A nil filter matches all entries. func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) { if r == nil { return nil, errors.New("nil source for subid-formatted data") @@ -544,8 +566,15 @@ func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) { } // see: man 5 subuid + // name:subid:count + // Name:SubID:Count + // user:100000:65536 + parts := bytes.Split(line, []byte(":")) p := SubID{} - parseLine(line, &p.Name, &p.SubID, &p.Count) + if len(parts) != 3 || !parseParts(parts, &p.Name, &p.SubID, &p.Count) || !p.valid() { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) @@ -558,23 +587,36 @@ func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) { return out, nil } +// ParseIDMapFile parses ID mappings from the specified file. func ParseIDMapFile(path string) ([]IDMap, error) { return ParseIDMapFileFilter(path, nil) } +// ParseIDMap parses ID mappings from r. func ParseIDMap(r io.Reader) ([]IDMap, error) { return ParseIDMapFilter(r, nil) } +// ParseIDMapFileFilter parses ID mappings from the specified file, +// returning only entries matching filter. A nil filter matches all entries. +// Reads are limited to 10 MiB, but non-regular files are allowed to support +// procfs-backed UID/GID mapping files. func ParseIDMapFileFilter(path string, filter func(IDMap) bool) ([]IDMap, error) { - r, err := os.Open(path) + // ID mapping files are typically procfs files, so we cannot use + // openUserFile's regular-file check. Enforce the read limit separately. + f, err := os.Open(path) if err != nil { return nil, err } - defer r.Close() + + r := newLimitedFile(f) + defer func() { _ = r.Close() }() + return ParseIDMapFilter(r, filter) } +// ParseIDMapFilter parses ID mappings from r, returning only entries +// matching filter. A nil filter matches all entries. func ParseIDMapFilter(r io.Reader, filter func(IDMap) bool) ([]IDMap, error) { if r == nil { return nil, errors.New("nil source for idmap-formatted data") @@ -593,7 +635,10 @@ func ParseIDMapFilter(r io.Reader, filter func(IDMap) bool) ([]IDMap, error) { // see: man 7 user_namespaces p := IDMap{} - parseParts(bytes.Fields(line), &p.ID, &p.ParentID, &p.Count) + if !parseParts(bytes.Fields(line), &p.ID, &p.ParentID, &p.Count) { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) diff --git a/vendor/github.com/moby/sys/user/user_utils.go b/vendor/github.com/moby/sys/user/user_utils.go index 978aa927ed30..86fe8830548e 100644 --- a/vendor/github.com/moby/sys/user/user_utils.go +++ b/vendor/github.com/moby/sys/user/user_utils.go @@ -12,6 +12,8 @@ import ( // generous headroom while bounding memory usage. const maxUserFileBytes = 10 << 20 +var errNotRegularFile = errors.New("not a regular file") + // openUserFile attempts to open a user-database file with a limitedFile // capped at maxUserFileBytes. It produces an error if the given path is // a non-regular file. @@ -31,18 +33,22 @@ func openUserFile(path string) (*limitedFile, error) { return nil, &os.PathError{ Op: "open", Path: path, - Err: errors.New("not a regular file"), + Err: errNotRegularFile, } } + return newLimitedFile(f), nil +} + +func newLimitedFile(f *os.File) *limitedFile { return &limitedFile{ File: f, // Allow one byte past the cap so an overflow surfaces as an // error rather than a silent EOF that the parser would treat as // a clean end-of-file (and miss any entries past the cap). LimitedReader: &io.LimitedReader{R: f, N: maxUserFileBytes + 1}, - name: path, - }, nil + name: f.Name(), + } } type limitedFile struct { @@ -62,3 +68,65 @@ func (l *limitedFile) Read(p []byte) (int, error) { } return n, err } + +// userArg is a parsed user argument for [GetExecUser]. +type userArg struct { + name string + uid int + isNumeric bool +} + +// parseUserArg parses a user argument as either a user name or UID. +// +// If name is empty, parseUserArg returns "nil, nil" to indicate that no user +// argument was specified. +func parseUserArg(name string) (*userArg, error) { + if name == "" { + return nil, nil + } + uid, isNumeric, err := parseMaybeNumeric(name) + if err != nil { + return nil, err + } + return &userArg{name: name, uid: uid, isNumeric: isNumeric}, nil +} + +// matches reports whether user u satisfies the argument. Numeric arguments +// are matched by UID only, others by name. +func (ua *userArg) matches(u User) bool { + if ua.isNumeric { + return u.Uid == ua.uid + } + return u.Name == ua.name +} + +// groupArg is a parsed group argument for [GetAdditionalGroups] or [GetExecUser]. +type groupArg struct { + name string + gid int + isNumeric bool +} + +// parseGroupArg parses a group argument as either a group name or GID. +// +// If name is empty, parseGroupArg returns "nil, nil" to indicate that no group +// argument was specified. +func parseGroupArg(name string) (*groupArg, error) { + if name == "" { + return nil, nil + } + gid, isNumeric, err := parseMaybeNumeric(name) + if err != nil { + return nil, err + } + return &groupArg{name: name, gid: gid, isNumeric: isNumeric}, nil +} + +// matches reports whether group g satisfies the argument. Numeric arguments +// are matched by GID only, others by name. +func (ag groupArg) matches(g Group) bool { + if ag.isNumeric { + return g.Gid == ag.gid + } + return g.Name == ag.name +} diff --git a/vendor/modules.txt b/vendor/modules.txt index a4d5bcda8909..d1d2f7a9a131 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -228,8 +228,8 @@ github.com/moby/sys/signal # github.com/moby/sys/symlink v0.3.0 ## explicit; go 1.17 github.com/moby/sys/symlink -# github.com/moby/sys/user v0.4.1 -## explicit; go 1.18 +# github.com/moby/sys/user v0.5.1 +## explicit; go 1.24 github.com/moby/sys/user # github.com/moby/sys/userns v0.2.1 ## explicit; go 1.21