feat(access): policy, denial and principal persistence on the State Store contract (archie-core-qc8p)
This commit is contained in:
17 files changed
+2925
-198
No files matched your search
@@ -21,11 +21,13 @@ import (
|
||||
|
||||
"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/health"
|
||||
"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/domain/storepkg"
|
||||
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/staterpc"
|
||||
@@ -105,6 +107,46 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error {
|
||||
return fmt.Errorf("upgrade default org: %w", err)
|
||||
}
|
||||
}
|
||||
// The shipped role policies mean the org level always has policies
|
||||
// (docs/prds/orgs-and-access.md, "Roles"): seed them for every org that
|
||||
// lacks them, then re-validate every stored policy this process serves.
|
||||
// An invalid org, workspace or object policy is logged here and named as
|
||||
// a problem by the engines the consumers build; an invalid instance
|
||||
// policy fails this boot -- the store stops serving until it is fixed.
|
||||
if policies, ok := b.st.(access.PolicyStore); ok {
|
||||
// An agent is granted access the way a user is: its assigned org,
|
||||
// with the shipped developer role, so dispatch's principal evaluates.
|
||||
if agents, ok := b.st.(interface {
|
||||
EnsureAgentOrgMembership(context.Context) error
|
||||
}); ok {
|
||||
if err := agents.EnsureAgentOrgMembership(ctx); err != nil {
|
||||
return fmt.Errorf("grant agent org membership: %w", err)
|
||||
}
|
||||
}
|
||||
if orgs, ok := b.st.(org.Repository); ok {
|
||||
list, err := orgs.ListOrgs(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list orgs for policy seeding: %w", err)
|
||||
}
|
||||
for _, o := range list {
|
||||
if err := policies.EnsureShippedOrgPolicies(ctx, o.ID); err != nil {
|
||||
return fmt.Errorf("seed shipped org policies for %s: %w", o.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
stored, err := policies.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load stored policies: %w", err)
|
||||
}
|
||||
engine, err := infraaccess.New(stored)
|
||||
if err != nil {
|
||||
return fmt.Errorf("validate stored policies: %w", err)
|
||||
}
|
||||
for _, problem := range engine.Problems() {
|
||||
b.log.Error("stored access policy is invalid and denies its level",
|
||||
"policy", problem.Policy.ID, "level", problem.Policy.Level, "err", problem.Err)
|
||||
}
|
||||
}
|
||||
resources, ok := b.st.(controlplane.ResourceStore)
|
||||
if !ok {
|
||||
return fmt.Errorf("state store does not support control-plane resources")
|
||||
@@ -287,6 +329,19 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
if wc, ok := b.st.(storecontract.WorkflowCaller); ok {
|
||||
deps.WorkflowCalls = wc
|
||||
}
|
||||
// The policy chain and its denial records are served from the same store
|
||||
// (docs/prds/orgs-and-access.md). A store without them -- one that owns
|
||||
// no tenant boundary yet -- degrades the access RPCs rather than failing
|
||||
// the boot, the same pattern the other optional surfaces use.
|
||||
if ps, ok := b.st.(access.PrincipalSource); ok {
|
||||
deps.Principals = ps
|
||||
}
|
||||
if ps, ok := b.st.(access.PolicyStore); ok {
|
||||
deps.Policies = ps
|
||||
}
|
||||
if ds, ok := b.st.(access.DenialStore); ok {
|
||||
deps.Denials = ds
|
||||
}
|
||||
if css, ok := b.st.(storecontract.ConfigSnapshotStore); ok {
|
||||
deps.ConfigSnapshots = css
|
||||
}
|
||||
|
||||
+1218
-197
File diff suppressed because it is too large.
Load diff
@@ -100,6 +100,13 @@ const (
|
||||
StateStoreService_EnqueueBindingTask_FullMethodName = "/state.v1.StateStoreService/EnqueueBindingTask"
|
||||
StateStoreService_EnqueueCallTask_FullMethodName = "/state.v1.StateStoreService/EnqueueCallTask"
|
||||
StateStoreService_WorkflowCallStatus_FullMethodName = "/state.v1.StateStoreService/WorkflowCallStatus"
|
||||
StateStoreService_GetPrincipal_FullMethodName = "/state.v1.StateStoreService/GetPrincipal"
|
||||
StateStoreService_ListPolicies_FullMethodName = "/state.v1.StateStoreService/ListPolicies"
|
||||
StateStoreService_PutPolicy_FullMethodName = "/state.v1.StateStoreService/PutPolicy"
|
||||
StateStoreService_DeletePolicy_FullMethodName = "/state.v1.StateStoreService/DeletePolicy"
|
||||
StateStoreService_EnsureShippedOrgPolicies_FullMethodName = "/state.v1.StateStoreService/EnsureShippedOrgPolicies"
|
||||
StateStoreService_RecordDenial_FullMethodName = "/state.v1.StateStoreService/RecordDenial"
|
||||
StateStoreService_ListDenials_FullMethodName = "/state.v1.StateStoreService/ListDenials"
|
||||
)
|
||||
|
||||
// StateStoreServiceClient is the client API for StateStoreService service.
|
||||
@@ -252,6 +259,19 @@ type StateStoreServiceClient interface {
|
||||
// relation server-side, so the grant only names the caller.
|
||||
EnqueueCallTask(ctx context.Context, in *EnqueueCallTaskRequest, opts ...grpc.CallOption) (*EnqueueCallTaskResponse, error)
|
||||
WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error)
|
||||
// Access: the stored policy chain and its denial records
|
||||
// (docs/prds/orgs-and-access.md). ListPolicies is the engine's snapshot;
|
||||
// the writes are administrative. RecordDenial is the dashboard's and
|
||||
// dispatch's write path; ListDenials is the operator surface.
|
||||
// The principal assembly the Authorizer evaluates: an identity, the org
|
||||
// it serves, and its memberships (internal/domain/access).
|
||||
GetPrincipal(ctx context.Context, in *GetPrincipalRequest, opts ...grpc.CallOption) (*GetPrincipalResponse, error)
|
||||
ListPolicies(ctx context.Context, in *ListPoliciesRequest, opts ...grpc.CallOption) (*ListPoliciesResponse, error)
|
||||
PutPolicy(ctx context.Context, in *PutPolicyRequest, opts ...grpc.CallOption) (*PutPolicyResponse, error)
|
||||
DeletePolicy(ctx context.Context, in *DeletePolicyRequest, opts ...grpc.CallOption) (*DeletePolicyResponse, error)
|
||||
EnsureShippedOrgPolicies(ctx context.Context, in *EnsureShippedOrgPoliciesRequest, opts ...grpc.CallOption) (*EnsureShippedOrgPoliciesResponse, error)
|
||||
RecordDenial(ctx context.Context, in *RecordDenialRequest, opts ...grpc.CallOption) (*RecordDenialResponse, error)
|
||||
ListDenials(ctx context.Context, in *ListDenialsRequest, opts ...grpc.CallOption) (*ListDenialsResponse, error)
|
||||
}
|
||||
|
||||
type stateStoreServiceClient struct {
|
||||
@@ -1099,6 +1119,76 @@ func (c *stateStoreServiceClient) WorkflowCallStatus(ctx context.Context, in *Wo
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) GetPrincipal(ctx context.Context, in *GetPrincipalRequest, opts ...grpc.CallOption) (*GetPrincipalResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetPrincipalResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_GetPrincipal_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListPolicies(ctx context.Context, in *ListPoliciesRequest, opts ...grpc.CallOption) (*ListPoliciesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListPoliciesResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListPolicies_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) PutPolicy(ctx context.Context, in *PutPolicyRequest, opts ...grpc.CallOption) (*PutPolicyResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(PutPolicyResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_PutPolicy_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) DeletePolicy(ctx context.Context, in *DeletePolicyRequest, opts ...grpc.CallOption) (*DeletePolicyResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeletePolicyResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_DeletePolicy_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) EnsureShippedOrgPolicies(ctx context.Context, in *EnsureShippedOrgPoliciesRequest, opts ...grpc.CallOption) (*EnsureShippedOrgPoliciesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(EnsureShippedOrgPoliciesResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_EnsureShippedOrgPolicies_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RecordDenial(ctx context.Context, in *RecordDenialRequest, opts ...grpc.CallOption) (*RecordDenialResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RecordDenialResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_RecordDenial_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListDenials(ctx context.Context, in *ListDenialsRequest, opts ...grpc.CallOption) (*ListDenialsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListDenialsResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListDenials_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// StateStoreServiceServer is the server API for StateStoreService service.
|
||||
// All implementations must embed UnimplementedStateStoreServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -1249,6 +1339,19 @@ type StateStoreServiceServer interface {
|
||||
// relation server-side, so the grant only names the caller.
|
||||
EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error)
|
||||
WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error)
|
||||
// Access: the stored policy chain and its denial records
|
||||
// (docs/prds/orgs-and-access.md). ListPolicies is the engine's snapshot;
|
||||
// the writes are administrative. RecordDenial is the dashboard's and
|
||||
// dispatch's write path; ListDenials is the operator surface.
|
||||
// The principal assembly the Authorizer evaluates: an identity, the org
|
||||
// it serves, and its memberships (internal/domain/access).
|
||||
GetPrincipal(context.Context, *GetPrincipalRequest) (*GetPrincipalResponse, error)
|
||||
ListPolicies(context.Context, *ListPoliciesRequest) (*ListPoliciesResponse, error)
|
||||
PutPolicy(context.Context, *PutPolicyRequest) (*PutPolicyResponse, error)
|
||||
DeletePolicy(context.Context, *DeletePolicyRequest) (*DeletePolicyResponse, error)
|
||||
EnsureShippedOrgPolicies(context.Context, *EnsureShippedOrgPoliciesRequest) (*EnsureShippedOrgPoliciesResponse, error)
|
||||
RecordDenial(context.Context, *RecordDenialRequest) (*RecordDenialResponse, error)
|
||||
ListDenials(context.Context, *ListDenialsRequest) (*ListDenialsResponse, error)
|
||||
mustEmbedUnimplementedStateStoreServiceServer()
|
||||
}
|
||||
|
||||
@@ -1502,6 +1605,27 @@ func (UnimplementedStateStoreServiceServer) EnqueueCallTask(context.Context, *En
|
||||
func (UnimplementedStateStoreServiceServer) WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method WorkflowCallStatus not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) GetPrincipal(context.Context, *GetPrincipalRequest) (*GetPrincipalResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetPrincipal not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListPolicies(context.Context, *ListPoliciesRequest) (*ListPoliciesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListPolicies not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) PutPolicy(context.Context, *PutPolicyRequest) (*PutPolicyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method PutPolicy not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) DeletePolicy(context.Context, *DeletePolicyRequest) (*DeletePolicyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeletePolicy not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) EnsureShippedOrgPolicies(context.Context, *EnsureShippedOrgPoliciesRequest) (*EnsureShippedOrgPoliciesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method EnsureShippedOrgPolicies not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RecordDenial(context.Context, *RecordDenialRequest) (*RecordDenialResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RecordDenial not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListDenials(context.Context, *ListDenialsRequest) (*ListDenialsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListDenials not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) mustEmbedUnimplementedStateStoreServiceServer() {}
|
||||
func (UnimplementedStateStoreServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -2960,6 +3084,132 @@ func _StateStoreService_WorkflowCallStatus_Handler(srv interface{}, ctx context.
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_GetPrincipal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetPrincipalRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).GetPrincipal(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_GetPrincipal_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).GetPrincipal(ctx, req.(*GetPrincipalRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListPolicies_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListPoliciesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListPolicies(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListPolicies_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListPolicies(ctx, req.(*ListPoliciesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_PutPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(PutPolicyRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).PutPolicy(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_PutPolicy_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).PutPolicy(ctx, req.(*PutPolicyRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_DeletePolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DeletePolicyRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).DeletePolicy(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_DeletePolicy_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).DeletePolicy(ctx, req.(*DeletePolicyRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_EnsureShippedOrgPolicies_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(EnsureShippedOrgPoliciesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).EnsureShippedOrgPolicies(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_EnsureShippedOrgPolicies_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).EnsureShippedOrgPolicies(ctx, req.(*EnsureShippedOrgPoliciesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RecordDenial_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RecordDenialRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).RecordDenial(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_RecordDenial_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).RecordDenial(ctx, req.(*RecordDenialRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListDenials_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListDenialsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListDenials(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListDenials_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListDenials(ctx, req.(*ListDenialsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// StateStoreService_ServiceDesc is the grpc.ServiceDesc for StateStoreService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -3279,6 +3529,34 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "WorkflowCallStatus",
|
||||
Handler: _StateStoreService_WorkflowCallStatus_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetPrincipal",
|
||||
Handler: _StateStoreService_GetPrincipal_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListPolicies",
|
||||
Handler: _StateStoreService_ListPolicies_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "PutPolicy",
|
||||
Handler: _StateStoreService_PutPolicy_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "DeletePolicy",
|
||||
Handler: _StateStoreService_DeletePolicy_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "EnsureShippedOrgPolicies",
|
||||
Handler: _StateStoreService_EnsureShippedOrgPolicies_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RecordDenial",
|
||||
Handler: _StateStoreService_RecordDenial_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListDenials",
|
||||
Handler: _StateStoreService_ListDenials_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
@@ -129,6 +130,16 @@ func DeniedAt(level Level, policies []string) Decision {
|
||||
return Decision{Level: level, Policies: policies}
|
||||
}
|
||||
|
||||
// PrincipalSource assembles the principal for one identity: the org it
|
||||
// serves and its memberships. The State Store implements it (the memberships
|
||||
// live in the State Store); the dashboard and dispatch call it over the wire.
|
||||
type PrincipalSource interface {
|
||||
// PrincipalFor returns the assembled principal. An identity in no org
|
||||
// resolves to the default org, a principal with no role, which no
|
||||
// shipped policy permits.
|
||||
PrincipalFor(ctx context.Context, id identity.IdentityID) (Principal, error)
|
||||
}
|
||||
|
||||
// Denial is one recorded refusal: who was refused, doing what, to what, by
|
||||
// which level and which policies (docs/prds/orgs-and-access.md, "Denials").
|
||||
type Denial struct {
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// Access policies and denial records: the Postgres implementation of
|
||||
// internal/domain/access's PolicyStore, Resetter and DenialStore
|
||||
// (docs/prds/orgs-and-access.md). Policy changes are versioned per level
|
||||
// scope and audited as one sys_audit row per change naming who made it.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"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/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var (
|
||||
_ access.PolicyStore = (*Store)(nil)
|
||||
_ access.Resetter = (*Store)(nil)
|
||||
_ access.DenialStore = (*Store)(nil)
|
||||
)
|
||||
|
||||
// shippedOrgPolicyIDs lists an org's shipped role policy IDs: the seed's
|
||||
// conflict keys, and what an org reset keeps.
|
||||
func shippedOrgPolicyIDs() []string {
|
||||
ids := make([]string, 0, 4)
|
||||
for _, p := range access.ShippedOrgPolicies("") {
|
||||
ids = append(ids, p.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// accessScopeOf is the scope tuple every access query carries.
|
||||
func accessScopeOf(p access.Policy) (string, string, string, string, string, string) {
|
||||
return string(p.Level), string(p.OrgID), string(p.WorkspaceID),
|
||||
string(p.ObjectKind), p.ObjectID, p.ID
|
||||
}
|
||||
|
||||
// auditKey is the sys_audit record_key for one policy: its scope and ID, so
|
||||
// an operator can trace one policy document's changes.
|
||||
func auditKey(p access.Policy) string {
|
||||
joined := strings.Join([]string{
|
||||
string(p.Level), string(p.OrgID), string(p.WorkspaceID),
|
||||
string(p.ObjectKind), p.ObjectID, p.ID,
|
||||
}, "/")
|
||||
return strings.Trim(joined, "/")
|
||||
}
|
||||
|
||||
// textJSON wraps a policy text as the JSON string sys_audit stores.
|
||||
func textJSON(text string) []byte {
|
||||
out, _ := json.Marshal(text)
|
||||
return out
|
||||
}
|
||||
|
||||
// ListPolicies returns every stored policy across levels.
|
||||
func (s *Store) ListPolicies(ctx context.Context) ([]access.Policy, error) {
|
||||
rows, err := s.queries().ListAccessPolicies(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]access.Policy, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, access.Policy{
|
||||
ID: r.PolicyID,
|
||||
Level: access.Level(r.Level),
|
||||
OrgID: org.OrgID(r.OrgID),
|
||||
WorkspaceID: org.WorkspaceID(r.WorkspaceID),
|
||||
ObjectKind: access.ResourceKind(r.ObjectKind),
|
||||
ObjectID: r.ObjectID,
|
||||
Text: r.Text,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PutPolicy stores or replaces one policy by its scope+ID key, bumps the
|
||||
// level's version, and writes the audit row -- in one transaction, so a
|
||||
// version that never moved cannot advertise a change that half-landed.
|
||||
func (s *Store) PutPolicy(ctx context.Context, p access.Policy) (int64, error) {
|
||||
if err := p.Validate(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
q := s.queries()
|
||||
level, orgID, wsID, kind, id, policyID := accessScopeOf(p)
|
||||
var version int64
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
q := q.WithTx(tx)
|
||||
if err := q.UpsertAccessPolicy(ctx, postgresdb.UpsertAccessPolicyParams{
|
||||
Level: level, OrgID: orgID, WorkspaceID: wsID,
|
||||
ObjectKind: kind, ObjectID: id,
|
||||
PolicyID: policyID, Text: p.Text,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
v, err := q.UpsertAccessPolicyVersion(ctx, postgresdb.UpsertAccessPolicyVersionParams{
|
||||
Level: level, OrgID: orgID, WorkspaceID: wsID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
version = v
|
||||
return q.InsertAccessPolicyAudit(ctx, postgresdb.InsertAccessPolicyAuditParams{
|
||||
RecordKey: auditKey(p),
|
||||
NewValue: textJSON(p.Text),
|
||||
RecordVersion: version,
|
||||
Actor: "archied",
|
||||
Source: "archied",
|
||||
RequestID: "",
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
// DeletePolicy removes one stored policy; an unknown key is
|
||||
// ErrPolicyNotFound.
|
||||
func (s *Store) DeletePolicy(ctx context.Context, p access.Policy) error {
|
||||
if err := p.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
level, orgID, wsID, kind, id, policyID := accessScopeOf(p)
|
||||
deleted, err := s.queries().DeleteAccessPolicy(ctx, postgresdb.DeleteAccessPolicyParams{
|
||||
Level: level, OrgID: orgID, WorkspaceID: wsID,
|
||||
ObjectKind: kind, ObjectID: id, PolicyID: policyID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deleted == 0 {
|
||||
return access.ErrPolicyNotFound
|
||||
}
|
||||
if _, err := s.queries().UpsertAccessPolicyVersion(ctx, postgresdb.UpsertAccessPolicyVersionParams{
|
||||
Level: level, OrgID: orgID, WorkspaceID: wsID,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
// A level-scope with no policies left keeps no version row.
|
||||
return s.queries().DeleteAccessPolicyVersion(ctx, postgresdb.DeleteAccessPolicyVersionParams{
|
||||
Level: level, OrgID: orgID, WorkspaceID: wsID,
|
||||
})
|
||||
}
|
||||
|
||||
// EnsureShippedOrgPolicies seeds an org's shipped role policies when it
|
||||
// carries none of them, so a restart never overwrites an edited role policy.
|
||||
func (s *Store) EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error {
|
||||
shipped := access.ShippedOrgPolicies(orgID)
|
||||
count, err := s.queries().CountShippedOrgPolicies(ctx, postgresdb.CountShippedOrgPoliciesParams{
|
||||
OrgID: string(orgID), Column2: shippedOrgPolicyIDs(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
for _, p := range shipped {
|
||||
if _, err := s.PutPolicy(ctx, p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResetOrgPolicies restores the shipped role policies for one org and
|
||||
// removes its other org-level policies. It is the store-side half of
|
||||
// `archied access reset --org`, which runs on this host and records the
|
||||
// reset as an audit event.
|
||||
func (s *Store) ResetOrgPolicies(ctx context.Context, orgID org.OrgID) error {
|
||||
if orgID == "" {
|
||||
return fmt.Errorf("%w: no org", access.ErrInvalidPolicy)
|
||||
}
|
||||
if err := s.queries().DeleteOrgPoliciesNotShipped(ctx, postgresdb.DeleteOrgPoliciesNotShippedParams{
|
||||
OrgID: string(orgID), Column2: shippedOrgPolicyIDs(),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, p := range access.ShippedOrgPolicies(orgID) {
|
||||
if _, err := s.PutPolicy(ctx, p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResetInstancePolicies removes every stored instance policy. The
|
||||
// cross-org forbid is engine-enforced and survives any reset.
|
||||
func (s *Store) ResetInstancePolicies(ctx context.Context) error {
|
||||
return s.queries().ResetInstancePolicies(ctx)
|
||||
}
|
||||
|
||||
// RecordDenial records one refusal. The store coalesces identical denials
|
||||
// within a minute into one row with a count, so a retry storm does not
|
||||
// flood the surface.
|
||||
func (s *Store) RecordDenial(ctx context.Context, d access.Denial) error {
|
||||
if d.Org == "" || d.Principal == "" {
|
||||
return fmt.Errorf("%w: org and principal are required", access.ErrInvalidPolicy)
|
||||
}
|
||||
return s.queries().RecordDenial(ctx, postgresdb.RecordDenialParams{
|
||||
OrgID: string(d.Org), Principal: string(d.Principal), Action: string(d.Action),
|
||||
ResourceKind: string(d.Kind), ResourceID: d.ResourceID, Level: string(d.Level),
|
||||
Policies: d.Policies,
|
||||
})
|
||||
}
|
||||
|
||||
// ListDenials returns an org's most recent denials, newest first.
|
||||
func (s *Store) ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]access.Denial, error) {
|
||||
rows, err := s.queries().ListDenials(ctx, postgresdb.ListDenialsParams{
|
||||
OrgID: string(orgID), Limit: int32(limit),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]access.Denial, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, access.Denial{
|
||||
Principal: identity.IdentityID(r.Principal),
|
||||
Org: org.OrgID(r.OrgID),
|
||||
Action: access.Action(r.Action),
|
||||
Kind: access.ResourceKind(r.ResourceKind),
|
||||
ResourceID: r.ResourceID,
|
||||
Level: access.Level(r.Level),
|
||||
Policies: r.Policies,
|
||||
At: r.CreatedAt,
|
||||
Count: r.Count,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func newStoreForAccess(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
func TestAccessPolicyStore(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
// PutPolicy stores one policy and reports a versioned level.
|
||||
p := access.Policy{
|
||||
ID: "test-policy", Level: access.LevelOrg, OrgID: "soc",
|
||||
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
|
||||
}
|
||||
v1, err := s.PutPolicy(ctx, p)
|
||||
if err != nil {
|
||||
t.Fatalf("PutPolicy: %v", err)
|
||||
}
|
||||
if v1 != 2 { // the counter starts at 1; the first write bumps it
|
||||
t.Fatalf("PutPolicy version = %d, want 2", v1)
|
||||
}
|
||||
v2, err := s.PutPolicy(ctx, p)
|
||||
if err != nil {
|
||||
t.Fatalf("second PutPolicy: %v", err)
|
||||
}
|
||||
if v2 <= v1 {
|
||||
t.Fatalf("second PutPolicy version = %d, want > %d", v2, v1)
|
||||
}
|
||||
|
||||
// A malformed policy is refused by the store's own structural check.
|
||||
bad := access.Policy{ID: "bad", Level: access.LevelOrg, OrgID: "soc"}
|
||||
if _, err := s.PutPolicy(ctx, bad); !errors.Is(err, access.ErrInvalidPolicy) {
|
||||
t.Fatalf("PutPolicy(structurally invalid) = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
|
||||
// ListPolicies round-trips the scope tuple.
|
||||
list, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("ListPolicies = %d policies, want 1", len(list))
|
||||
}
|
||||
if list[0].ID != "test-policy" || list[0].OrgID != "soc" {
|
||||
t.Fatalf("ListPolicies[0] = %+v, want the stored policy", list[0])
|
||||
}
|
||||
|
||||
// DeletePolicy removes it and reports an unknown key as a sentinel.
|
||||
if err := s.DeletePolicy(ctx, p); err != nil {
|
||||
t.Fatalf("DeletePolicy: %v", err)
|
||||
}
|
||||
if err := s.DeletePolicy(ctx, p); !errors.Is(err, access.ErrPolicyNotFound) {
|
||||
t.Fatalf("second DeletePolicy = %v, want ErrPolicyNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureShippedOrgPolicies(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("EnsureShippedOrgPolicies: %v", err)
|
||||
}
|
||||
list, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
if len(list) != 4 {
|
||||
t.Fatalf("seeding produced %d policies, want the 4 shipped roles", len(list))
|
||||
}
|
||||
|
||||
// An edited role policy survives a re-seed: an org that already carries
|
||||
// the shipped IDs is left untouched.
|
||||
edited := list[0]
|
||||
edited.Text = `permit(principal, action, resource) when { resource.kind == "edited" };`
|
||||
if _, err := s.PutPolicy(ctx, edited); err != nil {
|
||||
t.Fatalf("PutPolicy(edit): %v", err)
|
||||
}
|
||||
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("re-seed: %v", err)
|
||||
}
|
||||
after, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies after re-seed: %v", err)
|
||||
}
|
||||
for _, p := range after {
|
||||
if p.ID == edited.ID && p.Text != edited.Text {
|
||||
t.Fatalf("re-seed overwrote an edited role policy %s", p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPolicies(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("ResetOrgPolicies: %v", err)
|
||||
}
|
||||
// An operator's custom org policy on top of the shipped set.
|
||||
custom := access.Policy{
|
||||
ID: "org-lockdown", Level: access.LevelOrg, OrgID: "soc",
|
||||
Text: `forbid(principal, action, resource) when { resource.kind == "source" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, custom); err != nil {
|
||||
t.Fatalf("PutPolicy(custom): %v", err)
|
||||
}
|
||||
// A workspace policy must survive an org reset.
|
||||
ws := access.Policy{
|
||||
ID: "ws-rule", Level: access.LevelWorkspace, OrgID: "soc", WorkspaceID: "net",
|
||||
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, ws); err != nil {
|
||||
t.Fatalf("PutPolicy(ws): %v", err)
|
||||
}
|
||||
// And an instance policy must survive an org reset but not an instance
|
||||
// reset.
|
||||
instance := access.Policy{
|
||||
ID: "instance-rule", Level: access.LevelInstance,
|
||||
Text: `forbid(principal, action, resource) when { resource.kind == "secret" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, instance); err != nil {
|
||||
t.Fatalf("PutPolicy(instance): %v", err)
|
||||
}
|
||||
|
||||
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("org reset: %v", err)
|
||||
}
|
||||
after, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
orgPolicies := 0
|
||||
for _, p := range after {
|
||||
switch {
|
||||
case p.Level == access.LevelOrg && p.OrgID == "soc":
|
||||
orgPolicies++
|
||||
case p.Level == access.LevelOrg:
|
||||
t.Fatalf("org reset touched policy %s of another org", p.ID)
|
||||
}
|
||||
}
|
||||
if orgPolicies != 4 {
|
||||
t.Fatalf("org-level policies after reset = %d, want the 4 shipped roles", orgPolicies)
|
||||
}
|
||||
|
||||
if err := s.ResetInstancePolicies(ctx); err != nil {
|
||||
t.Fatalf("ResetInstancePolicies: %v", err)
|
||||
}
|
||||
after, err = s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies after instance reset: %v", err)
|
||||
}
|
||||
for _, p := range after {
|
||||
if p.Level == access.LevelInstance {
|
||||
t.Fatalf("instance reset left policy %s", p.ID)
|
||||
}
|
||||
}
|
||||
if len(after) == 0 {
|
||||
t.Fatal("instance reset removed non-instance policies")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDenialStore(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
denial := access.Denial{
|
||||
Principal: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
|
||||
Org: "soc", Action: access.ActionRead, Kind: access.KindBinding,
|
||||
ResourceID: "b1", Level: access.LevelOrg,
|
||||
Policies: []string{access.PolicyOrgRead, access.PolicyOrgEdit},
|
||||
}
|
||||
if err := s.RecordDenial(ctx, denial); err != nil {
|
||||
t.Fatalf("RecordDenial: %v", err)
|
||||
}
|
||||
if err := s.RecordDenial(ctx, denial); err != nil {
|
||||
t.Fatalf("repeat RecordDenial: %v", err)
|
||||
}
|
||||
// A different action is a separate row.
|
||||
other := denial
|
||||
other.Action = access.ActionDelete
|
||||
if err := s.RecordDenial(ctx, other); err != nil {
|
||||
t.Fatalf("RecordDenial(other action): %v", err)
|
||||
}
|
||||
|
||||
rows, err := s.ListDenials(ctx, "soc", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListDenials: %v", err)
|
||||
}
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("ListDenials = %d rows, want 2", len(rows))
|
||||
}
|
||||
if rows[0].Action != access.ActionDelete {
|
||||
t.Fatalf("newest denial = %v, want the delete denial", rows[0].Action)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if r.Action == access.ActionRead {
|
||||
if r.Count != 2 {
|
||||
t.Fatalf("repeated denial count = %d, want 2 (coalesced within the minute)", r.Count)
|
||||
}
|
||||
if len(r.Policies) != 2 {
|
||||
t.Fatalf("denial policies = %v, want the deciding policies", r.Policies)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Another org sees none of these.
|
||||
if rows, err := s.ListDenials(ctx, "other", 10); err != nil || len(rows) != 0 {
|
||||
t.Fatalf("ListDenials(other org) = %d rows %v, want none", len(rows), err)
|
||||
}
|
||||
// An org-less denial is refused at the producer.
|
||||
if err := s.RecordDenial(ctx, access.Denial{Action: access.ActionRead}); err == nil {
|
||||
t.Fatal("RecordDenial accepted a denial with no org or principal")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
-- Access policies and denial records: the stored half of the policy chain
|
||||
-- (docs/prds/orgs-and-access.md, "Storing and changing policies" and
|
||||
-- "Denials"). The shipped cross-org forbid is engine-enforced and has no row
|
||||
-- here; the shipped role policies are seeded per org as ordinary rows with
|
||||
-- the shipped IDs, so a reset overwrites them and an edit sticks until reset.
|
||||
--
|
||||
-- The scope tuple (level, org_id, workspace_id, object_kind, object_id) is
|
||||
-- the policy's place in the chain; policy_id names the document inside it.
|
||||
-- The version counter is per level-scope: PutPolicy bumps it and returns it,
|
||||
-- so the engine's next load can detect a change.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE access_policies (
|
||||
level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')),
|
||||
org_id text NOT NULL DEFAULT '',
|
||||
workspace_id text NOT NULL DEFAULT '',
|
||||
object_kind text NOT NULL DEFAULT '',
|
||||
object_id text NOT NULL DEFAULT '',
|
||||
policy_id text NOT NULL,
|
||||
text text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (level, org_id, workspace_id, object_kind, object_id, policy_id)
|
||||
);
|
||||
|
||||
CREATE TABLE access_policy_versions (
|
||||
level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')),
|
||||
org_id text NOT NULL DEFAULT '',
|
||||
workspace_id text NOT NULL DEFAULT '',
|
||||
version bigint NOT NULL DEFAULT 1,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (level, org_id, workspace_id)
|
||||
);
|
||||
|
||||
-- One denial row per (principal, action, resource, level, policies, minute):
|
||||
-- a retry storm inside one minute is a count bump, not a row flood
|
||||
-- (docs/prds/orgs-and-access.md, "Audit retention").
|
||||
CREATE TABLE access_denials (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
principal text NOT NULL,
|
||||
action text NOT NULL,
|
||||
resource_kind text NOT NULL,
|
||||
resource_id text NOT NULL,
|
||||
level text NOT NULL,
|
||||
policies text[] NOT NULL DEFAULT '{}',
|
||||
minute_at timestamptz NOT NULL DEFAULT date_trunc('minute', now()),
|
||||
count bigint NOT NULL DEFAULT 1,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_access_denials_dedup ON access_denials
|
||||
(org_id, principal, action, resource_kind, resource_id, level, policies, minute_at);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP INDEX idx_access_denials_dedup;
|
||||
DROP TABLE access_denials;
|
||||
DROP TABLE access_policy_versions;
|
||||
DROP TABLE access_policies;
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"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/postgres/postgresdb"
|
||||
@@ -150,6 +151,43 @@ func (s *Store) AssignAgent(ctx context.Context, value org.AgentAssignment) erro
|
||||
})
|
||||
}
|
||||
|
||||
// EnsureAgentOrgMembership grants every agent identity the shipped developer
|
||||
// role in the org it serves. It runs at the State Store's boot, after the
|
||||
// default-org upgrade, so dispatch's chain has a principal to evaluate.
|
||||
// Idempotent: an existing membership (any role) is left alone.
|
||||
func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error {
|
||||
return s.queries().EnsureAgentOrgMembership(ctx)
|
||||
}
|
||||
|
||||
// PrincipalFor assembles the access principal for one identity: the org it
|
||||
// serves and its memberships (internal/domain/access). An identity in no org
|
||||
// is the default org with no role, which the shipped role policies never
|
||||
// permit.
|
||||
func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
|
||||
resolved, err := s.OrgForIdentity(ctx, id)
|
||||
if err != nil {
|
||||
return access.Principal{}, err
|
||||
}
|
||||
rows, err := s.queries().ListMembershipsByIdentity(ctx, string(id))
|
||||
if err != nil {
|
||||
return access.Principal{}, err
|
||||
}
|
||||
memberships := make([]org.Membership, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
var ws org.WorkspaceID
|
||||
if r.WorkspaceID.Valid {
|
||||
ws = org.WorkspaceID(r.WorkspaceID.String)
|
||||
}
|
||||
memberships = append(memberships, org.Membership{
|
||||
IdentityID: id,
|
||||
OrgID: org.OrgID(r.OrgID),
|
||||
WorkspaceID: ws,
|
||||
Role: org.Role(r.Role),
|
||||
})
|
||||
}
|
||||
return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships}, nil
|
||||
}
|
||||
|
||||
// OrgForIdentity returns the org an identity serves: the assigned org for an
|
||||
// agent, the org of one of its memberships for a person, and the default org
|
||||
// for an identity in no org.
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: access.sql
|
||||
|
||||
package postgresdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const countShippedOrgPolicies = `-- name: CountShippedOrgPolicies :one
|
||||
SELECT count(*) FROM access_policies
|
||||
WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[])
|
||||
`
|
||||
|
||||
type CountShippedOrgPoliciesParams struct {
|
||||
OrgID string
|
||||
Column2 []string
|
||||
}
|
||||
|
||||
// How many of an org's shipped role policies are stored. The seeding runs
|
||||
// only when the org carries none of them, so a restart never overwrites an
|
||||
// edited role policy (the shipped IDs are reserved for the shipped text).
|
||||
func (q *Queries) CountShippedOrgPolicies(ctx context.Context, arg CountShippedOrgPoliciesParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countShippedOrgPolicies, arg.OrgID, arg.Column2)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const deleteAccessPolicy = `-- name: DeleteAccessPolicy :execrows
|
||||
DELETE FROM access_policies
|
||||
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
|
||||
AND object_id = $5 AND policy_id = $6
|
||||
`
|
||||
|
||||
type DeleteAccessPolicyParams struct {
|
||||
Level string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
ObjectKind string
|
||||
ObjectID string
|
||||
PolicyID string
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteAccessPolicy(ctx context.Context, arg DeleteAccessPolicyParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteAccessPolicy,
|
||||
arg.Level,
|
||||
arg.OrgID,
|
||||
arg.WorkspaceID,
|
||||
arg.ObjectKind,
|
||||
arg.ObjectID,
|
||||
arg.PolicyID,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const deleteAccessPolicyVersion = `-- name: DeleteAccessPolicyVersion :exec
|
||||
DELETE FROM access_policy_versions v
|
||||
WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3
|
||||
AND NOT EXISTS (SELECT 1 FROM access_policies p
|
||||
WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id)
|
||||
`
|
||||
|
||||
type DeleteAccessPolicyVersionParams struct {
|
||||
Level string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
}
|
||||
|
||||
// Tidy a level-scope with no policies left: its version row has no reader.
|
||||
func (q *Queries) DeleteAccessPolicyVersion(ctx context.Context, arg DeleteAccessPolicyVersionParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteOrgPoliciesNotShipped = `-- name: DeleteOrgPoliciesNotShipped :exec
|
||||
DELETE FROM access_policies
|
||||
WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]))
|
||||
`
|
||||
|
||||
type DeleteOrgPoliciesNotShippedParams struct {
|
||||
OrgID string
|
||||
Column2 []string
|
||||
}
|
||||
|
||||
// The org reset's removal half: every org-level policy except the shipped
|
||||
// role set.
|
||||
func (q *Queries) DeleteOrgPoliciesNotShipped(ctx context.Context, arg DeleteOrgPoliciesNotShippedParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteOrgPoliciesNotShipped, arg.OrgID, arg.Column2)
|
||||
return err
|
||||
}
|
||||
|
||||
const getAccessPolicy = `-- name: GetAccessPolicy :one
|
||||
SELECT text FROM access_policies
|
||||
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
|
||||
AND object_id = $5 AND policy_id = $6
|
||||
`
|
||||
|
||||
type GetAccessPolicyParams struct {
|
||||
Level string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
ObjectKind string
|
||||
ObjectID string
|
||||
PolicyID string
|
||||
}
|
||||
|
||||
func (q *Queries) GetAccessPolicy(ctx context.Context, arg GetAccessPolicyParams) (string, error) {
|
||||
row := q.db.QueryRow(ctx, getAccessPolicy,
|
||||
arg.Level,
|
||||
arg.OrgID,
|
||||
arg.WorkspaceID,
|
||||
arg.ObjectKind,
|
||||
arg.ObjectID,
|
||||
arg.PolicyID,
|
||||
)
|
||||
var text string
|
||||
err := row.Scan(&text)
|
||||
return text, err
|
||||
}
|
||||
|
||||
const insertAccessPolicyAudit = `-- name: InsertAccessPolicyAudit :exec
|
||||
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
|
||||
VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7)
|
||||
`
|
||||
|
||||
type InsertAccessPolicyAuditParams struct {
|
||||
RecordKey string
|
||||
OldValue []byte
|
||||
NewValue []byte
|
||||
RecordVersion int64
|
||||
Actor string
|
||||
Source string
|
||||
RequestID string
|
||||
}
|
||||
|
||||
// One audit row per policy change: the policy's old and new text
|
||||
// (docs/prds/orgs-and-access.md, "Storing and changing policies").
|
||||
func (q *Queries) InsertAccessPolicyAudit(ctx context.Context, arg InsertAccessPolicyAuditParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAccessPolicyAudit,
|
||||
arg.RecordKey,
|
||||
arg.OldValue,
|
||||
arg.NewValue,
|
||||
arg.RecordVersion,
|
||||
arg.Actor,
|
||||
arg.Source,
|
||||
arg.RequestID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listAccessPolicies = `-- name: ListAccessPolicies :many
|
||||
|
||||
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
|
||||
FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id
|
||||
`
|
||||
|
||||
// Access policies and denial records (internal/domain/access): the durable
|
||||
// half of the policy-chain contract. Versioning is per level-scope; every
|
||||
// policy change writes one sys_audit row naming who made it.
|
||||
func (q *Queries) ListAccessPolicies(ctx context.Context) ([]AccessPolicy, error) {
|
||||
rows, err := q.db.Query(ctx, listAccessPolicies)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AccessPolicy
|
||||
for rows.Next() {
|
||||
var i AccessPolicy
|
||||
if err := rows.Scan(
|
||||
&i.Level,
|
||||
&i.OrgID,
|
||||
&i.WorkspaceID,
|
||||
&i.ObjectKind,
|
||||
&i.ObjectID,
|
||||
&i.PolicyID,
|
||||
&i.Text,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listDenials = `-- name: ListDenials :many
|
||||
SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at
|
||||
FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2
|
||||
`
|
||||
|
||||
type ListDenialsParams struct {
|
||||
OrgID string
|
||||
Limit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListDenials(ctx context.Context, arg ListDenialsParams) ([]AccessDenial, error) {
|
||||
rows, err := q.db.Query(ctx, listDenials, arg.OrgID, arg.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AccessDenial
|
||||
for rows.Next() {
|
||||
var i AccessDenial
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Principal,
|
||||
&i.Action,
|
||||
&i.ResourceKind,
|
||||
&i.ResourceID,
|
||||
&i.Level,
|
||||
&i.Policies,
|
||||
&i.MinuteAt,
|
||||
&i.Count,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const recordDenial = `-- name: RecordDenial :exec
|
||||
INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at)
|
||||
DO UPDATE SET count = access_denials.count + 1, updated_at = now()
|
||||
`
|
||||
|
||||
type RecordDenialParams struct {
|
||||
OrgID string
|
||||
Principal string
|
||||
Action string
|
||||
ResourceKind string
|
||||
ResourceID string
|
||||
Level string
|
||||
Policies []string
|
||||
}
|
||||
|
||||
// One row per (principal, action, resource, level, policies, minute);
|
||||
// a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md,
|
||||
// "Audit retention").
|
||||
func (q *Queries) RecordDenial(ctx context.Context, arg RecordDenialParams) error {
|
||||
_, err := q.db.Exec(ctx, recordDenial,
|
||||
arg.OrgID,
|
||||
arg.Principal,
|
||||
arg.Action,
|
||||
arg.ResourceKind,
|
||||
arg.ResourceID,
|
||||
arg.Level,
|
||||
arg.Policies,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const resetInstancePolicies = `-- name: ResetInstancePolicies :exec
|
||||
DELETE FROM access_policies WHERE level = 'instance'
|
||||
`
|
||||
|
||||
func (q *Queries) ResetInstancePolicies(ctx context.Context) error {
|
||||
_, err := q.db.Exec(ctx, resetInstancePolicies)
|
||||
return err
|
||||
}
|
||||
|
||||
const upsertAccessPolicy = `-- name: UpsertAccessPolicy :exec
|
||||
INSERT INTO access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id)
|
||||
DO UPDATE SET text = excluded.text, updated_at = now()
|
||||
`
|
||||
|
||||
type UpsertAccessPolicyParams struct {
|
||||
Level string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
ObjectKind string
|
||||
ObjectID string
|
||||
PolicyID string
|
||||
Text string
|
||||
}
|
||||
|
||||
func (q *Queries) UpsertAccessPolicy(ctx context.Context, arg UpsertAccessPolicyParams) error {
|
||||
_, err := q.db.Exec(ctx, upsertAccessPolicy,
|
||||
arg.Level,
|
||||
arg.OrgID,
|
||||
arg.WorkspaceID,
|
||||
arg.ObjectKind,
|
||||
arg.ObjectID,
|
||||
arg.PolicyID,
|
||||
arg.Text,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const upsertAccessPolicyVersion = `-- name: UpsertAccessPolicyVersion :one
|
||||
INSERT INTO access_policy_versions (level, org_id, workspace_id, version) VALUES ($1, $2, $3, 2)
|
||||
ON CONFLICT (level, org_id, workspace_id)
|
||||
DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now()
|
||||
RETURNING version
|
||||
`
|
||||
|
||||
type UpsertAccessPolicyVersionParams struct {
|
||||
Level string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
}
|
||||
|
||||
func (q *Queries) UpsertAccessPolicyVersion(ctx context.Context, arg UpsertAccessPolicyVersionParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, upsertAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID)
|
||||
var version int64
|
||||
err := row.Scan(&version)
|
||||
return version, err
|
||||
}
|
||||
@@ -10,6 +10,40 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type AccessDenial struct {
|
||||
ID int64
|
||||
OrgID string
|
||||
Principal string
|
||||
Action string
|
||||
ResourceKind string
|
||||
ResourceID string
|
||||
Level string
|
||||
Policies []string
|
||||
MinuteAt time.Time
|
||||
Count int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type AccessPolicy struct {
|
||||
Level string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
ObjectKind string
|
||||
ObjectID string
|
||||
PolicyID string
|
||||
Text string
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type AccessPolicyVersion struct {
|
||||
Level string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
Version int64
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type ApplyStatus struct {
|
||||
Process string
|
||||
Kind string
|
||||
|
||||
@@ -11,6 +11,22 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const ensureAgentOrgMembership = `-- name: EnsureAgentOrgMembership :exec
|
||||
INSERT INTO memberships (identity_id, org_id, role)
|
||||
SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a
|
||||
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING
|
||||
`
|
||||
|
||||
// Every agent identity serves its org with the shipped developer role: an
|
||||
// agent is granted access the way a user is
|
||||
// (docs/prds/orgs-and-access.md, "Identity"). Idempotent, so an operator's
|
||||
// later role change survives a restart, and the shipped seed never
|
||||
// overwrites it.
|
||||
func (q *Queries) EnsureAgentOrgMembership(ctx context.Context) error {
|
||||
_, err := q.db.Exec(ctx, ensureAgentOrgMembership)
|
||||
return err
|
||||
}
|
||||
|
||||
const ensureMembership = `-- name: EnsureMembership :exec
|
||||
INSERT INTO memberships (identity_id, org_id, workspace_id, role)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
-- Access policies and denial records (internal/domain/access): the durable
|
||||
-- half of the policy-chain contract. Versioning is per level-scope; every
|
||||
-- policy change writes one sys_audit row naming who made it.
|
||||
|
||||
-- name: ListAccessPolicies :many
|
||||
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
|
||||
FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id;
|
||||
|
||||
-- name: UpsertAccessPolicy :exec
|
||||
INSERT INTO access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id)
|
||||
DO UPDATE SET text = excluded.text, updated_at = now();
|
||||
|
||||
-- name: GetAccessPolicy :one
|
||||
SELECT text FROM access_policies
|
||||
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
|
||||
AND object_id = $5 AND policy_id = $6;
|
||||
|
||||
-- name: DeleteAccessPolicy :execrows
|
||||
DELETE FROM access_policies
|
||||
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
|
||||
AND object_id = $5 AND policy_id = $6;
|
||||
|
||||
-- name: CountShippedOrgPolicies :one
|
||||
-- How many of an org's shipped role policies are stored. The seeding runs
|
||||
-- only when the org carries none of them, so a restart never overwrites an
|
||||
-- edited role policy (the shipped IDs are reserved for the shipped text).
|
||||
SELECT count(*) FROM access_policies
|
||||
WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[]);
|
||||
|
||||
-- name: DeleteOrgPoliciesNotShipped :exec
|
||||
-- The org reset's removal half: every org-level policy except the shipped
|
||||
-- role set.
|
||||
DELETE FROM access_policies
|
||||
WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]));
|
||||
|
||||
-- name: ResetInstancePolicies :exec
|
||||
DELETE FROM access_policies WHERE level = 'instance';
|
||||
|
||||
-- name: UpsertAccessPolicyVersion :one
|
||||
INSERT INTO access_policy_versions (level, org_id, workspace_id, version) VALUES ($1, $2, $3, 2)
|
||||
ON CONFLICT (level, org_id, workspace_id)
|
||||
DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now()
|
||||
RETURNING version;
|
||||
|
||||
-- name: DeleteAccessPolicyVersion :exec
|
||||
-- Tidy a level-scope with no policies left: its version row has no reader.
|
||||
DELETE FROM access_policy_versions v
|
||||
WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3
|
||||
AND NOT EXISTS (SELECT 1 FROM access_policies p
|
||||
WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id);
|
||||
|
||||
-- name: InsertAccessPolicyAudit :exec
|
||||
-- One audit row per policy change: the policy's old and new text
|
||||
-- (docs/prds/orgs-and-access.md, "Storing and changing policies").
|
||||
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
|
||||
VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7);
|
||||
|
||||
-- name: RecordDenial :exec
|
||||
-- One row per (principal, action, resource, level, policies, minute);
|
||||
-- a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md,
|
||||
-- "Audit retention").
|
||||
INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at)
|
||||
DO UPDATE SET count = access_denials.count + 1, updated_at = now();
|
||||
|
||||
-- name: ListDenials :many
|
||||
SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at
|
||||
FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2;
|
||||
@@ -40,4 +40,13 @@ SELECT COALESCE(
|
||||
(SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
|
||||
ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1),
|
||||
'default'
|
||||
)::text AS org_id;
|
||||
)::text AS org_id;
|
||||
-- name: EnsureAgentOrgMembership :exec
|
||||
-- Every agent identity serves its org with the shipped developer role: an
|
||||
-- agent is granted access the way a user is
|
||||
-- (docs/prds/orgs-and-access.md, "Identity"). Idempotent, so an operator's
|
||||
-- later role change survives a restart, and the shipped seed never
|
||||
-- overwrites it.
|
||||
INSERT INTO memberships (identity_id, org_id, role)
|
||||
SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a
|
||||
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING;
|
||||
@@ -0,0 +1,177 @@
|
||||
// Access: the policy-chain and denial-record RPCs (docs/prds/orgs-and-access.md).
|
||||
// The policies surface is the engine's snapshot plus the administrative
|
||||
// writes; the denials surface is the two callers' write path and the
|
||||
// operator's read.
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
var (
|
||||
errPoliciesUnavailable = status.Error(codes.Unavailable, "access policy store unavailable")
|
||||
errDenialsUnavailable = status.Error(codes.Unavailable, "access denial store unavailable")
|
||||
)
|
||||
|
||||
func accessPolicyProto(p access.Policy) *pb.AccessPolicy {
|
||||
return &pb.AccessPolicy{
|
||||
PolicyId: p.ID, Level: string(p.Level), OrgId: string(p.OrgID),
|
||||
WorkspaceId: string(p.WorkspaceID), ObjectKind: string(p.ObjectKind),
|
||||
ObjectId: p.ObjectID, Text: p.Text,
|
||||
}
|
||||
}
|
||||
|
||||
func accessPolicyValue(p *pb.AccessPolicy) access.Policy {
|
||||
return access.Policy{
|
||||
ID: p.GetPolicyId(), Level: access.Level(p.GetLevel()),
|
||||
OrgID: org.OrgID(p.GetOrgId()), WorkspaceID: org.WorkspaceID(p.GetWorkspaceId()),
|
||||
ObjectKind: access.ResourceKind(p.GetObjectKind()), ObjectID: p.GetObjectId(),
|
||||
Text: p.GetText(),
|
||||
}
|
||||
}
|
||||
|
||||
func accessDenialProto(d access.Denial) *pb.AccessDenial {
|
||||
out := &pb.AccessDenial{
|
||||
OrgId: string(d.Org), Principal: string(d.Principal), Action: string(d.Action),
|
||||
ResourceKind: string(d.Kind), ResourceId: d.ResourceID, Level: string(d.Level),
|
||||
Policies: d.Policies, Count: d.Count,
|
||||
}
|
||||
if !d.At.IsZero() {
|
||||
out.At = timestamp(d.At)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func accessDenialValue(d *pb.AccessDenial) access.Denial {
|
||||
value := access.Denial{
|
||||
Org: org.OrgID(d.GetOrgId()),
|
||||
Principal: identity.IdentityID(d.GetPrincipal()),
|
||||
Action: access.Action(d.GetAction()),
|
||||
Kind: access.ResourceKind(d.GetResourceKind()),
|
||||
ResourceID: d.GetResourceId(),
|
||||
Level: access.Level(d.GetLevel()),
|
||||
Policies: d.GetPolicies(),
|
||||
Count: d.GetCount(),
|
||||
}
|
||||
if d.GetAt() != nil {
|
||||
value.At = d.GetAt().AsTime()
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (s *server) GetPrincipal(ctx context.Context, request *pb.GetPrincipalRequest) (*pb.GetPrincipalResponse, error) {
|
||||
if s.deps.Principals == nil {
|
||||
return nil, status.Error(codes.Unavailable, "identity store unavailable")
|
||||
}
|
||||
value, err := s.deps.Principals.PrincipalFor(ctx, identity.IdentityID(request.IdentityId))
|
||||
if err != nil {
|
||||
return nil, identityStatus(err)
|
||||
}
|
||||
memberships := make([]*pb.PrincipalMembership, len(value.Memberships))
|
||||
for i := range value.Memberships {
|
||||
m := value.Memberships[i]
|
||||
memberships[i] = &pb.PrincipalMembership{
|
||||
OrgId: string(m.OrgID), WorkspaceId: string(m.WorkspaceID), Role: string(m.Role),
|
||||
}
|
||||
}
|
||||
return &pb.GetPrincipalResponse{Principal: &pb.AccessPrincipal{
|
||||
IdentityId: string(value.IdentityID),
|
||||
OrgId: string(value.Org),
|
||||
Memberships: memberships,
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListPolicies(ctx context.Context, _ *pb.ListPoliciesRequest) (*pb.ListPoliciesResponse, error) {
|
||||
if s.deps.Policies == nil {
|
||||
return nil, errPoliciesUnavailable
|
||||
}
|
||||
values, err := s.deps.Policies.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
return nil, accessStatus(err)
|
||||
}
|
||||
out := make([]*pb.AccessPolicy, len(values))
|
||||
for i := range values {
|
||||
out[i] = accessPolicyProto(values[i])
|
||||
}
|
||||
return &pb.ListPoliciesResponse{Policies: out}, nil
|
||||
}
|
||||
|
||||
func (s *server) PutPolicy(ctx context.Context, request *pb.PutPolicyRequest) (*pb.PutPolicyResponse, error) {
|
||||
if s.deps.Policies == nil {
|
||||
return nil, errPoliciesUnavailable
|
||||
}
|
||||
version, err := s.deps.Policies.PutPolicy(ctx, accessPolicyValue(request.Policy))
|
||||
if err != nil {
|
||||
return nil, accessStatus(err)
|
||||
}
|
||||
return &pb.PutPolicyResponse{Version: version}, nil
|
||||
}
|
||||
|
||||
func (s *server) DeletePolicy(ctx context.Context, request *pb.DeletePolicyRequest) (*pb.DeletePolicyResponse, error) {
|
||||
if s.deps.Policies == nil {
|
||||
return nil, errPoliciesUnavailable
|
||||
}
|
||||
if err := s.deps.Policies.DeletePolicy(ctx, accessPolicyValue(request.Policy)); err != nil {
|
||||
return nil, accessStatus(err)
|
||||
}
|
||||
return &pb.DeletePolicyResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) EnsureShippedOrgPolicies(ctx context.Context, request *pb.EnsureShippedOrgPoliciesRequest) (*pb.EnsureShippedOrgPoliciesResponse, error) {
|
||||
if s.deps.Policies == nil {
|
||||
return nil, errPoliciesUnavailable
|
||||
}
|
||||
if err := s.deps.Policies.EnsureShippedOrgPolicies(ctx, org.OrgID(request.OrgId)); err != nil {
|
||||
return nil, accessStatus(err)
|
||||
}
|
||||
return &pb.EnsureShippedOrgPoliciesResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) RecordDenial(ctx context.Context, request *pb.RecordDenialRequest) (*pb.RecordDenialResponse, error) {
|
||||
if s.deps.Denials == nil {
|
||||
return nil, errDenialsUnavailable
|
||||
}
|
||||
if err := s.deps.Denials.RecordDenial(ctx, accessDenialValue(request.Denial)); err != nil {
|
||||
return nil, accessStatus(err)
|
||||
}
|
||||
return &pb.RecordDenialResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListDenials(ctx context.Context, request *pb.ListDenialsRequest) (*pb.ListDenialsResponse, error) {
|
||||
if s.deps.Denials == nil {
|
||||
return nil, errDenialsUnavailable
|
||||
}
|
||||
limit := int(request.GetLimit())
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 100
|
||||
}
|
||||
values, err := s.deps.Denials.ListDenials(ctx, org.OrgID(request.OrgId), limit)
|
||||
if err != nil {
|
||||
return nil, accessStatus(err)
|
||||
}
|
||||
out := make([]*pb.AccessDenial, len(values))
|
||||
for i := range values {
|
||||
out[i] = accessDenialProto(values[i])
|
||||
}
|
||||
return &pb.ListDenialsResponse{Denials: out}, nil
|
||||
}
|
||||
|
||||
// accessStatus maps an access sentinel to its gRPC status.
|
||||
func accessStatus(err error) error {
|
||||
if errors.Is(err, access.ErrPolicyNotFound) {
|
||||
return status.Error(codes.NotFound, access.ErrPolicyNotFound.Error())
|
||||
}
|
||||
if errors.Is(err, access.ErrInvalidPolicy) {
|
||||
return status.Error(codes.InvalidArgument, access.ErrInvalidPolicy.Error())
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Access: the client half of the policy-chain and denial-record RPCs
|
||||
// (docs/prds/orgs-and-access.md). The reset surface is deliberately absent:
|
||||
// `archied access reset` runs on the State Store host, never over the wire.
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// The Client satisfies the access contracts the two callers depend on.
|
||||
var (
|
||||
_ access.PolicyStore = (*Client)(nil)
|
||||
_ access.DenialStore = (*Client)(nil)
|
||||
_ access.PrincipalSource = (*Client)(nil)
|
||||
)
|
||||
|
||||
func (c *Client) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
|
||||
r, err := c.client.GetPrincipal(ctx, &pb.GetPrincipalRequest{IdentityId: string(id)})
|
||||
if err != nil {
|
||||
return access.Principal{}, unmapError(err)
|
||||
}
|
||||
value := r.GetPrincipal()
|
||||
memberships := make([]org.Membership, len(value.GetMemberships()))
|
||||
for i := range value.GetMemberships() {
|
||||
m := value.GetMemberships()[i]
|
||||
memberships[i] = org.Membership{
|
||||
IdentityID: id,
|
||||
OrgID: org.OrgID(m.GetOrgId()),
|
||||
WorkspaceID: org.WorkspaceID(m.GetWorkspaceId()),
|
||||
Role: org.Role(m.GetRole()),
|
||||
}
|
||||
}
|
||||
return access.Principal{
|
||||
IdentityID: identity.IdentityID(value.GetIdentityId()),
|
||||
Org: org.OrgID(value.GetOrgId()),
|
||||
Memberships: memberships,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListPolicies(ctx context.Context) ([]access.Policy, error) {
|
||||
r, err := c.client.ListPolicies(ctx, &pb.ListPoliciesRequest{})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
out := make([]access.Policy, len(r.Policies))
|
||||
for i := range r.Policies {
|
||||
out[i] = accessPolicyValue(r.Policies[i])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *Client) PutPolicy(ctx context.Context, p access.Policy) (int64, error) {
|
||||
r, err := c.client.PutPolicy(ctx, &pb.PutPolicyRequest{Policy: accessPolicyProto(p)})
|
||||
if err != nil {
|
||||
return 0, unmapError(err)
|
||||
}
|
||||
return r.Version, nil
|
||||
}
|
||||
|
||||
func (c *Client) DeletePolicy(ctx context.Context, p access.Policy) error {
|
||||
_, err := c.client.DeletePolicy(ctx, &pb.DeletePolicyRequest{Policy: accessPolicyProto(p)})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error {
|
||||
_, err := c.client.EnsureShippedOrgPolicies(ctx, &pb.EnsureShippedOrgPoliciesRequest{OrgId: string(orgID)})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) RecordDenial(ctx context.Context, d access.Denial) error {
|
||||
_, err := c.client.RecordDenial(ctx, &pb.RecordDenialRequest{Denial: accessDenialProto(d)})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]access.Denial, error) {
|
||||
r, err := c.client.ListDenials(ctx, &pb.ListDenialsRequest{OrgId: string(orgID), Limit: int32(limit)})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
out := make([]access.Denial, len(r.Denials))
|
||||
for i := range r.Denials {
|
||||
out[i] = accessDenialValue(r.Denials[i])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
@@ -99,6 +100,18 @@ type Deps struct {
|
||||
// (docs/prds/eda-playbook-engine.md gap 2). Optional: nil disables the
|
||||
// two playbook dispatch RPCs with codes.Unavailable.
|
||||
PlaybookDispatcher storecontract.PlaybookDispatcher
|
||||
// Principals assembles the access principal for one identity: the org it
|
||||
// serves and its memberships. Optional: nil answers GetPrincipal with
|
||||
// codes.Unavailable.
|
||||
Principals access.PrincipalSource
|
||||
// Policies is the stored policy chain (docs/prds/orgs-and-access.md).
|
||||
// Optional: nil answers the access RPCs with codes.Unavailable. The reset
|
||||
// surface is deliberately not an RPC: `archied access reset` runs on the
|
||||
// State Store host, never over the network.
|
||||
Policies access.PolicyStore
|
||||
// Denials records and lists denial records. Optional: nil disables the
|
||||
// pair with codes.Unavailable.
|
||||
Denials access.DenialStore
|
||||
// TaskLogs reads one task attempt's persisted log out of the state
|
||||
// directory this process owns. Optional, and nil is the honest default for
|
||||
// a store service that shares no state directory with the daemon:
|
||||
|
||||
@@ -165,6 +165,20 @@ service StateStoreService {
|
||||
// relation server-side, so the grant only names the caller.
|
||||
rpc EnqueueCallTask(EnqueueCallTaskRequest) returns (EnqueueCallTaskResponse);
|
||||
rpc WorkflowCallStatus(WorkflowCallStatusRequest) returns (WorkflowCallStatusResponse);
|
||||
|
||||
// Access: the stored policy chain and its denial records
|
||||
// (docs/prds/orgs-and-access.md). ListPolicies is the engine's snapshot;
|
||||
// the writes are administrative. RecordDenial is the dashboard's and
|
||||
// dispatch's write path; ListDenials is the operator surface.
|
||||
// The principal assembly the Authorizer evaluates: an identity, the org
|
||||
// it serves, and its memberships (internal/domain/access).
|
||||
rpc GetPrincipal(GetPrincipalRequest) returns (GetPrincipalResponse);
|
||||
rpc ListPolicies(ListPoliciesRequest) returns (ListPoliciesResponse);
|
||||
rpc PutPolicy(PutPolicyRequest) returns (PutPolicyResponse);
|
||||
rpc DeletePolicy(DeletePolicyRequest) returns (DeletePolicyResponse);
|
||||
rpc EnsureShippedOrgPolicies(EnsureShippedOrgPoliciesRequest) returns (EnsureShippedOrgPoliciesResponse);
|
||||
rpc RecordDenial(RecordDenialRequest) returns (RecordDenialResponse);
|
||||
rpc ListDenials(ListDenialsRequest) returns (ListDenialsResponse);
|
||||
}
|
||||
|
||||
message RegisterTaskGrantRequest {
|
||||
@@ -923,3 +937,56 @@ message RemoveInstalledPackageRequest { string org_id = 1; string name = 2; }
|
||||
message RemoveInstalledPackageResponse {}
|
||||
|
||||
// Task mirrors internal/domain/workflow.Task.
|
||||
|
||||
message GetPrincipalRequest { string identity_id = 1; }
|
||||
// PrincipalMembership mirrors org.Membership: an identity's role in an org,
|
||||
// or in one workspace of it.
|
||||
message PrincipalMembership {
|
||||
string org_id = 1;
|
||||
string workspace_id = 2;
|
||||
string role = 3;
|
||||
}
|
||||
message AccessPrincipal {
|
||||
string identity_id = 1;
|
||||
string org_id = 2;
|
||||
repeated PrincipalMembership memberships = 3;
|
||||
}
|
||||
message GetPrincipalResponse { AccessPrincipal principal = 1; }
|
||||
|
||||
// AccessPolicy mirrors internal/domain/access.Policy: one Cedar policy
|
||||
// document and the level-scope tuple that places it in the chain.
|
||||
message AccessPolicy {
|
||||
string policy_id = 1;
|
||||
string level = 2;
|
||||
string org_id = 3;
|
||||
string workspace_id = 4;
|
||||
string object_kind = 5;
|
||||
string object_id = 6;
|
||||
string text = 7;
|
||||
}
|
||||
message ListPoliciesRequest {}
|
||||
message ListPoliciesResponse { repeated AccessPolicy policies = 1; }
|
||||
message PutPolicyRequest { AccessPolicy policy = 1; }
|
||||
message PutPolicyResponse { int64 version = 1; }
|
||||
message DeletePolicyRequest { AccessPolicy policy = 1; }
|
||||
message DeletePolicyResponse {}
|
||||
message EnsureShippedOrgPoliciesRequest { string org_id = 1; }
|
||||
message EnsureShippedOrgPoliciesResponse {}
|
||||
// AccessDenial mirrors internal/domain/access.Denial: one refusal with the
|
||||
// level that decided it and the deciding policies. The store coalesces
|
||||
// identical denials within a minute into one row with a count.
|
||||
message AccessDenial {
|
||||
string org_id = 1;
|
||||
string principal = 2;
|
||||
string action = 3;
|
||||
string resource_kind = 4;
|
||||
string resource_id = 5;
|
||||
string level = 6;
|
||||
repeated string policies = 7;
|
||||
int64 count = 8;
|
||||
google.protobuf.Timestamp at = 9;
|
||||
}
|
||||
message RecordDenialRequest { AccessDenial denial = 1; }
|
||||
message RecordDenialResponse {}
|
||||
message ListDenialsRequest { string org_id = 1; int32 limit = 2; }
|
||||
message ListDenialsResponse { repeated AccessDenial denials = 1; }
|
||||
Reference in new issue
Block a user