Skip to content
Open
192 changes: 192 additions & 0 deletions adapter/admin_grpc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package adapter

import (
"context"
"crypto/subtle"
"strings"
"sync"

"github.com/bootjp/elastickv/internal/raftengine"
pb "github.com/bootjp/elastickv/proto"
"github.com/cockroachdb/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)

// AdminGroup exposes per-Raft-group state to the Admin service. It is a narrow
// subset of raftengine.Engine so tests can supply an in-memory fake without
// standing up a real Raft cluster.
type AdminGroup interface {
Status() raftengine.Status
}

// NodeIdentity is the value form of the protobuf NodeIdentity message used for
// AdminServer configuration. It avoids copying pb.NodeIdentity, which embeds a
// protoimpl.MessageState (and a mutex).
type NodeIdentity struct {
NodeID string
GRPCAddress string
}

func (n NodeIdentity) toProto() *pb.NodeIdentity {
return &pb.NodeIdentity{NodeId: n.NodeID, GrpcAddress: n.GRPCAddress}
}

// AdminServer implements the node-side Admin gRPC service described in
// docs/admin_ui_key_visualizer_design.md §4 (Layer A). Phase 0 only implements
// GetClusterOverview and GetRaftGroups; remaining RPCs return Unimplemented so
// the generated client can still compile against older nodes during rollout.
type AdminServer struct {
self NodeIdentity
members []NodeIdentity

groupsMu sync.RWMutex
groups map[uint64]AdminGroup

pb.UnimplementedAdminServer
}

// NewAdminServer constructs an AdminServer. `self` identifies the local node
// for responses that return node identity. `members` is the static membership
// snapshot shipped to the admin binary; callers that already have a membership
// source may pass nil and let the admin binary's fan-out layer discover peers
// by other means.
func NewAdminServer(self NodeIdentity, members []NodeIdentity) *AdminServer {
cloned := append([]NodeIdentity(nil), members...)
return &AdminServer{
self: self,
members: cloned,
groups: make(map[uint64]AdminGroup),
}
}

// RegisterGroup binds a Raft group ID to its engine so the Admin service can
// report leader and log state for that group.
func (s *AdminServer) RegisterGroup(groupID uint64, g AdminGroup) {
if g == nil {
return
}
s.groupsMu.Lock()
s.groups[groupID] = g
s.groupsMu.Unlock()
}

// GetClusterOverview returns the local node identity, the configured member
// list, and per-group leader identity collected from the engines registered
// via RegisterGroup.
func (s *AdminServer) GetClusterOverview(
_ context.Context,
_ *pb.GetClusterOverviewRequest,
) (*pb.GetClusterOverviewResponse, error) {
leaders := s.snapshotLeaders()
members := make([]*pb.NodeIdentity, 0, len(s.members))
for _, m := range s.members {
members = append(members, m.toProto())
}
return &pb.GetClusterOverviewResponse{
Self: s.self.toProto(),
Members: members,
GroupLeaders: leaders,
}, nil
}

// GetRaftGroups returns per-group state snapshots. Phase 0 wires commit/applied
// indices only; per-follower contact and term history land in later phases.
func (s *AdminServer) GetRaftGroups(
_ context.Context,
_ *pb.GetRaftGroupsRequest,
) (*pb.GetRaftGroupsResponse, error) {
s.groupsMu.RLock()
out := make([]*pb.RaftGroupState, 0, len(s.groups))
for id, g := range s.groups {
st := g.Status()
out = append(out, &pb.RaftGroupState{
RaftGroupId: id,
LeaderNodeId: st.Leader.ID,
LeaderTerm: st.Term,
CommitIndex: st.CommitIndex,
AppliedIndex: st.AppliedIndex,
})
}
Comment on lines +103 to +112
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Iterating over the s.groups map results in a non-deterministic order of groups in the gRPC response. For administrative tools and UIs, providing a stable order (e.g., sorted by RaftGroupId) improves the user experience by preventing UI elements from jumping around and makes testing more predictable.

s.groupsMu.RUnlock()
return &pb.GetRaftGroupsResponse{Groups: out}, nil
}

func (s *AdminServer) snapshotLeaders() []*pb.GroupLeader {
s.groupsMu.RLock()
defer s.groupsMu.RUnlock()
out := make([]*pb.GroupLeader, 0, len(s.groups))
for id, g := range s.groups {
st := g.Status()
out = append(out, &pb.GroupLeader{
RaftGroupId: id,
LeaderNodeId: st.Leader.ID,
LeaderTerm: st.Term,
})
}
Comment on lines +121 to +128
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to GetRaftGroups, the order of GroupLeaders in the response is non-deterministic due to map iteration. Sorting the results by RaftGroupId before returning would provide a more consistent API response.

return out
}

// AdminTokenAuth builds a gRPC unary+stream interceptor pair enforcing
// "authorization: Bearer <token>" metadata against the supplied token. An
// empty token disables enforcement; callers should pair that mode with a
// --adminInsecureNoAuth flag so operators knowingly opt in.
func AdminTokenAuth(token string) (grpc.UnaryServerInterceptor, grpc.StreamServerInterceptor) {
if token == "" {
return nil, nil
}
expected := []byte(token)
check := func(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Error(codes.Unauthenticated, "missing authorization metadata")
}
values := md.Get("authorization")
if len(values) == 0 {
return status.Error(codes.Unauthenticated, "missing authorization header")
}
got, ok := strings.CutPrefix(values[0], "Bearer ")
if !ok {
return status.Error(codes.Unauthenticated, "authorization is not a bearer token")
}
if subtle.ConstantTimeCompare([]byte(got), expected) != 1 {
return status.Error(codes.Unauthenticated, "invalid admin token")
}
return nil
}
unary := func(
ctx context.Context,
req any,
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (any, error) {
if !strings.HasPrefix(info.FullMethod, "/Admin/") {
return handler(ctx, req)
}
if err := check(ctx); err != nil {
return nil, err
}
return handler(ctx, req)
}
stream := func(
srv any,
ss grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler,
) error {
if !strings.HasPrefix(info.FullMethod, "/Admin/") {
return handler(srv, ss)
}
if err := check(ss.Context()); err != nil {
return err
}
return handler(srv, ss)
}
return unary, stream
}

// ErrAdminTokenRequired is returned by NewAdminServer helpers when the operator
// failed to supply a token and also did not opt into insecure mode.
var ErrAdminTokenRequired = errors.New("admin token file required; pass --adminInsecureNoAuth to run without")
141 changes: 141 additions & 0 deletions adapter/admin_grpc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package adapter

import (
"context"
"testing"

"github.com/bootjp/elastickv/internal/raftengine"
pb "github.com/bootjp/elastickv/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)

type fakeGroup struct {
leaderID string
term uint64
commit uint64
applied uint64
}

func (f fakeGroup) Status() raftengine.Status {
return raftengine.Status{
Leader: raftengine.LeaderInfo{ID: f.leaderID},
Term: f.term,
CommitIndex: f.commit,
AppliedIndex: f.applied,
}
}

func TestGetClusterOverviewReturnsSelfAndLeaders(t *testing.T) {
t.Parallel()
srv := NewAdminServer(
NodeIdentity{NodeID: "node-a", GRPCAddress: "127.0.0.1:50051"},
[]NodeIdentity{{NodeID: "node-b", GRPCAddress: "127.0.0.1:50052"}},
)
srv.RegisterGroup(1, fakeGroup{leaderID: "node-a", term: 7})
srv.RegisterGroup(2, fakeGroup{leaderID: "node-b", term: 3})

resp, err := srv.GetClusterOverview(context.Background(), &pb.GetClusterOverviewRequest{})
if err != nil {
t.Fatalf("GetClusterOverview: %v", err)
}
if resp.Self.NodeId != "node-a" {
t.Fatalf("self = %q, want node-a", resp.Self.NodeId)
}
if len(resp.Members) != 1 || resp.Members[0].NodeId != "node-b" {
t.Fatalf("members = %v, want [node-b]", resp.Members)
}
if len(resp.GroupLeaders) != 2 {
t.Fatalf("group_leaders count = %d, want 2", len(resp.GroupLeaders))
}
}

func TestGetRaftGroupsExposesCommitApplied(t *testing.T) {
t.Parallel()
srv := NewAdminServer(NodeIdentity{NodeID: "n1"}, nil)
srv.RegisterGroup(1, fakeGroup{leaderID: "n1", term: 2, commit: 99, applied: 97})

resp, err := srv.GetRaftGroups(context.Background(), &pb.GetRaftGroupsRequest{})
if err != nil {
t.Fatalf("GetRaftGroups: %v", err)
}
if len(resp.Groups) != 1 {
t.Fatalf("groups = %d, want 1", len(resp.Groups))
}
g := resp.Groups[0]
if g.CommitIndex != 99 || g.AppliedIndex != 97 || g.LeaderTerm != 2 {
t.Fatalf("unexpected state %+v", g)
}
}

func TestAdminTokenAuth(t *testing.T) {
t.Parallel()
unary, _ := AdminTokenAuth("s3cret")
if unary == nil {
t.Fatal("interceptor should be non-nil for configured token")
}

info := &grpc.UnaryServerInfo{FullMethod: "/Admin/GetClusterOverview"}
handler := func(_ context.Context, _ any) (any, error) { return "ok", nil }

cases := []struct {
name string
md metadata.MD
code codes.Code
call bool
}{
{"missing metadata", nil, codes.Unauthenticated, false},
{"missing header", metadata.Pairs(), codes.Unauthenticated, false},
{"wrong scheme", metadata.Pairs("authorization", "Basic zzz"), codes.Unauthenticated, false},
{"wrong token", metadata.Pairs("authorization", "Bearer nope"), codes.Unauthenticated, false},
{"correct", metadata.Pairs("authorization", "Bearer s3cret"), codes.OK, true},
}
for _, tc := range cases {

t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctx := context.Background()
if tc.md != nil {
ctx = metadata.NewIncomingContext(ctx, tc.md)
}
resp, err := unary(ctx, nil, info, handler)
if tc.code == codes.OK {
if err != nil {
t.Fatalf("want OK, got %v", err)
}
if resp != "ok" {
t.Fatalf("handler not called: resp=%v", resp)
}
return
}
if status.Code(err) != tc.code {
t.Fatalf("code = %v, want %v (err=%v)", status.Code(err), tc.code, err)
}
})
}
}

func TestAdminTokenAuthSkipsOtherServices(t *testing.T) {
t.Parallel()
unary, _ := AdminTokenAuth("s3cret")
info := &grpc.UnaryServerInfo{FullMethod: "/RawKV/Get"}
handler := func(_ context.Context, _ any) (any, error) { return "ok", nil }

resp, err := unary(context.Background(), nil, info, handler)
if err != nil {
t.Fatalf("non-admin method should not be gated: %v", err)
}
if resp != "ok" {
t.Fatalf("handler not called: resp=%v", resp)
}
}

func TestAdminTokenAuthEmptyTokenDisabled(t *testing.T) {
t.Parallel()
unary, stream := AdminTokenAuth("")
if unary != nil || stream != nil {
t.Fatal("empty token should disable interceptors")
}
}
Loading
Loading