diff --git a/models/set_administrators_request.go b/models/set_administrators_request.go new file mode 100644 index 000000000..0838e319c --- /dev/null +++ b/models/set_administrators_request.go @@ -0,0 +1,70 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// This file is part of MinIO Console Server +// Copyright (c) 2022 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" +) + +// SetAdministratorsRequest set administrators request +// +// swagger:model setAdministratorsRequest +type SetAdministratorsRequest struct { + + // group dns + GroupDNS []string `json:"group_dns"` + + // user dns + UserDNS []string `json:"user_dns"` +} + +// Validate validates this set administrators request +func (m *SetAdministratorsRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this set administrators request based on context it is used +func (m *SetAdministratorsRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SetAdministratorsRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SetAdministratorsRequest) UnmarshalBinary(b []byte) error { + var res SetAdministratorsRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/models/tenant_monitoring_info.go b/models/tenant_monitoring_info.go index 5e415f09a..b3770458a 100644 --- a/models/tenant_monitoring_info.go +++ b/models/tenant_monitoring_info.go @@ -42,9 +42,6 @@ type TenantMonitoringInfo struct { // disk capacity g b DiskCapacityGB string `json:"diskCapacityGB,omitempty"` - // fs group - FsGroup string `json:"fsGroup,omitempty"` - // image Image string `json:"image,omitempty"` diff --git a/operatorapi/embedded_spec.go b/operatorapi/embedded_spec.go index 68aed379d..4eced0d80 100644 --- a/operatorapi/embedded_spec.go +++ b/operatorapi/embedded_spec.go @@ -1704,6 +1704,48 @@ func init() { } } }, + "/namespaces/{namespace}/tenants/{tenant}/set-administrators": { + "post": { + "tags": [ + "OperatorAPI" + ], + "summary": "Set the consoleAdmin policy to the specified users and groups", + "operationId": "SetTenantAdministrators", + "parameters": [ + { + "type": "string", + "name": "namespace", + "in": "path", + "required": true + }, + { + "type": "string", + "name": "tenant", + "in": "path", + "required": true + }, + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/setAdministratorsRequest" + } + } + ], + "responses": { + "204": { + "description": "A successful response." + }, + "default": { + "description": "Generic error response.", + "schema": { + "$ref": "#/definitions/error" + } + } + } + } + }, "/namespaces/{namespace}/tenants/{tenant}/usage": { "get": { "tags": [ @@ -4005,6 +4047,23 @@ func init() { } } }, + "setAdministratorsRequest": { + "type": "object", + "properties": { + "group_dns": { + "type": "array", + "items": { + "type": "string" + } + }, + "user_dns": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, "state": { "type": "object", "properties": { @@ -4274,9 +4333,6 @@ func init() { "diskCapacityGB": { "type": "string" }, - "fsGroup": { - "type": "string" - }, "image": { "type": "string" }, @@ -6400,6 +6456,48 @@ func init() { } } }, + "/namespaces/{namespace}/tenants/{tenant}/set-administrators": { + "post": { + "tags": [ + "OperatorAPI" + ], + "summary": "Set the consoleAdmin policy to the specified users and groups", + "operationId": "SetTenantAdministrators", + "parameters": [ + { + "type": "string", + "name": "namespace", + "in": "path", + "required": true + }, + { + "type": "string", + "name": "tenant", + "in": "path", + "required": true + }, + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/setAdministratorsRequest" + } + } + ], + "responses": { + "204": { + "description": "A successful response." + }, + "default": { + "description": "Generic error response.", + "schema": { + "$ref": "#/definitions/error" + } + } + } + } + }, "/namespaces/{namespace}/tenants/{tenant}/usage": { "get": { "tags": [ @@ -9397,6 +9495,23 @@ func init() { } } }, + "setAdministratorsRequest": { + "type": "object", + "properties": { + "group_dns": { + "type": "array", + "items": { + "type": "string" + } + }, + "user_dns": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, "state": { "type": "object", "properties": { @@ -9666,9 +9781,6 @@ func init() { "diskCapacityGB": { "type": "string" }, - "fsGroup": { - "type": "string" - }, "image": { "type": "string" }, diff --git a/operatorapi/operations/operator_api.go b/operatorapi/operations/operator_api.go index 95f008dbc..059dada6b 100644 --- a/operatorapi/operations/operator_api.go +++ b/operatorapi/operations/operator_api.go @@ -175,6 +175,9 @@ func NewOperatorAPI(spec *loads.Document) *OperatorAPI { AuthSessionCheckHandler: auth.SessionCheckHandlerFunc(func(params auth.SessionCheckParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation auth.SessionCheck has not yet been implemented") }), + OperatorAPISetTenantAdministratorsHandler: operator_api.SetTenantAdministratorsHandlerFunc(func(params operator_api.SetTenantAdministratorsParams, principal *models.Principal) middleware.Responder { + return middleware.NotImplemented("operation operator_api.SetTenantAdministrators has not yet been implemented") + }), OperatorAPISetTenantLogsHandler: operator_api.SetTenantLogsHandlerFunc(func(params operator_api.SetTenantLogsParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation operator_api.SetTenantLogs has not yet been implemented") }), @@ -355,6 +358,8 @@ type OperatorAPI struct { OperatorAPIPutTenantYAMLHandler operator_api.PutTenantYAMLHandler // AuthSessionCheckHandler sets the operation handler for the session check operation AuthSessionCheckHandler auth.SessionCheckHandler + // OperatorAPISetTenantAdministratorsHandler sets the operation handler for the set tenant administrators operation + OperatorAPISetTenantAdministratorsHandler operator_api.SetTenantAdministratorsHandler // OperatorAPISetTenantLogsHandler sets the operation handler for the set tenant logs operation OperatorAPISetTenantLogsHandler operator_api.SetTenantLogsHandler // OperatorAPISetTenantMonitoringHandler sets the operation handler for the set tenant monitoring operation @@ -585,6 +590,9 @@ func (o *OperatorAPI) Validate() error { if o.AuthSessionCheckHandler == nil { unregistered = append(unregistered, "auth.SessionCheckHandler") } + if o.OperatorAPISetTenantAdministratorsHandler == nil { + unregistered = append(unregistered, "operator_api.SetTenantAdministratorsHandler") + } if o.OperatorAPISetTenantLogsHandler == nil { unregistered = append(unregistered, "operator_api.SetTenantLogsHandler") } @@ -888,6 +896,10 @@ func (o *OperatorAPI) initHandlerCache() { o.handlers["GET"] = make(map[string]http.Handler) } o.handlers["GET"]["/session"] = auth.NewSessionCheck(o.context, o.AuthSessionCheckHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/namespaces/{namespace}/tenants/{tenant}/set-administrators"] = operator_api.NewSetTenantAdministrators(o.context, o.OperatorAPISetTenantAdministratorsHandler) if o.handlers["PUT"] == nil { o.handlers["PUT"] = make(map[string]http.Handler) } diff --git a/operatorapi/operations/operator_api/set_tenant_administrators.go b/operatorapi/operations/operator_api/set_tenant_administrators.go new file mode 100644 index 000000000..c813bc675 --- /dev/null +++ b/operatorapi/operations/operator_api/set_tenant_administrators.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// This file is part of MinIO Console Server +// Copyright (c) 2022 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 operator_api + +// 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" +) + +// SetTenantAdministratorsHandlerFunc turns a function with the right signature into a set tenant administrators handler +type SetTenantAdministratorsHandlerFunc func(SetTenantAdministratorsParams, *models.Principal) middleware.Responder + +// Handle executing the request and returning a response +func (fn SetTenantAdministratorsHandlerFunc) Handle(params SetTenantAdministratorsParams, principal *models.Principal) middleware.Responder { + return fn(params, principal) +} + +// SetTenantAdministratorsHandler interface for that can handle valid set tenant administrators params +type SetTenantAdministratorsHandler interface { + Handle(SetTenantAdministratorsParams, *models.Principal) middleware.Responder +} + +// NewSetTenantAdministrators creates a new http.Handler for the set tenant administrators operation +func NewSetTenantAdministrators(ctx *middleware.Context, handler SetTenantAdministratorsHandler) *SetTenantAdministrators { + return &SetTenantAdministrators{Context: ctx, Handler: handler} +} + +/* SetTenantAdministrators swagger:route POST /namespaces/{namespace}/tenants/{tenant}/set-administrators OperatorAPI setTenantAdministrators + +Set the consoleAdmin policy to the specified users and groups + +*/ +type SetTenantAdministrators struct { + Context *middleware.Context + Handler SetTenantAdministratorsHandler +} + +func (o *SetTenantAdministrators) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewSetTenantAdministratorsParams() + 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/operatorapi/operations/operator_api/set_tenant_administrators_parameters.go b/operatorapi/operations/operator_api/set_tenant_administrators_parameters.go new file mode 100644 index 000000000..3a09ca00b --- /dev/null +++ b/operatorapi/operations/operator_api/set_tenant_administrators_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// This file is part of MinIO Console Server +// Copyright (c) 2022 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 operator_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "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" +) + +// NewSetTenantAdministratorsParams creates a new SetTenantAdministratorsParams object +// +// There are no default values defined in the spec. +func NewSetTenantAdministratorsParams() SetTenantAdministratorsParams { + + return SetTenantAdministratorsParams{} +} + +// SetTenantAdministratorsParams contains all the bound params for the set tenant administrators operation +// typically these are obtained from a http.Request +// +// swagger:parameters SetTenantAdministrators +type SetTenantAdministratorsParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /* + Required: true + In: body + */ + Body *models.SetAdministratorsRequest + /* + Required: true + In: path + */ + Namespace string + /* + Required: true + In: path + */ + Tenant 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 NewSetTenantAdministratorsParams() beforehand. +func (o *SetTenantAdministratorsParams) 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.SetAdministratorsRequest + 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(context.Background()) + 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", "")) + } + + rNamespace, rhkNamespace, _ := route.Params.GetOK("namespace") + if err := o.bindNamespace(rNamespace, rhkNamespace, route.Formats); err != nil { + res = append(res, err) + } + + rTenant, rhkTenant, _ := route.Params.GetOK("tenant") + if err := o.bindTenant(rTenant, rhkTenant, route.Formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindNamespace binds and validates parameter Namespace from path. +func (o *SetTenantAdministratorsParams) bindNamespace(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.Namespace = raw + + return nil +} + +// bindTenant binds and validates parameter Tenant from path. +func (o *SetTenantAdministratorsParams) bindTenant(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.Tenant = raw + + return nil +} diff --git a/operatorapi/operations/operator_api/set_tenant_administrators_responses.go b/operatorapi/operations/operator_api/set_tenant_administrators_responses.go new file mode 100644 index 000000000..256f38d09 --- /dev/null +++ b/operatorapi/operations/operator_api/set_tenant_administrators_responses.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// This file is part of MinIO Console Server +// Copyright (c) 2022 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 operator_api + +// 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" +) + +// SetTenantAdministratorsNoContentCode is the HTTP code returned for type SetTenantAdministratorsNoContent +const SetTenantAdministratorsNoContentCode int = 204 + +/*SetTenantAdministratorsNoContent A successful response. + +swagger:response setTenantAdministratorsNoContent +*/ +type SetTenantAdministratorsNoContent struct { +} + +// NewSetTenantAdministratorsNoContent creates SetTenantAdministratorsNoContent with default headers values +func NewSetTenantAdministratorsNoContent() *SetTenantAdministratorsNoContent { + + return &SetTenantAdministratorsNoContent{} +} + +// WriteResponse to the client +func (o *SetTenantAdministratorsNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(204) +} + +/*SetTenantAdministratorsDefault Generic error response. + +swagger:response setTenantAdministratorsDefault +*/ +type SetTenantAdministratorsDefault struct { + _statusCode int + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewSetTenantAdministratorsDefault creates SetTenantAdministratorsDefault with default headers values +func NewSetTenantAdministratorsDefault(code int) *SetTenantAdministratorsDefault { + if code <= 0 { + code = 500 + } + + return &SetTenantAdministratorsDefault{ + _statusCode: code, + } +} + +// WithStatusCode adds the status to the set tenant administrators default response +func (o *SetTenantAdministratorsDefault) WithStatusCode(code int) *SetTenantAdministratorsDefault { + o._statusCode = code + return o +} + +// SetStatusCode sets the status to the set tenant administrators default response +func (o *SetTenantAdministratorsDefault) SetStatusCode(code int) { + o._statusCode = code +} + +// WithPayload adds the payload to the set tenant administrators default response +func (o *SetTenantAdministratorsDefault) WithPayload(payload *models.Error) *SetTenantAdministratorsDefault { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the set tenant administrators default response +func (o *SetTenantAdministratorsDefault) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *SetTenantAdministratorsDefault) 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/operatorapi/operations/operator_api/set_tenant_administrators_urlbuilder.go b/operatorapi/operations/operator_api/set_tenant_administrators_urlbuilder.go new file mode 100644 index 000000000..1814a4287 --- /dev/null +++ b/operatorapi/operations/operator_api/set_tenant_administrators_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// This file is part of MinIO Console Server +// Copyright (c) 2022 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 operator_api + +// 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" +) + +// SetTenantAdministratorsURL generates an URL for the set tenant administrators operation +type SetTenantAdministratorsURL struct { + Namespace string + Tenant 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 *SetTenantAdministratorsURL) WithBasePath(bp string) *SetTenantAdministratorsURL { + 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 *SetTenantAdministratorsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *SetTenantAdministratorsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/namespaces/{namespace}/tenants/{tenant}/set-administrators" + + namespace := o.Namespace + if namespace != "" { + _path = strings.Replace(_path, "{namespace}", namespace, -1) + } else { + return nil, errors.New("namespace is required on SetTenantAdministratorsURL") + } + + tenant := o.Tenant + if tenant != "" { + _path = strings.Replace(_path, "{tenant}", tenant, -1) + } else { + return nil, errors.New("tenant is required on SetTenantAdministratorsURL") + } + + _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 *SetTenantAdministratorsURL) 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 *SetTenantAdministratorsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *SetTenantAdministratorsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on SetTenantAdministratorsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on SetTenantAdministratorsURL") + } + + 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 *SetTenantAdministratorsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/operatorapi/tenants.go b/operatorapi/tenants.go index 594fe3bdf..8c343a30b 100644 --- a/operatorapi/tenants.go +++ b/operatorapi/tenants.go @@ -128,6 +128,15 @@ func registerTenantHandlers(api *operations.OperatorAPI) { return operator_api.NewUpdateTenantSecurityNoContent() }) + // Set Tenant Administrators + api.OperatorAPISetTenantAdministratorsHandler = operator_api.SetTenantAdministratorsHandlerFunc(func(params operator_api.SetTenantAdministratorsParams, session *models.Principal) middleware.Responder { + err := getSetTenantAdministratorsResponse(session, params) + if err != nil { + return operator_api.NewSetTenantAdministratorsDefault(int(err.Code)).WithPayload(err) + } + return operator_api.NewSetTenantAdministratorsNoContent() + }) + // Tenant identity provider details api.OperatorAPITenantIdentityProviderHandler = operator_api.TenantIdentityProviderHandlerFunc(func(params operator_api.TenantIdentityProviderParams, session *models.Principal) middleware.Responder { resp, err := getTenantIdentityProviderResponse(session, params) @@ -912,6 +921,58 @@ func getUpdateTenantIdentityProviderResponse(session *models.Principal, params o return nil } +func getSetTenantAdministratorsResponse(session *models.Principal, params operator_api.SetTenantAdministratorsParams) *models.Error { + ctx, cancel := context.WithCancel(params.HTTPRequest.Context()) + defer cancel() + opClientClientSet, err := cluster.OperatorClient(session.STSSessionToken) + if err != nil { + return restapi.ErrorWithContext(ctx, err) + } + // get Kubernetes Client + clientSet, err := cluster.K8sClient(session.STSSessionToken) + if err != nil { + return restapi.ErrorWithContext(ctx, err) + } + k8sClient := &k8sClient{ + client: clientSet, + } + opClient := &operatorClient{ + client: opClientClientSet, + } + + minTenant, err := getTenant(ctx, opClient, params.Namespace, params.Tenant) + if err != nil { + return restapi.ErrorWithContext(ctx, err) + } + minTenant.EnsureDefaults() + + svcURL := GetTenantServiceURL(minTenant) + // getTenantAdminClient will use all certificates under ~/.console/certs/CAs to trust the TLS connections with MinIO tenants + mAdmin, err := getTenantAdminClient( + ctx, + k8sClient, + minTenant, + svcURL, + ) + if err != nil { + return restapi.ErrorWithContext(ctx, err) + } + // create a minioClient interface implementation + // defining the client to be used + adminClient := restapi.AdminClient{Client: mAdmin} + for _, user := range params.Body.UserDNS { + if err := restapi.SetPolicy(ctx, adminClient, "consoleAdmin", user, "user"); err != nil { + return restapi.ErrorWithContext(ctx, err) + } + } + for _, group := range params.Body.GroupDNS { + if err := restapi.SetPolicy(ctx, adminClient, "consoleAdmin", group, "group"); err != nil { + return restapi.ErrorWithContext(ctx, err) + } + } + return nil +} + func getTenantSecurityResponse(session *models.Principal, params operator_api.TenantSecurityParams) (*models.TenantSecurityResponse, *models.Error) { ctx, cancel := context.WithCancel(params.HTTPRequest.Context()) defer cancel() diff --git a/portal-ui/src/screens/Console/Tenants/AddTenant/Steps/IdentityProvider/IDPActiveDirectory.tsx b/portal-ui/src/screens/Console/Tenants/AddTenant/Steps/IdentityProvider/IDPActiveDirectory.tsx index 88af92e0e..4d67ac2ae 100644 --- a/portal-ui/src/screens/Console/Tenants/AddTenant/Steps/IdentityProvider/IDPActiveDirectory.tsx +++ b/portal-ui/src/screens/Console/Tenants/AddTenant/Steps/IdentityProvider/IDPActiveDirectory.tsx @@ -33,6 +33,9 @@ import { removeIDPADUsrAtIndex, setIDPADUsrAtIndex, updateAddField, + addIDPADGroupAtIndex, + removeIDPADGroupAtIndex, + setIDPADGroupAtIndex, } from "../../createTenantSlice"; import { useSelector } from "react-redux"; import { clearValidationError } from "../../../utils"; @@ -48,6 +51,7 @@ const useStyles = makeStyles((theme: Theme) => createStyles({ adUserDnRows: { display: "flex", + marginBottom: 10, }, buttonTray: { marginLeft: 10, @@ -102,6 +106,9 @@ const IDPActiveDirectory = () => { const ADUserDNs = useSelector( (state: AppState) => state.createTenant.fields.identityProvider.ADUserDNs ); + const ADGroupDNs = useSelector( + (state: AppState) => state.createTenant.fields.identityProvider.ADGroupDNs + ); const ADLookupBindDN = useSelector( (state: AppState) => state.createTenant.fields.identityProvider.ADLookupBindDN @@ -160,14 +167,6 @@ const IDPActiveDirectory = () => { value: ADLookupBindDN, }, ]; - // validate user DNs - for (let i = 0; i < ADUserDNs.length; i++) { - customIDPValidation.push({ - fieldKey: `ad-userdn-${i.toString()}`, - required: true, - value: ADUserDNs[i], - }); - } } const commonVal = commonFormValidation(customIDPValidation); @@ -187,6 +186,7 @@ const IDPActiveDirectory = () => { ADGroupSearchBaseDN, ADGroupSearchFilter, ADUserDNs, + ADGroupDNs, dispatch, ]); @@ -398,6 +398,67 @@ const IDPActiveDirectory = () => { })} +
+ + List of group DNs (Distinguished Names) to be Tenant Administrators + + + {ADGroupDNs.map((_, index) => { + return ( + +
+ ) => { + dispatch( + setIDPADGroupAtIndex({ + index: index, + userDN: e.target.value, + }) + ); + cleanValidation(`ad-groupdn-${index.toString()}`); + }} + index={index} + key={`csv-ad-groupdn-${index.toString()}`} + error={ + validationErrors[`ad-groupdn-${index.toString()}`] || "" + } + /> +
+ + { + dispatch(addIDPADGroupAtIndex()); + }} + > + + + + + { + if (ADGroupDNs.length > 1) { + dispatch(removeIDPADGroupAtIndex(index)); + } + }} + > + + + +
+
+
+ ); + })} +
+
); }; diff --git a/portal-ui/src/screens/Console/Tenants/AddTenant/createTenantSlice.ts b/portal-ui/src/screens/Console/Tenants/AddTenant/createTenantSlice.ts index 086c5f97d..d7d522e53 100644 --- a/portal-ui/src/screens/Console/Tenants/AddTenant/createTenantSlice.ts +++ b/portal-ui/src/screens/Console/Tenants/AddTenant/createTenantSlice.ts @@ -162,6 +162,7 @@ const initialState: ICreateTenant = { ADGroupSearchBaseDN: "", ADGroupSearchFilter: "", ADUserDNs: [""], + ADGroupDNs: [""], ADLookupBindDN: "", ADLookupBindPassword: "", ADUserDNSearchBaseDN: "", @@ -789,6 +790,28 @@ export const createTenantSlice = createSlice({ action.payload.userDN; } }, + addIDPADGroupAtIndex: (state) => { + state.fields.identityProvider.ADGroupDNs.push(""); + }, + removeIDPADGroupAtIndex: (state, action: PayloadAction) => { + if (state.fields.identityProvider.ADGroupDNs.length > action.payload) { + state.fields.identityProvider.ADGroupDNs.splice(action.payload, 1); + } + }, + setIDPADGroupAtIndex: ( + state, + action: PayloadAction<{ + index: number; + userDN: string; + }> + ) => { + if ( + state.fields.identityProvider.ADGroupDNs.length > action.payload.index + ) { + state.fields.identityProvider.ADGroupDNs[action.payload.index] = + action.payload.userDN; + } + }, setIDP: (state, action: PayloadAction) => { state.fields.identityProvider.idpSelection = action.payload; }, @@ -982,6 +1005,9 @@ export const { setIDPPwdAtIndex, setIDPADUsrAtIndex, addIDPADUsrAtIndex, + setIDPADGroupAtIndex, + addIDPADGroupAtIndex, + removeIDPADGroupAtIndex, removeIDPADUsrAtIndex, setIDP, setTenantName, diff --git a/portal-ui/src/screens/Console/Tenants/AddTenant/thunks/createTenantThunk.ts b/portal-ui/src/screens/Console/Tenants/AddTenant/thunks/createTenantThunk.ts index 5ba2bc62c..2985b551d 100644 --- a/portal-ui/src/screens/Console/Tenants/AddTenant/thunks/createTenantThunk.ts +++ b/portal-ui/src/screens/Console/Tenants/AddTenant/thunks/createTenantThunk.ts @@ -54,6 +54,7 @@ export const createTenantAsync = createAsyncThunk( const ADGroupSearchBaseDN = fields.identityProvider.ADGroupSearchBaseDN; const ADGroupSearchFilter = fields.identityProvider.ADGroupSearchFilter; const ADUserDNs = fields.identityProvider.ADUserDNs; + const ADGroupDNs = fields.identityProvider.ADGroupDNs; const ADLookupBindDN = fields.identityProvider.ADLookupBindDN; const ADLookupBindPassword = fields.identityProvider.ADLookupBindPassword; const ADUserDNSearchBaseDN = fields.identityProvider.ADUserDNSearchBaseDN; @@ -541,7 +542,8 @@ export const createTenantAsync = createAsyncThunk( server_insecure: ADServerInsecure, group_search_base_dn: ADGroupSearchBaseDN, group_search_filter: ADGroupSearchFilter, - user_dns: ADUserDNs, + user_dns: ADUserDNs.filter((user) => user.trim() !== ""), + group_dns: ADGroupDNs.filter((group) => group.trim() !== ""), lookup_bind_dn: ADLookupBindDN, lookup_bind_password: ADLookupBindPassword, user_dn_search_base_dn: ADUserDNSearchBaseDN, diff --git a/portal-ui/src/screens/Console/Tenants/TenantDetails/TenantIdentityProvider.tsx b/portal-ui/src/screens/Console/Tenants/TenantDetails/TenantIdentityProvider.tsx index 08cdba28b..2eef7031a 100644 --- a/portal-ui/src/screens/Console/Tenants/TenantDetails/TenantIdentityProvider.tsx +++ b/portal-ui/src/screens/Console/Tenants/TenantDetails/TenantIdentityProvider.tsx @@ -16,7 +16,13 @@ import React, { Fragment, useCallback, useEffect, useState } from "react"; import { connect, useSelector } from "react-redux"; -import { Button, DialogContentText, Typography } from "@mui/material"; +import { + Button, + DialogContentText, + IconButton, + Tooltip, + Typography, +} from "@mui/material"; import { Theme } from "@mui/material/styles"; import Grid from "@mui/material/Grid"; import createStyles from "@mui/styles/createStyles"; @@ -32,14 +38,20 @@ import { tenantDetailsStyles, wizardCommon, } from "../../Common/FormComponents/common/styleLibrary"; -import { ITenantIdentityProviderResponse } from "../types"; +import { + ITenantIdentityProviderResponse, + ITenantSetAdministratorsRequest, +} from "../types"; import { clearValidationError } from "../utils"; import { commonFormValidation, IValidation, } from "../../../../utils/validationFunctions"; import { ConfirmModalIcon } from "../../../../icons"; -import { setErrorSnackMessage } from "../../../../systemSlice"; +import { + setErrorSnackMessage, + setSnackBarMessage, +} from "../../../../systemSlice"; import { AppState, useAppDispatch } from "../../../../store"; import { ErrorResponseHandler } from "../../../../common/types"; import Loader from "../../Common/Loader/Loader"; @@ -48,6 +60,9 @@ import InputBoxWrapper from "../../Common/FormComponents/InputBoxWrapper/InputBo import FormSwitchWrapper from "../../Common/FormComponents/FormSwitchWrapper/FormSwitchWrapper"; import ConfirmDialog from "../../Common/ModalWrapper/ConfirmDialog"; import api from "../../../../common/api"; +import AddIcon from "@mui/icons-material/Add"; +import DeleteIcon from "@mui/icons-material/Delete"; +import SectionTitle from "../../Common/SectionTitle"; interface ITenantIdentityProvider { classes: any; @@ -55,6 +70,28 @@ interface ITenantIdentityProvider { const styles = (theme: Theme) => createStyles({ + adUserDnRows: { + display: "flex", + marginBottom: 10, + }, + buttonTray: { + marginLeft: 10, + display: "flex", + height: 38, + "& button": { + background: "#EAEAEA", + }, + }, + overlayAction: { + marginLeft: 10, + "& svg": { + maxWidth: 15, + maxHeight: 15, + }, + "& button": { + background: "#EAEAEA", + }, + }, ...tenantDetailsStyles, ...spacingUtils, loaderAlign: { @@ -111,6 +148,8 @@ const TenantIdentityProvider = ({ classes }: ITenantIdentityProvider) => { const [ADSkipTLS, setADSkipTLS] = useState(false); const [ADServerInsecure, setADServerInsecure] = useState(false); const [ADServerStartTLS, setADServerStartTLS] = useState(false); + const [ADUserDNs, setADUserDNs] = useState([""]); + const [ADGroupDNs, setADGroupDNs] = useState([""]); const [validationErrors, setValidationErrors] = useState({}); const cleanValidation = (fieldName: string) => { setValidationErrors(clearValidationError(validationErrors, fieldName)); @@ -272,6 +311,39 @@ const TenantIdentityProvider = ({ classes }: ITenantIdentityProvider) => { }); }; + const setAdministrators = () => { + setIsSending(true); + let payload: ITenantSetAdministratorsRequest = {}; + switch (idpSelection) { + case "AD": + payload = { + user_dns: ADUserDNs.filter((user) => user.trim() !== ""), + group_dns: ADGroupDNs.filter((group) => group.trim() !== ""), + }; + break; + default: + // Built-in IDP will be used by default + } + + api + .invoke( + "POST", + `/api/v1/namespaces/${tenant?.namespace}/tenants/${tenant?.name}/set-administrators`, + payload + ) + .then(() => { + setIsSending(false); + setADGroupDNs([""]); + setADUserDNs([""]); + getTenantIdentityProviderInfo(); + dispatch(setSnackBarMessage(`Administrators added successfully`)); + }) + .catch((err: ErrorResponseHandler) => { + dispatch(setErrorSnackMessage(err)); + setIsSending(false); + }); + }; + return ( { Save + + {idpSelection === "AD" && ( + + User & Group management +
+
+ + List of user DNs (Distinguished Names) to be added as Tenant + Administrators + + + {ADUserDNs.map((_, index) => { + return ( + +
+ + ) => { + setADUserDNs( + ADUserDNs.map((group, i) => + i === index ? e.target.value : group + ) + ); + }} + index={index} + key={`csv-ad-userdn-${index.toString()}`} + error={ + validationErrors[ + `ad-userdn-${index.toString()}` + ] || "" + } + /> +
+ + { + setADUserDNs([...ADUserDNs, ""]); + }} + > + + + + + { + if (ADUserDNs.length > 1) { + setADUserDNs( + ADUserDNs.filter((_, i) => i !== index) + ); + } + }} + > + + + +
+
+
+ ); + })} +
+
+
+ + List of group DNs (Distinguished Names) to be added as Tenant + Administrators + + + {ADGroupDNs.map((_, index) => { + return ( + +
+ + ) => { + setADGroupDNs( + ADGroupDNs.map((group, i) => + i === index ? e.target.value : group + ) + ); + }} + index={index} + key={`csv-ad-groupdn-${index.toString()}`} + error={ + validationErrors[ + `ad-groupdn-${index.toString()}` + ] || "" + } + /> +
+ + { + setADGroupDNs([...ADGroupDNs, ""]); + }} + > + + + + + { + if (ADGroupDNs.length > 1) { + setADGroupDNs( + ADGroupDNs.filter((_, i) => i !== index) + ); + } + }} + > + + + +
+
+
+ ); + })} +
+
+
+ + + +
+ )} )}
diff --git a/portal-ui/src/screens/Console/Tenants/types.ts b/portal-ui/src/screens/Console/Tenants/types.ts index e7a63fab9..d954cde4c 100644 --- a/portal-ui/src/screens/Console/Tenants/types.ts +++ b/portal-ui/src/screens/Console/Tenants/types.ts @@ -189,6 +189,7 @@ export interface IIdentityProviderFields { ADGroupSearchBaseDN: string; ADGroupSearchFilter: string; ADUserDNs: string[]; + ADGroupDNs: string[]; ADLookupBindDN: string; ADLookupBindPassword: string; ADUserDNSearchBaseDN: string; @@ -340,6 +341,11 @@ export interface ITenantIdentityProviderResponse { }; } +export interface ITenantSetAdministratorsRequest { + user_dns?: string[]; + group_dns?: string[]; +} + export interface IEditMonitoringSecurityContext { securityContextEnabled: boolean; runAsUser: string; diff --git a/restapi/admin_policies.go b/restapi/admin_policies.go index 51e397952..36fe8ef25 100644 --- a/restapi/admin_policies.go +++ b/restapi/admin_policies.go @@ -634,8 +634,8 @@ func getPolicyInfoResponse(session *models.Principal, params policyApi.PolicyInf return policy, nil } -// setPolicy() calls MinIO server to assign policy to a group or user. -func setPolicy(ctx context.Context, client MinioAdmin, name, entityName string, entityType models.PolicyEntity) error { +// SetPolicy calls MinIO server to assign policy to a group or user. +func SetPolicy(ctx context.Context, client MinioAdmin, name, entityName string, entityType models.PolicyEntity) error { isGroup := false if entityType == models.PolicyEntityGroup { isGroup = true @@ -643,7 +643,7 @@ func setPolicy(ctx context.Context, client MinioAdmin, name, entityName string, return client.setPolicy(ctx, name, entityName, isGroup) } -// getSetPolicyResponse() performs setPolicy() and serializes it to the handler's output +// getSetPolicyResponse() performs SetPolicy() and serializes it to the handler's output func getSetPolicyResponse(session *models.Principal, params policyApi.SetPolicyParams) *models.Error { ctx, cancel := context.WithCancel(params.HTTPRequest.Context()) defer cancel() @@ -656,7 +656,7 @@ func getSetPolicyResponse(session *models.Principal, params policyApi.SetPolicyP // defining the client to be used adminClient := AdminClient{Client: mAdmin} - if err := setPolicy(ctx, adminClient, strings.Join(params.Body.Name, ","), *params.Body.EntityName, *params.Body.EntityType); err != nil { + if err := SetPolicy(ctx, adminClient, strings.Join(params.Body.Name, ","), *params.Body.EntityName, *params.Body.EntityType); err != nil { return ErrorWithContext(ctx, err) } return nil diff --git a/restapi/admin_policies_test.go b/restapi/admin_policies_test.go index 969cfb4d6..c3623a994 100644 --- a/restapi/admin_policies_test.go +++ b/restapi/admin_policies_test.go @@ -60,7 +60,7 @@ func (ac adminClientMock) addPolicy(ctx context.Context, name string, policy *ia return minioAddPolicyMock(name, policy) } -// mock function setPolicy() +// mock function SetPolicy() func (ac adminClientMock) setPolicy(ctx context.Context, policyName, entityName string, isGroup bool) error { return minioSetPolicyMock(policyName, entityName, isGroup) } @@ -202,32 +202,32 @@ func TestSetPolicy(t *testing.T) { minioSetPolicyMock = func(policyName, entityName string, isGroup bool) error { return nil } - // Test-1 : setPolicy() set policy to user - function := "setPolicy()" - err := setPolicy(ctx, adminClient, policyName, entityName, entityObject) + // Test-1 : SetPolicy() set policy to user + function := "SetPolicy()" + err := SetPolicy(ctx, adminClient, policyName, entityName, entityObject) if err != nil { t.Errorf("Failed on %s:, error occurred: %s", function, err.Error()) } - // Test-2 : setPolicy() set policy to group + // Test-2 : SetPolicy() set policy to group entityObject = models.PolicyEntityGroup - err = setPolicy(ctx, adminClient, policyName, entityName, entityObject) + err = SetPolicy(ctx, adminClient, policyName, entityName, entityObject) if err != nil { t.Errorf("Failed on %s:, error occurred: %s", function, err.Error()) } - // Test-3 : setPolicy() set policy to user and get error + // Test-3 : SetPolicy() set policy to user and get error entityObject = models.PolicyEntityUser minioSetPolicyMock = func(policyName, entityName string, isGroup bool) error { return errors.New("error") } - if err := setPolicy(ctx, adminClient, policyName, entityName, entityObject); funcAssert.Error(err) { + if err := SetPolicy(ctx, adminClient, policyName, entityName, entityObject); funcAssert.Error(err) { funcAssert.Equal("error", err.Error()) } - // Test-4 : setPolicy() set policy to group and get error + // Test-4 : SetPolicy() set policy to group and get error entityObject = models.PolicyEntityGroup minioSetPolicyMock = func(policyName, entityName string, isGroup bool) error { return errors.New("error") } - if err := setPolicy(ctx, adminClient, policyName, entityName, entityObject); funcAssert.Error(err) { + if err := SetPolicy(ctx, adminClient, policyName, entityName, entityObject); funcAssert.Error(err) { funcAssert.Equal("error", err.Error()) } } diff --git a/restapi/admin_profiling.go b/restapi/admin_profiling.go index 91f764237..0ad11c267 100644 --- a/restapi/admin_profiling.go +++ b/restapi/admin_profiling.go @@ -116,7 +116,7 @@ func stopProfiling(ctx context.Context, client MinioAdmin) (io.ReadCloser, error return zippedData, nil } -// getProfilingStopResponse() performs setPolicy() and serializes it to the handler's output +// getProfilingStopResponse() performs SetPolicy() and serializes it to the handler's output func getProfilingStopResponse(session *models.Principal, params profileApi.ProfilingStopParams) (io.ReadCloser, *models.Error) { ctx := params.HTTPRequest.Context() mAdmin, err := NewMinioAdminClient(session) diff --git a/restapi/admin_users.go b/restapi/admin_users.go index f49478635..ce2cc1940 100644 --- a/restapi/admin_users.go +++ b/restapi/admin_users.go @@ -194,7 +194,7 @@ func addUser(ctx context.Context, client MinioAdmin, accessKey, secretKey *strin // set policies for the newly created user if len(policies) > 0 { policyString := strings.Join(policies, ",") - if err := setPolicy(ctx, client, policyString, *accessKey, "user"); err != nil { + if err := SetPolicy(ctx, client, policyString, *accessKey, "user"); err != nil { return nil, err } } diff --git a/restapi/user_buckets_test.go b/restapi/user_buckets_test.go index edbbdbfc9..fb0576cbc 100644 --- a/restapi/user_buckets_test.go +++ b/restapi/user_buckets_test.go @@ -361,7 +361,7 @@ func TestSetBucketAccess(t *testing.T) { assert.Equal("error: bucket access not present", err.Error()) } - // Test-5: setBucketAccessPolicy() handle errors on setPolicy call + // Test-5: setBucketAccessPolicy() handle errors on SetPolicy call minioSetBucketPolicyWithContextMock = func(ctx context.Context, bucketName, policy string) error { return errors.New("error") } diff --git a/swagger-operator.yml b/swagger-operator.yml index b28f3a67d..375d00805 100644 --- a/swagger-operator.yml +++ b/swagger-operator.yml @@ -386,6 +386,34 @@ paths: tags: - OperatorAPI + /namespaces/{namespace}/tenants/{tenant}/set-administrators: + post: + summary: Set the consoleAdmin policy to the specified users and groups + operationId: SetTenantAdministrators + parameters: + - name: namespace + in: path + required: true + type: string + - name: tenant + in: path + required: true + type: string + - name: body + in: body + required: true + schema: + $ref: "#/definitions/setAdministratorsRequest" + responses: + 204: + description: A successful response. + default: + description: Generic error response. + schema: + $ref: "#/definitions/error" + tags: + - OperatorAPI + /namespaces/{namespace}/tenants/{tenant}/security: get: summary: Tenant Security @@ -1854,6 +1882,19 @@ definitions: securityContext: type: object $ref: "#/definitions/securityContext" + + setAdministratorsRequest: + type: object + properties: + user_dns: + type: array + items: + type: string + group_dns: + type: array + items: + type: string + idpConfiguration: type: object properties: