Compare commits

..
Author SHA1 Message Date
Payton Ward 77f82e18b5 Add --ldap-username and --ldap-password flags to mc idp ldap accesskey create-with-login (#5258)
Add ldap-username and ldap-password flags to "idp ldap accesskey create-with-login"
2025-11-06 08:25:29 -08:00
Klaus Post ed0b962588 Modernize + Go version bump + Pin linter (#5256)
* Upgrade go version in CI.
* Add toolchain to pin version.
* Add linter/fumpt as pinned version in tools.
* Run `go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix -test ./...`
2025-11-05 04:20:36 -08:00
dorman 7394ce0dd2 feat: beautify output for the ping command (#5237) 2025-08-13 01:35:41 -07:00
Daryl White b01f0c7371 Update links to new docs site (#5242) 2025-08-13 01:35:23 -07:00
dorman 5bb5df85e2 Fix the abnormal exit of the ping command (#5233)
The ping command abnormally exits after being executed more than 1000 times.
2025-07-23 13:36:38 -07:00
M Alvee ae1eab7d52 chore: clear error message with unauthorized credentials (#5236) 2025-07-23 13:36:17 -07:00
Yashwanth Krishnan ee72571936 update dependencies to fix dependent library CVEs: CVE-2025-22874, CVE-2025-4673 (#5235) 2025-07-20 22:28:08 -07:00
Shreyas Mali e5d2270535 fix: mirror active-active and race condition (#5234) 2025-07-19 07:45:24 -07:00
M Alvee 2676e50bc1 fix: redact sse key in debug logs (#5231) 2025-07-16 08:35:03 -07:00
dorman f72d75db5a mv:support set tag and checksum (#5133) 2025-07-13 11:52:53 -07:00
dorman c305d62fd5 ping: support ping a specified node and remove duplicate port printing (#5132) 2025-07-13 11:48:37 -07:00
Matthieu OLIVIER 4e38f39e25 feat: add --storage-class option to mc put subcommand (#5228)
feat: add --storage-class option to mc put
2025-07-13 11:46:49 -07:00
dorman 8576e735b1 mirror and cp support set the maximum number of threads (#5220) 2025-07-02 09:49:52 -07:00
Klaus Post 9a180cece7 Some paths like url2Stat will send resource with backslashes on windows (#5226)
This will cause key paths to mismatch and not be sent.

Example:

```
λ go build&&mc stat -enc-c="play/testbucket/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDA" play/testbucket/mc
Name      : mc
Date      : 2025-07-02 17:52:42 CEST
Size      : 43 MiB
ETag      : 398345f23dc2ad4dd277e437e6ca7a1d-3
Type      : file
Encryption: SSE-C
Metadata  :
  Content-Type: application/x-msdownload
```
2025-07-02 09:49:02 -07:00
Menno Finlay-Smits 039be57dd2 Include ARN in "replicate list" output (#5215)
The "replicate resync start" command requires the remote bucket ARN.
This is currently difficult to obtain and requires picking through the
output of "replicate list --json". Worse still, the JSON output doesn't
contain the human-readable host for the bucket, making it difficult to
know that you've got the correct one.

This change solves the issue by including the ARN in the default list
output.
2025-06-25 08:26:44 -07:00
Klaus Post 3c9df3f2ea Update build version (#5218)
Fixes #5217
2025-06-24 02:41:42 -07:00
Burkov Egor 00fb114bce fix: add checks for nil HTTP in admin-trace matches func (#5216) 2025-06-23 08:14:30 -07:00
Harshavardhana 68f1d43f05 remove fips 'mc' container Dockerfile 2025-05-24 22:02:12 -07:00
Krutika Dhananjay f71ad84bcf Fix deletion of previously sync'd buckets and objects during mc-mirror (#5205) 2025-05-20 18:59:54 -07:00
angry-garden-salad 99c1b4365a Add STATUS column to batch job list table output (#5202) 2025-05-19 14:17:46 -07:00
jiuker 18c1c94d85 fix: remove check if lock config exists before set (#5203) 2025-05-19 01:05:02 -07:00
Shreyas Mali b9f30231ca removing config cmd (#5201) 2025-05-19 00:46:25 -07:00
Shreyas Mali 19d87ba475 fix: support chained mirror properly for delete propagation #4558 (#5197) 2025-05-06 09:41:33 -07:00
Klaus Post bbfe579fef Change support profile defaults (#5198)
* Remove block and mutex as they are rather intensive and provide little information.
* Add 'runtime'. Small, not intensive and possibly useful. Ignored by non-AIStor.
* Do 15 seconds for better data.
2025-05-06 08:10:18 -07:00
angry-garden-salad 2c1e058767 Explicitly set file permissions for admin-cluster-{bucket,iam}-export… (#5194)
Explicitly set file permissions for admin-cluster-{bucket,iam}-export.go to 600 regardless of umask
2025-05-02 09:34:41 -07:00
Aditya Manthramurthy 0a686cf874 Add support for catalog batch job type (#5150)
- During batch yaml generation, we check if the server supports the kind
of batch job requested.
- Shows catalog job status
2025-05-02 09:33:45 -07:00
Taran Pelkey 719f121225 Add idp openid accesskey commands (#5182) 2025-05-02 09:33:10 -07:00
jiuker b00526b153 feat: add deletemarker info for batch status (#5191) 2025-04-16 11:13:26 -07:00
Olli Janatuinen 391616f9cf mirror: skip status message from excluded buckets (#5190) 2025-04-10 08:51:27 -07:00
Burkov Egor ddda0fce2c typo: fix typo in tracing error for path (#5189) 2025-04-10 08:51:05 -07:00
Burkov Egor 0b4d69bc57 fix: update better error handling (#5188) 2025-04-10 08:50:18 -07:00
Mark Theunissen e929f89cee ConsoleMsg is not set by open source or AIStor, we should remove this an… (#5186)
ConsoleMsg is not set by open source or eos, we should remove this and correctly show Message only
2025-04-08 08:39:49 -07:00
dorman 56f94fd375 fix the terminal is damaged when parameters are missing (#5175) 2025-04-03 10:07:56 -07:00
jiuker 2d305ce990 fix: error out when the source and destination might be subdirectories of each other (#5173) 2025-04-01 22:51:22 -07:00
Harshavardhana 3296636c25 fix: replace tag and point to relevant release 2025-03-31 15:31:04 -07:00
Taran Pelkey 5349af0082 Add admin accesskey sts-revoke and idp ldap accesskey sts-revoke (#5160) 2025-03-31 13:55:31 -07:00
dorman ceb07bee89 fix return EOF failure on lines with trailing empty lines (#5176) 2025-03-28 02:05:40 -07:00
jiuker 5ce725ba7d fix: no data transition will show error for when mc ilm info not found (#5177) 2025-03-28 01:26:11 -07:00
Harshavardhana c652022dab upgrade golang-lint to v2 (#5178) 2025-03-28 01:05:40 -07:00
Harshavardhana d249b65941 pre-emptively disable sha256 payload if checksum is set (#5167) 2025-03-27 12:54:23 -07:00
dependabot[bot] b2d265dcc6 build(deps): bump github.com/golang-jwt/jwt/v4 from 4.5.1 to 4.5.2 (#5169)
Bumps [github.com/golang-jwt/jwt/v4](https://github.com/golang-jwt/jwt) from 4.5.1 to 4.5.2.
- [Release notes](https://github.com/golang-jwt/jwt/releases)
- [Changelog](https://github.com/golang-jwt/jwt/blob/main/VERSION_HISTORY.md)
- [Commits](https://github.com/golang-jwt/jwt/compare/v4.5.1...v4.5.2)

---
updated-dependencies:
- dependency-name: github.com/golang-jwt/jwt/v4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-24 08:40:50 -07:00
Aditya Manthramurthy 0f061900ee batch: use server's generate API when available (#5166)
Uses the new GenerateBatchJobV2 API to request server to list supported
batch jobs and to request job templates in `mc batch generate`
2025-03-14 10:29:01 -07:00
Klaus Post cf909e1063 Add ping sort to mc support top rpc (#5158)
Use key 'p' to sort by ping.
2025-03-13 01:02:18 -07:00
Aditya Manthramurthy c1d5d4cbb4 Update all deps (#5165) 2025-03-12 10:29:24 -07:00
Shireesh Anjal b3a00e0f8c Update madmin-go to latest version (#5161)
and clear reference to the removed variable madmin.HealthDataTypeSysLoad
2025-03-11 10:47:28 -07:00
Aditya Manthramurthy 06520070bb Update ssh and jws libs for fixed CVEs (#5164)
-   https://pkg.go.dev/vuln/GO-2025-3488
-   https://pkg.go.dev/vuln/GO-2025-3487
2025-03-11 09:36:39 -07:00
Harshavardhana ce874fdc6a rename rcp -> rpc 2025-03-07 15:46:22 -08:00
Shireesh Anjal 1e412f58a5 Remove logs feature from 'mc support callhome' (#5157)
Both the flags --logs and --diag are removed, and the command supports
only diagnostics callhome.
2025-03-06 08:30:58 -08:00
jinapurapu b0f40b4db7 Reject add ILM rule with both day and date parameters (#5155) 2025-03-06 05:05:05 -08:00
jinapurapu 10035268c4 Fix transition days calculation (#5154) 2025-03-05 13:23:17 -08:00
Klaus Post 9eb205cb62 Mirror should delete on delete marker creation + ILM (#5148)
Fixes #5147
2025-02-21 08:00:46 -08:00
jiuker 0ba848a99e fix: use tags package instead of s3utils (#5146) 2025-02-20 00:54:15 -08:00
Grahit 28909abaa4 fix empty ilm tier list output (#5145) 2025-02-19 20:27:26 -08:00
Harshavardhana 383560b1c3 update all dependencies (#5143) 2025-02-15 02:36:16 -08:00
Anis Eleuch 8585339d12 More fixes to custom arch hotfix building (#5135)
Set TARGET_GOOS and TARGET_GOARCH to specify the target architecture of
the built binary.
2025-02-14 08:49:56 -08:00
jiuker 468ab39f41 test: add tags copy test for mirror (#5141) 2025-02-14 08:49:41 -08:00
Klaus Post 217d92358b Add CRC64NVME checksum type. (#5142)
Also adds `CRC32-FO` and `CRC32C-FO` for complete object checksums.

```
λ mc cp -checksum=crc64nvme mc.exe myminio/testbucket
...com\minio\mc\mc.exe: 41.95 MiB / 41.95 MiB

λ mc stat myminio/testbucket/mc.exe
Name      : mc.exe
Date      : 2025-02-14 13:59:05 CET
Size      : 42 MiB
ETag      : 7f130846cec6e6ece750565b1f3d9518-3
VersionID : f4daeb78-9eaf-4da9-b9ca-d8b65fbc69e3
Type      : file
Checksum  : CRC64NVME:TOfg0RHhpZk=
Metadata  :
  Content-Type: application/x-msdownload

λ mc cp -checksum=crc32-fo mc.exe myminio/testbucket
...com\minio\mc\mc.exe: 41.95 MiB / 41.95 MiB

λ mc stat myminio/testbucket/mc.exe
Name      : mc.exe
Date      : 2025-02-14 13:58:52 CET
Size      : 42 MiB
ETag      : 7f130846cec6e6ece750565b1f3d9518-3
VersionID : 1ec587dd-9127-42ee-ad82-58b48f9676d5
Type      : file
Checksum  : CRC32:3Dt3fQ==
Metadata  :
  Content-Type: application/x-msdownload

λ _
```
2025-02-14 08:13:46 -08:00
Mark Theunissen c32317ef80 Improve docs to hint to the user that MD5 is not stored (#5138)
Improve docs to hint to the user that MD5 is the odd one out in this list
2025-02-13 10:19:41 -08:00
jiuker 089f833ce0 feat: support --custom-header flags (#5127) 2025-02-13 10:18:53 -08:00
Burkov Egor 42b78ded3a fix: explicit fd close fix (#5129) 2025-02-13 02:41:18 -08:00
jiuker 147e8f5b3b feat: add tags copy for mirror (#5137) 2025-02-13 02:39:59 -08:00
Klaus Post e97f4324d5 Fix vet check (#5134)
... and pin toolchain.
2025-02-12 08:36:32 -08:00
Harshavardhana 859c5989a1 make custom ARCH based hotfixes 2025-02-11 15:37:45 -08:00
Harshavardhana 10c50368c5 remove fips build 2025-02-08 13:06:32 -08:00
dorman bd925c01a1 mirror: add the duration time and beautify the output (#5125)
add the duration time and beautify the output
2025-02-08 11:14:21 -08:00
Burkov Egor 030c8125eb fix: urls equals nil deref (#5126)
Now in checks we can get nil dereference while both struct has Content
field of nil. But in code we cheching for nil, and I believe that
testcase can be real:
```go
urls1 := URLs{};
urls2 := URLs{};
urls1.Equal(urls2);
```
2025-02-07 02:46:26 -08:00
Harshavardhana 6376279f15 add support for pre-2023 minio deployments (#5122) 2025-02-04 14:18:02 -08:00
Taran Pelkey 5aee0b1c9e Change enable to "enable=" (#5104) 2025-02-04 12:34:19 -08:00
Sveinn ( keyb1nd ) 8d713ff927 Giving mirror the option to exit early when --remove is not set (#5116)
* Giving mirror the option to exit early when --remove is not set
* Making sure always to cancel the context on exit
* Adding an internal flag to enable local listing only based on active/active and remove flags
* Renaming localListingOnly to sourceListingOnly
2025-02-04 12:32:54 -08:00
Klaus Post 318e707071 Add "mc support upload" encryption (#5113)
* Add `--enc` parameter to `mc support upload` to encrypt the file content.
* Add file size as zstd frame content size.
* Test opening the file before doing more.
* Uses same key as "mc support inspect".
2025-02-03 20:57:50 -08:00
Harshavardhana 423ef1ba2a update go deps 2025-01-22 23:47:51 -08:00
Shubhendu a4f20fe74c Use latest madmin-go for policy content check (#5109)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2025-01-22 23:41:01 -08:00
Mark Theunissen 5cfac09600 Improve the error message when trying to add multiple expiry options (#5117) 2025-01-22 22:51:38 -08:00
Klaus Post b436cd2436 mc find - allow absolute times (#5118)
For `--newer-than` and `--older-than`, allow using absolute times.

Example:

```
λ mc ls play/testbucket
[2025-01-22 09:57:12 CET] 676KiB STANDARD Daily checks Procedure for Portainer.docx
[2025-01-22 16:40:07 CET]  22KiB STANDARD dovrennost_mobilizaciya_0-2.docx

λ mc find -newer-than="2025-01-22 09:57:00 CET" play/testbucket
play/testbucket/Daily checks Procedure for Portainer.docx
play/testbucket/dovrennost_mobilizaciya_0-2.docx

λ mc find -newer-than="2025-01-22 09:57:13 CET" play/testbucket
play/testbucket/dovrennost_mobilizaciya_0-2.docx
```

We allow the same timestamp types as `--rewind` and add the printed type for easy copy+paste.
2025-01-22 22:51:15 -08:00
dorman 0019b7b83c fix: cp and mirror commands fail to be executed when the file length is 255 characters (#5114) 2025-01-21 02:19:00 -08:00
150 changed files with 3508 additions and 1156 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
go-version: [1.23.x]
go-version: [1.25.x]
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v4
+2 -5
View File
@@ -19,7 +19,7 @@ jobs:
GO111MODULE: on
strategy:
matrix:
go-version: [1.23.x]
go-version: [1.25.x]
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
@@ -69,7 +69,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.23.x
go-version: 1.24.x
- name: Checkout code
uses: actions/checkout@v2
@@ -77,6 +77,3 @@ jobs:
- name: Test 386
run: GOOS=linux GOARCH=386 go test -short ./...
- name: Staticcheck
# Run with defaults, but allow errors with other formats ST1005
run: go install honnef.co/go/tools/cmd/staticcheck@latest && make lint
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: 1.23.4
go-version: 1.25.x
- name: Get official govulncheck
run: go install golang.org/x/vuln/cmd/govulncheck@latest
shell: bash
+2 -1
View File
@@ -14,4 +14,5 @@ mc
mc.RELEASE*
mc.gz
.DS_Store
.vscode/
.vscode/
.bin/
+37 -27
View File
@@ -1,32 +1,42 @@
version: "2"
linters:
disable-all: true
default: none
enable:
- typecheck
- goimports
- misspell
- staticcheck
- govet
- revive
- ineffassign
- gomodguard
- gofmt
- govet
- ineffassign
- misspell
- revive
- staticcheck
- unused
settings:
misspell:
locale: US
exclusions:
generated: lax
rules:
- path: (.+)\.go$
text: instead of using struct literal
- path: (.+)\.go$
text: should have a package comment
- path: (.+)\.go$
text: error strings should not be capitalized or end with punctuation or a newline
- path: (.+)\.go$
text: error strings should not end with punctuation or newlines
- path: (.+)\.go$
text: error strings should not be capitalized
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofmt
- gofumpt
linters-settings:
golint:
min-confidence: 0
misspell:
locale: US
# Choose whether or not to use the extra rules that are disabled
# by default
extra-rules: false
issues:
exclude-use-default: false
exclude:
- instead of using struct literal
- should have a package comment
- error strings should not be capitalized or end with punctuation or a newline
- goimports
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$
+416 -1
View File
@@ -4245,6 +4245,214 @@ SOFTWARE.
================================================================
github.com/minio/crc64nvme
https://github.com/minio/crc64nvme
----------------------------------------------------------------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================================
github.com/minio/madmin-go/v3
https://github.com/minio/madmin-go/v3
----------------------------------------------------------------
@@ -8109,7 +8317,7 @@ https://github.com/safchain/ethtool
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Copyright (c) 2015 The Ethtool Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -10025,6 +10233,213 @@ https://go.etcd.io/etcd/client/v3
================================================================
go.opentelemetry.io/auto/sdk
https://go.opentelemetry.io/auto/sdk
----------------------------------------------------------------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================================
go.opentelemetry.io/otel
https://go.opentelemetry.io/otel
----------------------------------------------------------------
-24
View File
@@ -1,24 +0,0 @@
FROM registry.access.redhat.com/ubi9/ubi-minimal:latest AS build
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
FROM registry.access.redhat.com/ubi9/ubi-micro:latest
ARG TARGETARCH
ARG RELEASE
LABEL maintainer="MinIO Inc <dev@min.io>"
# On RHEL the certificate bundle is located at:
# - /etc/pki/tls/certs/ca-bundle.crt (RHEL 6)
# - /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem (RHEL 7)
COPY --from=build /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem /etc/pki/ca-trust/extracted/pem/
COPY CREDITS /licenses/CREDITS
COPY LICENSE /licenses/LICENSE
ADD https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE}.fips /usr/bin/mc
RUN chmod +x /usr/bin/mc
ENTRYPOINT ["mc"]
+8 -10
View File
@@ -2,14 +2,13 @@ PWD := $(shell pwd)
GOPATH := $(shell go env GOPATH)
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
GOARCH := $(shell go env GOARCH)
GOOS := $(shell go env GOOS)
TARGET_GOARCH ?= $(shell go env GOARCH)
TARGET_GOOS ?= $(shell go env GOOS)
VERSION ?= $(shell git describe --tags)
TAG ?= "minio/mc:$(VERSION)"
GOLANGCI_DIR = .bin/golangci/$(GOLANGCI_VERSION)
GOLANGCI = $(GOLANGCI_DIR)/golangci-lint
GOLANGCI = $(GOPATH)/bin/golangci-lint
all: build
@@ -19,8 +18,7 @@ checks:
getdeps:
@mkdir -p ${GOPATH}/bin
@echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOLANGCI_DIR)
@echo "Installing stringer" && go install -v golang.org/x/tools/cmd/stringer@latest
@echo "Installing tools" && go install tool
crosscompile:
@(env bash $(PWD)/buildscripts/cross-compile.sh)
@@ -64,7 +62,7 @@ verify:
# Builds mc locally.
build: checks
@echo "Building mc binary to './mc'"
@GO111MODULE=on CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags "$(LDFLAGS)" -o $(PWD)/mc
@GO111MODULE=on GOOS=$(TARGET_GOOS) GOARCH=$(TARGET_GOARCH) CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags "$(LDFLAGS)" -o $(PWD)/mc
hotfix-vars:
$(eval LDFLAGS := $(shell MC_RELEASE="RELEASE" MC_HOTFIX="hotfix.$(shell git rev-parse --short HEAD)" go run buildscripts/gen-ldflags.go $(shell git describe --tags --abbrev=0 | \
@@ -78,9 +76,9 @@ hotfix: hotfix-vars install ## builds mc binary with hotfix tags
@sha256sum < ./mc.$(VERSION) | sed 's, -,mc.$(VERSION),g' > mc.$(VERSION).sha256sum
hotfix-push: hotfix
@scp -q -r mc.$(VERSION)* minio@dl-0.min.io:~/releases/client/mc/hotfixes/linux-amd64/archive/
@scp -q -r mc.$(VERSION)* minio@dl-1.min.io:~/releases/client/mc/hotfixes/linux-amd64/archive/
@echo "Published new hotfix binaries at https://dl.min.io/client/mc/hotfixes/linux-amd64/archive/mc.$(VERSION)"
@scp -q -r mc.$(VERSION)* minio@dl-0.min.io:~/releases/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/
@scp -q -r mc.$(VERSION)* minio@dl-1.min.io:~/releases/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/
@echo "Published new hotfix binaries at https://dl.min.io/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/mc.$(VERSION)"
docker-hotfix-push: docker-hotfix
@docker push -q $(TAG) && echo "Published new container $(TAG)"
+1 -1
View File
@@ -2,7 +2,7 @@
[![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Go Report Card](https://goreportcard.com/badge/minio/mc)](https://goreportcard.com/report/minio/mc) [![Docker Pulls](https://img.shields.io/docker/pulls/minio/mc.svg?maxAge=604800)](https://hub.docker.com/r/minio/mc/) [![license](https://img.shields.io/badge/license-AGPL%20V3-blue)](https://github.com/minio/mc/blob/master/LICENSE)
# Documentation
- [MC documentation](https://min.io/docs/minio/linux/reference/minio-mc.html)
- [MC documentation](https://docs.min.io/community/minio-object-store/reference/minio-mc.html)
MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
+3 -3
View File
@@ -165,9 +165,9 @@ cat cp events mb pipe rm share version
```
## 了解更多
- [MinIO Client完全指南](https://min.io/docs/minio/linux/reference/minio-mc.html?ref=gh)
- [MinIO快速入门](https://min.io/docs/minio/linux/index.html#quickstart-for-linux?ref=gh)
- [MinIO官方文档](https://min.io/docs/minio/linux/index.html?ref=gh)
- [MinIO Client完全指南](https://docs.min.io/community/minio-object-store/reference/minio-mc.html?ref=gh)
- [MinIO快速入门](https://docs.min.io/community/minio-object-store/operations/deployments/baremetal-deploy-minio-on-redhat-linux.html?ref=gh)
- [MinIO官方文档](https://docs.min.io/community/minio-object-store/index.html?ref=gh)
## 贡献
请遵守MinIO[贡献者指南](https://github.com/minio/mc/blob/master/docs/zh_CN/CONTRIBUTING.md)
+43 -12
View File
@@ -18,11 +18,14 @@
package cmd
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/fatih/color"
"github.com/minio/pkg/v3/console"
"github.com/cheggaaa/pb"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
@@ -56,14 +59,14 @@ func newAccounter(total int64) *accounter {
}
// write calculate the final speed.
func (a *accounter) write(current int64) float64 {
func (a *accounter) write(current int64) (float64, time.Duration) {
fromStart := time.Since(a.startTime)
currentFromStart := current - a.startValue
if currentFromStart > 0 {
speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second))
return speed
return speed, fromStart
}
return 0.0
return 0.0, 0
}
// writer update new accounting data for a specified refreshRate.
@@ -81,10 +84,11 @@ func (a *accounter) writer() {
// accountStat cantainer for current stats captured.
type accountStat struct {
Status string `json:"status"`
Total int64 `json:"total"`
Transferred int64 `json:"transferred"`
Speed float64 `json:"speed"`
Status string `json:"status"`
Total int64 `json:"total"`
Transferred int64 `json:"transferred"`
Duration time.Duration `json:"duration"`
Speed float64 `json:"speed"`
}
func (c accountStat) JSON() string {
@@ -96,15 +100,42 @@ func (c accountStat) JSON() string {
}
func (c accountStat) String() string {
dspOrder := []col{colGreen} // Header
dspOrder = append(dspOrder, colGrey)
var printColors []*color.Color
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
var builder strings.Builder
cellText := make([][]string, 0, 2)
cellText = append(cellText, []string{
"Total",
"Transferred",
"Duration",
"Speed",
})
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
if speedBox == "" {
speedBox = "0 MB"
} else {
speedBox = speedBox + "/s"
}
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
return message
cellText = append(cellText, []string{
pb.Format(c.Total).To(pb.U_BYTES).String(),
pb.Format(c.Transferred).To(pb.U_BYTES).String(),
pb.Format(int64(c.Duration)).To(pb.U_DURATION).String(),
speedBox,
})
e := tbl.PopulateTable(&builder, cellText)
fatalIf(probe.NewError(e), "unable to populate the table")
return builder.String()
}
// Stat provides current stats captured.
@@ -114,7 +145,7 @@ func (a *accounter) Stat() accountStat {
close(a.isFinished)
acntStat.Total = a.total
acntStat.Transferred = atomic.LoadInt64(&a.current)
acntStat.Speed = a.write(atomic.LoadInt64(&a.current))
acntStat.Speed, acntStat.Duration = a.write(atomic.LoadInt64(&a.current))
})
return acntStat
}
+152
View File
@@ -18,7 +18,15 @@
package cmd
import (
"strings"
"time"
"github.com/charmbracelet/lipgloss"
humanize "github.com/dustin/go-humanize"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
var adminAccesskeyInfoCmd = cli.Command{
@@ -45,6 +53,150 @@ EXAMPLES:
`,
}
type accesskeyMessage struct {
op string
Status string `json:"status"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey,omitempty"`
STS bool `json:"sts,omitempty"`
ParentUser string `json:"parentUser,omitempty"`
AccountStatus string `json:"accountStatus,omitempty"`
ImpliedPolicy bool `json:"impliedPolicy,omitempty"`
Policy json.RawMessage `json:"policy,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Expiration *time.Time `json:"expiration,omitempty"`
Provider string `json:"provider,omitempty"`
ProviderInfo providerInfo `json:"providerInfo,omitempty"`
}
func (m accesskeyMessage) String() string {
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")) // green
o := strings.Builder{}
switch m.op {
case "info":
expirationStr := "NONE"
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
expirationStr = humanize.Time(*m.Expiration)
}
policyStr := "embedded"
if m.ImpliedPolicy {
policyStr = "implied"
}
statusStr := "enabled"
if m.AccountStatus == "off" {
statusStr = "disabled"
}
stsStr := "false"
if m.STS {
stsStr = "true"
}
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Parent User:"), m.ParentUser))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Status:"), statusStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Policy:"), policyStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("STS:"), stsStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Provider:"), m.Provider))
if m.ProviderInfo != nil {
o.WriteString(iFmt(0, "%s\n", labelStyle.Render("Provider Specific Info:")))
o.WriteString(m.ProviderInfo.String())
}
case "create":
expirationStr := "NONE"
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
expirationStr = m.Expiration.String()
}
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Secret Key:"), m.SecretKey))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
case "remove":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully removed access key `%s`.", m.AccessKey)))
case "edit":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully edited access key `%s`.", m.AccessKey)))
case "enable":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully enabled access key `%s`.", m.AccessKey)))
case "disable":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully disabled access key `%s`.", m.AccessKey)))
}
return o.String()
}
func (m accesskeyMessage) JSON() string {
m.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
type providerInfo interface {
String() string
}
func mainAdminAccesskeyInfo(ctx *cli.Context) error {
return commonAccesskeyInfo(ctx)
}
func commonAccesskeyInfo(ctx *cli.Context) error {
if len(ctx.Args()) < 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
args := ctx.Args()
aliasedURL := args.Get(0)
accessKeys := args.Tail()
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
for _, accessKey := range accessKeys {
// Assume service account by default
res, e := client.InfoAccessKey(globalContext, accessKey)
fatalIf(probe.NewError(e), "Unable to get info for access key.")
m := accesskeyMessage{
op: "info",
AccessKey: accessKey,
ParentUser: res.ParentUser,
AccountStatus: res.AccountStatus,
ImpliedPolicy: res.ImpliedPolicy,
Policy: json.RawMessage(res.Policy),
Name: res.Name,
Description: res.Description,
Expiration: nilExpiry(res.Expiration),
Provider: res.UserProvider,
}
switch res.UserProvider {
case madmin.LDAPProvider:
info := res.LDAPSpecificInfo
m.ProviderInfo = ldapAccessKeyInfo{
Username: info.Username,
}
case madmin.OpenIDProvider:
info := res.OpenIDSpecificInfo
m.ProviderInfo = openIDAccessKeyInfo{
ConfigName: info.ConfigName,
UserID: info.UserID,
UserIDClaim: info.UserIDClaim,
DisplayName: info.DisplayName,
DisplayNameClaim: info.DisplayNameClaim,
}
}
printMsg(m)
}
return nil
}
func nilExpiry(expiry *time.Time) *time.Time {
if expiry != nil && expiry.Equal(timeSentinel) {
return nil
}
return expiry
}
+149
View File
@@ -0,0 +1,149 @@
// Copyright (c) 2015-2025 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
var adminAccesskeySTSRevokeFlags = []cli.Flag{
cli.BoolFlag{
Name: "all",
Usage: "revoke all STS accounts for the specified user",
},
cli.BoolFlag{
Name: "self",
Usage: "revoke all STS accounts for the authenticated user",
},
cli.StringFlag{
Name: "token-type",
Usage: "specify the token type to revoke",
},
}
var adminAccesskeySTSRevokeCmd = cli.Command{
Name: "sts-revoke",
Usage: "revokes all STS accounts or specified types for the specified user",
Action: mainAdminAccesskeySTSRevoke,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminAccesskeySTSRevokeFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS USER [--all | --token-type TOKEN_TYPE]
Exactly one of --all or --token-type must be specified.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Revoke all STS accounts for user "user1"
{{.Prompt}} {{.HelpName}} myminio user1 --all
2. Revoke STS accounts of a token type "app-1" for user "user1"
{{.Prompt}} {{.HelpName}} myminio user1 --token-type app-1
3. Revoke all STS accounts for the authenticated user
{{.Prompt}} {{.HelpName}} myminio --self
4. Revoke STS accounts of a token type "app-1" for the authenticated user
{{.Prompt}} {{.HelpName}} myminio --self --token-type app-1
`,
}
type stsRevokeMessage struct {
Status string `json:"status"`
User string `json:"user"`
TokenRevokeType string `json:"tokenRevokeType,omitempty"`
}
func (m stsRevokeMessage) String() string {
userString := "user " + m.User
if m.User == "" {
userString = "authenticated user"
}
if m.TokenRevokeType == "" {
return "Successfully revoked all STS accounts for " + userString
}
return "Successfully revoked all STS accounts of type " + m.TokenRevokeType + " for " + userString
}
func (m stsRevokeMessage) JSON() string {
if m.Status == "" {
m.Status = "success"
}
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// checkSTSRevokeSyntax - validate all the passed arguments
func checkSTSRevokeSyntax(ctx *cli.Context) {
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
showCommandHelpAndExit(ctx, 1)
}
if !ctx.Bool("self") && ctx.Args().Get(1) == "" {
fatalIf(errInvalidArgument().Trace(), "Must specify user or use --self flag.")
}
if ctx.Bool("self") && ctx.Args().Get(1) != "" {
fatalIf(errInvalidArgument().Trace(), "Cannot specify user with --self flag.")
}
if (!ctx.Bool("all") && ctx.String("token-type") == "") || (ctx.Bool("all") && ctx.String("token-type") != "") {
fatalIf(errDummy().Trace(), "Exactly one of --all or --token-type must be specified.")
}
}
// mainAdminAccesskeySTSRevoke is the handle for "mc admin accesskey sts-revoke" command.
func mainAdminAccesskeySTSRevoke(ctx *cli.Context) error {
checkSTSRevokeSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
user := args.Get(1) // will be empty if --self flag is set
tokenRevokeType := ctx.String("token-type")
fullRevoke := ctx.Bool("all")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.RevokeTokens(globalContext, madmin.RevokeTokensReq{
User: user,
TokenRevokeType: tokenRevokeType,
FullRevoke: fullRevoke,
})
fatalIf(probe.NewError(e).Trace(args...), "Unable to revoke tokens for %s", user)
printMsg(stsRevokeMessage{
User: user,
TokenRevokeType: tokenRevokeType,
})
return nil
}
+1
View File
@@ -27,6 +27,7 @@ var adminAccesskeySubcommands = []cli.Command{
adminAccesskeyEditCmd,
adminAccesskeyEnableCmd,
adminAccesskeyDisableCmd,
adminAccesskeySTSRevokeCmd,
}
var adminAccesskeyCmd = cli.Command{
-1
View File
@@ -121,7 +121,6 @@ func TestGetBandwidthInBytes(t *testing.T) {
}
t.Parallel()
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got, err := getBandwidthInBytes(tt.args.bandwidthStr); err != nil || got != tt.want {
t.Errorf("getBandwidthInBytes() = %v, want %v", got, tt.want)
+5
View File
@@ -119,6 +119,11 @@ func mainClusterBucketExport(ctx *cli.Context) error {
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
// Explicitly set permissions to 0o600 and override umask
// to ensure that the file is not world-readable.
e = os.Chmod(downloadPath, 0o600)
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
if !globalJSON {
console.Infof("Bucket metadata successfully downloaded as %s\n", downloadPath)
return nil
+3 -2
View File
@@ -96,6 +96,7 @@ func mainClusterBucketImport(ctx *cli.Context) error {
f, e = os.Open(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket metadata")
defer f.Close()
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
@@ -141,7 +142,7 @@ func statusTick(s madmin.MetaStatus) string {
}
func (i importMetaMsg) String() string {
m := i.BucketMetaImportErrs.Buckets
m := i.Buckets
totBuckets := len(m)
totErrs := 0
for _, st := range m {
@@ -185,7 +186,7 @@ func (i importMetaMsg) JSON() string {
// Disable escaping special chars to display XML tags correctly
enc.SetEscapeHTML(false)
fatalIf(probe.NewError(enc.Encode(i.BucketMetaImportErrs.Buckets)), "Unable to marshal into JSON.")
fatalIf(probe.NewError(enc.Encode(i.Buckets)), "Unable to marshal into JSON.")
return buf.String()
}
+5
View File
@@ -125,6 +125,11 @@ func mainClusterIAMExport(ctx *cli.Context) error {
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
// Explicitly set permissions to 0o600 and override umask
// to ensure that the file is not world-readable.
e = os.Chmod(downloadPath, 0o600)
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
if !globalJSON {
console.Infof("IAM info successfully downloaded as %s\n", downloadPath)
return nil
+1
View File
@@ -207,6 +207,7 @@ func mainClusterIAMImport(ctx *cli.Context) error {
f, e = os.Open(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get IAM info")
defer f.Close()
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
+1 -1
View File
@@ -125,7 +125,7 @@ func mainAdminDecommissionStatus(ctx *cli.Context) error {
}
dspOrder := []col{colGreen} // Header
for i := 0; i < len(poolStatuses); i++ {
for range poolStatuses {
dspOrder = append(dspOrder, colGrey)
}
var printColors []*color.Color
+4 -4
View File
@@ -87,11 +87,11 @@ func (h hri) getBucketHCCChange() (b, a col, err error) {
a, b = colGrey, colGrey
if len(h.HealResultItem.Before.Drives) > 0 {
b = getColCode(h.HealResultItem.Before.Drives)
if len(h.Before.Drives) > 0 {
b = getColCode(h.Before.Drives)
}
if len(h.HealResultItem.After.Drives) > 0 {
a = getColCode(h.HealResultItem.After.Drives)
if len(h.After.Drives) > 0 {
a = getColCode(h.After.Drives)
}
return
}
-1
View File
@@ -398,7 +398,6 @@ func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) {
default:
ui.updateUI(s)
}
return
}
func (ui *uiData) healResumeMsg(aliasedURL string) string {
+16 -16
View File
@@ -95,9 +95,11 @@ func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
}
}
if disk.DiskIndex < (info.Backend.DrivesPerSet[disk.PoolIndex] - info.Backend.StandardSCParity) {
pool.drivesTotalFreeSpace += disk.AvailableSpace
pool.drivesTotalUsableSpace += disk.TotalSpace
if len(info.Backend.DrivesPerSet) > 0 {
if disk.DiskIndex < (info.Backend.DrivesPerSet[disk.PoolIndex] - info.Backend.StandardSCParity) {
pool.drivesTotalFreeSpace += disk.AvailableSpace
pool.drivesTotalUsableSpace += disk.TotalSpace
}
}
pool.endpoints.Add(srv.Endpoint)
@@ -105,8 +107,6 @@ func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
}
}
// This was already added in 2022 enough time has passed to remove
// any other deprecated calculations
for idx := range info.Backend.TotalSets {
pool := summary[idx]
if pool != nil {
@@ -150,11 +150,6 @@ func (u clusterStruct) String() (msg string) {
fatal(probe.NewError(errors.New("Unable to get service info")), "")
}
// Validate such that we expect the server to be atleast from 2022
if len(u.Info.Backend.TotalSets) == 0 || len(u.Info.Backend.DrivesPerSet) == 0 {
fatal(probe.NewError(errors.New("Unable to display service info, server is too old")), "")
}
// Initialization
var totalOfflineNodes int
@@ -299,6 +294,7 @@ func (u clusterStruct) String() (msg string) {
"Erasure sets",
})
var printSummary bool
// Keep the pool order while printing the output
for poolIdx := 0; poolIdx < len(clusterSummary); poolIdx++ {
summary := clusterSummary[poolIdx]
@@ -308,12 +304,14 @@ func (u clusterStruct) String() (msg string) {
totalSize := summary.drivesTotalUsableSpace
usedCurrent := summary.drivesTotalUsableSpace - summary.drivesTotalFreeSpace
var capacity string
if totalSize == 0 {
capacity = "0% (total: 0B)"
} else {
if totalSize > 0 {
capacity = fmt.Sprintf("%.1f%% (total: %s)", 100*float64(usedCurrent)/float64(totalSize), humanize.IBytes(totalSize))
}
if summary.drivesPerSet > 0 {
printSummary = true
}
cellText = append(cellText, []string{
humanize.Ordinal(poolIdx + 1),
capacity,
@@ -322,10 +320,12 @@ func (u clusterStruct) String() (msg string) {
})
}
e := tbl.PopulateTable(&builder, cellText)
fatalIf(probe.NewError(e), "unable to populate the table")
if printSummary {
e := tbl.PopulateTable(&builder, cellText)
fatalIf(probe.NewError(e), "unable to populate the table")
msg += builder.String() + "\n"
msg += builder.String() + "\n"
}
}
// Summary on used space, total no of buckets and
+3 -9
View File
@@ -107,15 +107,6 @@ func (l logMessage) String() string {
if l.NodeName != "" {
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
}
log := l.LogInfo
if log.ConsoleMsg != "" {
if strings.HasPrefix(log.ConsoleMsg, "\n") {
fmt.Fprintf(b, "%s\n", hostStr)
log.ConsoleMsg = strings.TrimPrefix(log.ConsoleMsg, "\n")
}
fmt.Fprintf(b, "%s %s", hostStr, log.ConsoleMsg)
return b.String()
}
if l.API != nil {
apiString := "API: " + l.API.Name + "("
if l.API.Args != nil && l.API.Args.Bucket != "" {
@@ -142,6 +133,9 @@ func (l logMessage) String() string {
if l.UserAgent != "" {
fmt.Fprintf(b, "\n%s UserAgent: %s", hostStr, l.UserAgent)
}
if l.Message != "" {
fmt.Fprintf(b, "\n%s Message: %s", hostStr, l.Message)
}
if l.Trace != nil {
if l.Trace.Message != "" {
fmt.Fprintf(b, "\n%s Error: %s", hostStr, console.Colorize("LogMessage", l.Trace.Message))
+1 -1
View File
@@ -107,7 +107,7 @@ func userAttachOrDetachPolicy(ctx *cli.Context, attach bool) error {
}
var emptyResp madmin.PolicyAssociationResp
if res.UpdatedAt == emptyResp.UpdatedAt {
if res.UpdatedAt.Equal(emptyResp.UpdatedAt) {
// Older minio does not send a result, so we populate res manually to
// simulate a result. TODO(aditya): remove this after newer minio is
// released in a few months (Older API Deprecated in Jun 2023)
+3 -3
View File
@@ -83,13 +83,13 @@ func (i srRemoveStatus) String() string {
if i.RemoveAll {
return console.Colorize("UserMessage", "All site(s) were removed successfully")
}
if i.ReplicateRemoveStatus.Status == madmin.ReplicateRemoveStatusSuccess {
if i.Status == madmin.ReplicateRemoveStatusSuccess {
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed successfully", i.sites))
}
if len(i.sites) == 1 {
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ErrDetail))
}
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ErrDetail))
}
func checkAdminReplicateRemoveSyntax(ctx *cli.Context) {
+5 -6
View File
@@ -74,13 +74,12 @@ func (m resyncCancelMessage) String() string {
}
func mainAdminReplicateResyncCancel(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
cli.ShowCommandHelpAndExit(ctx, "cancel", 1) // last argument is exit code
}
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("ResyncMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
+6 -7
View File
@@ -21,10 +21,11 @@ import (
"fmt"
"strings"
"github.com/minio/madmin-go/v3"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
)
@@ -74,12 +75,10 @@ func (m resyncMessage) String() string {
}
func mainAdminReplicateResyncStart(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
}
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("ResyncMessage", color.New(color.FgGreen))
+5 -7
View File
@@ -60,12 +60,10 @@ EXAMPLES:
}
func mainAdminReplicationResyncStatus(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("ResyncMessage", color.New(color.FgGreen))
@@ -208,7 +206,7 @@ func (m *resyncMetricsUI) View() string {
table.SetNoWhiteSpace(true)
var data [][]string
addLine := func(prefix string, value interface{}) {
addLine := func(prefix string, value any) {
data = append(data, []string{
prefix,
whiteStyle.Render(fmt.Sprint(value)),
+20 -33
View File
@@ -167,8 +167,8 @@ func (i srStatus) String() string {
if i.opts.Buckets {
messages = append(messages,
console.Colorize("SummaryHdr", "Bucket replication status:"))
switch {
case i.MaxBuckets == 0:
switch i.MaxBuckets {
case 0:
messages = append(messages, console.Colorize("Summary", "No Buckets present\n"))
default:
msg := console.Colorize(i.getTheme(len(info.BucketStats) == 0), fmt.Sprintf("%d/%d Buckets in sync", info.MaxBuckets-len(info.BucketStats), info.MaxBuckets)) + "\n"
@@ -204,8 +204,8 @@ func (i srStatus) String() string {
if i.opts.Policies {
messages = append(messages,
console.Colorize("SummaryHdr", "Policy replication status:"))
switch {
case i.MaxPolicies == 0:
switch i.MaxPolicies {
case 0:
messages = append(messages, console.Colorize("Summary", "No Policies present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.PolicyStats) == 0), fmt.Sprintf("%d/%d Policies in sync", info.MaxPolicies-len(info.PolicyStats), info.MaxPolicies)) + "\n"
@@ -243,8 +243,8 @@ func (i srStatus) String() string {
if i.opts.Users {
messages = append(messages,
console.Colorize("SummaryHdr", "User replication status:"))
switch {
case i.MaxUsers == 0:
switch i.MaxUsers {
case 0:
messages = append(messages, console.Colorize("Summary", "No Users present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.UserStats) == 0), fmt.Sprintf("%d/%d Users in sync", info.MaxUsers-len(i.UserStats), info.MaxUsers)) + "\n"
@@ -284,8 +284,8 @@ func (i srStatus) String() string {
if i.opts.Groups {
messages = append(messages,
console.Colorize("SummaryHdr", "Group replication status:"))
switch {
case i.MaxGroups == 0:
switch i.MaxGroups {
case 0:
messages = append(messages, console.Colorize("Summary", "No Groups present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.GroupStats) == 0), fmt.Sprintf("%d/%d Groups in sync", i.MaxGroups-len(i.GroupStats), i.MaxGroups)) + "\n"
@@ -426,10 +426,7 @@ func (i srStatus) String() string {
currDowntime = UTCNow().Sub(m.LastOnline)
}
// normalize because total downtime is calculated at server side at heartbeat interval, may be slightly behind
totalDowntime := m.TotalDowntime
if currDowntime > totalDowntime {
totalDowntime = currDowntime
}
totalDowntime := max(currDowntime, m.TotalDowntime)
var linkStatus string
if m.Online {
linkStatus = healthDot + fmt.Sprintf(" online (total downtime: %s)", timeDurationToHumanizedDuration(totalDowntime).String())
@@ -478,7 +475,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.BucketStats[i.opts.EntityValue] {
for _, st := range i.BucketStats[i.opts.EntityValue] {
if st.HasBucket {
found = true
break
@@ -518,7 +515,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.BucketStats[i.opts.EntityValue][dID]
ss := i.BucketStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -582,7 +579,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.PolicyStats[i.opts.EntityValue] {
for _, st := range i.PolicyStats[i.opts.EntityValue] {
if st.HasPolicy {
found = true
break
@@ -603,7 +600,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.PolicyStats[i.opts.EntityValue][dID]
ss := i.PolicyStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -634,7 +631,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.UserStats[i.opts.EntityValue] {
for _, st := range i.UserStats[i.opts.EntityValue] {
if st.HasUser {
found = true
break
@@ -662,7 +659,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.UserStats[i.opts.EntityValue][dID]
ss := i.UserStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -702,7 +699,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
rowLegend := []string{"Info", "Policy mapping"}
detailFields := make([][]Field, len(rowLegend))
var found bool
for _, st := range i.SRStatusInfo.GroupStats[i.opts.EntityValue] {
for _, st := range i.GroupStats[i.opts.EntityValue] {
if st.HasGroup {
found = true
break
@@ -728,7 +725,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
// b := i.opts.EntityValue
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.GroupStats[i.opts.EntityValue][dID]
ss := i.GroupStats[i.opts.EntityValue][dID]
// sm := i.SRStatusInfo.StatsSummary
var theme, msgStr string
for r := range rowLegend {
@@ -767,7 +764,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.ILMExpiryStats[i.opts.EntityValue] {
for _, st := range i.ILMExpiryStats[i.opts.EntityValue] {
if st.HasILMExpiryRules {
found = true
break
@@ -788,7 +785,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.ILMExpiryStats[i.opts.EntityValue][dID]
ss := i.ILMExpiryStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -817,17 +814,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
// Calculate srstatus options for command line flags
func srStatusOpts(ctx *cli.Context) (opts madmin.SRStatusOptions) {
if !(ctx.IsSet("buckets") ||
ctx.IsSet("users") ||
ctx.IsSet("groups") ||
ctx.IsSet("policies") ||
ctx.IsSet("ilm-expiry-rules") ||
ctx.IsSet("bucket") ||
ctx.IsSet("user") ||
ctx.IsSet("group") ||
ctx.IsSet("policy") ||
ctx.IsSet("ilm-expiry-rule") ||
ctx.IsSet("all")) || ctx.IsSet("all") {
if (!ctx.IsSet("buckets") && !ctx.IsSet("users") && !ctx.IsSet("groups") && !ctx.IsSet("policies") && !ctx.IsSet("ilm-expiry-rules") && !ctx.IsSet("bucket") && !ctx.IsSet("user") && !ctx.IsSet("group") && !ctx.IsSet("policy") && !ctx.IsSet("ilm-expiry-rule") && !ctx.IsSet("all")) || ctx.IsSet("all") {
opts.Buckets = true
opts.Users = true
opts.Groups = true
+2 -2
View File
@@ -397,7 +397,7 @@ func (m *scannerMetricsUI) View() string {
writtenRows++
}
_ = addRow
addRowF := func(format string, vals ...interface{}) {
addRowF := func(format string, vals ...any) {
s := fmt.Sprintf(format, vals...)
table.Append([]string{s})
writtenRows++
@@ -442,7 +442,7 @@ func (m *scannerMetricsUI) View() string {
if sc.CurrentCycle > 0 {
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
} else {
addRowF(title("Current cycle:") + " (between cycles)")
addRowF("%s", title("Current cycle:")+" (between cycles)")
}
}
+1 -1
View File
@@ -173,7 +173,7 @@ func (m *serviceRestartUI) View() string {
func initServiceRestartUI(rowCount int, currentCh chan serviceRestartMessage) *serviceRestartUI {
var printColors []*color.Color
for i := 0; i < rowCount; i++ {
for range rowCount {
printColors = append(printColors, getPrintCol(colGreen))
}
+4 -6
View File
@@ -411,12 +411,10 @@ func (opts matchOpts) matches(traceInfo madmin.ServiceTraceInfo) bool {
}
}
if opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize) {
return false
}
if opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize) {
return false
if traceInfo.Trace.HTTP != nil {
if (opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize)) || (opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize)) {
return false
}
}
return true
+1 -1
View File
@@ -244,7 +244,7 @@ func generateCredentials() (accessKey, secretKey string, err *probe.Error) {
if e != nil {
return "", "", probe.NewError(e)
}
for i := 0; i < accessKeyMaxLen; i++ {
for i := range accessKeyMaxLen {
keyBytes[i] = alphaNumericTable[keyBytes[i]%alphaNumericTableLen]
}
accessKey = string(keyBytes)
+1 -1
View File
@@ -148,7 +148,7 @@ func checkAliasSetSyntax(ctx *cli.Context, accessKey, secretKey string, deprecat
}
} else {
if !isValidPath(path) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
fatalIf(errInvalidArgument().Trace(path),
"Unrecognized path value. Valid options are `[auto, on, off]`.")
}
}
+6 -6
View File
@@ -116,11 +116,11 @@ func (s anonymousRules) JSON() string {
// anonymousMessage is container for anonymous command on bucket success and failure messages.
type anonymousMessage struct {
Operation string `json:"operation"`
Status string `json:"status"`
Bucket string `json:"bucket"`
Perms accessPerms `json:"permission"`
Anonymous map[string]interface{} `json:"anonymous,omitempty"`
Operation string `json:"operation"`
Status string `json:"status"`
Bucket string `json:"bucket"`
Perms accessPerms `json:"permission"`
Anonymous map[string]any `json:"anonymous,omitempty"`
}
// String colorized access message.
@@ -464,7 +464,7 @@ func runAnonymousCmd(args cli.Args) {
"Unable to "+operation+" anonymous `"+string(perms)+"` for `"+targetURL+"`.")
}
}
anonymousJSON := map[string]interface{}{}
anonymousJSON := map[string]any{}
if anonymousStr != "" {
e := json.Unmarshal([]byte(anonymousStr), &anonymousJSON)
fatalIf(probe.NewError(e), "Unable to unmarshal custom anonymous file.")
+20 -9
View File
@@ -369,6 +369,15 @@ var completeCmds = map[string]complete.Predictor{
"/idp/openid/enable": aliasCompleter,
"/idp/openid/disable": aliasCompleter,
"/idp/openid/accesskey/list": aliasCompleter,
"/idp/openid/accesskey/ls": aliasCompleter,
"/idp/openid/accesskey/info": aliasCompleter,
"/idp/openid/accesskey/remove": aliasCompleter,
"/idp/openid/accesskey/rm": aliasCompleter,
"/idp/openid/accesskey/edit": aliasCompleter,
"/idp/openid/accesskey/enable": aliasCompleter,
"/idp/openid/accesskey/disable": aliasCompleter,
"/idp/ldap/add": aliasCompleter,
"/idp/ldap/update": aliasCompleter,
"/idp/ldap/remove": aliasCompleter,
@@ -391,16 +400,18 @@ var completeCmds = map[string]complete.Predictor{
"/idp/ldap/accesskey/edit": aliasCompleter,
"/idp/ldap/accesskey/enable": aliasCompleter,
"/idp/ldap/accesskey/disable": aliasCompleter,
"/idp/ldap/accesskey/sts-revoke": aliasCompleter,
"/admin/accesskey/create": aliasCompleter,
"/admin/accesskey/list": aliasCompleter,
"/admin/accesskey/ls": aliasCompleter,
"/admin/accesskey/remove": aliasCompleter,
"/admin/accesskey/rm": aliasCompleter,
"/admin/accesskey/info": aliasCompleter,
"/admin/accesskey/edit": aliasCompleter,
"/admin/accesskey/enable": aliasCompleter,
"/admin/accesskey/disable": aliasCompleter,
"/admin/accesskey/create": aliasCompleter,
"/admin/accesskey/list": aliasCompleter,
"/admin/accesskey/ls": aliasCompleter,
"/admin/accesskey/remove": aliasCompleter,
"/admin/accesskey/rm": aliasCompleter,
"/admin/accesskey/info": aliasCompleter,
"/admin/accesskey/edit": aliasCompleter,
"/admin/accesskey/enable": aliasCompleter,
"/admin/accesskey/disable": aliasCompleter,
"/admin/accesskey/sts-revoke": aliasCompleter,
"/admin/policy/info": aliasCompleter,
"/admin/policy/update": aliasCompleter,
+47 -12
View File
@@ -19,9 +19,9 @@ package cmd
import (
"fmt"
"strings"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
@@ -40,26 +40,22 @@ USAGE:
{{.HelpName}} TARGET JOBTYPE
JOBTYPE:
` + supportedJobTypes() + `
- replicate
- keyrotate
- expire
Use the special value "list" to request server to list supported job types.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Generate a new batch 'replication' job definition:
{{.Prompt}} {{.HelpName}} myminio replicate > replication.yaml
2. List all supported job types:
{{.Prompt}} {{.HelpName}} myminio list
`,
}
func supportedJobTypes() string {
var builder strings.Builder
for _, jobType := range madmin.SupportedJobTypes {
builder.WriteString(" - ")
builder.WriteString(string(jobType))
builder.WriteString("\n")
}
return builder.String()
}
// checkBatchGenerateSyntax - validate all the passed arguments
func checkBatchGenerateSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
@@ -80,6 +76,45 @@ func mainBatchGenerate(ctx *cli.Context) error {
adminClient, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
if jobType == "list" {
supportedJobTypes, apiUnavailable, e := adminClient.GetSupportedBatchJobTypes(globalContext)
if e != nil {
fatalIf(probe.NewError(e), "Unable to list supported job types")
}
if apiUnavailable {
// Fallback to default supported jobs.
supportedJobTypes = madmin.SupportedJobTypes
}
if globalJSON {
j, err := json.Marshal(supportedJobTypes)
if err != nil {
fatalIf(probe.NewError(err), "Unable to marshal supported job types")
}
fmt.Println(string(j))
} else {
for _, jobType := range supportedJobTypes {
fmt.Println(jobType)
}
}
return nil
}
// Try GenerateV2 API.
template, apiUnavailable, e := adminClient.GenerateBatchJobV2(globalContext, madmin.GenerateBatchJobOpts{
Type: madmin.BatchJobType(jobType),
})
if e != nil {
fatalIf(probe.NewError(e), "Unable to generate template for %s", args.Get(1))
}
// Check if server supports GenerateV2 API.
if !apiUnavailable {
fmt.Println(template)
return nil
}
// As API is not supported we fallback to returning the static job template.
var found bool
for _, job := range madmin.SupportedJobTypes {
if jobType == string(job) {
+61 -3
View File
@@ -66,6 +66,7 @@ EXAMPLES:
type batchListMessage struct {
Status string `json:"status"`
Jobs []madmin.BatchJobResult `json:"jobs"`
Admin *madmin.AdminClient `json:"-"` // Add AdminClient to fetch job status
}
// String colorized batchList message
@@ -90,15 +91,35 @@ func (c batchListMessage) String() string {
table.SetTablePadding("\t") // pad with tabs
table.SetNoWhiteSpace(true)
table.SetHeader([]string{"ID", "TYPE", "USER", "STARTED"})
data := make([][]string, 0, 4)
// Add a new "STATUS" column to the table header
table.SetHeader([]string{"ID", "TYPE", "USER", "STARTED", "STATUS"})
data := make([][]string, 0, 5)
// Fetch the status for the batch job using BatchJobStatus API
for _, job := range c.Jobs {
jobStatus := "unknown"
jobMetric, err := c.Admin.BatchJobStatus(context.Background(), job.ID)
// Output error if the API call fails, but continue processing remaining jobs
if err != nil {
println("Failed to fetch job status for Job ID:", job.ID, "Error:", err.Error())
} else {
if jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "completed"
} else if !jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "in-progress"
} else if jobMetric.LastMetric.Failed {
jobStatus = "failed"
}
}
// Add jobStatus details to the data table
data = append(data, []string{
job.ID,
string(job.Type),
job.User,
humanize.Time(job.Started),
jobStatus,
})
}
@@ -111,7 +132,43 @@ func (c batchListMessage) String() string {
// JSON jsonified batchList message
func (c batchListMessage) JSON() string {
c.Status = "success"
batchListMessageBytes, e := json.MarshalIndent(c, "", " ")
// Create a temporary slice to hold jobs with derived statuses
jobsWithStatus := make([]map[string]interface{}, len(c.Jobs))
// Fetch the status for the batch job using BatchJobStatus API
for i, job := range c.Jobs {
jobStatus := "unknown"
jobMetric, err := c.Admin.BatchJobStatus(context.Background(), job.ID)
// Output error if the API call fails, but continue processing remaining jobs
if err != nil {
println("Failed to fetch job status for Job ID:", job.ID, "Error:", err.Error())
} else {
if jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "completed"
} else if !jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "in-progress"
} else if jobMetric.LastMetric.Failed {
jobStatus = "failed"
}
}
// Add the job details along with the derived status
jobsWithStatus[i] = map[string]interface{}{
"id": job.ID,
"type": job.Type,
"user": job.User,
"started": job.Started,
"status": jobStatus,
}
}
// Marshal the updated jobs into JSON
batchListMessageBytes, e := json.MarshalIndent(map[string]interface{}{
"status": c.Status,
"jobs": jobsWithStatus,
}, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(batchListMessageBytes)
@@ -147,6 +204,7 @@ func mainBatchList(ctx *cli.Context) error {
printMsg(batchListMessage{
Status: "success",
Jobs: res.Jobs,
Admin: adminClient, // Pass the adminClient for status lookups
})
return nil
}
+21 -2
View File
@@ -232,7 +232,7 @@ func (m *batchJobMetricsUI) View() string {
table.SetNoWhiteSpace(true)
var data [][]string
addLine := func(prefix string, value interface{}) {
addLine := func(prefix string, value any) {
data = append(data, []string{
prefix,
whiteStyle.Render(fmt.Sprint(value)),
@@ -258,6 +258,8 @@ func (m *batchJobMetricsUI) View() string {
addLine("Objects: ", m.metric.Replicate.Objects)
addLine("Versions: ", m.metric.Replicate.Objects)
addLine("FailedObjects: ", m.metric.Replicate.ObjectsFailed)
addLine("DeleteMarker: ", m.metric.Replicate.DeleteMarkers)
addLine("FailedDeleteMarker: ", m.metric.Replicate.DeleteMarkersFailed)
if accElapsedTime > 0 {
bytesTransferredPerSec := float64(m.metric.Replicate.BytesTransferred) / accElapsedTime.Seconds()
objectsPerSec := float64(int64(time.Second)*m.metric.Replicate.Objects) / float64(accElapsedTime)
@@ -271,13 +273,30 @@ func (m *batchJobMetricsUI) View() string {
addLine("JobType: ", m.metric.JobType)
addLine("Objects: ", m.metric.Expired.Objects)
addLine("FailedObjects: ", m.metric.Expired.ObjectsFailed)
addLine("DeleteMarker: ", m.metric.Expired.DeleteMarkers)
addLine("FailedDeleteMarker: ", m.metric.Expired.DeleteMarkersFailed)
addLine("CurrObjName: ", m.metric.Expired.Object)
if !m.metric.LastUpdate.IsZero() {
accElapsedTime := m.metric.LastUpdate.Sub(m.metric.StartTime)
addLine("Elapsed: ", accElapsedTime.String())
}
case string(madmin.BatchJobCatalog):
addLine("JobType: ", m.metric.JobType)
addLine("ObjectsScannedCount: ", m.metric.Catalog.ObjectsScannedCount)
addLine("ObjectsMatchedCount: ", m.metric.Catalog.ObjectsMatchedCount)
lastScanned := fmt.Sprintf("%s/%s", m.metric.Catalog.LastBucketScanned, m.metric.Catalog.LastObjectScanned)
addLine("LastScanned: ", lastScanned)
lastMatched := fmt.Sprintf("%s/%s", m.metric.Catalog.LastBucketMatched, m.metric.Catalog.LastObjectMatched)
addLine("LastMatched: ", lastMatched)
accElapsedTime := m.metric.LastUpdate.Sub(m.metric.StartTime)
addLine("RecordsWrittenCount: ", m.metric.Catalog.RecordsWrittenCount)
addLine("OutputObjectsCount: ", m.metric.Catalog.OutputObjectsCount)
addLine("Elapsed: ", accElapsedTime.Round(time.Second).String())
addLine("Scan Speed: ", fmt.Sprintf("%f objects/s", float64(m.metric.Catalog.ObjectsScannedCount)/accElapsedTime.Seconds()))
if m.metric.Catalog.ErrorMsg != "" {
addLine("Error: ", m.metric.Catalog.ErrorMsg)
}
}
table.AppendBulk(data)
+2 -4
View File
@@ -251,11 +251,9 @@ func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixS
versionID = content.VersionID
}
if o.tailO > 0 && content.Size > 0 {
o.startO = content.Size - o.tailO
if o.startO < 0 {
o.startO = max(content.Size-o.tailO,
// Return all.
o.startO = 0
}
0)
}
if client.GetURL().Type == objectStorage {
size = content.Size - o.startO
+1 -4
View File
@@ -137,10 +137,7 @@ func newAnonymousClient(aliasedURL string) (*madmin.AnonymousClient, *probe.Erro
}
// By default enable HTTPs.
useTLS := true
if targetURL.Scheme == "http" {
useTLS = false
}
useTLS := targetURL.Scheme != "http"
// Construct an anonymous client
anonClient, e := madmin.NewAnonymousClient(targetURL.Host, useTLS)
+2 -2
View File
@@ -35,8 +35,8 @@ func (h adminPolicyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
return
}
switch {
case r.Method == "PUT":
switch r.Method {
case "PUT":
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
if e != nil {
w.WriteHeader(http.StatusBadRequest)
+60 -10
View File
@@ -22,6 +22,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"os"
"path"
"path/filepath"
@@ -32,6 +33,8 @@ import (
"syscall"
"time"
"github.com/google/uuid"
"github.com/pkg/xattr"
"github.com/rjeczalik/notify"
@@ -301,8 +304,12 @@ func (f *fsClient) put(_ context.Context, reader io.Reader, size int64, progress
objectPath := f.PathURL.Path
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
if err := checkPathLength(objectPath); err != nil {
return 0, err
}
// Write to a temporary file "objectpath/uuid" before commit.
objectPartPath := filepath.Join(filepath.Dir(objectPath), uuid.NewString())
// We cannot resume this operation, then we
// should remove any partial download if any.
@@ -393,6 +400,49 @@ func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, progre
return f.put(ctx, reader, size, progress, opts)
}
// checkPathLength - returns error if given path name length more than 255
func checkPathLength(pathName string) *probe.Error {
// Apple OS X path length is limited to 1016
if runtime.GOOS == "darwin" && len(pathName) > 1016 {
return probe.NewError(errors.New("file name too long"))
}
// Disallow more than 32,767 characters on windows, there
// are no known name_max limits on Windows.
// Refer: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry
if runtime.GOOS == "windows" && len(pathName) > 32767 {
return probe.NewError(errors.New("file name too long"))
}
// On Unix we reject paths if they are just '.', '..' or '/'
if pathName == "." || pathName == ".." || pathName == "/" {
return probe.NewError(errors.New("file access denied"))
}
// Check each path segment length is > 255 on all Unix
// platforms, look for this value as NAME_MAX in
// /usr/include/linux/limits.h
var count int64
for _, p := range pathName {
switch p {
case '/':
count = 0 // Reset
case '\\':
if runtime.GOOS == "windows" {
count = 0
} else {
count++
}
default:
count++
}
if count > 255 {
return probe.NewError(errors.New("file name too long"))
}
} // Success.
return nil
}
func (f *fsClient) putN(_ context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (int64, *probe.Error) {
// ContentType is not handled on purpose.
// For filesystem this is a redundant information.
@@ -415,8 +465,12 @@ func (f *fsClient) putN(_ context.Context, reader io.Reader, size int64, progres
objectPath := f.PathURL.Path
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
if err := checkPathLength(objectPath); err != nil {
return 0, err
}
// Write to a temporary file ""objectpath/uuid"" before commit.
objectPartPath := filepath.Join(filepath.Dir(objectPath), uuid.NewString())
// We cannot resume this operation, then we
// should remove any partial download if any.
@@ -581,9 +635,7 @@ func (f *fsClient) Get(_ context.Context, opts GetOptions) (io.ReadCloser, *Clie
if pErr != nil {
return nil, content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
maps.Copy(content.Metadata, metaData)
content.Metadata[metadataKey] = fileAttr
}
@@ -1308,9 +1360,7 @@ func (f *fsClient) Stat(_ context.Context, opts StatOptions) (content *ClientCon
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
maps.Copy(content.Metadata, metaData)
content.Metadata[metadataKey] = fileAttr
}
-1
View File
@@ -1,5 +1,4 @@
//go:build darwin
// +build darwin
// Copyright (c) 2015-2021 MinIO, Inc.
//
-1
View File
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
// Copyright (c) 2015-2021 MinIO, Inc.
//
-1
View File
@@ -1,5 +1,4 @@
//go:build solaris || openbsd
// +build solaris openbsd
// Copyright (c) 2015-2021 MinIO, Inc.
//
-1
View File
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
// Copyright (c) 2015-2021 MinIO, Inc.
//
+6
View File
@@ -38,6 +38,7 @@ func newTraceV4() httptracer.HTTPTracer {
// Request - Trace HTTP Request
func (t traceV4) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
sseKey := req.Header.Get("X-Amz-Server-Side-Encryption-Customer-Key")
printTrace := func() error {
reqTrace, rerr := httputil.DumpRequestOut(req, false) // Only display header
@@ -47,6 +48,11 @@ func (t traceV4) Request(req *http.Request) (err error) {
return rerr
}
if strings.TrimSpace(sseKey) != "" {
// Stripe out SSE-C key from: X-Amz-Server-Side-Encryption-Customer-Key=<key>
req.Header.Set("X-Amz-Server-Side-Encryption-Customer-Key", "**REDACTED**")
}
if strings.TrimSpace(origAuth) != "" {
// Authorization (S3 v4 signature) Format:
// Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNACEGBGMXBHLEZA/20150524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=bbfaa693c626021bcb5f911cd898a1a30206c1fad6bad1e0eb89e282173bd24c
+11 -9
View File
@@ -26,6 +26,7 @@ import (
"fmt"
"hash/fnv"
"io"
"maps"
"net"
"net/http"
"net/url"
@@ -898,6 +899,9 @@ func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *Cl
return nil, nil, probe.NewError(err)
}
}
if opts.Preserve {
o.Set("X-Amz-Tagging-Directive", "ACCESS")
}
// Disallow automatic decompression for some objects with content-encoding set.
o.Set("Accept-Encoding", "identity")
@@ -933,9 +937,7 @@ func (c *S3Client) Copy(ctx context.Context, source string, opts CopyOptions, pr
}
metadata := make(map[string]string, len(opts.metadata))
for k, v := range opts.metadata {
metadata[k] = v
}
maps.Copy(metadata, opts.metadata)
delete(metadata, "X-Amz-Storage-Class")
if opts.storageClass != "" {
@@ -1021,9 +1023,7 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
}
metadata := make(map[string]string, len(putOpts.metadata))
for k, v := range putOpts.metadata {
metadata[k] = v
}
maps.Copy(metadata, putOpts.metadata)
// Do not copy storage class, it needs to be specified in putOpts
delete(metadata, "X-Amz-Storage-Class")
@@ -1083,6 +1083,8 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
}
}
disableSha256 := putOpts.checksum.IsSet() // pre-emptively disable sha256 payload, if checksum is set.
opts := minio.PutObjectOptions{
UserMetadata: metadata,
UserTags: tagsMap,
@@ -1097,6 +1099,7 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
SendContentMd5: putOpts.md5,
Checksum: putOpts.checksum,
DisableMultipart: putOpts.disableMultipart,
DisableContentSha256: disableSha256,
PartSize: putOpts.multipartSize,
NumThreads: putOpts.multipartThreads,
ConcurrentStreamParts: putOpts.concurrentStream, // if enabled honors NumThreads for piped() uploads
@@ -2254,9 +2257,7 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
content.Tags = entry.UserTags
content.ReplicationStatus = entry.ReplicationStatus
for k, v := range entry.UserMetadata {
content.UserMetadata[k] = v
}
maps.Copy(content.UserMetadata, entry.UserMetadata)
for k := range entry.Metadata {
content.Metadata[k] = entry.Metadata.Get(k)
}
@@ -2292,6 +2293,7 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
setChecksum("CRC32C", entry.ChecksumCRC32C)
setChecksum("SHA1", entry.ChecksumSHA1)
setChecksum("SHA256", entry.ChecksumSHA256)
setChecksum("CRC64NVME", entry.ChecksumCRC64NVME)
return content
}
+24 -25
View File
@@ -26,7 +26,7 @@ import (
"net/http/httptest"
"strconv"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7"
checkv1 "gopkg.in/check.v1"
)
@@ -35,8 +35,8 @@ type bucketHandler struct {
}
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
switch r.Method {
case "GET":
// Handler for incoming getBucketLocation request.
if _, ok := r.URL.Query()["location"]; ok {
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
@@ -44,28 +44,28 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write(response)
return
}
switch {
case r.URL.Path == "/":
switch r.URL.Path {
case "/":
// Handler for incoming ListBuckets request.
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
case r.URL.Path == "/bucket/":
case "/bucket/":
// Handler for incoming ListObjects request.
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
}
case r.Method == "PUT":
switch {
case r.URL.Path == h.resource:
case "PUT":
switch r.URL.Path {
case h.resource:
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusBadRequest)
}
case r.Method == "HEAD":
switch {
case r.URL.Path == h.resource:
case "HEAD":
switch r.URL.Path {
case h.resource:
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusForbidden)
@@ -85,8 +85,8 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
switch {
case r.Method == http.MethodPut:
switch r.Method {
case http.MethodPut:
// Handler for PUT object request.
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
if e != nil {
@@ -100,7 +100,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == http.MethodHead:
case http.MethodHead:
// Handler for Stat object request.
if r.URL.Path != h.resource {
w.WriteHeader(http.StatusNotFound)
@@ -110,7 +110,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == http.MethodPost:
case http.MethodPost:
// Handler for multipart upload request.
if _, ok := r.URL.Query()["uploads"]; ok {
if r.URL.Path == h.resource {
@@ -132,7 +132,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
return
}
case r.Method == http.MethodGet:
case http.MethodGet:
// Handler for get bucket location request.
if _, ok := r.URL.Query()["location"]; ok {
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
@@ -171,8 +171,8 @@ func (h stsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
switch {
case r.Method == http.MethodPost:
switch r.Method {
case http.MethodPost:
token := r.Form.Get("WebIdentityToken")
if token == string(h.jwt) {
response := []byte("<AssumeRoleWithWebIdentityResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><AssumeRoleWithWebIdentityResult><AssumedRoleUser><Arn></Arn><AssumeRoleId></AssumeRoleId></AssumedRoleUser><Credentials><AccessKeyId>7NL5BR739GUQ0ZOD4JNB</AccessKeyId><SecretAccessKey>A2mxZSxPnHNhSduedUHczsXZpVSSssOLpDruUmTV</SecretAccessKey><Expiration>0001-01-01T00:00:00Z</Expiration><SessionToken>eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiI3Tkw1QlI3MzlHVVEwWk9ENEpOQiIsImV4cCI6MTY5OTYwMzMwNiwicGFyZW50IjoibWluaW8iLCJzZXNzaW9uUG9saWN5IjoiZXlKV1pYSnphVzl1SWpvaU1qQXhNaTB4TUMweE55SXNJbE4wWVhSbGJXVnVkQ0k2VzNzaVJXWm1aV04wSWpvaVFXeHNiM2NpTENKQlkzUnBiMjRpT2xzaVlXUnRhVzQ2S2lKZGZTeDdJa1ZtWm1WamRDSTZJa0ZzYkc5M0lpd2lRV04wYVc5dUlqcGJJbXR0Y3pvcUlsMTlMSHNpUldabVpXTjBJam9pUVd4c2IzY2lMQ0pCWTNScGIyNGlPbHNpY3pNNktpSmRMQ0pTWlhOdmRYSmpaU0k2V3lKaGNtNDZZWGR6T25Nek9qbzZLaUpkZlYxOSJ9.uuE_x7PO8QoPfUk9KzUELoAqxihIknZAvJLl5aYJjwpSjJYFTPLp6EvuyJX2hc18s9HzeiJ-vU0dPzsy50dXmg</SessionToken></Credentials></AssumeRoleWithWebIdentityResult><ResponseMetadata></ResponseMetadata></AssumeRoleWithWebIdentityResponse>")
@@ -181,13 +181,12 @@ func (h stsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "MinIO")
w.Write(response)
return
} else {
response := []byte("<ErrorResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><Error><Type></Type><Code>AccessDenied</Code><Message>Access denied: Invalid Token</Message></Error><RequestId></RequestId></ErrorResponse>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Header().Set("Content-Type", "application/xml")
w.Write(response)
return
}
response := []byte("<ErrorResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><Error><Type></Type><Code>AccessDenied</Code><Message>Access denied: Invalid Token</Message></Error><RequestId></RequestId></ErrorResponse>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Header().Set("Content-Type", "application/xml")
w.Write(response)
return
}
}
+1 -2
View File
@@ -65,8 +65,7 @@ func TestSTSS3Operation(t *testing.T) {
t.Fatal(err)
}
var reader io.Reader
reader = bytes.NewReader(object.data)
var reader io.Reader = bytes.NewReader(object.data)
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), nil, PutOptions{
metadata: map[string]string{
"Content-Type": "application/octet-stream",
+34
View File
@@ -267,3 +267,37 @@ func guessURLContentType(urlStr string) string {
contentType := mimedb.TypeByExtension(filepath.Ext(url.Path))
return contentType
}
// urlParts - split URL into parts.
func urlParts(urlStr string) []string {
// Convert '/' on windows to filepath.Separator.
urlStr = filepath.FromSlash(urlStr)
if runtime.GOOS == "windows" {
// Remove '/' prefix before alias if any to support '\\home' alias
// style under Windows
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
}
// Remove everything after alias (i.e. after '/').
return strings.Split(urlStr, string(filepath.Separator))
}
// isURLPrefix - check if source and destination be subdirectories of each other
func isURLPrefix(src string, dest string) bool {
srcURLParts := urlParts(src)
dstURLParts := urlParts(dest)
minIndex := min(len(srcURLParts), len(dstURLParts))
isPrefix := true
for i := range minIndex {
// if one of the URLs ends with '/' and other does not
if (i == minIndex-1) && (dstURLParts[i] == "" || srcURLParts[i] == "" || dstURLParts[i] == "*" || srcURLParts[i] == "*") {
continue
}
if srcURLParts[i] != dstURLParts[i] {
isPrefix = false
break
}
}
return isPrefix
}
+35 -1
View File
@@ -17,7 +17,11 @@
package cmd
import checkv1 "gopkg.in/check.v1"
import (
"testing"
checkv1 "gopkg.in/check.v1"
)
// TestURL - tests url parsing and fields.
func (s *TestSuite) TestURL(c *checkv1.C) {
@@ -52,3 +56,33 @@ func (s *TestSuite) TestURLJoinPath(c *checkv1.C) {
url = urlJoinPath(url1, url2)
c.Assert(url, checkv1.Equals, "http://s3.mycompany.io/dev/mybucket/bin/")
}
func Test_isURLPrefix(t *testing.T) {
type args struct {
src string
dest string
}
tests := []struct {
name string
args args
want bool
}{
{"test1", args{"s3/test", "s3/test/test"}, true},
{"test2", args{"s3/test/", "s3/test/test"}, true},
{"test3", args{"s3/test/test", "s3/test/"}, true},
{"test4", args{"s3/test/test", "s3/test/test.123"}, false},
{"test5", args{"s3/test/", "s3/test/test/test/test"}, true},
{"test6", args{"s3/test/*", "s3/test/test/"}, true},
{"test7", args{"s3/test/*", "s3/test1/test/"}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isURLPrefix(tt.args.src, tt.args.dest); got != tt.want {
t.Errorf("isURLPrefix() = %v, want %v", got, tt.want)
}
if got := isURLPrefix(tt.args.dest, tt.args.src); got != tt.want {
t.Errorf("isURLPrefix() = %v, want %v", got, tt.want)
}
})
}
}
+21 -1
View File
@@ -22,6 +22,7 @@ import (
"crypto/tls"
"fmt"
"io"
"maps"
"math/rand"
"net/http"
"net/url"
@@ -372,7 +373,16 @@ func (config *Config) initTransport(withS3v2 bool) {
// return nil, probe.NewError(e)
// }
}
transport = tr
if len(globalCustomHeader) > 0 {
transport = &headerTransport{
RoundTripper: tr,
customHeader: globalCustomHeader.Clone(),
}
} else {
transport = tr
}
}
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
@@ -399,3 +409,13 @@ type SelectObjectOpts struct {
OutputSerOpts map[string]map[string]string
CompressionType minio.SelectCompressionType
}
type headerTransport struct {
http.RoundTripper
customHeader http.Header
}
func (h *headerTransport) RoundTrip(request *http.Request) (*http.Response, error) {
maps.Copy(request.Header, h.customHeader)
return h.RoundTripper.RoundTrip(request)
}
+18 -15
View File
@@ -21,10 +21,12 @@ import (
"context"
"errors"
"io"
"maps"
"net/http"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
@@ -35,6 +37,7 @@ import (
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/tags"
"github.com/minio/pkg/v3/env"
)
@@ -134,15 +137,12 @@ func isReadAt(reader io.Reader) (ok bool) {
// which happen to also be io.ReaderAt compatible
// we need to add special conditions for them to
// be ignored by this function.
for _, f := range []string{
if slices.Contains([]string{
"/dev/stdin",
"/dev/stdout",
"/dev/stderr",
} {
if f == v.Name() {
ok = false
break
}
}, v.Name()) {
ok = false
}
}
return
@@ -360,9 +360,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
if err != nil {
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
maps.Copy(metadata, currentMetadata)
}
// Get metadata from target content as well
@@ -400,9 +398,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
if err != nil {
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
maps.Copy(metadata, currentMetadata)
}
// Get metadata from target content as well
@@ -446,9 +442,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
}
metadata := make(map[string]string, len(content.Metadata))
for k, v := range content.Metadata {
metadata[k] = v
}
maps.Copy(metadata, content.Metadata)
// Get metadata from target content as well
for k, v := range uploadOpts.urls.TargetContent.Metadata {
@@ -460,6 +454,15 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
metadata[http.CanonicalHeaderKey(k)] = v
}
if content.Tags != nil {
tags, err := tags.NewTags(content.Tags, true)
if err != nil {
return uploadOpts.urls.WithError(probe.NewError(err))
}
metadata["X-Amz-Tagging"] = tags.String()
delete(metadata, "X-Amz-Tagging-Count")
}
var e error
var multipartSize uint64
var multipartThreads int
-101
View File
@@ -1,101 +0,0 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var configCmd = cli.Command{
Name: "config",
Usage: "configure MinIO client",
Action: func(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
},
Hidden: true,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostCmd,
},
}
var configHostCmd = cli.Command{
Name: "host",
Usage: "add, remove and list hosts in configuration file",
Action: func(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
},
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostAddCmd,
configHostRemoveCmd,
configHostListCmd,
},
HideHelpCommand: true,
}
var configHostAddFlags = []cli.Flag{
cli.StringFlag{
Name: "lookup",
Value: "auto",
Usage: "bucket lookup supported by the server. Valid options are '[dns, path, auto]'",
},
cli.StringFlag{
Name: "api",
Usage: "API signature. Valid options are '[S3v4, S3v2]'",
},
}
var configHostAddCmd = cli.Command{
Name: "add",
ShortName: "a",
Usage: "add a new host to configuration file",
Action: func(cli *cli.Context) error {
return mainAliasSet(cli, true)
},
Before: setGlobalsFromContext,
Flags: append(configHostAddFlags, globalFlags...),
HideHelpCommand: true,
}
var configHostListCmd = cli.Command{
Name: "list",
ShortName: "ls",
Usage: "list hosts in configuration file",
Action: func(cli *cli.Context) error {
return mainAliasList(cli, true)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
}
var configHostRemoveCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "remove a host from configuration file",
Action: func(cli *cli.Context) error {
return mainAliasRemove(cli)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
}
+3 -6
View File
@@ -19,6 +19,7 @@ package cmd
import (
"fmt"
"maps"
"os"
"path/filepath"
"runtime"
@@ -94,9 +95,7 @@ func fixConfigV3() {
cfgV3 := newConfigV3()
isMutated := false
for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases {
cfgV3.Aliases[k] = v
}
maps.Copy(cfgV3.Aliases, brokenMcCfgV3.Data().(*brokenConfigV3).Aliases)
for host, brokenHostCfgV3 := range brokenMcCfgV3.Data().(*brokenConfigV3).Hosts {
@@ -144,9 +143,7 @@ func fixConfigV6ForHosts() {
isMutated := false
// Copy aliases.
for k, v := range brokenMcCfgV6.Data().(*configV6).Aliases {
newCfgV6.Aliases[k] = v
}
maps.Copy(newCfgV6.Aliases, brokenMcCfgV6.Data().(*configV6).Aliases)
url := &ClientURL{}
// Copy hosts.
+11 -21
View File
@@ -19,6 +19,7 @@ package cmd
import (
"fmt"
"maps"
"strings"
"github.com/minio/mc/pkg/probe"
@@ -70,9 +71,7 @@ func migrateConfigV1ToV101() {
cfgV101 := newConfigV101()
// Copy aliases.
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
cfgV101.Aliases[k] = v
}
maps.Copy(cfgV101.Aliases, mcCfgV1.Data().(*configV1).Aliases)
// Copy hosts.
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
@@ -128,9 +127,7 @@ func migrateConfigV101ToV2() {
cfgV2 := newConfigV2()
// Copy aliases.
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
cfgV2.Aliases[k] = v
}
maps.Copy(cfgV2.Aliases, mcCfgV101.Data().(*configV101).Aliases)
// Copy hosts.
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
@@ -166,9 +163,7 @@ func migrateConfigV2ToV3() {
cfgV3 := newConfigV3()
// Copy aliases.
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
cfgV3.Aliases[k] = v
}
maps.Copy(cfgV3.Aliases, mcCfgV2.Data().(*configV2).Aliases)
// Copy hosts.
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
@@ -203,9 +198,7 @@ func migrateConfigV3ToV4() {
fatalIf(probe.NewError(e), "Unable to load mc config V3.")
cfgV4 := newConfigV4()
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
cfgV4.Aliases[k] = v
}
maps.Copy(cfgV4.Aliases, mcCfgV3.Data().(*configV3).Aliases)
// New hostConfig has API signature. All older entries were V4
// only. So it is safe to assume V4 as default for all older
// entries.
@@ -244,9 +237,7 @@ func migrateConfigV4ToV5() {
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
cfgV5 := newConfigV5()
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
cfgV5.Aliases[k] = v
}
maps.Copy(cfgV5.Aliases, mcCfgV4.Data().(*configV4).Aliases)
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
cfgV5.Hosts[host] = hostConfigV5{
AccessKeyID: hostCfgV4.AccessKeyID,
@@ -286,9 +277,7 @@ func migrateConfigV5ToV6() {
// Add new Google Cloud Storage alias.
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
cfgV6.Aliases[k] = v
}
maps.Copy(cfgV6.Aliases, mcCfgV5.Data().(*configV5).Aliases)
// Add defaults.
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
@@ -366,7 +355,8 @@ func migrateConfigV6ToV7() {
continue
}
}
if host == "https://s3.amazonaws.com" {
switch host {
case "https://s3.amazonaws.com":
// Only one entry can exist for "s3" domain.
cfgV7.Hosts["s3"] = hostConfigV7{
URL: host,
@@ -374,7 +364,7 @@ func migrateConfigV6ToV7() {
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else if host == "https://storage.googleapis.com" {
case "https://storage.googleapis.com":
// Only one entry can exist for "gcs" domain.
cfgV7.Hosts["gcs"] = hostConfigV7{
URL: host,
@@ -382,7 +372,7 @@ func migrateConfigV6ToV7() {
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else {
default:
// Assign a generic "cloud1", cloud2..." key
// for all other entries that has valid keys set.
alias := fmt.Sprintf("cloud%d", aliasIndex)
+6 -13
View File
@@ -17,7 +17,10 @@
package cmd
import "strings"
import (
"slices"
"strings"
)
var validAPIs = []string{"S3v4", "S3v2"}
@@ -73,21 +76,11 @@ func isValidAPI(api string) (ok bool) {
// isValidLookup - validates if bucket lookup is of valid type
func isValidLookup(lookup string) (ok bool) {
l := strings.ToLower(strings.TrimSpace(lookup))
for _, v := range []string{"dns", "path", "auto"} {
if l == v {
return true
}
}
return false
return slices.Contains([]string{"dns", "path", "auto"}, l)
}
// isValidPath - validates the alias path config
func isValidPath(path string) (ok bool) {
l := strings.ToLower(strings.TrimSpace(path))
for _, v := range []string{"on", "off", "auto"} {
if l == v {
return true
}
}
return false
return slices.Contains([]string{"on", "off", "auto"}, l)
}
+6 -3
View File
@@ -248,9 +248,12 @@ func parseEnvURLStr(envURL string) (*url.URL, string, string, string, *probe.Err
return nil, "", "", "", probe.NewError(e)
}
// Look for if URL has invalid values and return error.
if !((u.Scheme == "http" || u.Scheme == "https") &&
(u.Path == "/" || u.Path == "") && u.Opaque == "" &&
!u.ForceQuery && u.RawQuery == "" && u.Fragment == "") {
if (u.Scheme != "http" && u.Scheme != "https") ||
(u.Path != "/" && u.Path != "") ||
u.Opaque != "" ||
u.ForceQuery ||
u.RawQuery != "" ||
u.Fragment != "" {
return nil, "", "", "", errInvalidArgument().Trace(u.String())
}
if accessKey == "" && secretKey == "" {
+14 -11
View File
@@ -22,6 +22,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"path/filepath"
"strings"
@@ -97,6 +98,10 @@ var (
Name: "zip",
Usage: "Extract from remote zip file (MinIO server source only)",
},
cli.IntFlag{
Name: "max-workers",
Usage: "maximum number of concurrent copies (default: autodetect)",
},
checksumFlag,
}
)
@@ -279,7 +284,7 @@ func doCopy(ctx context.Context, copyOpts doCopyOpts) URLs {
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
func doCopyFake(cpURLs URLs, pg Progress) URLs {
if progressReader, ok := pg.(*progressBar); ok {
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
progressReader.Add64(cpURLs.SourceContent.Size)
}
return cpURLs
@@ -366,7 +371,7 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
quitCh := make(chan struct{})
statusCh := make(chan URLs)
parallel := newParallelManager(statusCh)
parallel := newParallelManager(statusCh, cli.Int("max-workers"))
go func() {
gracefulStop := func() {
@@ -422,9 +427,7 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
isZip := cli.Bool("zip")
if cli.String("attr") != "" {
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
for metadataKey, metaDataVal := range userMetaMap {
cpURLs.TargetContent.UserMetadata[metadataKey] = metaDataVal
}
maps.Copy(cpURLs.TargetContent.UserMetadata, userMetaMap)
}
cpURLs.MD5 = md5
@@ -493,13 +496,13 @@ loop:
errSeen = true
if progressReader, pgok := pg.(*progressBar); pgok {
if progressReader.ProgressBar.Get() > 0 {
if progressReader.Get() > 0 {
writeContSize := (int)(cpURLs.SourceContent.Size)
totalPGSize := (int)(progressReader.ProgressBar.Total)
written := (int)(progressReader.ProgressBar.Get())
totalPGSize := (int)(progressReader.Total)
written := (int)(progressReader.Get())
if totalPGSize > writeContSize && written > writeContSize {
progressReader.ProgressBar.Set((written - writeContSize))
progressReader.ProgressBar.Update()
progressReader.Set((written - writeContSize))
progressReader.Update()
}
}
}
@@ -514,7 +517,7 @@ loop:
if !globalQuiet && !globalJSON {
console.Eraseline()
}
} else if progressReader.ProgressBar.Get() > 0 {
} else if progressReader.Get() > 0 {
progressReader.Finish()
}
} else {
+14 -11
View File
@@ -48,11 +48,12 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
var key, value strings.Builder
writeRune := func(ch rune, pt pToken) {
if pt == KEY {
switch pt {
case KEY:
key.WriteRune(ch)
} else if pt == VALUE {
case VALUE:
value.WriteRune(ch)
} else {
default:
panic("Invalid parser token type")
}
}
@@ -73,26 +74,28 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
}
if ch == '"' {
if ps == DQSTRING {
switch ps {
case DQSTRING:
ps = NORMAL
} else if ps == QSTRING {
case QSTRING:
writeRune(ch, pt)
} else if ps == NORMAL {
case NORMAL:
ps = DQSTRING
} else {
default:
break
}
continue
}
if ch == '\'' {
if ps == QSTRING {
switch ps {
case QSTRING:
ps = NORMAL
} else if ps == DQSTRING {
case DQSTRING:
writeRune(ch, pt)
} else if ps == NORMAL {
case NORMAL:
ps = QSTRING
} else {
default:
break
}
continue
+1 -1
View File
@@ -336,7 +336,7 @@ func prepareCopyURLs(ctx context.Context, o prepareCopyURLsOpts) chan URLs {
defer close(copyURLsCh)
copyURLsContent, err := guessCopyURLType(ctx, o)
if err != nil {
copyURLsCh <- URLs{Error: errUnableToGuess().Trace(o.sourceURLs...)}
copyURLsCh <- URLs{Error: errUnableToGuess(err.Cause.Error()).Trace(o.sourceURLs...)}
return
}
+1 -1
View File
@@ -184,7 +184,7 @@ func doDiffMain(ctx context.Context, firstURL, secondURL string) error {
}
// Diff first and second urls.
for diffMsg := range objectDifference(ctx, firstClient, secondClient, true) {
for diffMsg := range bucketObjectDifference(ctx, firstClient, secondClient) {
if diffMsg.Error != nil {
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
// Ignore error and proceed to next object.
+34 -17
View File
@@ -161,17 +161,23 @@ func metadataEqual(m1, m2 map[string]string) bool {
return true
}
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, isMetadata bool) (diffCh chan diffMessage) {
sourceURL := sourceClnt.GetURL().String()
sourceCh := sourceClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: isMetadata, ShowDir: DirNone})
targetURL := targetClnt.GetURL().String()
targetCh := targetClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: isMetadata, ShowDir: DirNone})
return difference(sourceURL, sourceCh, targetURL, targetCh, isMetadata, false)
func bucketObjectDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffCh chan diffMessage) {
return objectDifference(ctx, sourceClnt, targetClnt, mirrorOptions{
isMetadata: false,
})
}
func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffCh chan diffMessage) {
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, opts mirrorOptions) (diffCh chan diffMessage) {
sourceURL := sourceClnt.GetURL().String()
sourceCh := sourceClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: opts.isMetadata, ShowDir: DirNone})
targetURL := targetClnt.GetURL().String()
targetCh := targetClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: opts.isMetadata, ShowDir: DirNone})
return difference(sourceURL, sourceCh, targetURL, targetCh, opts, false)
}
func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client, opts mirrorOptions) (diffCh chan diffMessage) {
sourceURL := sourceClnt.GetURL().String()
sourceCh := make(chan *ClientContent)
@@ -215,11 +221,16 @@ func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffC
}
}()
return difference(sourceURL, sourceCh, targetURL, targetCh, false, false)
return difference(sourceURL, sourceCh, targetURL, targetCh, opts, false)
}
func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL string, tgtCh <-chan *ClientContent,
cmpMetadata, returnSimilar bool, diffCh chan<- diffMessage,
func differenceInternal(sourceURL string,
srcCh <-chan *ClientContent,
targetURL string,
tgtCh <-chan *ClientContent,
opts mirrorOptions,
returnSimilar bool,
diffCh chan<- diffMessage,
) *probe.Error {
// Pop first entries from the source and targets
srcCtnt, srcOk := <-srcCh
@@ -232,8 +243,14 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
tgtEOF = !tgtOk
// No objects from source AND target: Finish
if srcEOF && tgtEOF {
break
if opts.sourceListingOnly {
if srcEOF {
break
}
} else {
if srcEOF && tgtEOF {
break
}
}
if !srcEOF && srcCtnt.Err != nil {
@@ -332,7 +349,7 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
} else if cmpMetadata &&
} else if opts.isMetadata &&
!metadataEqual(srcCtnt.UserMetadata, tgtCtnt.UserMetadata) &&
!metadataEqual(srcCtnt.Metadata, tgtCtnt.Metadata) {
@@ -375,13 +392,13 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
// objectDifference function finds the difference between all objects
// recursively in sorted order from source and target.
func difference(sourceURL string, sourceCh <-chan *ClientContent, targetURL string, targetCh <-chan *ClientContent, cmpMetadata, returnSimilar bool) (diffCh chan diffMessage) {
func difference(sourceURL string, sourceCh <-chan *ClientContent, targetURL string, targetCh <-chan *ClientContent, opts mirrorOptions, returnSimilar bool) (diffCh chan diffMessage) {
diffCh = make(chan diffMessage, 10000)
go func() {
defer close(diffCh)
err := differenceInternal(sourceURL, sourceCh, targetURL, targetCh, cmpMetadata, returnSimilar, diffCh)
err := differenceInternal(sourceURL, sourceCh, targetURL, targetCh, opts, returnSimilar, diffCh)
if err != nil {
// handle this specifically for filesystem related errors.
switch v := err.ToGoError().(type) {
+1 -1
View File
@@ -125,7 +125,7 @@ func ParseDuration(s string) (Duration, error) {
var err error
// The next character must be [0-9.]
if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') {
if s[0] != '.' && ('0' > s[0] || s[0] > '9') {
return 0, errors.New("invalid duration " + orig)
}
// Consume [0-9]*
+3 -1
View File
@@ -22,6 +22,7 @@ import (
"encoding/base64"
"encoding/hex"
"fmt"
"path/filepath"
"sort"
"strings"
@@ -60,6 +61,7 @@ func (p byPrefixLength) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// get SSE Key if object prefix matches with given resource.
func getSSE(resource string, encKeys []prefixSSEPair) encrypt.ServerSide {
resource = filepath.ToSlash(resource)
for _, k := range encKeys {
if strings.HasPrefix(resource, k.Prefix) {
return k.SSE
@@ -168,7 +170,7 @@ func validateAndParseKey(ctx *cli.Context, key string, keyType sseKeyType) (SSEP
}
func validateOverLappingSSEKeys(keyMap []prefixSSEPair) (err *probe.Error) {
for i := 0; i < len(keyMap); i++ {
for i := range keyMap {
for j := i + 1; j < len(keyMap); j++ {
if strings.HasPrefix(keyMap[i].Prefix, keyMap[j].Prefix) ||
strings.HasPrefix(keyMap[j].Prefix, keyMap[i].Prefix) {
+3 -3
View File
@@ -46,14 +46,14 @@ type errorMessage struct {
}
// fatalIf wrapper function which takes error and selectively prints stack frames if available on debug
func fatalIf(err *probe.Error, msg string, data ...interface{}) {
func fatalIf(err *probe.Error, msg string, data ...any) {
if err == nil {
return
}
fatal(err, msg, data...)
}
func fatal(err *probe.Error, msg string, data ...interface{}) {
func fatal(err *probe.Error, msg string, data ...any) {
if globalJSON {
errorMsg := errorMessage{
Message: msg,
@@ -128,7 +128,7 @@ func exitStatus(status int) error {
}
// errorIf synonymous with fatalIf but doesn't exit on error != nil
func errorIf(err *probe.Error, msg string, data ...interface{}) {
func errorIf(err *probe.Error, msg string, data ...any) {
if err == nil {
return
}
+3 -3
View File
@@ -50,9 +50,9 @@ type findMessage struct {
// String calls tells the console what to print and how to print it.
func (f findMessage) String() string {
var msg string
msg += f.contentMessage.Key
msg += f.Key
if f.VersionID != "" {
msg += " (" + f.contentMessage.VersionID + ")"
msg += " (" + f.VersionID + ")"
}
return console.Colorize("Find", msg)
}
@@ -118,7 +118,7 @@ func getExitStatus(err error) int {
return 0
}
if pe, ok := err.(*exec.ExitError); ok {
if es, ok := pe.ProcessState.Sys().(syscall.WaitStatus); ok {
if es, ok := pe.Sys().(syscall.WaitStatus); ok {
return es.ExitStatus()
}
}
+12 -2
View File
@@ -96,6 +96,10 @@ var globalFlags = []cli.Flag{
Hidden: true,
Value: 10 * time.Minute,
},
cli.StringSliceFlag{
Name: "custom-header,H",
Usage: "add custom HTTP header to the request. 'key:value' format.",
},
}
// bundled encryption flags
@@ -124,7 +128,7 @@ var encS3Flag = cli.StringSliceFlag{
var checksumFlag = cli.StringFlag{
Name: "checksum",
Usage: "Add checksum to uploaded object. Values: MD5, CRC32, CRC32C, SHA1 or SHA256. Requires server trailing headers (AWS, MinIO)",
Usage: "Add checksum to uploaded object. Values: CRC64NVME, CRC32, CRC32C, SHA1 or SHA256. Requires server trailing headers (AWS, MinIO)",
Value: "",
}
@@ -136,14 +140,20 @@ func parseChecksum(ctx *cli.Context) (useMD5 bool, ct minio.ChecksumType) {
ct = minio.ChecksumCRC32
case "CRC32C":
ct = minio.ChecksumCRC32C
case "CRC32-FO":
ct = minio.ChecksumFullObjectCRC32
case "CRC32C-FO":
ct = minio.ChecksumFullObjectCRC32C
case "SHA1":
ct = minio.ChecksumSHA1
case "SHA256":
ct = minio.ChecksumSHA256
case "CRC64N", "CRC64NVME":
ct = minio.ChecksumCRC64NVME
case "MD5":
useMD5 = true
default:
err := fmt.Errorf("unknown checksum type: %s. Should be one of MD5, CRC32, CRC32C, SHA1 or SHA256", cs)
err := fmt.Errorf("unknown checksum type: %s. Should be one of CRC64NVME, MD5, CRC32, CRC32C, SHA1 or SHA256", cs)
fatalIf(probe.NewError(err), "")
}
if ct.IsSet() {
-1
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
// Copyright (c) 2015-2021 MinIO, Inc.
//
-1
View File
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
// Copyright (c) 2015-2021 MinIO, Inc.
//
+25
View File
@@ -23,6 +23,7 @@ import (
"crypto/x509"
"fmt"
"net"
"net/http"
"net/netip"
"net/url"
"os"
@@ -36,6 +37,7 @@ import (
"github.com/minio/madmin-go/v3"
"github.com/minio/pkg/v3/console"
"github.com/muesli/termenv"
"golang.org/x/net/http/httpguts"
)
const (
@@ -80,6 +82,9 @@ var (
// GlobalDevMode is set to true if the program is running in development mode
GlobalDevMode = false
// GlobalTrapSignals is set to true if need to trap the registered signals and cancel the global context.
GlobalTrapSignals = true
// GlobalSubnetProxyURL is the proxy to be used for communication with subnet
GlobalSubnetProxyURL *url.URL
@@ -90,6 +95,8 @@ var (
globalLimitDownload uint64
globalContext, globalCancel = context.WithCancel(context.Background())
globalCustomHeader http.Header
)
var (
@@ -200,5 +207,23 @@ func setGlobalsFromContext(ctx *cli.Context) error {
globalResolvers[host] = addr
}
}
customHeaders := ctx.StringSlice("custom-header")
if len(customHeaders) > 0 {
globalCustomHeader = make(http.Header)
for _, header := range customHeaders {
i := strings.IndexByte(header, ':')
if i <= 0 {
return fmt.Errorf("invalid custom header entry %s", header)
}
h := strings.TrimSpace(header[:i])
hv := strings.TrimSpace(header[i+1:])
if !httpguts.ValidHeaderFieldName(h) || !httpguts.ValidHeaderFieldValue(hv) {
return fmt.Errorf("invalid custom header entry %s", header)
}
globalCustomHeader.Add(h, hv)
}
}
return nil
}
+7 -3
View File
@@ -22,6 +22,7 @@ import (
"compress/bzip2"
"compress/gzip"
"context"
"errors"
"io"
"os"
"strings"
@@ -142,9 +143,12 @@ func headOut(r io.Reader, nlines int64) *probe.Error {
}
for nlines > 0 {
line, _, e := br.ReadLine()
if e != nil {
return probe.NewError(e)
line, _, err := br.ReadLine()
if err != nil && !errors.Is(err, io.EOF) {
return probe.NewError(err)
}
if errors.Is(err, io.EOF) {
break
}
if _, e := stdout.Write(line); e != nil {
switch e := e.(type) {
+1 -1
View File
@@ -95,7 +95,7 @@ type SwInfoV1 struct {
// MinioHealthInfoV1 - Health info of the MinIO cluster
type MinioHealthInfoV1 struct {
Info madmin.InfoMessage `json:"info,omitempty"`
Config interface{} `json:"config,omitempty"`
Config any `json:"config,omitempty"`
ProcInfo []madmin.ServerProcInfo `json:"procinfos,omitempty"`
Error string `json:"error,omitempty"`
}
+29 -11
View File
@@ -23,6 +23,7 @@ import (
"net/http"
"net/url"
"os"
"slices"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -33,12 +34,23 @@ import (
"golang.org/x/term"
)
var idpLdapAccesskeyCreateWithLoginFlags = []cli.Flag{
cli.StringFlag{
Name: "ldap-username",
Usage: "username to login as (prompt if empty)",
},
cli.StringFlag{
Name: "ldap-password",
Usage: "password for ldap-user (prompt if empty)",
},
}
var idpLdapAccesskeyCreateWithLoginCmd = cli.Command{
Name: "create-with-login",
Usage: "login using LDAP credentials to generate access key pair",
Action: mainIDPLdapAccesskeyCreateWithLogin,
Before: setGlobalsFromContext,
Flags: append(idpLdapAccesskeyCreateFlags, globalFlags...),
Flags: slices.Concat(idpLdapAccesskeyCreateWithLoginFlags, idpLdapAccesskeyCreateFlags, globalFlags),
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -74,7 +86,7 @@ func mainIDPLdapAccesskeyCreateWithLogin(ctx *cli.Context) error {
res, e := client.AddServiceAccountLDAP(globalContext, opts)
fatalIf(probe.NewError(e), "unable to add service account")
m := ldapAccesskeyMessage{
m := accesskeyMessage{
op: "create",
Status: "success",
AccessKey: res.AccessKey,
@@ -97,16 +109,22 @@ func loginLDAPAccesskey(ctx *cli.Context) (*madmin.AdminClient, madmin.AddServic
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Username: "))
value, _, e := reader.ReadLine()
fatalIf(probe.NewError(e), "unable to read username")
username := string(value)
username := ctx.String("ldap-username")
if username == "" {
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Username: "))
value, _, e := reader.ReadLine()
fatalIf(probe.NewError(e), "unable to read username")
username = string(value)
}
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Password: "))
bytePassword, e := term.ReadPassword(int(os.Stdin.Fd()))
fatalIf(probe.NewError(e), "unable to read password")
fmt.Printf("\n")
password := string(bytePassword)
password := ctx.String("ldap-password")
if password == "" {
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Password: "))
bytePassword, e := term.ReadPassword(int(os.Stdin.Fd()))
fatalIf(probe.NewError(e), "unable to read password")
fmt.Printf("\n")
password = string(bytePassword)
}
stsCreds, e := credentials.NewLDAPIdentity(urlStr, username, password)
fatalIf(probe.NewError(e), "unable to initialize LDAP identity")
+1 -1
View File
@@ -127,7 +127,7 @@ func commonAccesskeyCreate(ctx *cli.Context, ldap bool) error {
}
fatalIf(probe.NewError(e), "Unable to add service account.")
m := ldapAccesskeyMessage{
m := accesskeyMessage{
op: "create",
Status: "success",
AccessKey: res.AccessKey,
+1 -1
View File
@@ -101,7 +101,7 @@ func commonAccesskeyEdit(ctx *cli.Context) error {
e := client.UpdateServiceAccount(globalContext, accessKey, opts)
fatalIf(probe.NewError(e), "Unable to edit service account.")
m := ldapAccesskeyMessage{
m := accesskeyMessage{
op: "edit",
Status: "success",
AccessKey: accessKey,
+1 -1
View File
@@ -73,7 +73,7 @@ func enableDisableAccesskey(ctx *cli.Context, enable bool) error {
})
fatalIf(probe.NewError(e), "Unable to add service account.")
m := ldapAccesskeyMessage{
m := accesskeyMessage{
op: op,
Status: "success",
AccessKey: accessKey,
+5 -128
View File
@@ -19,13 +19,9 @@ package cmd
import (
"strings"
"time"
"github.com/charmbracelet/lipgloss"
humanize "github.com/dustin/go-humanize"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
)
var idpLdapAccesskeyInfoCmd = cli.Command{
@@ -52,137 +48,18 @@ EXAMPLES:
`,
}
type ldapAccesskeyMessage struct {
op string
Status string `json:"status"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey,omitempty"`
ParentUser string `json:"parentUser,omitempty"`
AccountStatus string `json:"accountStatus,omitempty"`
ImpliedPolicy bool `json:"impliedPolicy,omitempty"`
Policy json.RawMessage `json:"policy,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Expiration *time.Time `json:"expiration,omitempty"`
type ldapAccessKeyInfo struct {
Username string `json:"username,omitempty"`
}
func (m ldapAccesskeyMessage) String() string {
func (l ldapAccessKeyInfo) String() string {
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")) // green
o := strings.Builder{}
switch m.op {
case "info":
expirationStr := "NONE"
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
expirationStr = humanize.Time(*m.Expiration)
}
policyStr := "embedded"
if m.ImpliedPolicy {
policyStr = "implied"
}
statusStr := "enabled"
if m.AccountStatus == "off" {
statusStr = "disabled"
}
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Parent User:"), m.ParentUser))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Status:"), statusStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Policy:"), policyStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
case "create":
expirationStr := "NONE"
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
expirationStr = m.Expiration.String()
}
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Secret Key:"), m.SecretKey))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
case "remove":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully removed access key `%s`.", m.AccessKey)))
case "edit":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully edited access key `%s`.", m.AccessKey)))
case "enable":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully enabled access key `%s`.", m.AccessKey)))
case "disable":
o.WriteString(labelStyle.Render(iFmt(0, "Successfully disabled access key `%s`.", m.AccessKey)))
}
o.WriteString(labelStyle.Render("Username: "))
o.WriteString(l.Username)
return o.String()
}
func (m ldapAccesskeyMessage) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func mainIDPLdapAccesskeyInfo(ctx *cli.Context) error {
return commonAccesskeyInfo(ctx)
}
// currently no difference between ldap and builtin accesskey info
func commonAccesskeyInfo(ctx *cli.Context) error {
if len(ctx.Args()) < 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
args := ctx.Args()
aliasedURL := args.Get(0)
accessKeys := args.Tail()
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
for _, accessKey := range accessKeys {
// Assume service account by default
res, e := client.InfoServiceAccount(globalContext, accessKey)
if e != nil {
// If not a service account must be sts
tempRes, e := client.TemporaryAccountInfo(globalContext, accessKey)
if e != nil {
errorIf(probe.NewError(e), "Unable to retrieve access key %s info.", accessKey)
} else {
m := ldapAccesskeyMessage{
op: "info",
AccessKey: accessKey,
Status: "success",
ParentUser: tempRes.ParentUser,
AccountStatus: tempRes.AccountStatus,
ImpliedPolicy: tempRes.ImpliedPolicy,
Policy: json.RawMessage(tempRes.Policy),
Name: tempRes.Name,
Description: tempRes.Description,
Expiration: nilExpiry(tempRes.Expiration),
}
printMsg(m)
}
} else {
m := ldapAccesskeyMessage{
op: "info",
AccessKey: accessKey,
Status: "success",
ParentUser: res.ParentUser,
AccountStatus: res.AccountStatus,
ImpliedPolicy: res.ImpliedPolicy,
Policy: json.RawMessage(res.Policy),
Name: res.Name,
Description: res.Description,
Expiration: nilExpiry(res.Expiration),
}
printMsg(m)
}
}
return nil
}
func nilExpiry(expiry *time.Time) *time.Time {
if expiry != nil && expiry.Equal(timeSentinel) {
return nil
}
return expiry
}
+8 -1
View File
@@ -19,6 +19,7 @@ package cmd
import (
"errors"
"strings"
"github.com/minio/cli"
"github.com/minio/madmin-go/v3"
@@ -129,18 +130,24 @@ func commonAccesskeyList(ctx *cli.Context) (aliasedURL string, tentativeAll bool
svcaccOnly := ctx.Bool("svcacc-only")
selfFlag := ctx.Bool("self")
opts.All = ctx.Bool("all")
opts.AllConfigs = ctx.Bool("all-configs")
args := ctx.Args()
aliasedURL = args.Get(0)
users = args.Tail()
aliasedURL, cfgName, _ := strings.Cut(aliasedURL, ":")
if cfgName != "" {
opts.ConfigName = cfgName
}
var e error
if (usersOnly && svcaccOnly) || (usersOnly && stsOnly) || (svcaccOnly && stsOnly) {
e = errors.New("only one of --users-only, --temp-only, or --permanent-only can be specified")
} else if selfFlag && opts.All {
e = errors.New("only one of --self or --all can be specified")
} else if (selfFlag || opts.All) && len(users) > 0 {
e = errors.New("user DNs cannot be specified with --self or --all")
e = errors.New("users cannot be specified with --self or --all")
}
fatalIf(probe.NewError(e), "Invalid flags.")
+1 -1
View File
@@ -66,7 +66,7 @@ func commonAccesskeyRemove(ctx *cli.Context) error {
e := client.DeleteServiceAccount(globalContext, accessKey)
fatalIf(probe.NewError(e), "Unable to remove service account.")
m := ldapAccesskeyMessage{
m := accesskeyMessage{
op: "remove",
Status: "success",
AccessKey: accessKey,
+90
View File
@@ -0,0 +1,90 @@
// Copyright (c) 2015-2025 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
var idpLdapAccesskeySTSRevokeCmd = cli.Command{
Name: "sts-revoke",
Usage: "revokes all STS accounts or specified types for the specified user",
Action: mainIdpLdapAccesskeySTSRevoke,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminAccesskeySTSRevokeFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS USER [--all | --token-type TOKEN_TYPE]
Exactly one of --all or --token-type must be specified.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Revoke all STS accounts for LDAP user 'bobfisher'
{{.Prompt}} {{.HelpName}} myminio uid=bobfisher,ou=people,ou=hwengg,dc=min,dc=io --all
2. Revoke all STS accounts for LDAP user 'bobfisher' (alt)
{{.Prompt}} {{.HelpName}} myminio bobfisher --all
3. Revoke STS accounts of a token type 'app-1' for user 'user1'
{{.Prompt}} {{.HelpName}} myminio user1 --token-type app-1
4. Revoke all STS accounts for the authenticated user (must be LDAP service account)
{{.Prompt}} {{.HelpName}} myminio --self
5. Revoke STS accounts of a token type 'app-1' for the authenticated user (must be LDAP service account)
{{.Prompt}} {{.HelpName}} myminio --self --token-type app-1
`,
}
// mainIdpLdapAccesskeySTSRevoke is the handle for "mc idp ldap accesskey sts-revoke" command.
func mainIdpLdapAccesskeySTSRevoke(ctx *cli.Context) error {
checkSTSRevokeSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
user := args.Get(1) // will be empty if --self flag is set
tokenRevokeType := ctx.String("token-type")
fullRevoke := ctx.Bool("all")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.RevokeTokens(globalContext, madmin.RevokeTokensReq{
User: user,
TokenRevokeType: tokenRevokeType,
FullRevoke: fullRevoke,
})
fatalIf(probe.NewError(e).Trace(args...), "Unable to revoke tokens for %s", user)
printMsg(stsRevokeMessage{
User: user,
TokenRevokeType: tokenRevokeType,
})
return nil
}
+1
View File
@@ -28,6 +28,7 @@ var idpLdapAccesskeySubcommands = []cli.Command{
idpLdapAccesskeyEditCmd,
idpLdapAccesskeyEnableCmd,
idpLdapAccesskeyDisableCmd,
idpLdapAccesskeySTSRevokeCmd,
}
var idpLdapAccesskeyCmd = cli.Command{
+2 -2
View File
@@ -185,7 +185,7 @@ func mainIDPLDAPRemove(ctx *cli.Context) error {
showCommandHelpAndExit(ctx, 1)
}
var cfgName string = madmin.Default
cfgName := madmin.Default
return idpRemove(ctx, false, cfgName)
}
@@ -247,7 +247,7 @@ func mainIDPLDAPInfo(ctx *cli.Context) error {
showCommandHelpAndExit(ctx, 1)
}
var cfgName string = madmin.Default
cfgName := madmin.Default
return idpInfo(ctx, false, cfgName)
}
+48
View File
@@ -0,0 +1,48 @@
// Copyright (c) 2015-2024 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var idpOpenidAccesskeyDisableCmd = cli.Command{
Name: "disable",
Usage: "disable an access key",
Action: mainIDPOpenIDAccesskeyDisable,
Before: setGlobalsFromContext,
Flags: globalFlags,
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] [TARGET]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Disable LDAP access key
{{.Prompt}} {{.HelpName}} myminio myaccesskey
`,
}
func mainIDPOpenIDAccesskeyDisable(ctx *cli.Context) error {
return enableDisableAccesskey(ctx, false)
}
+77
View File
@@ -0,0 +1,77 @@
// Copyright (c) 2015-2024 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var idpOpenIDAccesskeyEditFlags = []cli.Flag{
cli.StringFlag{
Name: "secret-key",
Usage: "set a secret key for the account",
},
cli.StringFlag{
Name: "policy",
Usage: "path to a JSON policy file",
},
cli.StringFlag{
Name: "name",
Usage: "friendly name for the account",
},
cli.StringFlag{
Name: "description",
Usage: "description for the account",
},
cli.StringFlag{
Name: "expiry-duration",
Usage: "duration before the access key expires",
},
cli.StringFlag{
Name: "expiry",
Usage: "expiry date for the access key",
},
}
var idpOpenidAccesskeyEditCmd = cli.Command{
Name: "edit",
Usage: "edit existing access keys for OpenID",
Action: mainIDPOpenIDAccesskeyEdit,
Before: setGlobalsFromContext,
Flags: append(idpOpenIDAccesskeyEditFlags, globalFlags...),
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] [TARGET]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Change the secret key for the access key "testkey"
{{.Prompt}} {{.HelpName}} myminio/ testkey --secret-key 'xxxxxxx'
2. Change the expiry duration for the access key "testkey"
{{.Prompt}} {{.HelpName}} myminio/ testkey --expiry-duration 24h
`,
}
func mainIDPOpenIDAccesskeyEdit(ctx *cli.Context) error {
return commonAccesskeyEdit(ctx)
}
+48
View File
@@ -0,0 +1,48 @@
// Copyright (c) 2015-2024 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var idpOpenidAccesskeyEnableCmd = cli.Command{
Name: "enable",
Usage: "enable an access key",
Action: mainIDPOpenIDAccesskeyEnable,
Before: setGlobalsFromContext,
Flags: globalFlags,
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] [TARGET]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable LDAP access key
{{.Prompt}} {{.HelpName}} myminio myaccesskey
`,
}
func mainIDPOpenIDAccesskeyEnable(ctx *cli.Context) error {
return enableDisableAccesskey(ctx, true)
}
+78
View File
@@ -0,0 +1,78 @@
// Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/minio/cli"
)
var idpOpenidAccesskeyInfoCmd = cli.Command{
Name: "info",
Usage: "info about given access key pairs for OpenID",
Action: mainIDPOpenIDAccesskeyInfo,
Before: setGlobalsFromContext,
Flags: globalFlags,
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET ACCESSKEY [ACCESSKEY...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get info for the access key "testkey"
{{.Prompt}} {{.HelpName}} local/ testkey
2. Get info for the access keys "testkey" and "testkey2"
{{.Prompt}} {{.HelpName}} local/ testkey testkey2
`,
}
type openIDAccessKeyInfo struct {
ConfigName string `json:"configName"`
UserID string `json:"userID"`
UserIDClaim string `json:"userIDClaim"`
DisplayName string `json:"displayName,omitempty"`
DisplayNameClaim string `json:"displayNameClaim,omitempty"`
}
func (l openIDAccessKeyInfo) String() string {
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")) // green
o := strings.Builder{}
if l.ConfigName == "_" {
l.ConfigName = "_ (default)"
}
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render("Config:"), l.ConfigName))
if l.DisplayNameClaim != "" {
dispNameLabel := fmt.Sprintf("Display Name (%s):", l.DisplayNameClaim)
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render(dispNameLabel), l.DisplayName))
}
uidLabel := fmt.Sprintf("User ID (%s):", l.UserIDClaim)
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render(uidLabel), l.UserID))
return o.String()
}
func mainIDPOpenIDAccesskeyInfo(ctx *cli.Context) error {
return commonAccesskeyInfo(ctx)
}
+169
View File
@@ -0,0 +1,169 @@
// Copyright (c) 2015-2025 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"strings"
"github.com/charmbracelet/lipgloss"
humanize "github.com/dustin/go-humanize"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
var idpOpenIDAccesskeyListFlags = []cli.Flag{
cli.BoolFlag{
Name: "users-only",
Usage: "only list user DNs",
},
cli.BoolFlag{
Name: "temp-only",
Usage: "only list temporary access keys",
},
cli.BoolFlag{
Name: "svcacc-only",
Usage: "only list service account access keys",
},
cli.BoolFlag{
Name: "self",
Usage: "list access keys for the authenticated user",
},
cli.BoolFlag{
Name: "all",
Usage: "list all access keys for all OpenID users",
},
cli.BoolFlag{
Name: "all-configs",
Usage: "list access keys for all OpenID configurations",
},
}
var idpOpenidAccesskeyListCmd = cli.Command{
Name: "list",
ShortName: "ls",
Usage: "list access key pairs for OpenID",
Action: mainIDPOpenIDAccesskeyList,
Before: setGlobalsFromContext,
Flags: append(idpOpenIDAccesskeyListFlags, globalFlags...),
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET[:CFGNAME] [USER/ID...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get list of all OpenID users and associated access keys in local server (if admin)
{{.Prompt}} {{.HelpName}} local/
2. Get list of OpenID users in local server (if admin)
{{.Prompt}} {{.HelpName}} local/ --users-only
3. Get list of all users and associated temporary access keys in play server (if admin)
{{.Prompt}} {{.HelpName}} play/ --temp-only
4. Get list of access keys associated with internal name 'openidinternalname'
{{.Prompt}} {{.HelpName}} play/ openidinternalname
5. Get list of access keys associated with ID claim 'openidsub' (default claim is sub)
{{.Prompt}} {{.HelpName}} play/ openidsub
7. Get authenticated user and associated access keys in local server (if not admin)
{{.Prompt}} {{.HelpName}} local/
`,
}
type openIDAccesskeyList struct {
Status string `json:"status"`
ConfigName string `json:"configName"`
Users []madmin.OpenIDUserAccessKeys `json:"users"`
}
func (m openIDAccesskeyList) String() string {
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575"))
o := strings.Builder{}
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Config Name:"), m.ConfigName))
userStr := "User ID"
for _, user := range m.Users {
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render(userStr+":"), user.MinioAccessKey))
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render("ID:"), user.ID))
if user.ReadableName != "" {
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render("Readable Name:"), user.ReadableName))
}
if len(user.STSKeys) > 0 || len(user.ServiceAccounts) > 0 {
o.WriteString(iFmt(4, "%s\n", labelStyle.Render("Access Keys:")))
}
for _, k := range user.STSKeys {
expiration := "never"
if nilExpiry(k.Expiration) != nil {
expiration = humanize.Time(*k.Expiration)
}
o.WriteString(iFmt(6, "%s, expires: %s, sts: true\n", k.AccessKey, expiration))
}
for _, k := range user.ServiceAccounts {
expiration := "never"
if nilExpiry(k.Expiration) != nil {
expiration = humanize.Time(*k.Expiration)
}
o.WriteString(iFmt(6, "%s, expires: %s, sts: false\n", k.AccessKey, expiration))
}
}
return o.String()
}
func (m openIDAccesskeyList) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func mainIDPOpenIDAccesskeyList(ctx *cli.Context) error {
aliasedURL, tentativeAll, users, opts := commonAccesskeyList(ctx)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
accessKeys, e := client.ListAccessKeysOpenIDBulk(globalContext, users, opts)
if e != nil {
if e.Error() == "Access Denied." && tentativeAll {
// retry with self
opts.All = false
accessKeys, e = client.ListAccessKeysOpenIDBulk(globalContext, users, opts)
}
fatalIf(probe.NewError(e), "Unable to list access keys.")
}
for _, cfg := range accessKeys {
m := openIDAccesskeyList{
Status: "success",
ConfigName: cfg.ConfigName,
Users: cfg.Users,
}
printMsg(m)
}
return nil
}
+49
View File
@@ -0,0 +1,49 @@
// Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var idpOpenidAccesskeyRemoveCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "delete access key pairs for OpenID",
Action: mainIDPOpenIDAccesskeyRemove,
Before: setGlobalsFromContext,
Flags: globalFlags,
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET ACCESSKEY
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove the access key "testkey" from local server
{{.Prompt}} {{.HelpName}} local/ testkey
`,
}
func mainIDPOpenIDAccesskeyRemove(ctx *cli.Context) error {
return commonAccesskeyRemove(ctx)
}
+44
View File
@@ -0,0 +1,44 @@
// Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var idpOpenidAccesskeySubcommands = []cli.Command{
idpOpenidAccesskeyListCmd,
idpOpenidAccesskeyRemoveCmd,
idpOpenidAccesskeyInfoCmd,
idpOpenidAccesskeyEditCmd,
idpOpenidAccesskeyEnableCmd,
idpOpenidAccesskeyDisableCmd,
}
var idpOpenIDAccesskeyCmd = cli.Command{
Name: "accesskey",
Usage: "manage OpenID access key pairs",
Action: mainIDPOpenIDAccesskey,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: idpOpenidAccesskeySubcommands,
HideHelpCommand: true,
}
func mainIDPOpenIDAccesskey(ctx *cli.Context) error {
commandNotFound(ctx, idpOpenidAccesskeySubcommands)
return nil
}
+12 -1
View File
@@ -416,12 +416,16 @@ func (i idpConfig) String() string {
return "Not configured."
}
enableStr := "on"
// Determine required width for key column.
fieldColWidth := 0
for _, kv := range i.Info {
if fieldColWidth < len(kv.Key) {
fieldColWidth = len(kv.Key)
}
if kv.Key == "enable" {
enableStr = kv.Value
}
}
// Add 1 for the colon-suffix in each entry.
fieldColWidth++
@@ -439,7 +443,14 @@ func (i idpConfig) String() string {
PaddingLeft(1)
var lines []string
lines = append(lines, fmt.Sprintf("%s%s",
fieldColStyle.Render("enable:"),
valueColStyle.Render(enableStr),
))
for _, kv := range i.Info {
if kv.Key == "enable" {
continue
}
envStr := ""
if kv.IsCfg && kv.IsEnv {
envStr = " (environment)"
@@ -509,7 +520,7 @@ func idpEnableDisable(ctx *cli.Context, isOpenID, enable bool) error {
idpType = madmin.OpenidIDPCfg
}
configBody := "enable=on"
configBody := "enable="
if !enable {
configBody = "enable=off"
}
+1
View File
@@ -28,6 +28,7 @@ var (
idpOpenidInfoCmd,
idpOpenidEnableCmd,
idpOpenidDisableCmd,
idpOpenIDAccesskeyCmd,
// TODO: idpOpenidPolicyCmd,
}
idpOpenidCmd = cli.Command{
+1 -1
View File
@@ -224,7 +224,7 @@ func checkRestoreStatus(ctx context.Context, targetAlias, targetURL, targetVersi
var dotCycle = 0
// Clear and print text in the same line
func printStatus(msg string, args ...interface{}) {
func printStatus(msg string, args ...any) {
if globalJSON {
return
}
+22 -1
View File
@@ -27,6 +27,7 @@ import (
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
)
@@ -180,13 +181,33 @@ func mainAdminTierInfo(ctx *cli.Context) error {
NumbersStyle = lipgloss.NewStyle().Align(lipgloss.Right)
)
tableData := tierInfos(tInfos)
filteredData := table.NewFilter(tableData).
var filteredData table.Data
filteredData = table.NewFilter(tableData).
Filter(func(row int) bool {
if tier == "" {
return true
}
return tableData.At(row, 0) == tier
})
if filteredData.Rows() == 0 {
// check if that tier name is valid
// if valid will show that with empty data
tiers, e := client.ListTiers(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to list configured remote tier targets")
for _, t := range tiers {
if t.Name == tier {
filteredData = tierInfos([]madmin.TierInfo{
{
Name: tier,
Type: t.Type.String(),
},
})
break
}
}
}
tbl := table.New().
Border(lipgloss.NormalBorder()).
Headers(tableData.Headers()...).
+6
View File
@@ -28,6 +28,7 @@ import (
json "github.com/minio/colorjson"
madmin "github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
)
var adminTierListCmd = cli.Command{
@@ -109,6 +110,11 @@ func mainAdminTierList(ctx *cli.Context) error {
tiers, e := client.ListTiers(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to list configured remote tier targets")
if len(tiers) == 0 {
console.Infoln("No remote tier targets found for alias '" + aliasedURL + "'. Use `mc ilm tier add` to configure one.")
return nil
}
if globalJSON {
printMsg(&tierListMessage{
Status: "success",
+9
View File
@@ -272,6 +272,8 @@ func GetLifecycleOptions(ctx *cli.Context) (LifecycleOptions, *probe.Error) {
}
}
expiryRulesCount := 0
if ctx.IsSet("size-lt") {
szStr := ctx.String("size-lt")
szLt, err := humanize.ParseBytes(szStr)
@@ -321,9 +323,11 @@ func GetLifecycleOptions(ctx *cli.Context) (LifecycleOptions, *probe.Error) {
tags = strPtr(ctx.String("tags"))
}
if ctx.IsSet("expiry-date") {
expiryRulesCount++
expiryDate = strPtr(ctx.String("expiry-date"))
}
if ctx.IsSet("expiry-days") {
expiryRulesCount++
expiryDays = strPtr(ctx.String("expiry-days"))
}
if f := "expire-days"; ctx.IsSet(f) {
@@ -339,6 +343,7 @@ func GetLifecycleOptions(ctx *cli.Context) (LifecycleOptions, *probe.Error) {
expiredObjectDeleteMarker = boolPtr(ctx.Bool("expired-object-delete-marker"))
}
if f := "expire-delete-marker"; ctx.IsSet(f) {
expiryRulesCount++
expiredObjectDeleteMarker = boolPtr(ctx.Bool(f))
}
if ctx.IsSet("noncurrentversion-expiration-days") {
@@ -374,6 +379,10 @@ func GetLifecycleOptions(ctx *cli.Context) (LifecycleOptions, *probe.Error) {
expiredObjectAllversions = boolPtr(ctx.Bool("expire-all-object-versions"))
}
if expiryRulesCount > 1 {
return LifecycleOptions{}, probe.NewError(errors.New("only one of expiry-date, expiry-days and expire-delete-marker can be used in a single rule. Try adding multiple rules to achieve the desired effect"))
}
return LifecycleOptions{
ID: id,
Status: status,
+12 -1
View File
@@ -113,6 +113,13 @@ func validateExpiration(rule lifecycle.Rule) error {
return nil
}
func validateTransition(rule lifecycle.Rule) error {
if !rule.Transition.IsDaysNull() && !rule.Transition.IsDateNull() {
return errors.New("only one parameter under Transition can be specified")
}
return nil
}
func validateNoncurrentExpiration(rule lifecycle.Rule) error {
days := rule.NoncurrentVersionExpiration.NoncurrentDays
if days < 0 {
@@ -162,6 +169,9 @@ func validateILMRule(rule lifecycle.Rule) *probe.Error {
if e := validateExpiration(rule); e != nil {
return probe.NewError(e)
}
if e := validateTransition(rule); e != nil {
return probe.NewError(e)
}
if e := validateTranExpCurdate(rule); e != nil {
return probe.NewError(e)
}
@@ -206,7 +216,8 @@ func parseTransition(storageClass, transitionDateStr, transitionDaysStr *string)
return lifecycle.Transition{}, err
}
transition.Date = transitionDate
} else if transitionDaysStr != nil {
}
if transitionDaysStr != nil {
transitionDays, err := parseTransitionDays(*transitionDaysStr)
if err != nil {
return lifecycle.Transition{}, err

Some files were not shown because too many files have changed in this diff Show More