2023-03-28 22:48:58 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2023-03-27 15:35:39 +00:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
"google.golang.org/grpc/status"
|
|
|
|
|
2023-04-11 11:10:14 +00:00
|
|
|
"github.com/hashicorp/consul/acl"
|
2023-03-27 15:35:39 +00:00
|
|
|
"github.com/hashicorp/consul/internal/storage"
|
|
|
|
"github.com/hashicorp/consul/proto-public/pbresource"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Server) Read(ctx context.Context, req *pbresource.ReadRequest) (*pbresource.ReadResponse, error) {
|
2023-04-17 21:33:20 +00:00
|
|
|
if err := validateReadRequest(req); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-03-27 15:35:39 +00:00
|
|
|
// check type exists
|
2023-04-11 11:10:14 +00:00
|
|
|
reg, err := s.resolveType(req.Id.Type)
|
|
|
|
if err != nil {
|
2023-03-27 21:25:27 +00:00
|
|
|
return nil, err
|
2023-03-27 15:35:39 +00:00
|
|
|
}
|
|
|
|
|
2023-04-11 11:10:14 +00:00
|
|
|
authz, err := s.getAuthorizer(tokenFromContext(ctx))
|
2023-03-27 15:35:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-04-11 11:10:14 +00:00
|
|
|
|
|
|
|
// check acls
|
|
|
|
err = reg.ACLs.Read(authz, req.Id)
|
|
|
|
switch {
|
|
|
|
case acl.IsErrPermissionDenied(err):
|
|
|
|
return nil, status.Error(codes.PermissionDenied, err.Error())
|
|
|
|
case err != nil:
|
|
|
|
return nil, status.Errorf(codes.Internal, "failed read acl: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
resource, err := s.Backend.Read(ctx, readConsistencyFrom(ctx), req.Id)
|
|
|
|
switch {
|
|
|
|
case err == nil:
|
|
|
|
return &pbresource.ReadResponse{Resource: resource}, nil
|
|
|
|
case errors.Is(err, storage.ErrNotFound):
|
|
|
|
return nil, status.Error(codes.NotFound, err.Error())
|
|
|
|
case errors.As(err, &storage.GroupVersionMismatchError{}):
|
|
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
|
|
default:
|
|
|
|
return nil, status.Errorf(codes.Internal, "failed read: %v", err)
|
|
|
|
}
|
2023-03-27 15:35:39 +00:00
|
|
|
}
|
2023-04-17 21:33:20 +00:00
|
|
|
|
|
|
|
func validateReadRequest(req *pbresource.ReadRequest) error {
|
|
|
|
if req.Id == nil {
|
|
|
|
return status.Errorf(codes.InvalidArgument, "id is required")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := validateId(req.Id, "id"); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|