2023-03-28 22:48:58 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2023-03-27 21:25:27 +00:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2023-04-11 11:10:14 +00:00
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
"google.golang.org/grpc/status"
|
|
|
|
|
|
|
|
"github.com/hashicorp/consul/acl"
|
2023-03-27 21:25:27 +00:00
|
|
|
"github.com/hashicorp/consul/internal/storage"
|
|
|
|
"github.com/hashicorp/consul/proto-public/pbresource"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Server) List(ctx context.Context, req *pbresource.ListRequest) (*pbresource.ListResponse, error) {
|
2023-05-10 09:38:48 +00:00
|
|
|
if err := validateListRequest(req); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-04-11 11:10:14 +00:00
|
|
|
// check type
|
|
|
|
reg, err := s.resolveType(req.Type)
|
|
|
|
if err != nil {
|
2023-03-27 21:25:27 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-04-11 11:10:14 +00:00
|
|
|
authz, err := s.getAuthorizer(tokenFromContext(ctx))
|
2023-03-27 21:25:27 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-04-11 11:10:14 +00:00
|
|
|
// check acls
|
|
|
|
err = reg.ACLs.List(authz, req.Tenancy)
|
|
|
|
switch {
|
|
|
|
case acl.IsErrPermissionDenied(err):
|
|
|
|
return nil, status.Error(codes.PermissionDenied, err.Error())
|
|
|
|
case err != nil:
|
|
|
|
return nil, status.Errorf(codes.Internal, "failed list acl: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
resources, err := s.Backend.List(
|
|
|
|
ctx,
|
|
|
|
readConsistencyFrom(ctx),
|
|
|
|
storage.UnversionedTypeFrom(req.Type),
|
|
|
|
req.Tenancy,
|
|
|
|
req.NamePrefix,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, status.Errorf(codes.Internal, "failed list: %v", err)
|
|
|
|
}
|
|
|
|
|
2023-03-27 21:25:27 +00:00
|
|
|
result := make([]*pbresource.Resource, 0)
|
|
|
|
for _, resource := range resources {
|
2023-04-11 11:10:14 +00:00
|
|
|
// filter out non-matching GroupVersion
|
|
|
|
if resource.Id.Type.GroupVersion != req.Type.GroupVersion {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// filter out items that don't pass read ACLs
|
|
|
|
err = reg.ACLs.Read(authz, resource.Id)
|
|
|
|
switch {
|
|
|
|
case acl.IsErrPermissionDenied(err):
|
|
|
|
continue
|
|
|
|
case err != nil:
|
|
|
|
return nil, status.Errorf(codes.Internal, "failed read acl: %v", err)
|
2023-03-27 21:25:27 +00:00
|
|
|
}
|
2023-04-11 11:10:14 +00:00
|
|
|
result = append(result, resource)
|
2023-03-27 21:25:27 +00:00
|
|
|
}
|
|
|
|
return &pbresource.ListResponse{Resources: result}, nil
|
|
|
|
}
|
2023-05-10 09:38:48 +00:00
|
|
|
|
|
|
|
func validateListRequest(req *pbresource.ListRequest) error {
|
|
|
|
var field string
|
|
|
|
switch {
|
|
|
|
case req.Type == nil:
|
|
|
|
field = "type"
|
|
|
|
case req.Tenancy == nil:
|
|
|
|
field = "tenancy"
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return status.Errorf(codes.InvalidArgument, "%s is required", field)
|
|
|
|
}
|