From ad790c4feb0c89044c92169b9c2f20fc657f6bee Mon Sep 17 00:00:00 2001 From: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com> Date: Wed, 14 May 2025 14:47:47 -0700 Subject: [PATCH 1/7] Remove more unused APIs --- api/client.go | 40 -- api/config.go | 17 - api/config_test.go | 66 --- api/consts.go | 8 - api/embedded_spec.go | 332 ----------- api/operations/auth/login_oauth2_auth.go | 73 --- .../auth/login_oauth2_auth_parameters.go | 101 ---- .../auth/login_oauth2_auth_responses.go | 115 ---- .../auth/login_oauth2_auth_urlbuilder.go | 104 ---- api/operations/bucket/put_bucket_tags.go | 88 --- .../bucket/put_bucket_tags_parameters.go | 126 ----- .../bucket/put_bucket_tags_responses.go | 115 ---- .../bucket/put_bucket_tags_urlbuilder.go | 116 ---- api/operations/console_api.go | 37 -- api/operations/user/list_users.go | 88 --- api/operations/user/list_users_parameters.go | 146 ----- api/operations/user/list_users_responses.go | 135 ----- api/operations/user/list_users_urlbuilder.go | 131 ----- api/user_buckets.go | 46 +- api/user_login.go | 158 +----- api/user_login_test.go | 75 --- api/user_session.go | 25 +- api/user_session_test.go | 10 +- integration/user_api_bucket_test.go | 531 ------------------ models/list_users_response.go | 138 ----- models/login_details.go | 7 +- models/login_oauth2_auth_request.go | 105 ---- models/put_bucket_tags_request.go | 67 --- models/user.go | 79 --- pkg/auth/idp/oauth2/config.go | 47 -- pkg/auth/idp/oauth2/const.go | 12 +- pkg/auth/idp/oauth2/provider.go | 70 --- pkg/auth/idp/oauth2/provider_test.go | 71 --- pkg/auth/ldap.go | 15 - pkg/auth/ldap/config.go | 27 - pkg/auth/ldap/const.go | 22 - pkg/certs/certs.go | 7 - pkg/kes/kes.go | 18 - swagger.yml | 125 +---- web-app/src/api/consoleApi.ts | 191 +------ web-app/src/screens/LoginPage/Login.tsx | 1 - .../websockets/objectBrowserWSMiddleware.ts | 4 +- 42 files changed, 40 insertions(+), 3649 deletions(-) delete mode 100644 api/operations/auth/login_oauth2_auth.go delete mode 100644 api/operations/auth/login_oauth2_auth_parameters.go delete mode 100644 api/operations/auth/login_oauth2_auth_responses.go delete mode 100644 api/operations/auth/login_oauth2_auth_urlbuilder.go delete mode 100644 api/operations/bucket/put_bucket_tags.go delete mode 100644 api/operations/bucket/put_bucket_tags_parameters.go delete mode 100644 api/operations/bucket/put_bucket_tags_responses.go delete mode 100644 api/operations/bucket/put_bucket_tags_urlbuilder.go delete mode 100644 api/operations/user/list_users.go delete mode 100644 api/operations/user/list_users_parameters.go delete mode 100644 api/operations/user/list_users_responses.go delete mode 100644 api/operations/user/list_users_urlbuilder.go delete mode 100644 models/list_users_response.go delete mode 100644 models/login_oauth2_auth_request.go delete mode 100644 models/put_bucket_tags_request.go delete mode 100644 models/user.go delete mode 100644 pkg/auth/idp/oauth2/provider_test.go delete mode 100644 pkg/auth/ldap/config.go delete mode 100644 pkg/auth/ldap/const.go diff --git a/api/client.go b/api/client.go index d4de74baff..64c95bb185 100644 --- a/api/client.go +++ b/api/client.go @@ -31,8 +31,6 @@ import ( "github.com/minio/console/models" "github.com/minio/console/pkg" - "github.com/minio/console/pkg/auth" - "github.com/minio/console/pkg/auth/ldap" xjwt "github.com/minio/console/pkg/auth/token" mc "github.com/minio/mc/cmd" "github.com/minio/mc/pkg/probe" @@ -333,44 +331,6 @@ func stsCredentials(minioURL, accessKey, secretKey, location string, client *htt func NewConsoleCredentials(accessKey, secretKey, location string, client *http.Client) (*credentials.Credentials, error) { minioURL := getMinIOServer() - // LDAP authentication for Console - if ldap.GetLDAPEnabled() { - creds, err := auth.GetCredentialsFromLDAP(client, minioURL, accessKey, secretKey) - if err != nil { - return nil, err - } - - credContext := &credentials.CredContext{ - Client: client, - } - - // We verify if LDAP credentials are correct and no error is returned - _, err = creds.GetWithContext(credContext) - - if err != nil && strings.Contains(strings.ToLower(err.Error()), "not found") { - // We try to use STS Credentials in case LDAP credentials are incorrect. - stsCreds, errSTS := stsCredentials(minioURL, accessKey, secretKey, location, client) - - // If there is an error with STS too, then we return the original LDAP error - if errSTS != nil { - LogError("error in STS credentials for LDAP case: %v ", errSTS) - - // We return LDAP result - return creds, nil - } - - _, err := stsCreds.GetWithContext(credContext) - // There is an error with STS credentials, We return the result of LDAP as STS is not a priority in this case. - if err != nil { - return creds, nil - } - - return stsCreds, nil - } - - return creds, nil - } - return stsCredentials(minioURL, accessKey, secretKey, location, client) } diff --git a/api/config.go b/api/config.go index e424416c1e..a87d07093a 100644 --- a/api/config.go +++ b/api/config.go @@ -227,11 +227,6 @@ func GetSecureSTSPreload() bool { return strings.ToLower(env.Get(ConsoleSecureSTSPreload, "off")) == "on" } -// If TLSTemporaryRedirect is true, the a 302 will be used while redirecting. Default is false (301). -func GetSecureTLSTemporaryRedirect() bool { - return strings.ToLower(env.Get(ConsoleSecureTLSTemporaryRedirect, "off")) == "on" -} - // STS header is only included when the connection is HTTPS. func GetSecureForceSTSHeader() bool { return strings.ToLower(env.Get(ConsoleSecureForceSTSHeader, "off")) == "on" @@ -254,18 +249,6 @@ func getLogSearchAPIToken() string { return env.Get(LogSearchQueryAuthToken, "") } -func getLogSearchURL() string { - return env.Get(ConsoleLogQueryURL, "") -} - -func getPrometheusURL() string { - return env.Get(PrometheusURL, "") -} - -func getPrometheusJobID() string { - return env.Get(PrometheusJobID, "minio-job") -} - func getMaxConcurrentUploadsLimit() int64 { cu, err := strconv.ParseInt(env.Get(ConsoleMaxConcurrentUploads, "10"), 10, 64) if err != nil { diff --git a/api/config_test.go b/api/config_test.go index 84d2ee6ef2..5c3caacbe4 100644 --- a/api/config_test.go +++ b/api/config_test.go @@ -227,72 +227,6 @@ func Test_getLogSearchAPIToken(t *testing.T) { } } -func Test_getPrometheusURL(t *testing.T) { - type args struct { - env string - } - tests := []struct { - name string - args args - want string - }{ - { - name: "env set", - args: args{ - env: "value", - }, - want: "value", - }, - { - name: "env not set", - args: args{ - env: "", - }, - want: "", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(_ *testing.T) { - os.Setenv(PrometheusURL, tt.args.env) - assert.Equalf(t, tt.want, getPrometheusURL(), "getPrometheusURL()") - os.Setenv(PrometheusURL, tt.args.env) - }) - } -} - -func Test_getPrometheusJobID(t *testing.T) { - type args struct { - env string - } - tests := []struct { - name string - args args - want string - }{ - { - name: "env set", - args: args{ - env: "value", - }, - want: "value", - }, - { - name: "env not set", - args: args{ - env: "", - }, - want: "minio-job", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(_ *testing.T) { - os.Setenv(PrometheusJobID, tt.args.env) - assert.Equalf(t, tt.want, getPrometheusJobID(), "getPrometheusJobID()") - os.Setenv(PrometheusJobID, tt.args.env) - }) - } -} - func Test_getMaxConcurrentUploadsLimit(t *testing.T) { type args struct { env string diff --git a/api/consts.go b/api/consts.go index 1048e375c3..ab477b12f8 100644 --- a/api/consts.go +++ b/api/consts.go @@ -20,7 +20,6 @@ package api const ( // Constants for common configuration ConsoleMinIOServer = "CONSOLE_MINIO_SERVER" - ConsoleSubnetProxy = "CONSOLE_SUBNET_PROXY" ConsoleMinIORegion = "CONSOLE_MINIO_REGION" ConsoleHostname = "CONSOLE_HOSTNAME" ConsolePort = "CONSOLE_PORT" @@ -40,16 +39,9 @@ const ( ConsoleSecureSTSPreload = "CONSOLE_SECURE_STS_PRELOAD" ConsoleSecureTLSRedirect = "CONSOLE_SECURE_TLS_REDIRECT" ConsoleSecureTLSHost = "CONSOLE_SECURE_TLS_HOST" - ConsoleSecureTLSTemporaryRedirect = "CONSOLE_SECURE_TLS_TEMPORARY_REDIRECT" ConsoleSecureForceSTSHeader = "CONSOLE_SECURE_FORCE_STS_HEADER" - ConsoleSecurePublicKey = "CONSOLE_SECURE_PUBLIC_KEY" ConsoleSecureReferrerPolicy = "CONSOLE_SECURE_REFERRER_POLICY" ConsoleSecureFeaturePolicy = "CONSOLE_SECURE_FEATURE_POLICY" - ConsoleSecureExpectCTHeader = "CONSOLE_SECURE_EXPECT_CT_HEADER" - PrometheusURL = "CONSOLE_PROMETHEUS_URL" - PrometheusAuthToken = "CONSOLE_PROMETHEUS_AUTH_TOKEN" - PrometheusJobID = "CONSOLE_PROMETHEUS_JOB_ID" - PrometheusExtraLabels = "CONSOLE_PROMETHEUS_EXTRA_LABELS" ConsoleLogQueryURL = "CONSOLE_LOG_QUERY_URL" ConsoleLogQueryAuthToken = "CONSOLE_LOG_QUERY_AUTH_TOKEN" ConsoleMaxConcurrentUploads = "CONSOLE_MAX_CONCURRENT_UPLOADS" diff --git a/api/embedded_spec.go b/api/embedded_spec.go index e52e55e52b..3d9982db09 100644 --- a/api/embedded_spec.go +++ b/api/embedded_spec.go @@ -709,42 +709,6 @@ func init() { } } }, - "/buckets/{bucket_name}/tags": { - "put": { - "tags": [ - "Bucket" - ], - "summary": "Put Bucket's tags", - "operationId": "PutBucketTags", - "parameters": [ - { - "type": "string", - "name": "bucket_name", - "in": "path", - "required": true - }, - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/putBucketTagsRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response." - }, - "default": { - "description": "Generic error response.", - "schema": { - "$ref": "#/definitions/ApiError" - } - } - } - } - }, "/buckets/{bucket_name}/versioning": { "get": { "tags": [ @@ -980,37 +944,6 @@ func init() { } } }, - "/login/oauth2/auth": { - "post": { - "security": [], - "tags": [ - "Auth" - ], - "summary": "Identity Provider oauth2 callback endpoint.", - "operationId": "LoginOauth2Auth", - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/loginOauth2AuthRequest" - } - } - ], - "responses": { - "204": { - "description": "A successful login." - }, - "default": { - "description": "Generic error response.", - "schema": { - "$ref": "#/definitions/ApiError" - } - } - } - } - }, "/logout": { "post": { "tags": [ @@ -1063,37 +996,6 @@ func init() { } } } - }, - "/users": { - "get": { - "tags": [ - "User" - ], - "summary": "List Users", - "operationId": "ListUsers", - "parameters": [ - { - "$ref": "#/parameters/offset" - }, - { - "$ref": "#/parameters/limit" - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/listUsersResponse" - } - }, - "default": { - "description": "Generic error response.", - "schema": { - "$ref": "#/definitions/ApiError" - } - } - } - } } }, "definitions": { @@ -1434,18 +1336,6 @@ func init() { } } }, - "listUsersResponse": { - "type": "object", - "properties": { - "users": { - "type": "array", - "title": "list of resulting users", - "items": { - "$ref": "#/definitions/user" - } - } - } - }, "loginDetails": { "type": "object", "properties": { @@ -1459,7 +1349,6 @@ func init() { "type": "string", "enum": [ "form", - "redirect", "service-account", "redirect-service-account" ] @@ -1472,21 +1361,6 @@ func init() { } } }, - "loginOauth2AuthRequest": { - "type": "object", - "required": [ - "state", - "code" - ], - "properties": { - "code": { - "type": "string" - }, - "state": { - "type": "string" - } - } - }, "loginRequest": { "type": "object", "properties": { @@ -1625,16 +1499,6 @@ func init() { } } }, - "putBucketTagsRequest": { - "type": "object", - "properties": { - "tags": { - "additionalProperties": { - "type": "string" - } - } - } - }, "putObjectTagsRequest": { "type": "object", "properties": { @@ -1849,32 +1713,6 @@ func init() { } } }, - "user": { - "type": "object", - "properties": { - "accessKey": { - "type": "string" - }, - "hasPolicy": { - "type": "boolean" - }, - "memberOf": { - "type": "array", - "items": { - "type": "string" - } - }, - "policy": { - "type": "array", - "items": { - "type": "string" - } - }, - "status": { - "type": "string" - } - } - }, "widget": { "type": "object", "properties": { @@ -2642,42 +2480,6 @@ func init() { } } }, - "/buckets/{bucket_name}/tags": { - "put": { - "tags": [ - "Bucket" - ], - "summary": "Put Bucket's tags", - "operationId": "PutBucketTags", - "parameters": [ - { - "type": "string", - "name": "bucket_name", - "in": "path", - "required": true - }, - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/putBucketTagsRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response." - }, - "default": { - "description": "Generic error response.", - "schema": { - "$ref": "#/definitions/ApiError" - } - } - } - } - }, "/buckets/{bucket_name}/versioning": { "get": { "tags": [ @@ -2913,37 +2715,6 @@ func init() { } } }, - "/login/oauth2/auth": { - "post": { - "security": [], - "tags": [ - "Auth" - ], - "summary": "Identity Provider oauth2 callback endpoint.", - "operationId": "LoginOauth2Auth", - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/loginOauth2AuthRequest" - } - } - ], - "responses": { - "204": { - "description": "A successful login." - }, - "default": { - "description": "Generic error response.", - "schema": { - "$ref": "#/definitions/ApiError" - } - } - } - } - }, "/logout": { "post": { "tags": [ @@ -2996,45 +2767,6 @@ func init() { } } } - }, - "/users": { - "get": { - "tags": [ - "User" - ], - "summary": "List Users", - "operationId": "ListUsers", - "parameters": [ - { - "type": "number", - "format": "int32", - "default": 0, - "name": "offset", - "in": "query" - }, - { - "type": "number", - "format": "int32", - "default": 20, - "name": "limit", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/listUsersResponse" - } - }, - "default": { - "description": "Generic error response.", - "schema": { - "$ref": "#/definitions/ApiError" - } - } - } - } } }, "definitions": { @@ -3477,18 +3209,6 @@ func init() { } } }, - "listUsersResponse": { - "type": "object", - "properties": { - "users": { - "type": "array", - "title": "list of resulting users", - "items": { - "$ref": "#/definitions/user" - } - } - } - }, "loginDetails": { "type": "object", "properties": { @@ -3502,7 +3222,6 @@ func init() { "type": "string", "enum": [ "form", - "redirect", "service-account", "redirect-service-account" ] @@ -3515,21 +3234,6 @@ func init() { } } }, - "loginOauth2AuthRequest": { - "type": "object", - "required": [ - "state", - "code" - ], - "properties": { - "code": { - "type": "string" - }, - "state": { - "type": "string" - } - } - }, "loginRequest": { "type": "object", "properties": { @@ -3668,16 +3372,6 @@ func init() { } } }, - "putBucketTagsRequest": { - "type": "object", - "properties": { - "tags": { - "additionalProperties": { - "type": "string" - } - } - } - }, "putObjectTagsRequest": { "type": "object", "properties": { @@ -3892,32 +3586,6 @@ func init() { } } }, - "user": { - "type": "object", - "properties": { - "accessKey": { - "type": "string" - }, - "hasPolicy": { - "type": "boolean" - }, - "memberOf": { - "type": "array", - "items": { - "type": "string" - } - }, - "policy": { - "type": "array", - "items": { - "type": "string" - } - }, - "status": { - "type": "string" - } - } - }, "widget": { "type": "object", "properties": { diff --git a/api/operations/auth/login_oauth2_auth.go b/api/operations/auth/login_oauth2_auth.go deleted file mode 100644 index 05248cc7b7..0000000000 --- a/api/operations/auth/login_oauth2_auth.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package auth - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// LoginOauth2AuthHandlerFunc turns a function with the right signature into a login oauth2 auth handler -type LoginOauth2AuthHandlerFunc func(LoginOauth2AuthParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn LoginOauth2AuthHandlerFunc) Handle(params LoginOauth2AuthParams) middleware.Responder { - return fn(params) -} - -// LoginOauth2AuthHandler interface for that can handle valid login oauth2 auth params -type LoginOauth2AuthHandler interface { - Handle(LoginOauth2AuthParams) middleware.Responder -} - -// NewLoginOauth2Auth creates a new http.Handler for the login oauth2 auth operation -func NewLoginOauth2Auth(ctx *middleware.Context, handler LoginOauth2AuthHandler) *LoginOauth2Auth { - return &LoginOauth2Auth{Context: ctx, Handler: handler} -} - -/* - LoginOauth2Auth swagger:route POST /login/oauth2/auth Auth loginOauth2Auth - -Identity Provider oauth2 callback endpoint. -*/ -type LoginOauth2Auth struct { - Context *middleware.Context - Handler LoginOauth2AuthHandler -} - -func (o *LoginOauth2Auth) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewLoginOauth2AuthParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/api/operations/auth/login_oauth2_auth_parameters.go b/api/operations/auth/login_oauth2_auth_parameters.go deleted file mode 100644 index 3b822222b2..0000000000 --- a/api/operations/auth/login_oauth2_auth_parameters.go +++ /dev/null @@ -1,101 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package auth - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/validate" - - "github.com/minio/console/models" -) - -// NewLoginOauth2AuthParams creates a new LoginOauth2AuthParams object -// -// There are no default values defined in the spec. -func NewLoginOauth2AuthParams() LoginOauth2AuthParams { - - return LoginOauth2AuthParams{} -} - -// LoginOauth2AuthParams contains all the bound params for the login oauth2 auth operation -// typically these are obtained from a http.Request -// -// swagger:parameters LoginOauth2Auth -type LoginOauth2AuthParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /* - Required: true - In: body - */ - Body *models.LoginOauth2AuthRequest -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewLoginOauth2AuthParams() beforehand. -func (o *LoginOauth2AuthParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body models.LoginOauth2AuthRequest - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("body", "body", "")) - } else { - res = append(res, errors.NewParseError("body", "body", "", err)) - } - } else { - // validate body object - if err := body.Validate(route.Formats); err != nil { - res = append(res, err) - } - - ctx := validate.WithOperationRequest(r.Context()) - if err := body.ContextValidate(ctx, route.Formats); err != nil { - res = append(res, err) - } - - if len(res) == 0 { - o.Body = &body - } - } - } else { - res = append(res, errors.Required("body", "body", "")) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/api/operations/auth/login_oauth2_auth_responses.go b/api/operations/auth/login_oauth2_auth_responses.go deleted file mode 100644 index 1781e63fca..0000000000 --- a/api/operations/auth/login_oauth2_auth_responses.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package auth - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - - "github.com/minio/console/models" -) - -// LoginOauth2AuthNoContentCode is the HTTP code returned for type LoginOauth2AuthNoContent -const LoginOauth2AuthNoContentCode int = 204 - -/* -LoginOauth2AuthNoContent A successful login. - -swagger:response loginOauth2AuthNoContent -*/ -type LoginOauth2AuthNoContent struct { -} - -// NewLoginOauth2AuthNoContent creates LoginOauth2AuthNoContent with default headers values -func NewLoginOauth2AuthNoContent() *LoginOauth2AuthNoContent { - - return &LoginOauth2AuthNoContent{} -} - -// WriteResponse to the client -func (o *LoginOauth2AuthNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(204) -} - -/* -LoginOauth2AuthDefault Generic error response. - -swagger:response loginOauth2AuthDefault -*/ -type LoginOauth2AuthDefault struct { - _statusCode int - - /* - In: Body - */ - Payload *models.APIError `json:"body,omitempty"` -} - -// NewLoginOauth2AuthDefault creates LoginOauth2AuthDefault with default headers values -func NewLoginOauth2AuthDefault(code int) *LoginOauth2AuthDefault { - if code <= 0 { - code = 500 - } - - return &LoginOauth2AuthDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the login oauth2 auth default response -func (o *LoginOauth2AuthDefault) WithStatusCode(code int) *LoginOauth2AuthDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the login oauth2 auth default response -func (o *LoginOauth2AuthDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WithPayload adds the payload to the login oauth2 auth default response -func (o *LoginOauth2AuthDefault) WithPayload(payload *models.APIError) *LoginOauth2AuthDefault { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the login oauth2 auth default response -func (o *LoginOauth2AuthDefault) SetPayload(payload *models.APIError) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *LoginOauth2AuthDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(o._statusCode) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} diff --git a/api/operations/auth/login_oauth2_auth_urlbuilder.go b/api/operations/auth/login_oauth2_auth_urlbuilder.go deleted file mode 100644 index 9e2ab8a2bd..0000000000 --- a/api/operations/auth/login_oauth2_auth_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package auth - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" -) - -// LoginOauth2AuthURL generates an URL for the login oauth2 auth operation -type LoginOauth2AuthURL struct { - _basePath string -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *LoginOauth2AuthURL) WithBasePath(bp string) *LoginOauth2AuthURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *LoginOauth2AuthURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *LoginOauth2AuthURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/login/oauth2/auth" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *LoginOauth2AuthURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *LoginOauth2AuthURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *LoginOauth2AuthURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on LoginOauth2AuthURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on LoginOauth2AuthURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *LoginOauth2AuthURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/api/operations/bucket/put_bucket_tags.go b/api/operations/bucket/put_bucket_tags.go deleted file mode 100644 index ce6b379ba0..0000000000 --- a/api/operations/bucket/put_bucket_tags.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package bucket - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" - - "github.com/minio/console/models" -) - -// PutBucketTagsHandlerFunc turns a function with the right signature into a put bucket tags handler -type PutBucketTagsHandlerFunc func(PutBucketTagsParams, *models.Principal) middleware.Responder - -// Handle executing the request and returning a response -func (fn PutBucketTagsHandlerFunc) Handle(params PutBucketTagsParams, principal *models.Principal) middleware.Responder { - return fn(params, principal) -} - -// PutBucketTagsHandler interface for that can handle valid put bucket tags params -type PutBucketTagsHandler interface { - Handle(PutBucketTagsParams, *models.Principal) middleware.Responder -} - -// NewPutBucketTags creates a new http.Handler for the put bucket tags operation -func NewPutBucketTags(ctx *middleware.Context, handler PutBucketTagsHandler) *PutBucketTags { - return &PutBucketTags{Context: ctx, Handler: handler} -} - -/* - PutBucketTags swagger:route PUT /buckets/{bucket_name}/tags Bucket putBucketTags - -Put Bucket's tags -*/ -type PutBucketTags struct { - Context *middleware.Context - Handler PutBucketTagsHandler -} - -func (o *PutBucketTags) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPutBucketTagsParams() - uprinc, aCtx, err := o.Context.Authorize(r, route) - if err != nil { - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - if aCtx != nil { - *r = *aCtx - } - var principal *models.Principal - if uprinc != nil { - principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise - } - - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params, principal) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/api/operations/bucket/put_bucket_tags_parameters.go b/api/operations/bucket/put_bucket_tags_parameters.go deleted file mode 100644 index 2a90b78f02..0000000000 --- a/api/operations/bucket/put_bucket_tags_parameters.go +++ /dev/null @@ -1,126 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package bucket - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" - - "github.com/minio/console/models" -) - -// NewPutBucketTagsParams creates a new PutBucketTagsParams object -// -// There are no default values defined in the spec. -func NewPutBucketTagsParams() PutBucketTagsParams { - - return PutBucketTagsParams{} -} - -// PutBucketTagsParams contains all the bound params for the put bucket tags operation -// typically these are obtained from a http.Request -// -// swagger:parameters PutBucketTags -type PutBucketTagsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /* - Required: true - In: body - */ - Body *models.PutBucketTagsRequest - /* - Required: true - In: path - */ - BucketName string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPutBucketTagsParams() beforehand. -func (o *PutBucketTagsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body models.PutBucketTagsRequest - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("body", "body", "")) - } else { - res = append(res, errors.NewParseError("body", "body", "", err)) - } - } else { - // validate body object - if err := body.Validate(route.Formats); err != nil { - res = append(res, err) - } - - ctx := validate.WithOperationRequest(r.Context()) - if err := body.ContextValidate(ctx, route.Formats); err != nil { - res = append(res, err) - } - - if len(res) == 0 { - o.Body = &body - } - } - } else { - res = append(res, errors.Required("body", "body", "")) - } - - rBucketName, rhkBucketName, _ := route.Params.GetOK("bucket_name") - if err := o.bindBucketName(rBucketName, rhkBucketName, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindBucketName binds and validates parameter BucketName from path. -func (o *PutBucketTagsParams) bindBucketName(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.BucketName = raw - - return nil -} diff --git a/api/operations/bucket/put_bucket_tags_responses.go b/api/operations/bucket/put_bucket_tags_responses.go deleted file mode 100644 index 3cc7fee0b2..0000000000 --- a/api/operations/bucket/put_bucket_tags_responses.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package bucket - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - - "github.com/minio/console/models" -) - -// PutBucketTagsOKCode is the HTTP code returned for type PutBucketTagsOK -const PutBucketTagsOKCode int = 200 - -/* -PutBucketTagsOK A successful response. - -swagger:response putBucketTagsOK -*/ -type PutBucketTagsOK struct { -} - -// NewPutBucketTagsOK creates PutBucketTagsOK with default headers values -func NewPutBucketTagsOK() *PutBucketTagsOK { - - return &PutBucketTagsOK{} -} - -// WriteResponse to the client -func (o *PutBucketTagsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(200) -} - -/* -PutBucketTagsDefault Generic error response. - -swagger:response putBucketTagsDefault -*/ -type PutBucketTagsDefault struct { - _statusCode int - - /* - In: Body - */ - Payload *models.APIError `json:"body,omitempty"` -} - -// NewPutBucketTagsDefault creates PutBucketTagsDefault with default headers values -func NewPutBucketTagsDefault(code int) *PutBucketTagsDefault { - if code <= 0 { - code = 500 - } - - return &PutBucketTagsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the put bucket tags default response -func (o *PutBucketTagsDefault) WithStatusCode(code int) *PutBucketTagsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the put bucket tags default response -func (o *PutBucketTagsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WithPayload adds the payload to the put bucket tags default response -func (o *PutBucketTagsDefault) WithPayload(payload *models.APIError) *PutBucketTagsDefault { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put bucket tags default response -func (o *PutBucketTagsDefault) SetPayload(payload *models.APIError) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutBucketTagsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(o._statusCode) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} diff --git a/api/operations/bucket/put_bucket_tags_urlbuilder.go b/api/operations/bucket/put_bucket_tags_urlbuilder.go deleted file mode 100644 index c33fe5fc6f..0000000000 --- a/api/operations/bucket/put_bucket_tags_urlbuilder.go +++ /dev/null @@ -1,116 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package bucket - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// PutBucketTagsURL generates an URL for the put bucket tags operation -type PutBucketTagsURL struct { - BucketName string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutBucketTagsURL) WithBasePath(bp string) *PutBucketTagsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutBucketTagsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PutBucketTagsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/buckets/{bucket_name}/tags" - - bucketName := o.BucketName - if bucketName != "" { - _path = strings.Replace(_path, "{bucket_name}", bucketName, -1) - } else { - return nil, errors.New("bucketName is required on PutBucketTagsURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PutBucketTagsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PutBucketTagsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PutBucketTagsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PutBucketTagsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PutBucketTagsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PutBucketTagsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/api/operations/console_api.go b/api/operations/console_api.go index 9ec9db1585..12669443d5 100644 --- a/api/operations/console_api.go +++ b/api/operations/console_api.go @@ -42,7 +42,6 @@ import ( "github.com/minio/console/api/operations/object" "github.com/minio/console/api/operations/public" "github.com/minio/console/api/operations/system" - "github.com/minio/console/api/operations/user" "github.com/minio/console/models" ) @@ -115,18 +114,12 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI { ObjectListObjectsHandler: object.ListObjectsHandlerFunc(func(params object.ListObjectsParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation object.ListObjects has not yet been implemented") }), - UserListUsersHandler: user.ListUsersHandlerFunc(func(params user.ListUsersParams, principal *models.Principal) middleware.Responder { - return middleware.NotImplemented("operation user.ListUsers has not yet been implemented") - }), AuthLoginHandler: auth.LoginHandlerFunc(func(params auth.LoginParams) middleware.Responder { return middleware.NotImplemented("operation auth.Login has not yet been implemented") }), AuthLoginDetailHandler: auth.LoginDetailHandlerFunc(func(params auth.LoginDetailParams) middleware.Responder { return middleware.NotImplemented("operation auth.LoginDetail has not yet been implemented") }), - AuthLoginOauth2AuthHandler: auth.LoginOauth2AuthHandlerFunc(func(params auth.LoginOauth2AuthParams) middleware.Responder { - return middleware.NotImplemented("operation auth.LoginOauth2Auth has not yet been implemented") - }), AuthLogoutHandler: auth.LogoutHandlerFunc(func(params auth.LogoutParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation auth.Logout has not yet been implemented") }), @@ -136,9 +129,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI { ObjectPostBucketsBucketNameObjectsUploadHandler: object.PostBucketsBucketNameObjectsUploadHandlerFunc(func(params object.PostBucketsBucketNameObjectsUploadParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation object.PostBucketsBucketNameObjectsUpload has not yet been implemented") }), - BucketPutBucketTagsHandler: bucket.PutBucketTagsHandlerFunc(func(params bucket.PutBucketTagsParams, principal *models.Principal) middleware.Responder { - return middleware.NotImplemented("operation bucket.PutBucketTags has not yet been implemented") - }), ObjectPutObjectRestoreHandler: object.PutObjectRestoreHandlerFunc(func(params object.PutObjectRestoreParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation object.PutObjectRestore has not yet been implemented") }), @@ -247,22 +237,16 @@ type ConsoleAPI struct { BucketListBucketsHandler bucket.ListBucketsHandler // ObjectListObjectsHandler sets the operation handler for the list objects operation ObjectListObjectsHandler object.ListObjectsHandler - // UserListUsersHandler sets the operation handler for the list users operation - UserListUsersHandler user.ListUsersHandler // AuthLoginHandler sets the operation handler for the login operation AuthLoginHandler auth.LoginHandler // AuthLoginDetailHandler sets the operation handler for the login detail operation AuthLoginDetailHandler auth.LoginDetailHandler - // AuthLoginOauth2AuthHandler sets the operation handler for the login oauth2 auth operation - AuthLoginOauth2AuthHandler auth.LoginOauth2AuthHandler // AuthLogoutHandler sets the operation handler for the logout operation AuthLogoutHandler auth.LogoutHandler // BucketMakeBucketHandler sets the operation handler for the make bucket operation BucketMakeBucketHandler bucket.MakeBucketHandler // ObjectPostBucketsBucketNameObjectsUploadHandler sets the operation handler for the post buckets bucket name objects upload operation ObjectPostBucketsBucketNameObjectsUploadHandler object.PostBucketsBucketNameObjectsUploadHandler - // BucketPutBucketTagsHandler sets the operation handler for the put bucket tags operation - BucketPutBucketTagsHandler bucket.PutBucketTagsHandler // ObjectPutObjectRestoreHandler sets the operation handler for the put object restore operation ObjectPutObjectRestoreHandler object.PutObjectRestoreHandler // ObjectPutObjectTagsHandler sets the operation handler for the put object tags operation @@ -408,18 +392,12 @@ func (o *ConsoleAPI) Validate() error { if o.ObjectListObjectsHandler == nil { unregistered = append(unregistered, "object.ListObjectsHandler") } - if o.UserListUsersHandler == nil { - unregistered = append(unregistered, "user.ListUsersHandler") - } if o.AuthLoginHandler == nil { unregistered = append(unregistered, "auth.LoginHandler") } if o.AuthLoginDetailHandler == nil { unregistered = append(unregistered, "auth.LoginDetailHandler") } - if o.AuthLoginOauth2AuthHandler == nil { - unregistered = append(unregistered, "auth.LoginOauth2AuthHandler") - } if o.AuthLogoutHandler == nil { unregistered = append(unregistered, "auth.LogoutHandler") } @@ -429,9 +407,6 @@ func (o *ConsoleAPI) Validate() error { if o.ObjectPostBucketsBucketNameObjectsUploadHandler == nil { unregistered = append(unregistered, "object.PostBucketsBucketNameObjectsUploadHandler") } - if o.BucketPutBucketTagsHandler == nil { - unregistered = append(unregistered, "bucket.PutBucketTagsHandler") - } if o.ObjectPutObjectRestoreHandler == nil { unregistered = append(unregistered, "object.PutObjectRestoreHandler") } @@ -615,10 +590,6 @@ func (o *ConsoleAPI) initHandlerCache() { o.handlers["GET"] = make(map[string]http.Handler) } o.handlers["GET"]["/buckets/{bucket_name}/objects"] = object.NewListObjects(o.context, o.ObjectListObjectsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/users"] = user.NewListUsers(o.context, o.UserListUsersHandler) if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) } @@ -630,10 +601,6 @@ func (o *ConsoleAPI) initHandlerCache() { if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) } - o.handlers["POST"]["/login/oauth2/auth"] = auth.NewLoginOauth2Auth(o.context, o.AuthLoginOauth2AuthHandler) - if o.handlers["POST"] == nil { - o.handlers["POST"] = make(map[string]http.Handler) - } o.handlers["POST"]["/logout"] = auth.NewLogout(o.context, o.AuthLogoutHandler) if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) @@ -646,10 +613,6 @@ func (o *ConsoleAPI) initHandlerCache() { if o.handlers["PUT"] == nil { o.handlers["PUT"] = make(map[string]http.Handler) } - o.handlers["PUT"]["/buckets/{bucket_name}/tags"] = bucket.NewPutBucketTags(o.context, o.BucketPutBucketTagsHandler) - if o.handlers["PUT"] == nil { - o.handlers["PUT"] = make(map[string]http.Handler) - } o.handlers["PUT"]["/buckets/{bucket_name}/objects/restore"] = object.NewPutObjectRestore(o.context, o.ObjectPutObjectRestoreHandler) if o.handlers["PUT"] == nil { o.handlers["PUT"] = make(map[string]http.Handler) diff --git a/api/operations/user/list_users.go b/api/operations/user/list_users.go deleted file mode 100644 index 3277010b47..0000000000 --- a/api/operations/user/list_users.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package user - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" - - "github.com/minio/console/models" -) - -// ListUsersHandlerFunc turns a function with the right signature into a list users handler -type ListUsersHandlerFunc func(ListUsersParams, *models.Principal) middleware.Responder - -// Handle executing the request and returning a response -func (fn ListUsersHandlerFunc) Handle(params ListUsersParams, principal *models.Principal) middleware.Responder { - return fn(params, principal) -} - -// ListUsersHandler interface for that can handle valid list users params -type ListUsersHandler interface { - Handle(ListUsersParams, *models.Principal) middleware.Responder -} - -// NewListUsers creates a new http.Handler for the list users operation -func NewListUsers(ctx *middleware.Context, handler ListUsersHandler) *ListUsers { - return &ListUsers{Context: ctx, Handler: handler} -} - -/* - ListUsers swagger:route GET /users User listUsers - -List Users -*/ -type ListUsers struct { - Context *middleware.Context - Handler ListUsersHandler -} - -func (o *ListUsers) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewListUsersParams() - uprinc, aCtx, err := o.Context.Authorize(r, route) - if err != nil { - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - if aCtx != nil { - *r = *aCtx - } - var principal *models.Principal - if uprinc != nil { - principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise - } - - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params, principal) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/api/operations/user/list_users_parameters.go b/api/operations/user/list_users_parameters.go deleted file mode 100644 index 2da360d4e2..0000000000 --- a/api/operations/user/list_users_parameters.go +++ /dev/null @@ -1,146 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package user - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// NewListUsersParams creates a new ListUsersParams object -// with the default values initialized. -func NewListUsersParams() ListUsersParams { - - var ( - // initialize parameters with default values - - limitDefault = int32(20) - offsetDefault = int32(0) - ) - - return ListUsersParams{ - Limit: &limitDefault, - - Offset: &offsetDefault, - } -} - -// ListUsersParams contains all the bound params for the list users operation -// typically these are obtained from a http.Request -// -// swagger:parameters ListUsers -type ListUsersParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /* - In: query - Default: 20 - */ - Limit *int32 - /* - In: query - Default: 0 - */ - Offset *int32 -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewListUsersParams() beforehand. -func (o *ListUsersParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qLimit, qhkLimit, _ := qs.GetOK("limit") - if err := o.bindLimit(qLimit, qhkLimit, route.Formats); err != nil { - res = append(res, err) - } - - qOffset, qhkOffset, _ := qs.GetOK("offset") - if err := o.bindOffset(qOffset, qhkOffset, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindLimit binds and validates parameter Limit from query. -func (o *ListUsersParams) bindLimit(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewListUsersParams() - return nil - } - - value, err := swag.ConvertInt32(raw) - if err != nil { - return errors.InvalidType("limit", "query", "int32", raw) - } - o.Limit = &value - - return nil -} - -// bindOffset binds and validates parameter Offset from query. -func (o *ListUsersParams) bindOffset(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewListUsersParams() - return nil - } - - value, err := swag.ConvertInt32(raw) - if err != nil { - return errors.InvalidType("offset", "query", "int32", raw) - } - o.Offset = &value - - return nil -} diff --git a/api/operations/user/list_users_responses.go b/api/operations/user/list_users_responses.go deleted file mode 100644 index 2950b66d18..0000000000 --- a/api/operations/user/list_users_responses.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package user - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - - "github.com/minio/console/models" -) - -// ListUsersOKCode is the HTTP code returned for type ListUsersOK -const ListUsersOKCode int = 200 - -/* -ListUsersOK A successful response. - -swagger:response listUsersOK -*/ -type ListUsersOK struct { - - /* - In: Body - */ - Payload *models.ListUsersResponse `json:"body,omitempty"` -} - -// NewListUsersOK creates ListUsersOK with default headers values -func NewListUsersOK() *ListUsersOK { - - return &ListUsersOK{} -} - -// WithPayload adds the payload to the list users o k response -func (o *ListUsersOK) WithPayload(payload *models.ListUsersResponse) *ListUsersOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the list users o k response -func (o *ListUsersOK) SetPayload(payload *models.ListUsersResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *ListUsersOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -ListUsersDefault Generic error response. - -swagger:response listUsersDefault -*/ -type ListUsersDefault struct { - _statusCode int - - /* - In: Body - */ - Payload *models.APIError `json:"body,omitempty"` -} - -// NewListUsersDefault creates ListUsersDefault with default headers values -func NewListUsersDefault(code int) *ListUsersDefault { - if code <= 0 { - code = 500 - } - - return &ListUsersDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the list users default response -func (o *ListUsersDefault) WithStatusCode(code int) *ListUsersDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the list users default response -func (o *ListUsersDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WithPayload adds the payload to the list users default response -func (o *ListUsersDefault) WithPayload(payload *models.APIError) *ListUsersDefault { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the list users default response -func (o *ListUsersDefault) SetPayload(payload *models.APIError) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *ListUsersDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(o._statusCode) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} diff --git a/api/operations/user/list_users_urlbuilder.go b/api/operations/user/list_users_urlbuilder.go deleted file mode 100644 index 3fae90c9d7..0000000000 --- a/api/operations/user/list_users_urlbuilder.go +++ /dev/null @@ -1,131 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package user - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - - "github.com/go-openapi/swag" -) - -// ListUsersURL generates an URL for the list users operation -type ListUsersURL struct { - Limit *int32 - Offset *int32 - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *ListUsersURL) WithBasePath(bp string) *ListUsersURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *ListUsersURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *ListUsersURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/users" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var limitQ string - if o.Limit != nil { - limitQ = swag.FormatInt32(*o.Limit) - } - if limitQ != "" { - qs.Set("limit", limitQ) - } - - var offsetQ string - if o.Offset != nil { - offsetQ = swag.FormatInt32(*o.Offset) - } - if offsetQ != "" { - qs.Set("offset", offsetQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *ListUsersURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *ListUsersURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *ListUsersURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on ListUsersURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on ListUsersURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *ListUsersURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/api/user_buckets.go b/api/user_buckets.go index a44308a519..54f4e0af98 100644 --- a/api/user_buckets.go +++ b/api/user_buckets.go @@ -27,18 +27,16 @@ import ( "github.com/minio/minio-go/v7" - "github.com/minio/madmin-go/v3" - "github.com/minio/mc/cmd" - "github.com/minio/mc/pkg/probe" - "github.com/minio/minio-go/v7/pkg/credentials" - "github.com/minio/minio-go/v7/pkg/tags" - "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/swag" "github.com/minio/console/api/operations" bucketApi "github.com/minio/console/api/operations/bucket" "github.com/minio/console/models" "github.com/minio/console/pkg/auth/token" + "github.com/minio/madmin-go/v3" + "github.com/minio/mc/cmd" + "github.com/minio/mc/pkg/probe" + "github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/minio-go/v7/pkg/policy" minioIAMPolicy "github.com/minio/pkg/v3/policy" ) @@ -69,14 +67,6 @@ func registerBucketsHandlers(api *operations.ConsoleAPI) { return bucketApi.NewBucketInfoOK().WithPayload(bucketInfoResp) }) - // set bucket tags - api.BucketPutBucketTagsHandler = bucketApi.PutBucketTagsHandlerFunc(func(params bucketApi.PutBucketTagsParams, session *models.Principal) middleware.Responder { - err := getPutBucketTagsResponse(session, params) - if err != nil { - return bucketApi.NewPutBucketTagsDefault(err.Code).WithPayload(err.APIError) - } - return bucketApi.NewPutBucketTagsOK() - }) // get bucket versioning api.BucketGetBucketVersioningHandler = bucketApi.GetBucketVersioningHandlerFunc(func(params bucketApi.GetBucketVersioningParams, session *models.Principal) middleware.Responder { getBucketVersioning, err := getBucketVersionedResponse(session, params) @@ -337,34 +327,6 @@ func setBucketAccessPolicy(ctx context.Context, client MinioClient, bucketName s return client.setBucketPolicyWithContext(ctx, bucketName, string(policyJSON)) } -// putBucketTags sets tags for a bucket -func getPutBucketTagsResponse(session *models.Principal, params bucketApi.PutBucketTagsParams) *CodedAPIError { - ctx, cancel := context.WithCancel(params.HTTPRequest.Context()) - defer cancel() - - mClient, err := newMinioClient(session, getClientIP(params.HTTPRequest)) - if err != nil { - return ErrorWithContext(ctx, err) - } - // create a minioClient interface implementation - // defining the client to be used - minioClient := minioClient{client: mClient} - - req := params.Body - bucketName := params.BucketName - - newTagSet, err := tags.NewTags(req.Tags, true) - if err != nil { - return ErrorWithContext(ctx, err) - } - - err = minioClient.SetBucketTagging(ctx, bucketName, newTagSet) - if err != nil { - return ErrorWithContext(ctx, err) - } - return nil -} - // removeBucket deletes a bucket func removeBucket(client MinioClient, bucketName string) error { return client.removeBucket(context.Background(), bucketName) diff --git a/api/user_login.go b/api/user_login.go index 8ec646d1eb..18813d9e42 100644 --- a/api/user_login.go +++ b/api/user_login.go @@ -18,9 +18,6 @@ package api import ( "context" - "encoding/base64" - "encoding/json" - "fmt" "net/http" "strings" @@ -30,7 +27,6 @@ import ( authApi "github.com/minio/console/api/operations/auth" "github.com/minio/console/models" "github.com/minio/console/pkg/auth" - "github.com/minio/console/pkg/auth/idp/oauth2" "github.com/minio/madmin-go/v3" "github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/pkg/v3/env" @@ -39,8 +35,8 @@ import ( func registerLoginHandlers(api *operations.ConsoleAPI) { // GET login strategy - api.AuthLoginDetailHandler = authApi.LoginDetailHandlerFunc(func(params authApi.LoginDetailParams) middleware.Responder { - loginDetails, err := getLoginDetailsResponse(params, GlobalMinIOConfig.OpenIDProviders) + api.AuthLoginDetailHandler = authApi.LoginDetailHandlerFunc(func(_ authApi.LoginDetailParams) middleware.Responder { + loginDetails, err := getLoginDetailsResponse() if err != nil { return authApi.NewLoginDetailDefault(err.Code).WithPayload(err.APIError) } @@ -59,27 +55,6 @@ func registerLoginHandlers(api *operations.ConsoleAPI) { authApi.NewLoginNoContent().WriteResponse(w, p) }) }) - // POST login using external IDP - api.AuthLoginOauth2AuthHandler = authApi.LoginOauth2AuthHandlerFunc(func(params authApi.LoginOauth2AuthParams) middleware.Responder { - loginResponse, err := getLoginOauth2AuthResponse(params, GlobalMinIOConfig.OpenIDProviders) - if err != nil { - return authApi.NewLoginOauth2AuthDefault(err.Code).WithPayload(err.APIError) - } - // Custom response writer to set the session cookies - return middleware.ResponderFunc(func(w http.ResponseWriter, p runtime.Producer) { - cookie := NewSessionCookieForConsole(loginResponse.SessionID) - http.SetCookie(w, &cookie) - http.SetCookie(w, &http.Cookie{ - Path: "/", - Name: "idp-refresh-token", - Value: loginResponse.IDPRefreshToken, - HttpOnly: true, - Secure: len(GlobalPublicCerts) > 0, - SameSite: http.SameSiteLaxMode, - }) - authApi.NewLoginOauth2AuthNoContent().WriteResponse(w, p) - }) - }) } // login performs a check of ConsoleCredentials against MinIO, generates some claims and returns the jwt @@ -184,61 +159,11 @@ func isKubernetes() bool { } // getLoginDetailsResponse returns information regarding the Console authentication mechanism. -func getLoginDetailsResponse(params authApi.LoginDetailParams, openIDProviders oauth2.OpenIDPCfg) (ld *models.LoginDetails, apiErr *CodedAPIError) { +func getLoginDetailsResponse() (ld *models.LoginDetails, apiErr *CodedAPIError) { loginStrategy := models.LoginDetailsLoginStrategyForm var redirectRules []*models.RedirectRule - r := params.HTTPRequest - - var loginDetails *models.LoginDetails - if len(openIDProviders) > 0 { - loginStrategy = models.LoginDetailsLoginStrategyRedirect - } - - for name, provider := range openIDProviders { - // initialize new oauth2 client - - oauth2Client, err := provider.GetOauth2Provider(name, nil, r, GetConsoleHTTPClient(getClientIP(params.HTTPRequest))) - if err != nil { - continue - } - - // Validate user against IDP - identityProvider := &auth.IdentityProvider{ - KeyFunc: provider.GetStateKeyFunc(), - Client: oauth2Client, - } - - displayName := fmt.Sprintf("Login with SSO (%s)", name) - serviceType := "" - - if provider.DisplayName != "" { - displayName = provider.DisplayName - } - - if provider.RoleArn != "" { - splitRoleArn := strings.Split(provider.RoleArn, ":") - - if len(splitRoleArn) > 2 { - serviceType = splitRoleArn[2] - } - } - - redirectRule := models.RedirectRule{ - Redirect: identityProvider.GenerateLoginURL(), - DisplayName: displayName, - ServiceType: serviceType, - } - - redirectRules = append(redirectRules, &redirectRule) - } - - if len(openIDProviders) > 0 && len(redirectRules) == 0 { - loginStrategy = models.LoginDetailsLoginStrategyForm - // No IDP configured fallback to username/password - } - - loginDetails = &models.LoginDetails{ + loginDetails := &models.LoginDetails{ LoginStrategy: loginStrategy, RedirectRules: redirectRules, IsK8S: isKubernetes(), @@ -247,78 +172,3 @@ func getLoginDetailsResponse(params authApi.LoginDetailParams, openIDProviders o return loginDetails, nil } - -// verifyUserAgainstIDP will verify user identity against the configured IDP and return MinIO credentials -func verifyUserAgainstIDP(ctx context.Context, provider auth.IdentityProviderI, code, state string) (*credentials.Credentials, error) { - userCredentials, err := provider.VerifyIdentity(ctx, code, state) - if err != nil { - LogError("error validating user identity against idp: %v", err) - return nil, err - } - return userCredentials, nil -} - -func getLoginOauth2AuthResponse(params authApi.LoginOauth2AuthParams, openIDProviders oauth2.OpenIDPCfg) (*models.LoginResponse, *CodedAPIError) { - ctx, cancel := context.WithCancel(params.HTTPRequest.Context()) - defer cancel() - r := params.HTTPRequest - lr := params.Body - - client := GetConsoleHTTPClient(getClientIP(params.HTTPRequest)) - if len(openIDProviders) > 0 { - // we read state - rState := *lr.State - - decodedRState, err := base64.StdEncoding.DecodeString(rState) - if err != nil { - return nil, ErrorWithContext(ctx, err) - } - - var requestItems oauth2.LoginURLParams - if err = json.Unmarshal(decodedRState, &requestItems); err != nil { - return nil, ErrorWithContext(ctx, err) - } - - IDPName := requestItems.IDPName - state := requestItems.State - - providerCfg, ok := openIDProviders[IDPName] - if !ok { - return nil, ErrorWithContext(ctx, fmt.Errorf("selected IDP %s does not exist", IDPName)) - } - - // Initialize new identity provider with new oauth2Client per IDPName - oauth2Client, err := providerCfg.GetOauth2Provider(IDPName, nil, r, client) - if err != nil { - return nil, ErrorWithContext(ctx, err) - } - - identityProvider := auth.IdentityProvider{ - KeyFunc: providerCfg.GetStateKeyFunc(), - Client: oauth2Client, - RoleARN: providerCfg.RoleArn, - } - // Validate user against IDP - userCredentials, err := verifyUserAgainstIDP(ctx, identityProvider, *lr.Code, state) - if err != nil { - return nil, ErrorWithContext(ctx, err) - } - // initialize admin client - // login user against console and generate session token - token, err := login(&ConsoleCredentials{ - ConsoleCredentials: userCredentials, - AccountAccessKey: "", - CredContext: &credentials.CredContext{Client: client}, - }, nil) - if err != nil { - return nil, ErrorWithContext(ctx, err) - } - // serialize output - loginResponse := &models.LoginResponse{ - SessionID: *token, - IDPRefreshToken: identityProvider.Client.RefreshToken, - } - return loginResponse, nil - } - return nil, ErrorWithContext(ctx, ErrDefault) -} diff --git a/api/user_login_test.go b/api/user_login_test.go index bfdc041b41..80bdcd4c40 100644 --- a/api/user_login_test.go +++ b/api/user_login_test.go @@ -22,14 +22,10 @@ import ( "reflect" "testing" - xoauth2 "golang.org/x/oauth2" - "github.com/minio/madmin-go/v3" iampolicy "github.com/minio/pkg/v3/policy" - "github.com/minio/console/pkg/auth" - "github.com/minio/minio-go/v7/pkg/credentials" "github.com/stretchr/testify/assert" ) @@ -77,77 +73,6 @@ func TestLogin(t *testing.T) { funcAssert.NotNil(err, "not error returned creating a session") } -type IdentityProviderMock struct{} - -var ( - idpVerifyIdentityMock func(ctx context.Context, code, state string) (*credentials.Credentials, error) - idpVerifyIdentityForOperatorMock func(ctx context.Context, code, state string) (*xoauth2.Token, error) - idpGenerateLoginURLMock func() string -) - -func (ac IdentityProviderMock) VerifyIdentity(ctx context.Context, code, state string) (*credentials.Credentials, error) { - return idpVerifyIdentityMock(ctx, code, state) -} - -func (ac IdentityProviderMock) VerifyIdentityForOperator(ctx context.Context, code, state string) (*xoauth2.Token, error) { - return idpVerifyIdentityForOperatorMock(ctx, code, state) -} - -func (ac IdentityProviderMock) GenerateLoginURL() string { - return idpGenerateLoginURLMock() -} - -func Test_validateUserAgainstIDP(t *testing.T) { - provider := IdentityProviderMock{} - mockCode := "EAEAEAE" - mockState := "HUEHUEHUE" - type args struct { - ctx context.Context - provider auth.IdentityProviderI - code string - state string - } - tests := []struct { - name string - args args - want *credentials.Credentials - wantErr bool - mockFunc func() - }{ - { - name: "failed to verify user identity with idp", - args: args{ - ctx: context.Background(), - provider: provider, - code: mockCode, - state: mockState, - }, - want: nil, - wantErr: true, - mockFunc: func() { - idpVerifyIdentityMock = func(_ context.Context, _, _ string) (*credentials.Credentials, error) { - return nil, errors.New("something went wrong") - } - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(_ *testing.T) { - if tt.mockFunc != nil { - tt.mockFunc() - } - got, err := verifyUserAgainstIDP(tt.args.ctx, tt.args.provider, tt.args.code, tt.args.state) - if (err != nil) != tt.wantErr { - t.Errorf("verifyUserAgainstIDP() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("verifyUserAgainstIDP() got = %v, want %v", got, tt.want) - } - }) - } -} - func Test_getAccountInfo(t *testing.T) { type args struct { ctx context.Context diff --git a/api/user_session.go b/api/user_session.go index 4c98bd14f0..a562f6217c 100644 --- a/api/user_session.go +++ b/api/user_session.go @@ -35,8 +35,6 @@ import ( "github.com/minio/console/api/operations" authApi "github.com/minio/console/api/operations/auth" "github.com/minio/console/models" - "github.com/minio/console/pkg/auth/idp/oauth2" - "github.com/minio/console/pkg/auth/ldap" ) type Conditions struct { @@ -240,7 +238,7 @@ func getSessionResponse(ctx context.Context, session *models.Principal) (*models envConstants.MaxConcurrentDownloads = getMaxConcurrentDownloadsLimit() sessionResp := &models.SessionResponse{ - Features: getListOfEnabledFeatures(ctx, userAdminClient, session), + Features: getListOfEnabledFeatures(session), Status: models.SessionResponseStatusOk, Operator: false, DistributedMode: erasure, @@ -254,21 +252,8 @@ func getSessionResponse(ctx context.Context, session *models.Principal) (*models } // getListOfEnabledFeatures returns a list of features -func getListOfEnabledFeatures(ctx context.Context, minioClient MinioAdmin, session *models.Principal) []string { +func getListOfEnabledFeatures(session *models.Principal) []string { features := []string{} - logSearchURL := getLogSearchURL() - oidcEnabled := oauth2.IsIDPEnabled() - ldapEnabled := ldap.GetLDAPEnabled() - - if logSearchURL != "" { - features = append(features, "log-search") - } - if oidcEnabled { - features = append(features, "oidc-idp", "external-idp") - } - if ldapEnabled { - features = append(features, "ldap-idp", "external-idp") - } if session.Hm { features = append(features, "hide-menu") @@ -276,12 +261,6 @@ func getListOfEnabledFeatures(ctx context.Context, minioClient MinioAdmin, sessi if session.Ob { features = append(features, "object-browser-only") } - if minioClient != nil { - _, err := minioClient.kmsStatus(ctx) - if err == nil { - features = append(features, "kms") - } - } return features } diff --git a/api/user_session_test.go b/api/user_session_test.go index 5874d4b30b..00c4d57695 100644 --- a/api/user_session_test.go +++ b/api/user_session_test.go @@ -25,8 +25,6 @@ import ( "github.com/minio/console/pkg/utils" "github.com/minio/console/models" - "github.com/minio/console/pkg/auth/idp/oauth2" - "github.com/minio/console/pkg/auth/ldap" "github.com/stretchr/testify/assert" ) @@ -115,15 +113,9 @@ func Test_getListOfEnabledFeatures(t *testing.T) { want: []string{"log-search", "oidc-idp", "external-idp", "ldap-idp", "external-idp", "hide-menu"}, preFunc: func() { os.Setenv(ConsoleLogQueryURL, "http://logsearchapi:8080") - os.Setenv(oauth2.ConsoleIDPURL, "http://external-idp.com") - os.Setenv(oauth2.ConsoleIDPClientID, "eaeaeaeaeaea") - os.Setenv(ldap.ConsoleLDAPEnabled, "on") }, postFunc: func() { os.Unsetenv(ConsoleLogQueryURL) - os.Unsetenv(oauth2.ConsoleIDPURL) - os.Unsetenv(oauth2.ConsoleIDPClientID) - os.Unsetenv(ldap.ConsoleLDAPEnabled) }, }, } @@ -132,7 +124,7 @@ func Test_getListOfEnabledFeatures(t *testing.T) { if tt.preFunc != nil { tt.preFunc() } - assert.Equalf(t, tt.want, getListOfEnabledFeatures(context.Background(), nil, tt.args.session), "getListOfEnabledFeatures(%v)", tt.args.session) + assert.Equalf(t, tt.want, getListOfEnabledFeatures(tt.args.session), "getListOfEnabledFeatures(%v)", tt.args.session) if tt.postFunc != nil { tt.postFunc() } diff --git a/integration/user_api_bucket_test.go b/integration/user_api_bucket_test.go index db17038eda..a1de0f9a89 100644 --- a/integration/user_api_bucket_test.go +++ b/integration/user_api_bucket_test.go @@ -47,17 +47,6 @@ type AddBucketOps struct { UseToken *string } -func AddBucket(name string, locking bool, versioning, quota, retention map[string]interface{}) (*http.Response, error) { - return AddBucketWithOpts(&AddBucketOps{ - Name: name, - Locking: locking, - Versioning: versioning, - Quota: quota, - Retention: retention, - Endpoint: nil, - }) -} - func AddBucketWithOpts(opts *AddBucketOps) (*http.Response, error) { /* This is an atomic function that we can re-use to create a bucket on any @@ -155,25 +144,6 @@ func ListBuckets() (*http.Response, error) { return response, err } -func DeleteBucket(name string) (*http.Response, error) { - /* - Helper function to delete bucket. - DELETE: {{baseUrl}}/buckets/:name - */ - request, err := http.NewRequest( - "DELETE", "http://localhost:9090/api/v1/buckets/"+name, nil) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - func BucketInfo(name string) (*http.Response, error) { /* Helper function to test Bucket Info End Point @@ -194,57 +164,6 @@ func BucketInfo(name string) (*http.Response, error) { return response, err } -func SetBucketRetention(bucketName, mode, unit string, validity int) (*http.Response, error) { - /* - Helper function to set bucket's retention - PUT: {{baseUrl}}/buckets/:bucket_name/retention - { - "mode":"compliance", - "unit":"years", - "validity":2 - } - */ - requestDataAdd := map[string]interface{}{ - "mode": mode, - "unit": unit, - "validity": validity, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest("PUT", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/retention", - requestDataBody) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func GetBucketRetention(bucketName string) (*http.Response, error) { - /* - Helper function to get the bucket's retention - */ - request, err := http.NewRequest("GET", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/retention", - nil) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - func PutObjectTags(bucketName, prefix string, tags map[string]string, versionID string) (*http.Response, error) { /* Helper function to put object's tags. @@ -437,33 +356,6 @@ func SharesAnObjectOnAUrl(bucketName, prefix, versionID, expires string) (*http. return response, err } -func PutObjectsRetentionStatus(bucketName, prefix, versionID, mode, expires string, governanceBypass bool) (*http.Response, error) { - requestDataAdd := map[string]interface{}{ - "mode": mode, - "expires": expires, - "governance_bypass": governanceBypass, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - apiURL := "http://localhost:9090/api/v1/buckets/" + bucketName + "/objects/retention?prefix=" + prefix + "&version_id=" + versionID - - request, err := http.NewRequest( - "PUT", - apiURL, - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - func GetsTheMetadataOfAnObject(bucketName, prefix string) (*http.Response, error) { /* Gets the metadata of an object @@ -533,176 +425,6 @@ func RestoreObjectToASelectedVersion(bucketName, prefix, versionID string) (*htt return response, err } -func BucketSetPolicy(bucketName, access, definition string) (*http.Response, error) { - /* - Helper function to set policy on a bucket - Name: Bucket Set Policy - HTTP Verb: PUT - URL: {{baseUrl}}/buckets/:name/set-policy - Body: - { - "access": "PRIVATE", - "definition": "dolo" - } - */ - requestDataAdd := map[string]interface{}{ - "access": access, - "definition": definition, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest( - "PUT", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/set-policy", - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func DeleteObjectsRetentionStatus(bucketName, prefix, versionID string) (*http.Response, error) { - /* - Helper function to Delete Object Retention Status - DELETE: - {{baseUrl}}/buckets/:bucket_name/objects/retention?prefix=proident velit&version_id=proident velit - */ - url := "http://localhost:9090/api/v1/buckets/" + bucketName + "/objects/retention?prefix=" + - prefix + "&version_id=" + versionID - request, err := http.NewRequest( - "DELETE", - url, - nil, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func ListBucketEvents(bucketName string) (*http.Response, error) { - /* - Helper function to list bucket's events - Name: List Bucket Events - HTTP Verb: GET - URL: {{baseUrl}}/buckets/:bucket_name/events - */ - request, err := http.NewRequest( - "GET", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/events", - nil, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func PutBucketQuota(bucketName string, enabled bool, quotaType string, amount int) (*http.Response, error) { - /* - Helper function to put bucket quota - Name: Bucket Quota - URL: {{baseUrl}}/buckets/:name/quota - HTTP Verb: PUT - Body: - { - "enabled": false, - "quota_type": "fifo", - "amount": 18462288 - } - */ - requestDataAdd := map[string]interface{}{ - "enabled": enabled, - "quota_type": quotaType, - "amount": amount, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest( - "PUT", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/quota", - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func GetBucketQuota(bucketName string) (*http.Response, error) { - /* - Helper function to get bucket quota - Name: Get Bucket Quota - URL: {{baseUrl}}/buckets/:name/quota - HTTP Verb: GET - */ - request, err := http.NewRequest( - "GET", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/quota", - nil, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func PutObjectsLegalholdStatus(bucketName, prefix, status, versionID string) (*http.Response, error) { - // Helper function to test "Put Object's legalhold status" end point - requestDataAdd := map[string]interface{}{ - "status": status, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - apiURL := "http://localhost:9090/api/v1/buckets/" + bucketName + "/objects/legalhold?prefix=" + prefix + "&version_id=" + versionID - request, err := http.NewRequest( - "PUT", - apiURL, - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - func TestRestoreObjectToASelectedVersion(t *testing.T) { // Variables assert := assert.New(t) @@ -1643,249 +1365,6 @@ func TestAddBucket(t *testing.T) { } } -func CreateBucketEvent(bucketName string, ignoreExisting bool, arn, prefix, suffix string, events []string) (*http.Response, error) { - /* - Helper function to create bucket event - POST: /buckets/{bucket_name}/events - { - "configuration": - { - "arn":"arn:minio:sqs::_:postgresql", - "events":["put"], - "prefix":"", - "suffix":"" - }, - "ignoreExisting":true - } - */ - configuration := map[string]interface{}{ - "arn": arn, - "events": events, - "prefix": prefix, - "suffix": suffix, - } - requestDataAdd := map[string]interface{}{ - "configuration": configuration, - "ignoreExisting": ignoreExisting, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest( - "POST", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/events", - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func DeleteBucketEvent(bucketName, arn string, events []string, prefix, suffix string) (*http.Response, error) { - /* - Helper function to test Delete Bucket Event - DELETE: /buckets/{bucket_name}/events/{arn} - { - "events":["put"], - "prefix":"", - "suffix":"" - } - */ - requestDataAdd := map[string]interface{}{ - "events": events, - "prefix": prefix, - "suffix": suffix, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest( - "DELETE", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/events/"+arn, - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func SetMultiBucketReplication(accessKey, secretKey, targetURL, region, originBucket, destinationBucket, syncMode string, bandwidth, healthCheckPeriod int, prefix, tags string, replicateDeleteMarkers, replicateDeletes bool, priority int, storageClass string, replicateMetadata bool) (*http.Response, error) { - /* - Helper function - URL: /buckets-replication - HTTP Verb: POST - Body: - { - "accessKey":"Q3AM3UQ867SPQQA43P2F", - "secretKey":"zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", - "targetURL":"https://play.min.io", - "region":"", - "bucketsRelation":[ - { - "originBucket":"test", - "destinationBucket":"versioningenabled" - } - ], - "syncMode":"async", - "bandwidth":107374182400, - "healthCheckPeriod":60, - "prefix":"", - "tags":"", - "replicateDeleteMarkers":true, - "replicateDeletes":true, - "priority":1, - "storageClass":"", - "replicateMetadata":true - } - */ - bucketsRelationArray := make([]map[string]interface{}, 1) - bucketsRelationIndex0 := map[string]interface{}{ - "originBucket": originBucket, - "destinationBucket": destinationBucket, - } - bucketsRelationArray[0] = bucketsRelationIndex0 - requestDataAdd := map[string]interface{}{ - "accessKey": accessKey, - "secretKey": secretKey, - "targetURL": targetURL, - "region": region, - "bucketsRelation": bucketsRelationArray, - "syncMode": syncMode, - "bandwidth": bandwidth, - "healthCheckPeriod": healthCheckPeriod, - "prefix": prefix, - "tags": tags, - "replicateDeleteMarkers": replicateDeleteMarkers, - "replicateDeletes": replicateDeletes, - "priority": priority, - "storageClass": storageClass, - "replicateMetadata": replicateMetadata, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest( - "POST", - "http://localhost:9090/api/v1/buckets-replication", - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func GetBucketReplication(bucketName string) (*http.Response, error) { - /* - URL: /buckets/{bucket_name}/replication - HTTP Verb: GET - */ - request, err := http.NewRequest("GET", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/replication", - nil) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func DeletesAllReplicationRulesOnABucket(bucketName string) (*http.Response, error) { - /* - Helper function to delete all replication rules in a bucket - URL: /buckets/{bucket_name}/delete-all-replication-rules - HTTP Verb: DELETE - */ - request, err := http.NewRequest( - "DELETE", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/delete-all-replication-rules", - nil, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func DeleteMultipleReplicationRules(bucketName string, rules []string) (*http.Response, error) { - /* - Helper function to delete multiple replication rules in a bucket - URL: /buckets/{bucket_name}/delete-multiple-replication-rules - HTTP Verb: DELETE - */ - body := map[string]interface{}{ - "rules": rules, - } - requestDataJSON, _ := json.Marshal(body) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest( - "DELETE", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/delete-selected-replication-rules", - requestDataBody, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - -func DeleteBucketReplicationRule(bucketName, ruleID string) (*http.Response, error) { - /* - Helper function to delete a bucket's replication rule - URL: /buckets/{bucket_name}/replication/{rule_id} - HTTP Verb: DELETE - */ - request, err := http.NewRequest( - "DELETE", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/replication/"+ruleID, - nil, - ) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - func GetBucketVersioning(bucketName string) (*http.Response, error) { /* Helper function to get bucket's versioning @@ -1894,16 +1373,6 @@ func GetBucketVersioning(bucketName string) (*http.Response, error) { return BaseGetFunction(bucketName, endPoint) } -func ReturnsTheStatusOfObjectLockingSupportOnTheBucket(bucketName string) (*http.Response, error) { - /* - Helper function to test end point below: - URL: /buckets/{bucket_name}/object-locking: - HTTP Verb: GET - */ - endPoint := "object-locking" - return BaseGetFunction(bucketName, endPoint) -} - func BaseGetFunction(bucketName, endPoint string) (*http.Response, error) { request, err := http.NewRequest( "GET", diff --git a/models/list_users_response.go b/models/list_users_response.go deleted file mode 100644 index 6402e70275..0000000000 --- a/models/list_users_response.go +++ /dev/null @@ -1,138 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// ListUsersResponse list users response -// -// swagger:model listUsersResponse -type ListUsersResponse struct { - - // list of resulting users - Users []*User `json:"users"` -} - -// Validate validates this list users response -func (m *ListUsersResponse) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateUsers(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ListUsersResponse) validateUsers(formats strfmt.Registry) error { - if swag.IsZero(m.Users) { // not required - return nil - } - - for i := 0; i < len(m.Users); i++ { - if swag.IsZero(m.Users[i]) { // not required - continue - } - - if m.Users[i] != nil { - if err := m.Users[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("users" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("users" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -// ContextValidate validate this list users response based on the context it is used -func (m *ListUsersResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateUsers(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ListUsersResponse) contextValidateUsers(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Users); i++ { - - if m.Users[i] != nil { - - if swag.IsZero(m.Users[i]) { // not required - return nil - } - - if err := m.Users[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("users" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("users" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ListUsersResponse) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ListUsersResponse) UnmarshalBinary(b []byte) error { - var res ListUsersResponse - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/models/login_details.go b/models/login_details.go index 9e908335ff..87e7314d7e 100644 --- a/models/login_details.go +++ b/models/login_details.go @@ -45,7 +45,7 @@ type LoginDetails struct { IsK8S bool `json:"isK8S,omitempty"` // login strategy - // Enum: ["form","redirect","service-account","redirect-service-account"] + // Enum: ["form","service-account","redirect-service-account"] LoginStrategy string `json:"loginStrategy,omitempty"` // redirect rules @@ -74,7 +74,7 @@ var loginDetailsTypeLoginStrategyPropEnum []interface{} func init() { var res []string - if err := json.Unmarshal([]byte(`["form","redirect","service-account","redirect-service-account"]`), &res); err != nil { + if err := json.Unmarshal([]byte(`["form","service-account","redirect-service-account"]`), &res); err != nil { panic(err) } for _, v := range res { @@ -87,9 +87,6 @@ const ( // LoginDetailsLoginStrategyForm captures enum value "form" LoginDetailsLoginStrategyForm string = "form" - // LoginDetailsLoginStrategyRedirect captures enum value "redirect" - LoginDetailsLoginStrategyRedirect string = "redirect" - // LoginDetailsLoginStrategyServiceDashAccount captures enum value "service-account" LoginDetailsLoginStrategyServiceDashAccount string = "service-account" diff --git a/models/login_oauth2_auth_request.go b/models/login_oauth2_auth_request.go deleted file mode 100644 index e50ff412d2..0000000000 --- a/models/login_oauth2_auth_request.go +++ /dev/null @@ -1,105 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// LoginOauth2AuthRequest login oauth2 auth request -// -// swagger:model loginOauth2AuthRequest -type LoginOauth2AuthRequest struct { - - // code - // Required: true - Code *string `json:"code"` - - // state - // Required: true - State *string `json:"state"` -} - -// Validate validates this login oauth2 auth request -func (m *LoginOauth2AuthRequest) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateState(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *LoginOauth2AuthRequest) validateCode(formats strfmt.Registry) error { - - if err := validate.Required("code", "body", m.Code); err != nil { - return err - } - - return nil -} - -func (m *LoginOauth2AuthRequest) validateState(formats strfmt.Registry) error { - - if err := validate.Required("state", "body", m.State); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this login oauth2 auth request based on context it is used -func (m *LoginOauth2AuthRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *LoginOauth2AuthRequest) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *LoginOauth2AuthRequest) UnmarshalBinary(b []byte) error { - var res LoginOauth2AuthRequest - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/models/put_bucket_tags_request.go b/models/put_bucket_tags_request.go deleted file mode 100644 index e5f45a1247..0000000000 --- a/models/put_bucket_tags_request.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// PutBucketTagsRequest put bucket tags request -// -// swagger:model putBucketTagsRequest -type PutBucketTagsRequest struct { - - // tags - Tags map[string]string `json:"tags,omitempty"` -} - -// Validate validates this put bucket tags request -func (m *PutBucketTagsRequest) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this put bucket tags request based on context it is used -func (m *PutBucketTagsRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PutBucketTagsRequest) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PutBucketTagsRequest) UnmarshalBinary(b []byte) error { - var res PutBucketTagsRequest - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/models/user.go b/models/user.go deleted file mode 100644 index 76d4f790b7..0000000000 --- a/models/user.go +++ /dev/null @@ -1,79 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// This file is part of MinIO Console Server -// Copyright (c) 2023 MinIO, Inc. -// -// 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 . -// - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// User user -// -// swagger:model user -type User struct { - - // access key - AccessKey string `json:"accessKey,omitempty"` - - // has policy - HasPolicy bool `json:"hasPolicy,omitempty"` - - // member of - MemberOf []string `json:"memberOf"` - - // policy - Policy []string `json:"policy"` - - // status - Status string `json:"status,omitempty"` -} - -// Validate validates this user -func (m *User) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this user based on context it is used -func (m *User) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *User) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *User) UnmarshalBinary(b []byte) error { - var res User - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/pkg/auth/idp/oauth2/config.go b/pkg/auth/idp/oauth2/config.go index a836e3daa1..2a5ad45424 100644 --- a/pkg/auth/idp/oauth2/config.go +++ b/pkg/auth/idp/oauth2/config.go @@ -24,7 +24,6 @@ import ( "net/http" "strings" - "github.com/minio/console/pkg/auth/token" "github.com/minio/minio-go/v7/pkg/set" "github.com/minio/pkg/v3/env" "golang.org/x/crypto/pbkdf2" @@ -135,49 +134,3 @@ type OpenIDPCfg map[string]ProviderConfig func GetSTSEndpoint() string { return strings.TrimSpace(env.Get(ConsoleMinIOServer, "http://localhost:9000")) } - -func GetIDPURL() string { - return env.Get(ConsoleIDPURL, "") -} - -func GetIDPClientID() string { - return env.Get(ConsoleIDPClientID, "") -} - -func GetIDPUserInfo() bool { - return env.Get(ConsoleIDPUserInfo, "") == "on" -} - -func GetIDPSecret() string { - return env.Get(ConsoleIDPSecret, "") -} - -// Public endpoint used by the identity oidcProvider when redirecting -// the user after identity verification -func GetIDPCallbackURL() string { - return env.Get(ConsoleIDPCallbackURL, "") -} - -func GetIDPCallbackURLDynamic() bool { - return env.Get(ConsoleIDPCallbackURLDynamic, "") == "on" -} - -func IsIDPEnabled() bool { - return GetIDPURL() != "" && - GetIDPClientID() != "" -} - -// GetPassphraseForIDPHmac returns passphrase for the pbkdf2 function used to sign the oauth2 state parameter -func getPassphraseForIDPHmac() string { - return env.Get(ConsoleIDPHmacPassphrase, token.GetPBKDFPassphrase()) -} - -// GetSaltForIDPHmac returns salt for the pbkdf2 function used to sign the oauth2 state parameter -func getSaltForIDPHmac() string { - return env.Get(ConsoleIDPHmacSalt, token.GetPBKDFSalt()) -} - -// getIDPScopes return default scopes during the IDP login request -func getIDPScopes() string { - return env.Get(ConsoleIDPScopes, "openid,profile,email") -} diff --git a/pkg/auth/idp/oauth2/const.go b/pkg/auth/idp/oauth2/const.go index 6fe1971a25..4665546c9f 100644 --- a/pkg/auth/idp/oauth2/const.go +++ b/pkg/auth/idp/oauth2/const.go @@ -18,15 +18,5 @@ package oauth2 // Environment constants for console IDP/SSO configuration const ( - ConsoleMinIOServer = "CONSOLE_MINIO_SERVER" - ConsoleIDPURL = "CONSOLE_IDP_URL" - ConsoleIDPClientID = "CONSOLE_IDP_CLIENT_ID" - ConsoleIDPSecret = "CONSOLE_IDP_SECRET" - ConsoleIDPCallbackURL = "CONSOLE_IDP_CALLBACK" - ConsoleIDPCallbackURLDynamic = "CONSOLE_IDP_CALLBACK_DYNAMIC" - ConsoleIDPHmacPassphrase = "CONSOLE_IDP_HMAC_PASSPHRASE" - ConsoleIDPHmacSalt = "CONSOLE_IDP_HMAC_SALT" - ConsoleIDPScopes = "CONSOLE_IDP_SCOPES" - ConsoleIDPUserInfo = "CONSOLE_IDP_USERINFO" - ConsoleIDPTokenExpiration = "CONSOLE_IDP_TOKEN_EXPIRATION" + ConsoleMinIOServer = "CONSOLE_MINIO_SERVER" ) diff --git a/pkg/auth/idp/oauth2/provider.go b/pkg/auth/idp/oauth2/provider.go index fa2fe295bc..a3003704ec 100644 --- a/pkg/auth/idp/oauth2/provider.go +++ b/pkg/auth/idp/oauth2/provider.go @@ -18,7 +18,6 @@ package oauth2 import ( "context" - "crypto/sha1" "encoding/base64" "encoding/json" "errors" @@ -33,7 +32,6 @@ import ( "github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/minio-go/v7/pkg/set" "github.com/minio/pkg/v3/env" - "golang.org/x/crypto/pbkdf2" "golang.org/x/oauth2" xoauth2 "golang.org/x/oauth2" ) @@ -115,12 +113,6 @@ type Provider struct { client *http.Client } -// DefaultDerivedKey is the key used to compute the HMAC for signing the oauth state parameter -// its derived using pbkdf on CONSOLE_IDP_HMAC_PASSPHRASE with CONSOLE_IDP_HMAC_SALT -var DefaultDerivedKey = func() []byte { - return pbkdf2.Key([]byte(getPassphraseForIDPHmac()), []byte(getSaltForIDPHmac()), 4096, 32, sha1.New) -} - const ( schemeHTTP = "http" schemeHTTPS = "https" @@ -146,68 +138,6 @@ func getLoginCallbackURL(r *http.Request) string { var requiredResponseTypes = set.CreateStringSet("code") -// NewOauth2ProviderClient instantiates a new oauth2 client using the configured credentials -// it returns a *Provider object that contains the necessary configuration to initiate an -// oauth2 authentication flow. -// -// We only support Authentication with the Authorization Code Flow - spec: -// https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth -func NewOauth2ProviderClient(scopes []string, r *http.Request, httpClient *http.Client) (*Provider, error) { - ddoc, err := parseDiscoveryDoc(r.Context(), GetIDPURL(), httpClient) - if err != nil { - return nil, err - } - - supportedResponseTypes := set.NewStringSet() - for _, responseType := range ddoc.ResponseTypesSupported { - // FIXME: ResponseTypesSupported is a JSON array of strings - it - // may not actually have strings with spaces inside them - - // making the following code unnecessary. - for _, s := range strings.Fields(responseType) { - supportedResponseTypes.Add(s) - } - } - isSupported := requiredResponseTypes.Difference(supportedResponseTypes).IsEmpty() - - if !isSupported { - return nil, fmt.Errorf("expected 'code' response type - got %s, login not allowed", ddoc.ResponseTypesSupported) - } - - // If provided scopes are empty we use a default list or the user configured list - if len(scopes) == 0 { - scopes = strings.Split(getIDPScopes(), ",") - } - - redirectURL := GetIDPCallbackURL() - - if GetIDPCallbackURLDynamic() { - // dynamic redirect if set, will generate redirect URLs - // dynamically based on incoming requests. - redirectURL = getLoginCallbackURL(r) - } - - // add "openid" scope always. - scopes = append(scopes, "openid") - - client := new(Provider) - client.oauth2Config = &xoauth2.Config{ - ClientID: GetIDPClientID(), - ClientSecret: GetIDPSecret(), - RedirectURL: redirectURL, - Endpoint: oauth2.Endpoint{ - AuthURL: ddoc.AuthEndpoint, - TokenURL: ddoc.TokenEndpoint, - }, - Scopes: scopes, - } - - client.IDPName = GetIDPClientID() - client.UserInfo = GetIDPUserInfo() - client.client = httpClient - - return client, nil -} - var defaultScopes = []string{"openid", "profile", "email"} // NewOauth2ProviderClientByName returns a provider if present specified by the input name of the provider. diff --git a/pkg/auth/idp/oauth2/provider_test.go b/pkg/auth/idp/oauth2/provider_test.go deleted file mode 100644 index a438274b98..0000000000 --- a/pkg/auth/idp/oauth2/provider_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// This file is part of MinIO Console Server -// Copyright (c) 2021 MinIO, Inc. -// -// 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 . - -package oauth2 - -import ( - "context" - "net/http" - "testing" - - "github.com/stretchr/testify/assert" - "golang.org/x/oauth2" -) - -type Oauth2configMock struct{} - -var ( - oauth2ConfigExchangeMock func(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) - oauth2ConfigAuthCodeURLMock func(state string, opts ...oauth2.AuthCodeOption) string - oauth2ConfigPasswordCredentialsTokenMock func(ctx context.Context, username, password string) (*oauth2.Token, error) - oauth2ConfigClientMock func(ctx context.Context, t *oauth2.Token) *http.Client - oauth2ConfigokenSourceMock func(ctx context.Context, t *oauth2.Token) oauth2.TokenSource -) - -func (ac Oauth2configMock) Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) { - return oauth2ConfigExchangeMock(ctx, code, opts...) -} - -func (ac Oauth2configMock) AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string { - return oauth2ConfigAuthCodeURLMock(state, opts...) -} - -func (ac Oauth2configMock) PasswordCredentialsToken(ctx context.Context, username, password string) (*oauth2.Token, error) { - return oauth2ConfigPasswordCredentialsTokenMock(ctx, username, password) -} - -func (ac Oauth2configMock) Client(ctx context.Context, t *oauth2.Token) *http.Client { - return oauth2ConfigClientMock(ctx, t) -} - -func (ac Oauth2configMock) TokenSource(ctx context.Context, t *oauth2.Token) oauth2.TokenSource { - return oauth2ConfigokenSourceMock(ctx, t) -} - -func TestGenerateLoginURL(t *testing.T) { - funcAssert := assert.New(t) - oauth2Provider := Provider{ - oauth2Config: Oauth2configMock{}, - } - // Test-1 : GenerateLoginURL() generates URL correctly with provided state - oauth2ConfigAuthCodeURLMock = func(state string, _ ...oauth2.AuthCodeOption) string { - // Internally we are testing the private method getRandomStateWithHMAC, this function should always returns - // a non-empty string - return state - } - url := oauth2Provider.GenerateLoginURL(DefaultDerivedKey, "testIDP") - funcAssert.NotEqual("", url) -} diff --git a/pkg/auth/ldap.go b/pkg/auth/ldap.go index 24935afbea..37777d6a19 100644 --- a/pkg/auth/ldap.go +++ b/pkg/auth/ldap.go @@ -16,20 +16,5 @@ package auth -import ( - "net/http" - - "github.com/minio/minio-go/v7/pkg/credentials" -) - // GetCredentialsFromLDAP authenticates the user against MinIO when the LDAP integration is enabled // if the authentication succeed *credentials.Login object is returned and we continue with the normal STSAssumeRole flow -func GetCredentialsFromLDAP(client *http.Client, endpoint, ldapUser, ldapPassword string) (*credentials.Credentials, error) { - creds := credentials.New(&credentials.LDAPIdentity{ - Client: client, - STSEndpoint: endpoint, - LDAPUsername: ldapUser, - LDAPPassword: ldapPassword, - }) - return creds, nil -} diff --git a/pkg/auth/ldap/config.go b/pkg/auth/ldap/config.go deleted file mode 100644 index 8f0a916a61..0000000000 --- a/pkg/auth/ldap/config.go +++ /dev/null @@ -1,27 +0,0 @@ -// This file is part of MinIO Console Server -// Copyright (c) 2021 MinIO, Inc. -// -// 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 . - -package ldap - -import ( - "strings" - - "github.com/minio/pkg/v3/env" -) - -func GetLDAPEnabled() bool { - return strings.ToLower(env.Get(ConsoleLDAPEnabled, "off")) == "on" -} diff --git a/pkg/auth/ldap/const.go b/pkg/auth/ldap/const.go deleted file mode 100644 index 574430d7b5..0000000000 --- a/pkg/auth/ldap/const.go +++ /dev/null @@ -1,22 +0,0 @@ -// This file is part of MinIO Console Server -// Copyright (c) 2021 MinIO, Inc. -// -// 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 . - -package ldap - -const ( - // const for ldap configuration - ConsoleLDAPEnabled = "CONSOLE_LDAP_ENABLED" -) diff --git a/pkg/certs/certs.go b/pkg/certs/certs.go index dbf3b53bc6..8dbac8b760 100644 --- a/pkg/certs/certs.go +++ b/pkg/certs/certs.go @@ -316,10 +316,3 @@ func GetAllCertificatesAndCAs() (*x509.CertPool, []*x509.Certificate, *xcerts.Ma } // EnsureCertAndKey checks if both client certificate and key paths are provided -func EnsureCertAndKey(clientCert, clientKey string) error { - if (clientCert != "" && clientKey == "") || - (clientCert == "" && clientKey != "") { - return errors.New("cert and key must be specified as a pair") - } - return nil -} diff --git a/pkg/kes/kes.go b/pkg/kes/kes.go index ea341d55c7..6ecda19bbb 100644 --- a/pkg/kes/kes.go +++ b/pkg/kes/kes.go @@ -17,9 +17,6 @@ package kes import ( - "crypto/x509" - "encoding/pem" - "errors" "time" "github.com/minio/kes" @@ -179,18 +176,3 @@ type ServerConfig struct { Log Log `yaml:"log,omitempty" json:"log,omitempty"` Keys Keys `yaml:"keys,omitempty" json:"keys,omitempty"` } - -func ParseCertificate(cert []byte) (*x509.Certificate, error) { - for { - var certDERBlock *pem.Block - certDERBlock, cert = pem.Decode(cert) - if certDERBlock == nil { - break - } - - if certDERBlock.Type == "CERTIFICATE" { - return x509.ParseCertificate(certDERBlock.Bytes) - } - } - return nil, errors.New("found no (non-CA) certificate in any PEM block") -} diff --git a/swagger.yml b/swagger.yml index 916777099a..62d8cfb3bc 100644 --- a/swagger.yml +++ b/swagger.yml @@ -77,27 +77,6 @@ paths: security: [ ] tags: - Auth - /login/oauth2/auth: - post: - summary: Identity Provider oauth2 callback endpoint. - operationId: LoginOauth2Auth - parameters: - - name: body - in: body - required: true - schema: - $ref: "#/definitions/loginOauth2AuthRequest" - responses: - 204: - description: A successful login. - default: - description: Generic error response. - schema: - $ref: "#/definitions/ApiError" - security: [ ] - tags: - - Auth - /logout: post: summary: Logout from Console. @@ -117,7 +96,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Auth - /session: get: summary: Endpoint to check if your session is still valid @@ -133,7 +111,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Auth - /buckets: get: summary: List Buckets @@ -169,7 +146,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Bucket - /buckets/{name}: get: summary: Bucket Info @@ -190,7 +166,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Bucket - /buckets/{bucket_name}/objects: get: summary: List Objects @@ -272,7 +247,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/delete-objects: post: summary: Delete Multiple Objects @@ -306,7 +280,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/objects/upload: post: summary: Uploads an Object. @@ -332,7 +305,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/objects/download-multiple: post: summary: Download Multiple Objects @@ -365,7 +337,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/objects/download: get: summary: Download Object @@ -409,7 +380,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/objects/share: get: summary: Shares an Object on a url @@ -442,7 +412,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/objects/tags: put: summary: Put Object's tags @@ -474,7 +443,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/objects/restore: put: summary: Restore Object to a selected version @@ -501,7 +469,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - /buckets/{bucket_name}/objects/metadata: get: summary: Gets the metadata of an object @@ -529,31 +496,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Object - - /buckets/{bucket_name}/tags: - put: - summary: Put Bucket's tags - operationId: PutBucketTags - parameters: - - name: bucket_name - in: path - required: true - type: string - - name: body - in: body - required: true - schema: - $ref: "#/definitions/putBucketTagsRequest" - responses: - 200: - description: A successful response. - default: - description: Generic error response. - schema: - $ref: "#/definitions/ApiError" - tags: - - Bucket - /buckets/{name}/quota: get: summary: Get Bucket Quota @@ -574,7 +516,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Bucket - /buckets/{bucket_name}/versioning: get: summary: Bucket Versioning @@ -617,7 +558,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Bucket - /buckets/{bucket_name}/rewind/{date}: get: summary: Get objects in a bucket for a rewind date @@ -646,7 +586,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Bucket - /buckets/max-share-exp: get: summary: Get max expiration time for share link in seconds @@ -662,26 +601,6 @@ paths: $ref: "#/definitions/ApiError" tags: - Bucket - - /users: - get: - summary: List Users - operationId: ListUsers - parameters: - - $ref: "#/parameters/offset" - - $ref: "#/parameters/limit" - responses: - 200: - description: A successful response. - schema: - $ref: "#/definitions/listUsersResponse" - default: - description: Generic error response. - schema: - $ref: "#/definitions/ApiError" - tags: - - User - /admin/info: get: summary: Returns information about the deployment @@ -909,32 +828,6 @@ definitions: type: string detailedMessage: type: string - user: - type: object - properties: - accessKey: - type: string - policy: - type: array - items: - type: string - memberOf: - type: array - items: - type: string - status: - type: string - hasPolicy: - type: boolean - - listUsersResponse: - type: object - properties: - users: - type: array - items: - $ref: "#/definitions/user" - title: list of resulting users makeBucketsResponse: type: object properties: @@ -961,7 +854,7 @@ definitions: properties: loginStrategy: type: string - enum: [ form, redirect, service-account, redirect-service-account ] + enum: [ form, service-account, redirect-service-account ] redirectRules: type: array items: @@ -970,16 +863,6 @@ definitions: type: boolean animatedLogin: type: boolean - loginOauth2AuthRequest: - type: object - required: - - state - - code - properties: - state: - type: string - code: - type: string loginRequest: type: object properties: @@ -1213,12 +1096,6 @@ definitions: additionalProperties: type: string - putBucketTagsRequest: - type: object - properties: - tags: - additionalProperties: - type: string deleteFile: type: object properties: diff --git a/web-app/src/api/consoleApi.ts b/web-app/src/api/consoleApi.ts index f91235c473..5b979239e8 100644 --- a/web-app/src/api/consoleApi.ts +++ b/web-app/src/api/consoleApi.ts @@ -111,19 +111,6 @@ export interface ApiError { detailedMessage?: string; } -export interface User { - accessKey?: string; - policy?: string[]; - memberOf?: string[]; - status?: string; - hasPolicy?: boolean; -} - -export interface ListUsersResponse { - /** list of resulting users */ - users?: User[]; -} - export interface MakeBucketsResponse { bucketName?: string; } @@ -139,21 +126,12 @@ export interface LoginResponse { } export interface LoginDetails { - loginStrategy?: - | "form" - | "redirect" - | "service-account" - | "redirect-service-account"; + loginStrategy?: "form" | "service-account" | "redirect-service-account"; redirectRules?: RedirectRule[]; isK8S?: boolean; animatedLogin?: boolean; } -export interface LoginOauth2AuthRequest { - state: string; - code: string; -} - export interface LoginRequest { accessKey?: string; secretKey?: string; @@ -275,10 +253,6 @@ export interface PutObjectTagsRequest { tags?: any; } -export interface PutBucketTagsRequest { - tags?: any; -} - export interface DeleteFile { path?: string; versionID?: string; @@ -348,22 +322,16 @@ export interface FullRequestParams extends Omit { cancelToken?: CancelToken; } -export type RequestParams = Omit< - FullRequestParams, - "body" | "method" | "query" | "path" ->; +export type RequestParams = Omit; export interface ApiConfig { baseUrl?: string; baseApiParams?: Omit; - securityWorker?: ( - securityData: SecurityDataType | null, - ) => Promise | RequestParams | void; + securityWorker?: (securityData: SecurityDataType | null) => Promise | RequestParams | void; customFetch?: typeof fetch; } -export interface HttpResponse - extends Response { +export interface HttpResponse extends Response { data: D; error: E; } @@ -382,8 +350,7 @@ export class HttpClient { private securityData: SecurityDataType | null = null; private securityWorker?: ApiConfig["securityWorker"]; private abortControllers = new Map(); - private customFetch = (...fetchParams: Parameters) => - fetch(...fetchParams); + private customFetch = (...fetchParams: Parameters) => fetch(...fetchParams); private baseApiParams: RequestParams = { credentials: "same-origin", @@ -416,15 +383,9 @@ export class HttpClient { protected toQueryString(rawQuery?: QueryParamsType): string { const query = rawQuery || {}; - const keys = Object.keys(query).filter( - (key) => "undefined" !== typeof query[key], - ); + const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]); return keys - .map((key) => - Array.isArray(query[key]) - ? this.addArrayQueryParam(query, key) - : this.addQueryParam(query, key), - ) + .map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key))) .join("&"); } @@ -435,13 +396,8 @@ export class HttpClient { private contentFormatters: Record any> = { [ContentType.Json]: (input: any) => - input !== null && (typeof input === "object" || typeof input === "string") - ? JSON.stringify(input) - : input, - [ContentType.Text]: (input: any) => - input !== null && typeof input !== "string" - ? JSON.stringify(input) - : input, + input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, + [ContentType.Text]: (input: any) => (input !== null && typeof input !== "string" ? JSON.stringify(input) : input), [ContentType.FormData]: (input: any) => Object.keys(input || {}).reduce((formData, key) => { const property = input[key]; @@ -458,10 +414,7 @@ export class HttpClient { [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input), }; - protected mergeRequestParams( - params1: RequestParams, - params2?: RequestParams, - ): RequestParams { + protected mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams { return { ...this.baseApiParams, ...params1, @@ -474,9 +427,7 @@ export class HttpClient { }; } - protected createAbortSignal = ( - cancelToken: CancelToken, - ): AbortSignal | undefined => { + protected createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => { if (this.abortControllers.has(cancelToken)) { const abortController = this.abortControllers.get(cancelToken); if (abortController) { @@ -520,26 +471,15 @@ export class HttpClient { const payloadFormatter = this.contentFormatters[type || ContentType.Json]; const responseFormat = format || requestParams.format; - return this.customFetch( - `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, - { - ...requestParams, - headers: { - ...(requestParams.headers || {}), - ...(type && type !== ContentType.FormData - ? { "Content-Type": type } - : {}), - }, - signal: - (cancelToken - ? this.createAbortSignal(cancelToken) - : requestParams.signal) || null, - body: - typeof body === "undefined" || body === null - ? null - : payloadFormatter(body), + return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, { + ...requestParams, + headers: { + ...(requestParams.headers || {}), + ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), }, - ).then(async (response) => { + signal: (cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal) || null, + body: typeof body === "undefined" || body === null ? null : payloadFormatter(body), + }).then(async (response) => { const r = response.clone() as HttpResponse; r.data = null as unknown as T; r.error = null as unknown as E; @@ -575,9 +515,7 @@ export class HttpClient { * @version 0.1.0 * @baseUrl /api/v1 */ -export class Api< - SecurityDataType extends unknown, -> extends HttpClient { +export class Api extends HttpClient { login = { /** * No description @@ -611,26 +549,6 @@ export class Api< type: ContentType.Json, ...params, }), - - /** - * No description - * - * @tags Auth - * @name LoginOauth2Auth - * @summary Identity Provider oauth2 callback endpoint. - * @request POST:/login/oauth2/auth - */ - loginOauth2Auth: ( - body: LoginOauth2AuthRequest, - params: RequestParams = {}, - ) => - this.request({ - path: `/login/oauth2/auth`, - method: "POST", - body: body, - type: ContentType.Json, - ...params, - }), }; logout = { /** @@ -854,11 +772,7 @@ export class Api< * @request POST:/buckets/{bucket_name}/objects/download-multiple * @secure */ - downloadMultipleObjects: ( - bucketName: string, - objectList: string[], - params: RequestParams = {}, - ) => + downloadMultipleObjects: (bucketName: string, objectList: string[], params: RequestParams = {}) => this.request({ path: `/buckets/${encodeURIComponent(bucketName)}/objects/download-multiple`, method: "POST", @@ -1003,29 +917,6 @@ export class Api< ...params, }), - /** - * No description - * - * @tags Bucket - * @name PutBucketTags - * @summary Put Bucket's tags - * @request PUT:/buckets/{bucket_name}/tags - * @secure - */ - putBucketTags: ( - bucketName: string, - body: PutBucketTagsRequest, - params: RequestParams = {}, - ) => - this.request({ - path: `/buckets/${encodeURIComponent(bucketName)}/tags`, - method: "PUT", - body: body, - secure: true, - type: ContentType.Json, - ...params, - }), - /** * No description * @@ -1071,11 +962,7 @@ export class Api< * @request PUT:/buckets/{bucket_name}/versioning * @secure */ - setBucketVersioning: ( - bucketName: string, - body: SetBucketVersioning, - params: RequestParams = {}, - ) => + setBucketVersioning: (bucketName: string, body: SetBucketVersioning, params: RequestParams = {}) => this.request({ path: `/buckets/${encodeURIComponent(bucketName)}/versioning`, method: "PUT", @@ -1129,40 +1016,6 @@ export class Api< ...params, }), }; - users = { - /** - * No description - * - * @tags User - * @name ListUsers - * @summary List Users - * @request GET:/users - * @secure - */ - listUsers: ( - query?: { - /** - * @format int32 - * @default 0 - */ - offset?: number; - /** - * @format int32 - * @default 20 - */ - limit?: number; - }, - params: RequestParams = {}, - ) => - this.request({ - path: `/users`, - method: "GET", - query: query, - secure: true, - format: "json", - ...params, - }), - }; admin = { /** * No description diff --git a/web-app/src/screens/LoginPage/Login.tsx b/web-app/src/screens/LoginPage/Login.tsx index 8a2623d5e6..bfc2cde66a 100644 --- a/web-app/src/screens/LoginPage/Login.tsx +++ b/web-app/src/screens/LoginPage/Login.tsx @@ -75,7 +75,6 @@ const Login = () => { let loginComponent; switch (loginStrategy.loginStrategy) { - case loginStrategyType.redirect: case loginStrategyType.form: { let redirectItems: RedirectRule[] = []; diff --git a/web-app/src/websockets/objectBrowserWSMiddleware.ts b/web-app/src/websockets/objectBrowserWSMiddleware.ts index d79050856c..4069c6674c 100644 --- a/web-app/src/websockets/objectBrowserWSMiddleware.ts +++ b/web-app/src/websockets/objectBrowserWSMiddleware.ts @@ -238,7 +238,9 @@ export const objectBrowserWSMiddleware = ( } break; case "socket/OBDisconnect": - objectsWS.close(); + if (objectsWS) { + objectsWS.close(); + } break; default: From 2a5a823795b1f9ec201a44b9257f2105b2ebb7d7 Mon Sep 17 00:00:00 2001 From: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com> Date: Wed, 14 May 2025 14:50:34 -0700 Subject: [PATCH 2/7] prettier --- web-app/src/api/consoleApi.ts | 86 ++++++++++++++++++++++++++--------- 1 file changed, 65 insertions(+), 21 deletions(-) diff --git a/web-app/src/api/consoleApi.ts b/web-app/src/api/consoleApi.ts index 5b979239e8..c9d02fce11 100644 --- a/web-app/src/api/consoleApi.ts +++ b/web-app/src/api/consoleApi.ts @@ -322,16 +322,22 @@ export interface FullRequestParams extends Omit { cancelToken?: CancelToken; } -export type RequestParams = Omit; +export type RequestParams = Omit< + FullRequestParams, + "body" | "method" | "query" | "path" +>; export interface ApiConfig { baseUrl?: string; baseApiParams?: Omit; - securityWorker?: (securityData: SecurityDataType | null) => Promise | RequestParams | void; + securityWorker?: ( + securityData: SecurityDataType | null, + ) => Promise | RequestParams | void; customFetch?: typeof fetch; } -export interface HttpResponse extends Response { +export interface HttpResponse + extends Response { data: D; error: E; } @@ -350,7 +356,8 @@ export class HttpClient { private securityData: SecurityDataType | null = null; private securityWorker?: ApiConfig["securityWorker"]; private abortControllers = new Map(); - private customFetch = (...fetchParams: Parameters) => fetch(...fetchParams); + private customFetch = (...fetchParams: Parameters) => + fetch(...fetchParams); private baseApiParams: RequestParams = { credentials: "same-origin", @@ -383,9 +390,15 @@ export class HttpClient { protected toQueryString(rawQuery?: QueryParamsType): string { const query = rawQuery || {}; - const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]); + const keys = Object.keys(query).filter( + (key) => "undefined" !== typeof query[key], + ); return keys - .map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key))) + .map((key) => + Array.isArray(query[key]) + ? this.addArrayQueryParam(query, key) + : this.addQueryParam(query, key), + ) .join("&"); } @@ -396,8 +409,13 @@ export class HttpClient { private contentFormatters: Record any> = { [ContentType.Json]: (input: any) => - input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, - [ContentType.Text]: (input: any) => (input !== null && typeof input !== "string" ? JSON.stringify(input) : input), + input !== null && (typeof input === "object" || typeof input === "string") + ? JSON.stringify(input) + : input, + [ContentType.Text]: (input: any) => + input !== null && typeof input !== "string" + ? JSON.stringify(input) + : input, [ContentType.FormData]: (input: any) => Object.keys(input || {}).reduce((formData, key) => { const property = input[key]; @@ -414,7 +432,10 @@ export class HttpClient { [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input), }; - protected mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams { + protected mergeRequestParams( + params1: RequestParams, + params2?: RequestParams, + ): RequestParams { return { ...this.baseApiParams, ...params1, @@ -427,7 +448,9 @@ export class HttpClient { }; } - protected createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => { + protected createAbortSignal = ( + cancelToken: CancelToken, + ): AbortSignal | undefined => { if (this.abortControllers.has(cancelToken)) { const abortController = this.abortControllers.get(cancelToken); if (abortController) { @@ -471,15 +494,26 @@ export class HttpClient { const payloadFormatter = this.contentFormatters[type || ContentType.Json]; const responseFormat = format || requestParams.format; - return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, { - ...requestParams, - headers: { - ...(requestParams.headers || {}), - ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), + return this.customFetch( + `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, + { + ...requestParams, + headers: { + ...(requestParams.headers || {}), + ...(type && type !== ContentType.FormData + ? { "Content-Type": type } + : {}), + }, + signal: + (cancelToken + ? this.createAbortSignal(cancelToken) + : requestParams.signal) || null, + body: + typeof body === "undefined" || body === null + ? null + : payloadFormatter(body), }, - signal: (cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal) || null, - body: typeof body === "undefined" || body === null ? null : payloadFormatter(body), - }).then(async (response) => { + ).then(async (response) => { const r = response.clone() as HttpResponse; r.data = null as unknown as T; r.error = null as unknown as E; @@ -515,7 +549,9 @@ export class HttpClient { * @version 0.1.0 * @baseUrl /api/v1 */ -export class Api extends HttpClient { +export class Api< + SecurityDataType extends unknown, +> extends HttpClient { login = { /** * No description @@ -772,7 +808,11 @@ export class Api extends HttpClient + downloadMultipleObjects: ( + bucketName: string, + objectList: string[], + params: RequestParams = {}, + ) => this.request({ path: `/buckets/${encodeURIComponent(bucketName)}/objects/download-multiple`, method: "POST", @@ -962,7 +1002,11 @@ export class Api extends HttpClient + setBucketVersioning: ( + bucketName: string, + body: SetBucketVersioning, + params: RequestParams = {}, + ) => this.request({ path: `/buckets/${encodeURIComponent(bucketName)}/versioning`, method: "PUT", From 4532f97dc9b54f39019dd882a41c4818fde48a51 Mon Sep 17 00:00:00 2001 From: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com> Date: Wed, 14 May 2025 14:54:36 -0700 Subject: [PATCH 3/7] Fix Test --- api/user_session_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/user_session_test.go b/api/user_session_test.go index 00c4d57695..524d1894cc 100644 --- a/api/user_session_test.go +++ b/api/user_session_test.go @@ -110,7 +110,7 @@ func Test_getListOfEnabledFeatures(t *testing.T) { Hm: true, }, }, - want: []string{"log-search", "oidc-idp", "external-idp", "ldap-idp", "external-idp", "hide-menu"}, + want: []string{"hide-menu"}, preFunc: func() { os.Setenv(ConsoleLogQueryURL, "http://logsearchapi:8080") }, From 1f174b2333005badd653b7066ca4b8bf05f98db2 Mon Sep 17 00:00:00 2001 From: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com> Date: Wed, 14 May 2025 15:01:25 -0700 Subject: [PATCH 4/7] Fix tests --- .github/workflows/jobs.yaml | 190 ++++++++-------------------- integration/user_api_bucket_test.go | 54 -------- 2 files changed, 52 insertions(+), 192 deletions(-) diff --git a/.github/workflows/jobs.yaml b/.github/workflows/jobs.yaml index 42dbe99754..c896890396 100644 --- a/.github/workflows/jobs.yaml +++ b/.github/workflows/jobs.yaml @@ -19,11 +19,11 @@ concurrency: jobs: lint-job: name: Checking Lint - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v4 @@ -46,7 +46,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - os: [ubuntu-latest] + os: [ ubuntu-latest ] steps: - name: Check out source code uses: actions/checkout@v3 @@ -64,8 +64,8 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -109,10 +109,10 @@ jobs: latest-minio: name: Build latest MinIO - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] strategy: matrix: - go-version: [1.23.x] + go-version: [ 1.23.x ] steps: # To build minio image, we need to clone the repository first - name: Clone github.com/minio/minio @@ -150,8 +150,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -185,12 +185,12 @@ jobs: name: Test Subpath with Nginx needs: - compile-binary - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] timeout-minutes: 10 strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -239,12 +239,12 @@ jobs: name: Permissions Tests Part 1 needs: - compile-binary - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] timeout-minutes: 10 strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -292,12 +292,12 @@ jobs: name: Permissions Tests Part 2 needs: - compile-binary - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] timeout-minutes: 10 strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -344,12 +344,12 @@ jobs: name: Permissions Tests Part 3 needs: - compile-binary - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] timeout-minutes: 10 strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -396,12 +396,12 @@ jobs: name: Permissions Tests Part 4 needs: - compile-binary - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] timeout-minutes: 15 strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -445,11 +445,11 @@ jobs: name: Permissions Tests Part 6 needs: - compile-binary - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -493,11 +493,11 @@ jobs: name: Permissions Tests Part B needs: - compile-binary - runs-on: [ubuntu-latest] + runs-on: [ ubuntu-latest ] strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -549,8 +549,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -584,8 +584,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -621,7 +621,7 @@ jobs: strategy: matrix: - go-version: [1.23.x] + go-version: [ 1.23.x ] steps: - name: Check out code @@ -707,103 +707,17 @@ jobs: working-directory: ./web-app run: yarn test - sso-integration: - name: SSO Integration Test - needs: - - lint-job - - ui-assets - - semgrep-static-code-analysis - - latest-minio - runs-on: ubuntu-latest - - strategy: - matrix: - go-version: [1.23.x] - - steps: - - name: Check out code - uses: actions/checkout@v3 - - - name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }} - uses: actions/setup-go@v5 - with: - go-version: ${{ matrix.go-version }} - id: go - - - name: Clone github.com/minio/minio - uses: actions/checkout@master - with: - repository: minio/minio - path: "minio_repository" - - name: Check-out matching MinIO branch - env: - GH_BRANCH: ${{ github.head_ref || github.ref_name }} - GH_PR_REPO: ${{ github.event.pull_request.head.repo.full_name }} - run: | - GH_PR_ACCOUNT=`echo $GH_PR_REPO | sed "s/\\/.*//"` - if [ ! -z "$GH_PR_ACCOUNT" ] && [ ! "$GH_PR_ACCOUNT" = "minio" ]; then - ALTREPO="https://github.com/$GH_PR_ACCOUNT/minio.git" - echo "Attempting to fetch $ALTREPO..." - git remote add alt $ALTREPO - (git fetch alt && git checkout "alt/$GH_BRANCH") || echo "$ALTREPO ($GH_BRANCH) not available, so keeping default repository/branch" - fi - - - name: Checkout proper minio/minio branch - run: | - - git checkout "${{ github.head_ref || github.ref_name }}" || echo "Okay, we'll stay on the master branch" - - - uses: actions/cache@v4 - id: minio-latest-cache - name: MinIO Latest Cache - with: - path: | - ./minio - key: ${{ runner.os }}-minio-latest-${{ hashFiles('./minio_repository/go.sum') }} - - - name: Build on ${{ matrix.os }} - run: | - echo "The idea is to build minio image from downloaded repository"; - cd $GITHUB_WORKSPACE/minio_repository; - echo "replace github.com/minio/console => ../" >> go.mod - - echo "updates to go.mod needed; to update it: go mod tidy" - go mod tidy -compat=1.23 - - echo "Get git version to build MinIO Image"; - VERSION=`git rev-parse HEAD`; - echo $VERSION; - echo "Create MinIO image"; - make docker VERSION=$VERSION; - - docker build -q --no-cache -t minio/minio:$VERSION . -f Dockerfile - echo "Jumping back to console repository to run the integration test" - cd $GITHUB_WORKSPACE; - - echo "We are going to use the built image on test-integration"; - MINIO_VERSION="minio/minio:$VERSION"; - echo $MINIO_VERSION; - - make test-sso-integration MINIO_VERSION=$MINIO_VERSION; - - uses: actions/cache@v4 - id: coverage-cache-sso - name: Coverage Cache SSO - with: - path: | - ./sso-integration/coverage/ - key: ${{ runner.os }}-sso-coverage-2-${{ github.run_id }} coverage: name: "Coverage Limit Check" needs: - b-integration-tests - test-api-on-go - test-pkg-on-go - - sso-integration runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -928,8 +842,8 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -970,8 +884,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -1010,8 +924,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -1038,8 +952,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -1065,8 +979,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -1093,8 +1007,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 @@ -1121,8 +1035,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - go-version: [1.23.x] - os: [ubuntu-latest] + go-version: [ 1.23.x ] + os: [ ubuntu-latest ] steps: - name: Check out code uses: actions/checkout@v3 diff --git a/integration/user_api_bucket_test.go b/integration/user_api_bucket_test.go index a1de0f9a89..8ec3687078 100644 --- a/integration/user_api_bucket_test.go +++ b/integration/user_api_bucket_test.go @@ -515,60 +515,6 @@ func TestRestoreObjectToASelectedVersion(t *testing.T) { } } -func TestPutBucketsTags(t *testing.T) { - // Focused test for "Put Bucket's tags" endpoint - - // 1. Create the bucket - assert := assert.New(t) - validBucketName := "testputbuckettags1" - if !setupBucket(validBucketName, false, nil, nil, nil, assert, 200) { - return - } - - type args struct { - bucketName string - } - tests := []struct { - name string - expectedStatus int - args args - }{ - { - name: "Put a tag to a valid bucket", - expectedStatus: 200, - args: args{ - bucketName: validBucketName, - }, - }, - { - name: "Put a tag to an invalid bucket", - expectedStatus: 500, - args: args{ - bucketName: "invalidbucketname", - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(_ *testing.T) { - // 2. Add a tag to the bucket - tags := make(map[string]string) - tags["tag2"] = "tag2" - putBucketTagResponse, putBucketTagError := PutBucketsTags( - tt.args.bucketName, tags) - if putBucketTagError != nil { - log.Println(putBucketTagError) - assert.Fail("Error putting the bucket's tags") - return - } - if putBucketTagResponse != nil { - assert.Equal( - tt.expectedStatus, putBucketTagResponse.StatusCode, - inspectHTTPResponse(putBucketTagResponse)) - } - }) - } -} - func TestGetsTheMetadataOfAnObject(t *testing.T) { // Vars assert := assert.New(t) From b3974e2ceb5f090c85b352c77e5e58c90a829496 Mon Sep 17 00:00:00 2001 From: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com> Date: Wed, 14 May 2025 15:04:02 -0700 Subject: [PATCH 5/7] Remove SSO Integreation --- .github/workflows/jobs.yaml | 15 +- Makefile | 50 ----- sso-integration/Dockerfile | 3 - sso-integration/allaccess.json | 14 -- sso-integration/config.docker.yaml | 23 --- sso-integration/dex-requests.py | 14 -- sso-integration/set-sso.sh | 9 - sso-integration/sso_test.go | 295 ----------------------------- 8 files changed, 1 insertion(+), 422 deletions(-) delete mode 100644 sso-integration/Dockerfile delete mode 100644 sso-integration/allaccess.json delete mode 100644 sso-integration/config.docker.yaml delete mode 100644 sso-integration/dex-requests.py delete mode 100755 sso-integration/set-sso.sh delete mode 100644 sso-integration/sso_test.go diff --git a/.github/workflows/jobs.yaml b/.github/workflows/jobs.yaml index c896890396..02909b89cf 100644 --- a/.github/workflows/jobs.yaml +++ b/.github/workflows/jobs.yaml @@ -740,14 +740,6 @@ jobs: ./integration/coverage/ key: ${{ runner.os }}-coverage-2-${{ github.run_id }} - - uses: actions/cache@v4 - id: coverage-cache-sso - name: Coverage Cache SSO - with: - path: | - ./sso-integration/coverage/ - key: ${{ runner.os }}-sso-coverage-2-${{ github.run_id }} - - uses: actions/cache@v4 id: coverage-cache-api name: Coverage Cache API @@ -775,7 +767,7 @@ jobs: echo "go build gocoverage.go" go build gocovmerge.go echo "put together the outs for final coverage resolution" - ./gocovmerge ../integration/coverage/system.out ../sso-integration/coverage/sso-system.out ../api/coverage/coverage.out ../pkg/coverage/coverage-pkg.out > all.out + ./gocovmerge ../integration/coverage/system.out ../api/coverage/coverage.out ../pkg/coverage/coverage-pkg.out > all.out echo "Download mc for Ubuntu" wget -q https://dl.min.io/client/mc/release/linux-amd64/mc echo "Change the permissions to execute mc command" @@ -804,11 +796,6 @@ jobs: ./mc cp system.html play/builds/${{ github.repository }}/${{ github.event.number }}/latest/ || true ./mc cp ../integration/coverage/system.out play/builds/${{ github.repository }}/${{ github.event.number }}/${{ github.run_id }}/ || true ./mc cp ../integration/coverage/system.out play/builds/${{ github.repository }}/${{ github.event.number }}/latest/ || true - go tool cover -html=../sso-integration/coverage/sso-system.out -o sso-system.html - ./mc cp sso-system.html play/builds/${{ github.repository }}/${{ github.event.number }}/${{ github.run_id }}/ || true - ./mc cp sso-system.html play/builds/${{ github.repository }}/${{ github.event.number }}/latest/ || true - ./mc cp ../sso-integration/coverage/sso-system.out play/builds/${{ github.repository }}/${{ github.event.number }}/${{ github.run_id }}/ || true - ./mc cp ../sso-integration/coverage/sso-system.out play/builds/${{ github.repository }}/${{ github.event.number }}/latest/ || true go tool cover -html=../api/coverage/coverage.out -o coverage.html ./mc cp coverage.html play/builds/${{ github.repository }}/${{ github.event.number }}/${{ github.run_id }}/ || true ./mc cp coverage.html play/builds/${{ github.repository }}/${{ github.event.number }}/latest/ || true diff --git a/Makefile b/Makefile index 1a7828f4c1..5371233480 100644 --- a/Makefile +++ b/Makefile @@ -140,56 +140,6 @@ test-replication: @(docker stop minio2 || true) @(docker network rm mynet123 || true) -test-sso-integration: - @echo "create the network in bridge mode to communicate all containers" - @(docker network create my-net) - @echo "run openldap container using MinIO Image: quay.io/minio/openldap:latest" - @(docker run \ - -e LDAP_ORGANIZATION="MinIO Inc" \ - -e LDAP_DOMAIN="min.io" \ - -e LDAP_ADMIN_PASSWORD="admin" \ - --network my-net \ - -p 389:389 \ - -p 636:636 \ - --name openldap \ - --detach quay.io/minio/openldap:latest) - @echo "Run Dex container using MinIO Image: quay.io/minio/dex:latest" - @(docker run \ - -e DEX_ISSUER=http://dex:5556/dex \ - -e DEX_CLIENT_REDIRECT_URI=http://127.0.0.1:9090/oauth_callback \ - -e DEX_LDAP_SERVER=openldap:389 \ - --network my-net \ - -p 5556:5556 \ - --name dex \ - --detach quay.io/minio/dex:latest) - @echo "running minio server" - @(docker run \ - -v /data1 -v /data2 -v /data3 -v /data4 \ - --network my-net \ - -d \ - --name minio \ - --rm \ - -p 9000:9000 \ - -p 9001:9001 \ - -e MINIO_IDENTITY_OPENID_CLIENT_ID="minio-client-app" \ - -e MINIO_IDENTITY_OPENID_CLIENT_SECRET="minio-client-app-secret" \ - -e MINIO_IDENTITY_OPENID_CLAIM_NAME=name \ - -e MINIO_IDENTITY_OPENID_CONFIG_URL=http://dex:5556/dex/.well-known/openid-configuration \ - -e MINIO_IDENTITY_OPENID_REDIRECT_URI=http://127.0.0.1:9090/oauth_callback \ - -e MINIO_ROOT_USER=minio \ - -e MINIO_ROOT_PASSWORD=minio123 $(MINIO_VERSION) server /data{1...4} --address :9000 --console-address :9001) - @echo "run mc commands to set the policy" - @(docker run --name minio-client --network my-net -dit --entrypoint=/bin/sh minio/mc) - @(docker exec minio-client mc alias set myminio/ http://minio:9000 minio minio123) - @echo "adding policy to Dillon Harper to be able to login:" - @(cd sso-integration && docker cp allaccess.json minio-client:/ && docker exec minio-client mc admin policy create myminio "Dillon Harper" allaccess.json) - @echo "starting bash script" - @(env bash $(PWD)/sso-integration/set-sso.sh) - @echo "add python module" - @(pip3 install bs4) - @echo "Executing the test:" - @(cd sso-integration && go test -coverpkg=../api -c -tags testrunmain . && mkdir -p coverage && ./sso-integration.test -test.v -test.run "^Test*" -test.coverprofile=coverage/sso-system.out) - test-permissions-1: @(docker run -v /data1 -v /data2 -v /data3 -v /data4 -d --name minio --rm -p 9000:9000 quay.io/minio/minio:latest server /data{1...4}) @(env bash $(PWD)/web-app/tests/scripts/permissions.sh "web-app/tests/permissions-1/") diff --git a/sso-integration/Dockerfile b/sso-integration/Dockerfile deleted file mode 100644 index 8d55afae23..0000000000 --- a/sso-integration/Dockerfile +++ /dev/null @@ -1,3 +0,0 @@ -FROM ghcr.io/dexidp/dex:latest - -ADD config.docker.yaml /etc/dex/ diff --git a/sso-integration/allaccess.json b/sso-integration/allaccess.json deleted file mode 100644 index 975e66cef1..0000000000 --- a/sso-integration/allaccess.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": [ - "s3:*" - ], - "Resource": [ - "arn:aws:s3:::*" - ] - } - ] -} diff --git a/sso-integration/config.docker.yaml b/sso-integration/config.docker.yaml deleted file mode 100644 index 6ad0282ecc..0000000000 --- a/sso-integration/config.docker.yaml +++ /dev/null @@ -1,23 +0,0 @@ -issuer: http://dex:5556/dex -storage: - type: sqlite3 - config: - file: /var/dex/dex.db -web: - http: 0.0.0.0:5556 -staticClients: -- id: minio-client-app - secret: minio-client-app-secret - name: 'MinIO Example Client App' - redirectURIs: - - 'http://127.0.0.1:9001/oauth_callback' -connectors: -- type: mockCallback - id: mock - name: Example -enablePasswordDB: true -staticPasswords: -- email: "admin@example.com" - hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W" - username: "admin" - userID: "08a8684b-db88-4b73-90a9-3cd1661f5466" diff --git a/sso-integration/dex-requests.py b/sso-integration/dex-requests.py deleted file mode 100644 index 8f9aa8304b..0000000000 --- a/sso-integration/dex-requests.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import pdb, sys, requests -from bs4 import BeautifulSoup - -# Log in to Your Account via OpenLDAP Connector -result = requests.get(sys.argv[1]) -soup = BeautifulSoup(result.text, "html.parser") -url = "http://dex:5556" + soup.findAll('a')[1].get('href') -result = requests.get(url) -soup = BeautifulSoup(result.text, "html.parser") -url = "http://dex:5556" + soup.form.get('action') -print(url) diff --git a/sso-integration/set-sso.sh b/sso-integration/set-sso.sh deleted file mode 100755 index 96665ad9be..0000000000 --- a/sso-integration/set-sso.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh - -echo "127.0.0.1 dex" | sudo tee -a /etc/hosts -echo " " -echo " " -echo "/etc/hosts:" -cat /etc/hosts -echo " " -echo " " diff --git a/sso-integration/sso_test.go b/sso-integration/sso_test.go deleted file mode 100644 index 0e75143cd9..0000000000 --- a/sso-integration/sso_test.go +++ /dev/null @@ -1,295 +0,0 @@ -// This file is part of MinIO Console Server -// Copyright (c) 2021 MinIO, Inc. -// -// 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 . - -package ssointegration - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "log" - "net/http" - "net/url" - "os/exec" - "strings" - "testing" - "time" - - "github.com/minio/console/models" - - "github.com/go-openapi/loads" - "github.com/minio/console/api" - "github.com/minio/console/api/operations" - consoleoauth2 "github.com/minio/console/pkg/auth/idp/oauth2" - "github.com/stretchr/testify/assert" -) - -var token string - -func initConsoleServer(consoleIDPURL string) (*api.Server, error) { - // Configure Console Server with vars to get the idp config from the container - pcfg := map[string]consoleoauth2.ProviderConfig{ - "_": { - URL: consoleIDPURL, - ClientID: "minio-client-app", - ClientSecret: "minio-client-app-secret", - RedirectCallback: "http://127.0.0.1:9090/oauth_callback", - }, - } - - swaggerSpec, err := loads.Embedded(api.SwaggerJSON, api.FlatSwaggerJSON) - if err != nil { - return nil, err - } - - noLog := func(string, ...interface{}) { - // nothing to log - } - - // Initialize MinIO loggers - api.LogInfo = noLog - api.LogError = noLog - - consoleAPI := operations.NewConsoleAPI(swaggerSpec) - consoleAPI.Logger = noLog - - api.GlobalMinIOConfig = api.MinIOConfig{ - OpenIDProviders: pcfg, - } - - server := api.NewServer(consoleAPI) - // register all APIs - server.ConfigureAPI() - - server.Host = "0.0.0.0" - server.Port = 9090 - api.Port = "9090" - api.Hostname = "0.0.0.0" - - return server, nil -} - -func TestMainSSO(t *testing.T) { - assert := assert.New(t) - - // start console server - go func() { - fmt.Println("start server") - srv, err := initConsoleServer("http://dex:5556/dex/.well-known/openid-configuration") - if err != nil { - log.Println(err) - log.Println("init fail") - return - } - srv.Serve() - }() - - fmt.Println("sleeping") - time.Sleep(2 * time.Second) - - client := &http.Client{ - Timeout: 2 * time.Second, - } - - // Let's move this API here to increment our coverage - getRequest, getError := http.NewRequest("GET", "http://localhost:9090/api/v1/login", nil) - if getError != nil { - log.Println(getError) - return - } - getRequest.Header.Add("Content-Type", "application/json") - getResponse, getErr := client.Do(getRequest) - // current value: - // {"loginStrategy":"form"} - // but we want our console server to provide loginStrategy = redirect for SSO - if getErr != nil { - log.Println(getErr) - return - } - - body, err := io.ReadAll(getResponse.Body) - getResponse.Body.Close() - if getResponse.StatusCode > 299 { - log.Fatalf("Response failed with status code: %d and\nbody: %s\n", getResponse.StatusCode, body) - } - if err != nil { - log.Fatal(err) - } - var jsonMap models.LoginDetails - - fmt.Println(body) - - err = json.Unmarshal(body, &jsonMap) - if err != nil { - fmt.Printf("error JSON Unmarshal %s\n", err) - } - - if len(jsonMap.RedirectRules) == 0 { - assert.Fail("redirect rules not found") - } else { - fmt.Println("redirect rules found") - } - redirectRule := jsonMap.RedirectRules[0] - redirectAsString := fmt.Sprint(redirectRule.Redirect) - fmt.Println(redirectAsString) - - // execute script to get the code and state - cmd, err := exec.Command("python3", "dex-requests.py", redirectAsString).Output() - if err != nil { - fmt.Printf("error %s\n", err) - } - urlOutput := string(cmd) - fmt.Println("url output:", urlOutput) - requestLoginBody := bytes.NewReader([]byte("login=dillon%40example.io&password=dillon")) - - // parse url remove carriage return - temp2 := strings.Split(urlOutput, "\n") - fmt.Println("temp2: ", temp2) - urlOutput = temp2[0] // remove carriage return to avoid invalid control character in url - - // validate url - urlParseResult, urlParseError := url.Parse(urlOutput) - if urlParseError != nil { - panic(urlParseError) - } - fmt.Println(urlParseResult) - - // prepare for post - httpRequestLogin, newRequestError := http.NewRequest( - "POST", - urlOutput, - requestLoginBody, - ) - if newRequestError != nil { - fmt.Println(newRequestError) - } - httpRequestLogin.Header.Add("Content-Type", "application/x-www-form-urlencoded") - responseLogin, errorLogin := client.Do(httpRequestLogin) - if errorLogin != nil { - log.Println(errorLogin) - } - rawQuery := responseLogin.Request.URL.RawQuery - fmt.Println(rawQuery) - splitRawQuery := strings.Split(rawQuery, "&state=") - codeValue := strings.ReplaceAll(splitRawQuery[0], "code=", "") - stateValue := splitRawQuery[1] - fmt.Println("stop", splitRawQuery, codeValue, stateValue) - - // get login credentials - codeVarIable := strings.TrimSpace(codeValue) - stateVarIabl := strings.TrimSpace(stateValue) - requestData := map[string]string{ - "code": codeVarIable, - "state": stateVarIabl, - } - requestDataJSON, _ := json.Marshal(requestData) - - requestDataBody := bytes.NewReader(requestDataJSON) - - request, _ := http.NewRequest( - "POST", - "http://localhost:9090/api/v1/login/oauth2/auth", - requestDataBody, - ) - request.Header.Add("Content-Type", "application/json") - - response, err := client.Do(request) - if err != nil { - log.Println(err) - } - if response != nil { - for _, cookie := range response.Cookies() { - if cookie.Name == "token" { - token = cookie.Value - break - } - } - } - fmt.Println(response.Status) - if token == "" { - assert.Fail("authentication token not found in cookies response") - } else { - fmt.Println(token) - } -} - -func TestBadLogin(t *testing.T) { - assert := assert.New(t) - - // start console server - go func() { - fmt.Println("start server") - srv, err := initConsoleServer("http://dex:5556") - if err != nil { - log.Println(err) - log.Println("init fail") - return - } - srv.Serve() - }() - fmt.Println("sleeping") - time.Sleep(2 * time.Second) - - client := &http.Client{ - Timeout: 2 * time.Second, - } - - encodeItem := consoleoauth2.LoginURLParams{ - State: "invalidState", - IDPName: "_", - } - - jsonState, err := json.Marshal(encodeItem) - if err != nil { - log.Println(err) - assert.Nil(err) - } - - // get login credentials - stateVarIable := base64.StdEncoding.EncodeToString(jsonState) - - codeVarIable := "invalidCode" - - requestData := map[string]string{ - "code": codeVarIable, - "state": stateVarIable, - } - requestDataJSON, _ := json.Marshal(requestData) - - requestDataBody := bytes.NewReader(requestDataJSON) - - request, _ := http.NewRequest( - "POST", - "http://localhost:9090/api/v1/login/oauth2/auth", - requestDataBody, - ) - request.Header.Add("Content-Type", "application/json") - - response, err := client.Do(request) - fmt.Println(response) - fmt.Println(err) - expectedError := response.Status - assert.Equal("400 Bad Request", expectedError) - bodyBytes, _ := io.ReadAll(response.Body) - result2 := models.APIError{} - err = json.Unmarshal(bodyBytes, &result2) - if err != nil { - log.Println(err) - assert.Nil(err) - } -} From f472cb4c08202ceabd2a8cc7e42f8f55c55d71c9 Mon Sep 17 00:00:00 2001 From: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com> Date: Wed, 14 May 2025 15:27:17 -0700 Subject: [PATCH 6/7] fix tests --- integration/user_api_bucket_test.go | 138 +--------------------------- 1 file changed, 1 insertion(+), 137 deletions(-) diff --git a/integration/user_api_bucket_test.go b/integration/user_api_bucket_test.go index 8ec3687078..25115cd298 100644 --- a/integration/user_api_bucket_test.go +++ b/integration/user_api_bucket_test.go @@ -1,5 +1,5 @@ // This file is part of MinIO Console Server -// Copyright (c) 2021 MinIO, Inc. +// Copyright (c) 2023 MinIO, Inc. // // 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 @@ -379,34 +379,6 @@ func GetsTheMetadataOfAnObject(bucketName, prefix string) (*http.Response, error return response, err } -func PutBucketsTags(bucketName string, tags map[string]string) (*http.Response, error) { - /* - Helper function to put bucket's tags. - PUT: {{baseUrl}}/buckets/:bucket_name/tags - { - "tags": {} - } - */ - requestDataAdd := map[string]interface{}{ - "tags": tags, - } - requestDataJSON, _ := json.Marshal(requestDataAdd) - requestDataBody := bytes.NewReader(requestDataJSON) - request, err := http.NewRequest("PUT", - "http://localhost:9090/api/v1/buckets/"+bucketName+"/tags", - requestDataBody) - if err != nil { - log.Println(err) - } - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - client := &http.Client{ - Timeout: 2 * time.Second, - } - response, err := client.Do(request) - return response, err -} - func RestoreObjectToASelectedVersion(bucketName, prefix, versionID string) (*http.Response, error) { request, err := http.NewRequest( "PUT", @@ -1019,22 +991,6 @@ func TestBucketInformationGenericErrorResponse(t *testing.T) { return } - // 2. Add a tag to the bucket - tags := make(map[string]string) - tags["tag2"] = "tag2" - putBucketTagResponse, putBucketTagError := PutBucketsTags( - "bucketinformation2", tags) - if putBucketTagError != nil { - log.Println(putBucketTagError) - assert.Fail("Error putting the bucket's tags") - return - } - if putBucketTagResponse != nil { - assert.Equal( - 200, putBucketTagResponse.StatusCode, - inspectHTTPResponse(putBucketTagResponse)) - } - // 3. Get the information bucketInfoResponse, bucketInfoError := BucketInfo("bucketinformation3") if bucketInfoError != nil { @@ -1042,15 +998,10 @@ func TestBucketInformationGenericErrorResponse(t *testing.T) { assert.Fail("Error getting the bucket information") return } - finalResponse := inspectHTTPResponse(bucketInfoResponse) if bucketInfoResponse != nil { assert.Equal(200, bucketInfoResponse.StatusCode) } - // 4. Verify the information - // Since bucketinformation3 hasn't been created, then it is expected that - // tag2 is not part of the response, this is why assert.False is used. - assert.False(strings.Contains(finalResponse, "tag2"), finalResponse) } func TestBucketInformationSuccessfulResponse(t *testing.T) { @@ -1064,22 +1015,6 @@ func TestBucketInformationSuccessfulResponse(t *testing.T) { return } - // 2. Add a tag to the bucket - tags := make(map[string]string) - tags["tag1"] = "tag1" - putBucketTagResponse, putBucketTagError := PutBucketsTags( - "bucketinformation1", tags) - if putBucketTagError != nil { - log.Println(putBucketTagError) - assert.Fail("Error putting the bucket's tags") - return - } - if putBucketTagResponse != nil { - assert.Equal( - 200, putBucketTagResponse.StatusCode, - inspectHTTPResponse(putBucketTagResponse)) - } - // 3. Get the information bucketInfoResponse, bucketInfoError := BucketInfo("bucketinformation1") if bucketInfoError != nil { @@ -1098,9 +1033,6 @@ func TestBucketInformationSuccessfulResponse(t *testing.T) { assert.True( strings.Contains(debugResponse, "bucketinformation1"), inspectHTTPResponse(bucketInfoResponse)) - assert.True( - strings.Contains(debugResponse, "tag1"), - inspectHTTPResponse(bucketInfoResponse)) } func TestListBuckets(t *testing.T) { @@ -1176,74 +1108,6 @@ func TestBucketsGet(t *testing.T) { } } -func TestSetBucketTags(t *testing.T) { - assert := assert.New(t) - - client := &http.Client{ - Timeout: 2 * time.Second, - } - - // put bucket - if !setupBucket("test4", false, nil, nil, nil, assert, 200) { - return - } - - requestDataTags := map[string]interface{}{ - "tags": map[string]interface{}{ - "test": "TAG", - }, - } - - requestTagsJSON, _ := json.Marshal(requestDataTags) - - requestTagsBody := bytes.NewBuffer(requestTagsJSON) - - request, err := http.NewRequest(http.MethodPut, "http://localhost:9090/api/v1/buckets/test4/tags", requestTagsBody) - request.Close = true - if err != nil { - log.Println(err) - return - } - - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - - _, err = client.Do(request) - assert.Nil(err) - if err != nil { - log.Println(err) - return - } - - // get bucket - request, err = http.NewRequest("GET", "http://localhost:9090/api/v1/buckets/test4", nil) - request.Close = true - if err != nil { - log.Println(err) - return - } - - request.Header.Add("Cookie", fmt.Sprintf("token=%s", token)) - request.Header.Add("Content-Type", "application/json") - - response, err := client.Do(request) - assert.Nil(err) - if err != nil { - log.Println(err) - return - } - - bodyBytes, _ := io.ReadAll(response.Body) - - bucket := models.Bucket{} - err = json.Unmarshal(bodyBytes, &bucket) - if err != nil { - log.Println(err) - } - - assert.Equal("TAG", bucket.Details.Tags["test"], "Failed to add tag") -} - func TestGetBucket(t *testing.T) { assert := assert.New(t) From 2482fa7a13dd51a9d49b9086d959c3128f1e56f2 Mon Sep 17 00:00:00 2001 From: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com> Date: Wed, 14 May 2025 15:29:31 -0700 Subject: [PATCH 7/7] lint --- integration/user_api_bucket_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/integration/user_api_bucket_test.go b/integration/user_api_bucket_test.go index 25115cd298..8eda25e9fb 100644 --- a/integration/user_api_bucket_test.go +++ b/integration/user_api_bucket_test.go @@ -1001,7 +1001,6 @@ func TestBucketInformationGenericErrorResponse(t *testing.T) { if bucketInfoResponse != nil { assert.Equal(200, bucketInfoResponse.StatusCode) } - } func TestBucketInformationSuccessfulResponse(t *testing.T) {