fix(gateway): attribute chat settings to signed-in users
This commit is contained in:
15 files changed
+296
-109
No files matched your search
@@ -9,10 +9,12 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
)
|
||||
|
||||
@@ -98,14 +100,15 @@ const inboundMessageHeadroomBytes = 1 << 20
|
||||
// request carries a channel attachment's bytes: the channel frontend
|
||||
// downloads the file, and this process -- which runs the turn -- holds no
|
||||
// platform credential to fetch it again.
|
||||
func gatewayServerOpts(listen, token string) (opts []grpc.ServerOption, loopback bool, err error) {
|
||||
func gatewayServerOpts(listen, token string, principals access.PrincipalSource) (opts []grpc.ServerOption, loopback bool, err error) {
|
||||
callers := rpcidentity.Callers{Principals: principals}
|
||||
recv := grpc.MaxRecvMsgSize(messaging.MaxInboundAttachmentBytes + inboundMessageHeadroomBytes)
|
||||
loopback, err = gatewayrpc.TargetIsLoopback(listen)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if loopback {
|
||||
return []grpc.ServerOption{recv}, true, nil
|
||||
return []grpc.ServerOption{recv, grpc.ChainUnaryInterceptor(callers.Unary()), grpc.ChainStreamInterceptor(callers.Stream())}, true, nil
|
||||
}
|
||||
if token == "" {
|
||||
return nil, false, fmt.Errorf(
|
||||
@@ -115,8 +118,8 @@ func gatewayServerOpts(listen, token string) (opts []grpc.ServerOption, loopback
|
||||
}
|
||||
return []grpc.ServerOption{
|
||||
recv,
|
||||
grpc.ChainUnaryInterceptor(gatewayrpc.UnaryServerInterceptor(token)),
|
||||
grpc.ChainStreamInterceptor(gatewayrpc.StreamServerInterceptor(token)),
|
||||
grpc.ChainUnaryInterceptor(gatewayrpc.UnaryServerInterceptor(token), callers.Unary()),
|
||||
grpc.ChainStreamInterceptor(gatewayrpc.StreamServerInterceptor(token), callers.Stream()),
|
||||
}, false, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agent"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
@@ -221,6 +223,7 @@ func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskAct
|
||||
}
|
||||
cfg := b.cfg
|
||||
router := gateway.NewRouter(b.stateStore, nil, "web")
|
||||
router.Settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(b.stateStore.ControlPlane())).WithIdentities(b.stateStore)
|
||||
router.Limiter = b.rateLimiter
|
||||
router.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", buildinfo.Version, buildinfo.Runtime)
|
||||
router.Models = b.chatModels
|
||||
|
||||
@@ -132,7 +132,7 @@ func Run(ctx context.Context, options Options) error {
|
||||
token = b.cfg.Services.ResolvedToken(config.ServiceNameGateway, b.secrets.Getenv)
|
||||
}
|
||||
//nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; gatewayrpc.StreamServerInterceptor derives its context from stream.Context() instead
|
||||
opts, loopback, err := gatewayServerOpts(listen, token)
|
||||
opts, loopback, err := gatewayServerOpts(listen, token, b.stateStore)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ func Run(ctx context.Context, o Options) error {
|
||||
return fmt.Errorf("resolve database telegram token: %w", settingsErr)
|
||||
}
|
||||
extensionChannels = openExtensionChannels(ctx, extensions, secrets, log)
|
||||
settings = messaging.NewSettingsCommand(messagingControlPlane{client: stateStore.ControlPlane()}).WithIdentities(stateStore)
|
||||
settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(stateStore.ControlPlane())).WithIdentities(stateStore)
|
||||
channelStatusStore, presenceStore = stateStore, stateStore
|
||||
settingsSource, applyReporter, appliedVersion = controlPlaneClient, reporter, channelVersion
|
||||
updates = controlplanerpc.UpdateService(controlPlaneClient, filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"), cfg.HealthURL)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package controlplane_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
)
|
||||
|
||||
func TestWebChatSettingsActor(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
db := pgstore.Open(t)
|
||||
if err := db.BootstrapIdentities(ctx, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.UpgradeDefaultOrg(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
steps, err := workflowsteps.NewManager()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cp, err := controlplane.NewServer(db, steps)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := cp.ImportConfig(ctx, config.Config{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := workflowRPC(t, cp, db)
|
||||
router := gateway.NewRouter(state, nil, "web")
|
||||
router.Settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(state.ControlPlane())).WithIdentities(state)
|
||||
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
callers := rpcidentity.Callers{Principals: state}
|
||||
srv := grpc.NewServer(grpc.ChainUnaryInterceptor(gatewayrpc.UnaryServerInterceptor("gateway-secret"), callers.Unary()), grpc.ChainStreamInterceptor(gatewayrpc.StreamServerInterceptor("gateway-secret"), callers.Stream()))
|
||||
gatewayrpc.RegisterServer(srv, &gateway.LocalChatAdapter{Router: router}, nil, gatewayrpc.Catalog{})
|
||||
go func() { _ = srv.Serve(listener) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
person, err := db.PrincipalFor(ctx, identity.OperatorID())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
name, token, sender string
|
||||
person, write, stream bool
|
||||
code codes.Code
|
||||
}{
|
||||
{name: "streamed signed-in person", stream: true, token: "gateway-secret", person: true, write: true},
|
||||
{name: "streamed wrong service credential", stream: true, token: "wrong", person: true, code: codes.Unauthenticated},
|
||||
{name: "signed-in person", token: "gateway-secret", person: true, write: true},
|
||||
{name: "message cannot spoof actor", token: "gateway-secret", sender: string(identity.SystemID), person: true, write: true},
|
||||
{name: "message alone cannot name a person", token: "gateway-secret", sender: string(identity.OperatorID())},
|
||||
{name: "wrong service credential cannot forward a principal", token: "wrong", person: true, code: codes.Unauthenticated},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
conn, err := grpc.NewClient(listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithUnaryInterceptor(gatewayrpc.UnaryClientTokenInterceptor(tt.token)), grpc.WithStreamInterceptor(gatewayrpc.StreamClientTokenInterceptor(tt.token)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
requestCtx := ctx
|
||||
if tt.person {
|
||||
requestCtx = access.WithPrincipal(ctx, person)
|
||||
}
|
||||
before, err := db.Resource(ctx, string(org.DefaultOrgID), controlplane.ReviewSettingsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
in := messaging.Inbound{Platform: "web", Message: messaging.Message{SenderID: tt.sender, Text: "/settings set review-settings precision_gate=true"}}
|
||||
client := gatewayrpc.NewClient(conn)
|
||||
reply, err := settingsReply(t, client, requestCtx, in, tt.stream, tt.code)
|
||||
if status.Code(err) != tt.code {
|
||||
t.Fatalf("route error = %v, want %s", err, tt.code)
|
||||
}
|
||||
after, err := db.Resource(ctx, string(org.DefaultOrgID), controlplane.ReviewSettingsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !tt.write {
|
||||
if after.Version != before.Version {
|
||||
t.Fatal("unauthenticated command changed settings")
|
||||
}
|
||||
return
|
||||
}
|
||||
history, err := db.ResourceHistory(ctx, string(org.DefaultOrgID), controlplane.ReviewSettingsKind, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(history) != 1 {
|
||||
t.Fatal("settings audit missing")
|
||||
}
|
||||
if !strings.Contains(reply.Text, "Updated review-settings") || after.Version != before.Version+1 || history[0].Actor != string(person.IdentityID) {
|
||||
t.Fatalf("reply %q, version %d -> %d, actor %q", reply.Text, before.Version, after.Version, history[0].Actor)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func settingsReply(t *testing.T, client *gatewayrpc.Client, ctx context.Context, in messaging.Inbound, stream bool, want codes.Code) (messaging.ChatReply, error) {
|
||||
t.Helper()
|
||||
if !stream {
|
||||
return client.Route(ctx, in)
|
||||
}
|
||||
events, err := client.Stream(ctx, in)
|
||||
if err != nil {
|
||||
return messaging.ChatReply{}, err
|
||||
}
|
||||
var reply messaging.ChatReply
|
||||
for event := range events {
|
||||
if event.Kind == "error" {
|
||||
if want == codes.OK || !strings.Contains(event.Text, "code = "+want.String()) {
|
||||
t.Fatalf("stream: %s", event.Text)
|
||||
}
|
||||
return messaging.ChatReply{}, status.Error(want, event.Text)
|
||||
}
|
||||
if event.Kind == "done" {
|
||||
reply.Text = event.Text
|
||||
}
|
||||
}
|
||||
return reply, nil
|
||||
}
|
||||
@@ -219,7 +219,7 @@ func resourceProto(resource storecontract.Resource) *pb.Resource {
|
||||
}
|
||||
|
||||
// requestOrg is the org a request acts in, derived from the caller's
|
||||
// principal when the call carried one (staterpc.Callers).
|
||||
// principal when the call carried one (rpcidentity.Callers).
|
||||
func requestOrg(ctx context.Context) string {
|
||||
return string(org.OrgFromContext(ctx))
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
@@ -123,7 +124,7 @@ func workflowRPC(t *testing.T, control *controlplane.Server, db *pgstore.TaskDB)
|
||||
}
|
||||
t.Cleanup(func() { _ = listener.Close() })
|
||||
grants := &staterpc.TaskGrants{}
|
||||
callers := staterpc.Callers{Principals: db}
|
||||
callers := rpcidentity.Callers{Principals: db}
|
||||
srv := grpc.NewServer(grpc.ChainUnaryInterceptor(grants.UnaryInterceptor("test-token"), callers.Unary()), grpc.ChainStreamInterceptor(grants.StreamInterceptor("test-token"), callers.Stream()))
|
||||
staterpc.RegisterServer(srv, staterpc.Deps{ControlPlane: control, Tasks: db, Principals: db, Identities: db})
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
@@ -29,6 +29,7 @@ import (
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/readiness"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
registry "github.com/samcharles93/archie-core/internal/infrastructure/storepkg"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
@@ -403,9 +404,9 @@ func (b *server) runCredentials(ctx context.Context) (*staterpc.TaskGrants, erro
|
||||
|
||||
// callers resolves the service and principal of each call against this
|
||||
// store's principals.
|
||||
func (b *server) callers() staterpc.Callers {
|
||||
func (b *server) callers() rpcidentity.Callers {
|
||||
ps, _ := b.st.(access.PrincipalSource)
|
||||
return staterpc.Callers{Principals: ps}
|
||||
return rpcidentity.Callers{Principals: ps}
|
||||
}
|
||||
|
||||
// accessDeps wires the policy chain and its denial records from the same
|
||||
@@ -511,7 +512,7 @@ func (b *server) startOptionalSurfaces(ctx context.Context, options Options) err
|
||||
// as a remote one (staterpc.Dial installs the client keepalive on every target,
|
||||
// loopback included), and grpc's default policy would answer their idle
|
||||
// watches with GOAWAY too_many_pings. See staterpc.ServerKeepaliveOption.
|
||||
func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants, callers staterpc.Callers) (opts []grpc.ServerOption, loopback bool, err error) {
|
||||
func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants, callers rpcidentity.Callers) (opts []grpc.ServerOption, loopback bool, err error) {
|
||||
loopback, err = staterpc.TargetIsLoopback(listen)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
@@ -104,6 +105,9 @@ func (c *SettingsCommand) Execute(ctx context.Context, actor, input string) stri
|
||||
// recorded against. A sender that does not resolve cannot run a command: the
|
||||
// audit record names an identity or the command does not happen.
|
||||
func (c *SettingsCommand) resolveActor(ctx context.Context, subject, actor string) (identity.IdentityID, string) {
|
||||
if p, ok := access.PrincipalFromContext(ctx); ok && p.IdentityID != "" {
|
||||
return p.IdentityID, ""
|
||||
}
|
||||
if strings.TrimSpace(actor) == "" {
|
||||
return "", subject + " require an authenticated Archie identity; this channel cannot resolve one."
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/ratelimit"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
@@ -344,7 +345,11 @@ func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platf
|
||||
reply, err := r.handleCancel(ctx, rest)
|
||||
return reply, true, err
|
||||
case "/settings":
|
||||
return r.Settings.Execute(ctx, "", rest), true, nil
|
||||
actor := ""
|
||||
if principal, ok := access.PrincipalFromContext(ctx); ok {
|
||||
actor = string(principal.IdentityID)
|
||||
}
|
||||
return r.Settings.Execute(ctx, actor, rest), true, nil
|
||||
case "/start":
|
||||
reply, err := r.handleStart()
|
||||
return reply, true, err
|
||||
|
||||
+12
-6
@@ -1,4 +1,4 @@
|
||||
package archiemessaging
|
||||
package controlplanerpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -13,9 +13,15 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type messagingControlPlane struct{ client pb.ControlPlaneServiceClient }
|
||||
// SettingsClient adapts control-plane resources for channel settings commands.
|
||||
type SettingsClient struct{ client pb.ControlPlaneServiceClient }
|
||||
|
||||
func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.SettingDescriptor, error) {
|
||||
// NewSettingsClient wraps the existing control-plane contract.
|
||||
func NewSettingsClient(client pb.ControlPlaneServiceClient) SettingsClient {
|
||||
return SettingsClient{client: client}
|
||||
}
|
||||
|
||||
func (c SettingsClient) Catalog(ctx context.Context) ([]messaging.SettingDescriptor, error) {
|
||||
response, err := c.client.Catalog(ctx, &pb.CatalogRequest{})
|
||||
if err != nil {
|
||||
return nil, settingsRPCError(err)
|
||||
@@ -29,7 +35,7 @@ func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.Setting
|
||||
WriteOnly bool `json:"writeOnly"`
|
||||
} `json:"properties"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(resource.SchemaJson), &schema); err != nil {
|
||||
if err := json.Unmarshal([]byte(resource.SchemaJson), &schema); strings.TrimSpace(resource.SchemaJson) != "" && err != nil {
|
||||
return nil, errors.Join(messaging.ErrSettingsValidation, err)
|
||||
}
|
||||
fields := make(map[string]messaging.SettingField, len(schema.Properties))
|
||||
@@ -45,7 +51,7 @@ func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.Setting
|
||||
return descriptors, nil
|
||||
}
|
||||
|
||||
func (c messagingControlPlane) Query(ctx context.Context, kind string) (messaging.SettingResource, error) {
|
||||
func (c SettingsClient) Query(ctx context.Context, kind string) (messaging.SettingResource, error) {
|
||||
response, err := c.client.Query(ctx, &pb.QueryRequest{Kind: kind})
|
||||
if err != nil {
|
||||
return messaging.SettingResource{}, settingsRPCError(err)
|
||||
@@ -53,7 +59,7 @@ func (c messagingControlPlane) Query(ctx context.Context, kind string) (messagin
|
||||
return settingResource(response.Resource)
|
||||
}
|
||||
|
||||
func (c messagingControlPlane) Command(ctx context.Context, command messaging.SettingCommand) (messaging.SettingResource, error) {
|
||||
func (c SettingsClient) Command(ctx context.Context, command messaging.SettingCommand) (messaging.SettingResource, error) {
|
||||
input := any(command.Value)
|
||||
if command.RawValue != nil {
|
||||
input = command.RawValue
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
)
|
||||
|
||||
// tokenMetadataKey is the gRPC metadata key the Gateway Bearer [REDACTED]
|
||||
@@ -79,7 +81,7 @@ func StreamServerInterceptor(token string) grpc.StreamServerInterceptor {
|
||||
// metadata under tokenMetadataKey.
|
||||
func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor {
|
||||
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
return invoker(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), method, req, reply, cc, opts...)
|
||||
return invoker(metadata.AppendToOutgoingContext(rpcidentity.Outgoing(ctx, "gateway-client"), tokenMetadataKey, token), method, req, reply, cc, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +90,6 @@ func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor {
|
||||
// see.
|
||||
func StreamClientTokenInterceptor(token string) grpc.StreamClientInterceptor {
|
||||
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
||||
return streamer(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), desc, cc, method, opts...)
|
||||
return streamer(metadata.AppendToOutgoingContext(rpcidentity.Outgoing(ctx, "gateway-client"), tokenMetadataKey, token), desc, cc, method, opts...)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Package rpcidentity attributes authenticated service calls to their principal.
|
||||
package rpcidentity
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// CallerKey names the service making the call.
|
||||
const CallerKey = "state-store-caller"
|
||||
|
||||
// PrincipalKey carries the identity a service acts for, when it acts
|
||||
// for one.
|
||||
const PrincipalKey = "state-store-principal"
|
||||
|
||||
// Outgoing forwards the context's principal, replacing any stale attribution.
|
||||
func Outgoing(ctx context.Context, caller string) context.Context {
|
||||
md, _ := metadata.FromOutgoingContext(ctx)
|
||||
md = md.Copy()
|
||||
md.Set(CallerKey, caller)
|
||||
md.Delete(PrincipalKey)
|
||||
if p, ok := access.PrincipalFromContext(ctx); ok {
|
||||
md.Set(PrincipalKey, string(p.IdentityID))
|
||||
}
|
||||
return metadata.NewOutgoingContext(ctx, md)
|
||||
}
|
||||
|
||||
// Callers resolves who a call is made by. It runs after authentication,
|
||||
// which is what makes the metadata trustworthy: only holders of the instance
|
||||
// credential reach it with their metadata intact (a task grant's is
|
||||
// stripped). A call naming a principal acts in that principal's org; any
|
||||
// other acts in the default org.
|
||||
type Callers struct {
|
||||
Principals access.PrincipalSource
|
||||
}
|
||||
|
||||
func (c Callers) resolve(ctx context.Context) (context.Context, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
caller := first(md, CallerKey)
|
||||
if caller != "" {
|
||||
ctx = access.WithActor(access.WithSource(ctx, caller), caller)
|
||||
}
|
||||
id := first(md, PrincipalKey)
|
||||
if id == "" {
|
||||
return ctx, nil
|
||||
}
|
||||
if c.Principals == nil {
|
||||
return nil, status.Error(codes.Unavailable, "principals unavailable")
|
||||
}
|
||||
p, err := c.Principals.PrincipalFor(ctx, identity.IdentityID(id))
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Unavailable, "resolve principal: %v", err)
|
||||
}
|
||||
return org.WithOrg(access.WithActor(access.WithPrincipal(ctx, p), id), p.Org), nil
|
||||
}
|
||||
|
||||
// Unary attributes unary calls.
|
||||
func (c Callers) Unary() grpc.UnaryServerInterceptor {
|
||||
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
ctx, err := c.resolve(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
}
|
||||
|
||||
// Stream attributes streams.
|
||||
func (c Callers) Stream() grpc.StreamServerInterceptor {
|
||||
return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
ctx, err := c.resolve(stream.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return handler(srv, attributedStream{ServerStream: stream, ctx: ctx})
|
||||
}
|
||||
}
|
||||
|
||||
type attributedStream struct {
|
||||
grpc.ServerStream
|
||||
ctx context.Context //nolint:containedctx // grpc.ServerStream exposes its context only through Context()
|
||||
}
|
||||
|
||||
func (s attributedStream) Context() context.Context { return s.ctx }
|
||||
|
||||
func first(md metadata.MD, key string) string {
|
||||
if values := md.Get(key); len(values) > 0 {
|
||||
return values[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -4,37 +4,21 @@ import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
)
|
||||
|
||||
// tokenMetadataKey is the gRPC metadata key the bearer token travels in.
|
||||
// Metadata, never a URL.
|
||||
const tokenMetadataKey = "state-store-token"
|
||||
|
||||
// callerMetadataKey names the service making the call.
|
||||
const callerMetadataKey = "state-store-caller"
|
||||
|
||||
// principalMetadataKey carries the identity a service acts for, when it acts
|
||||
// for one.
|
||||
const principalMetadataKey = "state-store-principal"
|
||||
|
||||
// outgoing stamps the caller's service name, the principal on ctx when there
|
||||
// is one, and the token when set.
|
||||
func outgoing(ctx context.Context, caller, token string) context.Context {
|
||||
pairs := []string{callerMetadataKey, caller}
|
||||
if p, ok := access.PrincipalFromContext(ctx); ok {
|
||||
pairs = append(pairs, principalMetadataKey, string(p.IdentityID))
|
||||
}
|
||||
ctx = rpcidentity.Outgoing(ctx, caller)
|
||||
if token != "" {
|
||||
pairs = append(pairs, tokenMetadataKey, token)
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token)
|
||||
}
|
||||
return metadata.AppendToOutgoingContext(ctx, pairs...)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// UnaryClientCredentialInterceptor attaches caller and token to every
|
||||
@@ -52,68 +36,3 @@ func StreamClientCredentialInterceptor(caller, token string) grpc.StreamClientIn
|
||||
return streamer(outgoing(ctx, caller, token), desc, cc, method, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// Callers resolves who a call is made by. It runs after authentication,
|
||||
// which is what makes the metadata trustworthy: only holders of the instance
|
||||
// credential reach it with their metadata intact (a task grant's is
|
||||
// stripped). A call naming a principal acts in that principal's org; any
|
||||
// other acts in the default org.
|
||||
type Callers struct {
|
||||
Principals access.PrincipalSource
|
||||
}
|
||||
|
||||
func (c Callers) resolve(ctx context.Context) (context.Context, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
caller := first(md, callerMetadataKey)
|
||||
if caller != "" {
|
||||
ctx = access.WithActor(access.WithSource(ctx, caller), caller)
|
||||
}
|
||||
id := first(md, principalMetadataKey)
|
||||
if id == "" {
|
||||
return ctx, nil
|
||||
}
|
||||
if c.Principals == nil {
|
||||
return nil, status.Error(codes.Unavailable, "principals unavailable")
|
||||
}
|
||||
p, err := c.Principals.PrincipalFor(ctx, identity.IdentityID(id))
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Unavailable, "resolve principal: %v", err)
|
||||
}
|
||||
return org.WithOrg(access.WithActor(access.WithPrincipal(ctx, p), id), p.Org), nil
|
||||
}
|
||||
|
||||
// Unary attributes unary calls.
|
||||
func (c Callers) Unary() grpc.UnaryServerInterceptor {
|
||||
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
ctx, err := c.resolve(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
}
|
||||
|
||||
// Stream attributes streams.
|
||||
func (c Callers) Stream() grpc.StreamServerInterceptor {
|
||||
return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
ctx, err := c.resolve(stream.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return handler(srv, attributedStream{ServerStream: stream, ctx: ctx})
|
||||
}
|
||||
}
|
||||
|
||||
type attributedStream struct {
|
||||
grpc.ServerStream
|
||||
ctx context.Context //nolint:containedctx // grpc.ServerStream exposes its context only through Context()
|
||||
}
|
||||
|
||||
func (s attributedStream) Context() context.Context { return s.ctx }
|
||||
|
||||
func first(md metadata.MD, key string) string {
|
||||
if values := md.Get(key); len(values) > 0 {
|
||||
return values[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
)
|
||||
|
||||
// credentials is an in-memory RunCredentialStore.
|
||||
@@ -53,7 +54,7 @@ func TestCallerAttribution(t *testing.T) {
|
||||
if err := grants.register(context.Background(), 7, taskToken, time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
callers := Callers{Principals: principalsByID{"alice": "acme"}}
|
||||
callers := rpcidentity.Callers{Principals: principalsByID{"alice": "acme"}}
|
||||
update := &grpc.UnaryServerInfo{FullMethod: pb.StateStoreService_Update_FullMethodName}
|
||||
|
||||
tests := []struct {
|
||||
@@ -62,9 +63,9 @@ func TestCallerAttribution(t *testing.T) {
|
||||
wantActor string
|
||||
wantOrg org.OrgID
|
||||
}{
|
||||
{"service alone acts in the default org", []string{tokenMetadataKey, admin, callerMetadataKey, "archied"}, "archied", org.DefaultOrgID},
|
||||
{"forwarded principal sets actor and org", []string{tokenMetadataKey, admin, callerMetadataKey, "archie-ui", principalMetadataKey, "alice"}, "alice", "acme"},
|
||||
{"task grant cannot claim a principal", []string{tokenMetadataKey, taskToken, callerMetadataKey, "archie-ui", principalMetadataKey, "alice"}, "task/7", org.DefaultOrgID},
|
||||
{"service alone acts in the default org", []string{tokenMetadataKey, admin, rpcidentity.CallerKey, "archied"}, "archied", org.DefaultOrgID},
|
||||
{"forwarded principal sets actor and org", []string{tokenMetadataKey, admin, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "alice", "acme"},
|
||||
{"task grant cannot claim a principal", []string{tokenMetadataKey, taskToken, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "task/7", org.DefaultOrgID},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user