diff --git a/seaweed-block/core/auth/authorize.go b/seaweed-block/core/auth/authorize.go new file mode 100644 index 0000000000..639434ceb5 --- /dev/null +++ b/seaweed-block/core/auth/authorize.go @@ -0,0 +1,196 @@ +package auth + +import ( + "context" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Rule is who may call one method: people from Min upwards (viewer < +// operator < admin; "" admits no person), and nodes when Node is set (a +// handler then checks the node's own server id with RequireNode). +type Rule struct { + Min Role + Node bool +} + +func rank(r Role) int { + switch r { + case RoleViewer: + return 1 + case RoleOperator: + return 2 + case RoleAdmin: + return 3 + } + return 0 +} + +// Allows reports whether p may call a method with this rule. +func (r Rule) Allows(p Principal) bool { + if p.Role == RoleNode { + return r.Node + } + return r.Min != "" && rank(p.Role) >= rank(r.Min) +} + +type ctxKey struct{} + +// callAuth is what the interceptor decided for one call: the principal, or +// development mode (plaintext on loopback, no role file). +type callAuth struct { + p Principal + dev bool +} + +// FromContext returns the call's principal (false in development mode or +// when no interceptor ran). +func FromContext(ctx context.Context) (Principal, bool) { + c, ok := ctx.Value(ctxKey{}).(callAuth) + return c.p, ok && !c.dev +} + +func forbidden(format string, args ...any) error { + return status.Errorf(codes.PermissionDenied, format, args...) +} + +// decided is the call's decision; a call no interceptor saw is refused, so a +// handler's own checks fail closed if the server was built without one. +func decided(ctx context.Context) (callAuth, error) { + c, ok := ctx.Value(ctxKey{}).(callAuth) + if !ok { + return callAuth{}, unauthenticated("no caller identity on this call") + } + return c, nil +} + +// RequireNode admits a node calling for its own server id (development mode +// admits every call). A person, or a node naming another server id, is +// refused. +func RequireNode(ctx context.Context, serverID string) error { + c, err := decided(ctx) + if err != nil || c.dev { + return err + } + if c.p.Role != RoleNode { + return forbidden("%s %s is not a node", c.p.Role, c.p.ID) + } + if c.p.ID != serverID { + return forbidden("node %s may act only for its own server id, not %q", c.p.ID, serverID) + } + return nil +} + +// RequireRole admits a person with at least min (development mode admits +// every call). +func RequireRole(ctx context.Context, min Role) error { + c, err := decided(ctx) + if err != nil || c.dev { + return err + } + if !(Rule{Min: min}).Allows(c.p) { + return forbidden("%s %s may not do this: it needs %s", c.p.Role, c.p.ID, min) + } + return nil +} + +func (a *Authenticator) admit(ctx context.Context, method string, rules map[string]Rule) (context.Context, error) { + p, err := a.PeerIdentity(ctx) + if err != nil { + return nil, err + } + r, ok := rules[method] + if !ok { + return nil, forbidden("method %s has no authorization rule", method) + } + if !r.Allows(p) { + return nil, forbidden("%s %s may not call %s", p.Role, p.ID, method) + } + return context.WithValue(ctx, ctxKey{}, callAuth{p: p}), nil +} + +// UnaryInterceptor authenticates every call (PeerIdentity) and applies its +// method's rule. +func (a *Authenticator) UnaryInterceptor(rules map[string]Rule) grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + ctx, err := a.admit(ctx, info.FullMethod, rules) + if err != nil { + return nil, err + } + return handler(ctx, req) + } +} + +// StreamInterceptor authenticates a stream when it opens, again before every +// message it sends, and again at every role-file reload: a caller removed +// from the file loses its open stream at the reload (UNAUTHENTICATED), not at +// the next message. +func (a *Authenticator) StreamInterceptor(rules map[string]Rule) grpc.StreamServerInterceptor { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + changed := a.Changed() + ctx, err := a.admit(ss.Context(), info.FullMethod, rules) + if err != nil { + return err + } + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + go func() { + for { + select { + case <-ctx.Done(): + return + case <-changed: + changed = a.Changed() + if _, err := a.PeerIdentity(ss.Context()); err != nil { + cancel(err) + return + } + } + } + }() + err = handler(srv, &authStream{ServerStream: ss, ctx: ctx, a: a}) + if cause := context.Cause(ctx); cause != nil && status.Code(cause) == codes.Unauthenticated { + return cause + } + return err + } +} + +type authStream struct { + grpc.ServerStream + ctx context.Context + a *Authenticator +} + +func (s *authStream) Context() context.Context { return s.ctx } + +func (s *authStream) SendMsg(m any) error { + if _, err := s.a.PeerIdentity(s.ServerStream.Context()); err != nil { + return err + } + return s.ServerStream.SendMsg(m) +} + +// DevUnaryInterceptor and DevStreamInterceptor mark every call as +// development mode (plaintext on loopback, no role file): RequireNode and +// RequireRole then admit it. +func DevUnaryInterceptor() grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + return handler(context.WithValue(ctx, ctxKey{}, callAuth{dev: true}), req) + } +} + +func DevStreamInterceptor() grpc.StreamServerInterceptor { + return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return handler(srv, &devStream{ServerStream: ss, ctx: context.WithValue(ss.Context(), ctxKey{}, callAuth{dev: true})}) + } +} + +type devStream struct { + grpc.ServerStream + ctx context.Context +} + +func (s *devStream) Context() context.Context { return s.ctx } diff --git a/seaweed-block/core/auth/authorize_test.go b/seaweed-block/core/auth/authorize_test.go new file mode 100644 index 0000000000..78fe84ec31 --- /dev/null +++ b/seaweed-block/core/auth/authorize_test.go @@ -0,0 +1,191 @@ +package auth_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +func TestRuleAllows(t *testing.T) { + p := func(r auth.Role) auth.Principal { return auth.Principal{Role: r, ID: "x"} } + for _, c := range []struct { + rule auth.Rule + role auth.Role + want bool + }{ + {auth.Rule{Min: auth.RoleViewer}, auth.RoleViewer, true}, + {auth.Rule{Min: auth.RoleViewer}, auth.RoleAdmin, true}, + {auth.Rule{Min: auth.RoleOperator}, auth.RoleViewer, false}, + {auth.Rule{Min: auth.RoleAdmin}, auth.RoleOperator, false}, + {auth.Rule{Min: auth.RoleAdmin}, auth.RoleNode, false}, + {auth.Rule{Node: true}, auth.RoleNode, true}, + {auth.Rule{Node: true}, auth.RoleAdmin, false}, + {auth.Rule{Min: auth.RoleViewer, Node: true}, auth.RoleNode, true}, + } { + if got := c.rule.Allows(p(c.role)); got != c.want { + t.Errorf("%+v allows %s = %v; want %v", c.rule, c.role, got, c.want) + } + } +} + +// The handler checks: a node only for its own server id; a person only +// with the role; development mode admits; a call no interceptor saw is +// refused (fail closed). +func TestRequireNodeAndRole(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1", op.Fingerprint+" operator alice"), nil) + rules := map[string]auth.Rule{"/m": {Min: auth.RoleViewer, Node: true}} + ctxOf := func(leaf *authtest.Leaf) context.Context { + var got context.Context + _, err := a.UnaryInterceptor(rules)(peerCtx(leaf, ca), nil, &grpc.UnaryServerInfo{FullMethod: "/m"}, func(ctx context.Context, _ any) (any, error) { + got = ctx + return nil, nil + }) + if err != nil { + t.Fatal(err) + } + return got + } + nodeCtx, opCtx := ctxOf(node), ctxOf(op) + if err := auth.RequireNode(nodeCtx, "s1"); err != nil { + t.Fatalf("node for its own id: %v", err) + } + if err := auth.RequireNode(nodeCtx, "s2"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("node for another id: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireNode(opCtx, "s1"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("operator as a node: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireRole(opCtx, auth.RoleOperator); err != nil { + t.Fatalf("operator needing operator: %v", err) + } + if err := auth.RequireRole(opCtx, auth.RoleAdmin); status.Code(err) != codes.PermissionDenied { + t.Fatalf("operator needing admin: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireRole(nodeCtx, auth.RoleViewer); status.Code(err) != codes.PermissionDenied { + t.Fatalf("node needing viewer: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireNode(context.Background(), "s1"); status.Code(err) != codes.Unauthenticated { + t.Fatalf("no interceptor ran: %v; want UNAUTHENTICATED (fail closed)", err) + } + var devCtx context.Context + _, _ = auth.DevUnaryInterceptor()(context.Background(), nil, &grpc.UnaryServerInfo{FullMethod: "/m"}, func(ctx context.Context, _ any) (any, error) { + devCtx = ctx + return nil, nil + }) + if auth.RequireNode(devCtx, "anything") != nil || auth.RequireRole(devCtx, auth.RoleAdmin) != nil { + t.Fatal("development mode must admit") + } + if _, ok := auth.FromContext(devCtx); ok { + t.Fatal("development mode has no principal") + } +} + +// The unary interceptor refuses a caller without a role on the method +// (PERMISSION_DENIED), an unauthenticated one (UNAUTHENTICATED), and any +// method without a rule (fail closed). +func TestUnaryInterceptor(t *testing.T) { + ca := authtest.NewCA(t, "ca") + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, op.Fingerprint+" operator alice"), nil) + rules := map[string]auth.Rule{"/viewer": {Min: auth.RoleViewer}, "/admin": {Min: auth.RoleAdmin}} + call := func(ctx context.Context, method string) error { + _, err := a.UnaryInterceptor(rules)(ctx, nil, &grpc.UnaryServerInfo{FullMethod: method}, func(ctx context.Context, _ any) (any, error) { + if p, ok := auth.FromContext(ctx); !ok || p.ID != "alice" { + t.Errorf("handler principal %+v %v", p, ok) + } + return nil, nil + }) + return err + } + if err := call(peerCtx(op, ca), "/viewer"); err != nil { + t.Fatalf("operator on a viewer method: %v", err) + } + if err := call(peerCtx(op, ca), "/admin"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("operator on an admin method: %v; want PERMISSION_DENIED", err) + } + if err := call(peerCtx(op, ca), "/unlisted"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("a method without a rule: %v; want PERMISSION_DENIED", err) + } + if err := call(peerCtx(nil, ca), "/viewer"); status.Code(err) != codes.Unauthenticated { + t.Fatalf("no client certificate: %v; want UNAUTHENTICATED", err) + } +} + +type fakeStream struct { + ctx context.Context + sent int +} + +func (s *fakeStream) SetHeader(metadata.MD) error { return nil } +func (s *fakeStream) SendHeader(metadata.MD) error { return nil } +func (s *fakeStream) SetTrailer(metadata.MD) {} +func (s *fakeStream) Context() context.Context { return s.ctx } +func (s *fakeStream) SendMsg(any) error { s.sent++; return nil } +func (s *fakeStream) RecvMsg(any) error { return nil } + +// T4: a stream whose caller is removed from the role file ends at the reload +// with UNAUTHENTICATED, without waiting for its next message; a send after an +// expiry is refused too. +func TestStreamEndsAtTheReloadThatRevokesItsCaller(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1"), nil) + rules := map[string]auth.Rule{"/stream": {Node: true}} + ss := &fakeStream{ctx: peerCtx(node, ca)} + done := make(chan error, 1) + opened := make(chan struct{}) + go func() { + done <- a.StreamInterceptor(rules)(nil, ss, &grpc.StreamServerInfo{FullMethod: "/stream"}, func(_ any, s grpc.ServerStream) error { + if err := s.SendMsg("first"); err != nil { + return err + } + close(opened) + <-s.Context().Done() // an idle stream: no message is pending + return s.Context().Err() + }) + }() + <-opened + a.Swap(table(t, "# s1 removed")) + select { + case err := <-done: + if status.Code(err) != codes.Unauthenticated { + t.Fatalf("stream after its caller was removed: %v; want UNAUTHENTICATED", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the stream did not end at the reload") + } + if ss.sent != 1 { + t.Fatalf("sent %d messages; want 1", ss.sent) + } + // A reload that keeps the caller does not end the stream. + a2 := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1"), nil) + ss2 := &fakeStream{ctx: peerCtx(node, ca)} + release := make(chan struct{}) + done2 := make(chan error, 1) + go func() { + done2 <- a2.StreamInterceptor(rules)(nil, ss2, &grpc.StreamServerInfo{FullMethod: "/stream"}, func(_ any, s grpc.ServerStream) error { + select { + case <-s.Context().Done(): + return s.Context().Err() + case <-release: + return s.SendMsg("after the reload") + } + }) + }() + a2.Swap(table(t, node.Fingerprint+" node s1", "# reloaded")) + time.Sleep(50 * time.Millisecond) + close(release) + if err := <-done2; err != nil { + t.Fatalf("a reload that keeps the caller ended its stream: %v", err) + } +} diff --git a/seaweed-block/core/auth/identity.go b/seaweed-block/core/auth/identity.go index 8059f083bc..b9f5d30edf 100644 --- a/seaweed-block/core/auth/identity.go +++ b/seaweed-block/core/auth/identity.go @@ -13,6 +13,7 @@ import ( "io" "os" "strings" + "sync" "sync/atomic" "time" @@ -113,6 +114,9 @@ func LoadRoleFile(path string) (*Table, error) { type Authenticator struct { table atomic.Pointer[Table] now func() time.Time + + mu sync.Mutex + changed chan struct{} // closed (and replaced) by every Swap } // NewAuthenticator starts with t; now nil is time.Now. @@ -120,13 +124,27 @@ func NewAuthenticator(t *Table, now func() time.Time) *Authenticator { if now == nil { now = time.Now } - a := &Authenticator{now: now} + a := &Authenticator{now: now, changed: make(chan struct{})} a.table.Store(t) return a } -// Swap installs t for every later call. -func (a *Authenticator) Swap(t *Table) { a.table.Store(t) } +// Swap installs t for every later call, and wakes every open stream to +// check its caller against it. +func (a *Authenticator) Swap(t *Table) { + a.table.Store(t) + a.mu.Lock() + close(a.changed) + a.changed = make(chan struct{}) + a.mu.Unlock() +} + +// Changed is closed by the next Swap. +func (a *Authenticator) Changed() <-chan struct{} { + a.mu.Lock() + defer a.mu.Unlock() + return a.changed +} // Reload parses path and installs it; on any error the current table stays. func (a *Authenticator) Reload(path string) error {