snapshot of https://github.com/ory/keto.git (master, 2026-09-16; blobs > 131072B omitted)
Some checks failed
CI / Run lints and checks (push) Failing after 47s
CI / Run tests (push) Failing after 1s
CI / Run race tests (push) Failing after 5s
CI / Build CLI docs (push) Has been skipped
CI / Run buf actions (push) Failing after 5s
CodeQL / Analyze (go) (push) Failing after 3s
CodeQL / Analyze (javascript) (push) Failing after 2s
Docker Image Scanners / scanners (push) Failing after 3s
Format / format (push) Failing after 3s
Synchronize Issue Labels / Synchronize Issue Labels (push) Has been skipped
CI / Generate release (push) Has been skipped
CI / Draft newsletter (push) Has been skipped
CI / Pending approval Slack notification (push) Has been skipped
CI / Send newsletter (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-16 01:08:34 +05:00
commit 9456a4e922
2560 changed files with 120911 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package ast
import "encoding/json"
type (
Relation struct {
Name string `json:"name"`
Types []RelationType `json:"types,omitempty"`
SubjectSetRewrite *SubjectSetRewrite `json:"rewrite,omitempty"`
}
RelationType struct {
Namespace string `json:"namespace"`
Relation string `json:"relation,omitempty"` // optional
}
SubjectSetRewrite struct {
Operation Operator `json:"operator"`
Children Children `json:"children"`
}
Children = []Child
// Child are all possible types of subject-set rewrites.
Child interface {
// AsRewrite returns the child as a subject-set rewrite, as relations
// require a top-level rewrite, even if just one child was parsed.
AsRewrite() *SubjectSetRewrite
// EstimatedSize approximates the memory in bytes retained by the node.
EstimatedSize() int64
}
ComputedSubjectSet struct {
Relation string `json:"relation"`
}
TupleToSubjectSet struct {
Relation string `json:"relation"`
ComputedSubjectSetRelation string `json:"computed_subject_set_relation"`
}
// InvertResult inverts the check result of the child.
InvertResult struct {
Child Child `json:"inverted"`
}
)
type Operator int
//go:generate stringer -type=Operator -linecomment
const (
OperatorOr Operator = iota // or
OperatorAnd // and
)
func (i Operator) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
func (r *SubjectSetRewrite) AsRewrite() *SubjectSetRewrite { return r }
func (c *ComputedSubjectSet) AsRewrite() *SubjectSetRewrite {
return &SubjectSetRewrite{Children: []Child{c}}
}
func (t *TupleToSubjectSet) AsRewrite() *SubjectSetRewrite {
return &SubjectSetRewrite{Children: []Child{t}}
}
func (i *InvertResult) AsRewrite() *SubjectSetRewrite {
return &SubjectSetRewrite{Children: []Child{i}}
}

View File

@@ -0,0 +1,24 @@
// Code generated by "stringer -type=Operator -linecomment"; DO NOT EDIT.
package ast
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[OperatorOr-0]
_ = x[OperatorAnd-1]
}
const _Operator_name = "orand"
var _Operator_index = [...]uint8{0, 2, 5}
func (i Operator) String() string {
if i < 0 || i >= Operator(len(_Operator_index)-1) {
return "Operator(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Operator_name[_Operator_index[i]:_Operator_index[i+1]]
}

View File

@@ -0,0 +1,54 @@
// Copyright © 2026 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package ast
import "unsafe"
// EstimatedSize approximates the memory in bytes retained by the relation.
func (r *Relation) EstimatedSize() int64 {
s := int64(unsafe.Sizeof(*r)) + int64(len(r.Name))
for _, t := range r.Types {
s += int64(unsafe.Sizeof(t)) + int64(len(t.Namespace)+len(t.Relation))
}
return s + r.SubjectSetRewrite.EstimatedSize()
}
func (r *SubjectSetRewrite) EstimatedSize() int64 {
if r == nil {
return 0
}
s := int64(unsafe.Sizeof(*r))
for _, c := range r.Children {
s += int64(unsafe.Sizeof(c)) + childSize(c)
}
return s
}
func (c *ComputedSubjectSet) EstimatedSize() int64 {
if c == nil {
return 0
}
return int64(unsafe.Sizeof(*c)) + int64(len(c.Relation))
}
func (t *TupleToSubjectSet) EstimatedSize() int64 {
if t == nil {
return 0
}
return int64(unsafe.Sizeof(*t)) + int64(len(t.Relation)+len(t.ComputedSubjectSetRelation))
}
func (i *InvertResult) EstimatedSize() int64 {
if i == nil {
return 0
}
return int64(unsafe.Sizeof(*i)) + childSize(i.Child)
}
func childSize(c Child) int64 {
if c == nil {
return 0
}
return c.EstimatedSize()
}

View File

@@ -0,0 +1,89 @@
// Copyright © 2026 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package ast_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/ory/keto/internal/namespace/ast"
)
// The expected values are exact struct sizes on 64-bit platforms:
// Relation 48, RelationType 32, SubjectSetRewrite 32, ComputedSubjectSet 16,
// TupleToSubjectSet 32, InvertResult 16, interface header 16, plus string
// lengths. If this test breaks, an AST type changed: update the size
// accounting in size.go together with these numbers.
func TestRelationEstimatedSize(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
relation ast.Relation
expected int64
}{
{
name: "empty relation",
relation: ast.Relation{},
expected: 48,
},
{
name: "relation with name and types",
relation: ast.Relation{
Name: "viewers",
Types: []ast.RelationType{
{Namespace: "User"},
{Namespace: "Group", Relation: "members"},
},
},
expected: 48 + 7 + // struct + "viewers"
32 + 4 + // type + "User"
32 + 5 + 7, // type + "Group" + "members"
},
{
name: "relation with a rewrite of every node type",
relation: ast.Relation{
Name: "view",
SubjectSetRewrite: &ast.SubjectSetRewrite{
Operation: ast.OperatorAnd,
Children: ast.Children{
&ast.ComputedSubjectSet{Relation: "editors"},
&ast.TupleToSubjectSet{Relation: "parents", ComputedSubjectSetRelation: "view"},
&ast.InvertResult{Child: &ast.ComputedSubjectSet{Relation: "banned"}},
&ast.SubjectSetRewrite{Children: ast.Children{
&ast.ComputedSubjectSet{Relation: "owners"},
}},
},
},
},
expected: 48 + 4 + // struct + "view"
32 + // rewrite
16 + 16 + 7 + // header + computed + "editors"
16 + 32 + 7 + 4 + // header + tuple + "parents" + "view"
16 + 16 + 16 + 6 + // header + invert + computed + "banned"
16 + 32 + 16 + 16 + 6, // header + nested rewrite + header + computed + "owners"
},
{
name: "nil children are safe and cost nothing",
relation: ast.Relation{
SubjectSetRewrite: &ast.SubjectSetRewrite{
Children: ast.Children{
nil,
(*ast.SubjectSetRewrite)(nil),
(*ast.ComputedSubjectSet)(nil),
(*ast.TupleToSubjectSet)(nil),
(*ast.InvertResult)(nil),
&ast.InvertResult{},
},
},
},
expected: 48 + 32 + 6*16 + 16, // struct + rewrite + 6 headers + empty invert
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
require.Equal(t, tc.expected, tc.relation.EstimatedSize())
})
}
}

View File

@@ -0,0 +1,73 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package namespace
import (
"context"
"encoding/json"
"github.com/ory/herodot"
"github.com/ory/keto/internal/namespace/ast"
)
type (
Namespace struct {
// Deprecated: Only use the Name instead.
ID int32 `json:"id" db:"-" toml:"id"`
// The unique name of the namespace.
Name string `json:"name" db:"-" toml:"name"`
Config json.RawMessage `json:"config,omitempty" db:"-" toml:"config,omitempty"`
Relations []ast.Relation `json:"-" db:"-"`
}
Manager interface {
GetNamespaceByName(ctx context.Context, name string) (*Namespace, error)
// Deprecated: Use GetNamespaceByName instead.
GetNamespaceByConfigID(ctx context.Context, id int32) (*Namespace, error)
Namespaces(ctx context.Context) ([]*Namespace, error)
ShouldReload(newValue interface{}) bool
}
ManagerProvider interface {
NamespaceManager() (Manager, error)
}
)
func (ns *Namespace) FindRelation(name string) *ast.Relation {
if ns == nil || len(ns.Relations) == 0 {
return nil
}
for _, rel := range ns.Relations {
if rel.Name == name {
return &rel
}
}
return nil
}
func ASTRelationFor(ctx context.Context, m Manager, namespace, relation string) (*ast.Relation, error) {
// Special case: If the relationTuple's relation is empty, then it is not an
// error that the relation was not found.
if relation == "" {
return nil, nil
}
ns, err := m.GetNamespaceByName(ctx, namespace)
if err != nil {
// On an unknown namespace the answer should be "not allowed", not "not
// found". Therefore, we don't return the error here.
return nil, nil
}
// Special case: If Relations is empty, then there is no namespace
// configuration, and it is not an error that the relation was not found.
if len(ns.Relations) == 0 {
return nil, nil
}
rel := ns.FindRelation(relation)
if rel == nil {
return nil, herodot.ErrBadRequest().WithReasonf("relation %q does not exist", relation)
}
return rel, nil
}

View File

@@ -0,0 +1,40 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package namespace_test
import (
"context"
"errors"
"net/http"
"testing"
"github.com/ory/herodot"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/keto/internal/driver/config"
"github.com/ory/keto/internal/namespace"
"github.com/ory/keto/internal/namespace/ast"
)
func TestASTRelationFor(t *testing.T) {
ctx := context.Background()
nm := config.NewMemoryNamespaceManager(&namespace.Namespace{
Name: "test",
Relations: []ast.Relation{{Name: "test"}},
})
rel, err := namespace.ASTRelationFor(ctx, nm, "test", "test")
require.NoError(t, err)
assert.Equal(t, "test", rel.Name)
_, err = namespace.ASTRelationFor(ctx, nm, "test", "unknown")
herr, ok := errors.AsType[*herodot.DefaultError](err)
require.True(t, ok)
assert.Equal(t, http.StatusBadRequest, herr.CodeField)
rel, err = namespace.ASTRelationFor(ctx, nm, "unknown", "")
require.NoError(t, err)
assert.Nil(t, rel)
}

View File

@@ -0,0 +1,103 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package namespacehandler
import (
"context"
"net/http"
"connectrpc.com/connect"
"google.golang.org/protobuf/reflect/protoreflect"
"github.com/ory/herodot"
"github.com/ory/x/httprouterx"
"github.com/ory/x/httpx"
"github.com/ory/x/logrusx"
rts "github.com/ory/keto/gen/go/ory/keto/relation_tuples/v1alpha2"
"github.com/ory/keto/gen/go/ory/keto/relation_tuples/v1alpha2/relationtuplesconnect"
"github.com/ory/keto/internal/driver/config"
"github.com/ory/keto/internal/x"
)
type (
handlerDeps interface {
logrusx.Provider
httpx.WriterProvider
config.Provider
x.HandlerOptionsProvider
}
Handler struct {
relationtuplesconnect.UnimplementedNamespacesServiceHandler
d handlerDeps
}
)
const (
RouteBase = "/namespaces"
)
func New(d handlerDeps) *Handler { return &Handler{d: d} }
func (h *Handler) RegisterReadRoutes(r *httprouterx.RouterPublic) {
r.GET(RouteBase, h.getNamespaces)
listNamespacesHandler := connect.NewUnaryHandler(
relationtuplesconnect.NamespacesServiceListNamespacesProcedure,
h.ListNamespaces,
connect.WithSchema(rts.File_ory_keto_relation_tuples_v1alpha2_namespaces_service_proto.
Services().ByName("NamespacesService").
Methods().ByName("ListNamespaces")),
connect.WithHandlerOptions(h.d.HandlerOptions()...),
)
r.Handle(relationtuplesconnect.NamespacesServiceListNamespacesProcedure, listNamespacesHandler)
}
func (h *Handler) ProtoFiles() []protoreflect.FileDescriptor {
return []protoreflect.FileDescriptor{rts.File_ory_keto_relation_tuples_v1alpha2_namespaces_service_proto}
}
func (h *Handler) ListNamespaces(ctx context.Context, _ *connect.Request[rts.ListNamespacesRequest]) (*connect.Response[rts.ListNamespacesResponse], error) {
m, err := h.d.Config(ctx).NamespaceManager()
if err != nil {
h.d.Logger().WithError(err).Errorf("could not get namespace manager")
return nil, herodot.ErrInternalServerError()
}
namespaces, err := m.Namespaces(ctx)
if err != nil {
h.d.Logger().WithError(err).Errorf("could not get namespaces")
return nil, herodot.ErrInternalServerError()
}
apiNamespaces := make([]*rts.Namespace, len(namespaces))
for i, n := range namespaces {
apiNamespaces[i] = &rts.Namespace{Name: n.Name}
}
return connect.NewResponse(&rts.ListNamespacesResponse{Namespaces: apiNamespaces}), nil
}
// swagger:route GET /namespaces relationship listRelationshipNamespaces
//
// # Query namespaces
//
// Get all namespaces
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: relationshipNamespaces
// default: errorGeneric
//
// Extensions:
// x-ory-ratelimit-bucket: keto-admin-low
func (h *Handler) getNamespaces(w http.ResponseWriter, r *http.Request) {
res, err := h.ListNamespaces(r.Context(), nil)
if err != nil {
h.d.Writer().WriteError(w, r, err)
return
}
h.d.Writer().Write(w, r, res.Msg)
}

View File

@@ -0,0 +1,21 @@
// Copyright © 2026 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package namespace
import "unsafe"
// EstimatedSize approximates the memory in bytes retained by the namespaces.
func EstimatedSize(nn []*Namespace) int64 {
var s int64
for _, n := range nn {
if n == nil {
continue
}
s += int64(unsafe.Sizeof(n)) + int64(unsafe.Sizeof(*n)) + int64(len(n.Name)+len(n.Config))
for i := range n.Relations {
s += n.Relations[i].EstimatedSize()
}
}
return s
}

View File

@@ -0,0 +1,32 @@
// Copyright © 2026 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package namespace_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/ory/keto/internal/namespace"
"github.com/ory/keto/internal/namespace/ast"
)
func TestEstimatedSize(t *testing.T) {
t.Parallel()
require.Zero(t, namespace.EstimatedSize(nil))
require.Zero(t, namespace.EstimatedSize([]*namespace.Namespace{}))
nn := []*namespace.Namespace{
{Name: "Document", Config: json.RawMessage(`{}`)},
nil, // Must not panic.
{Name: "User", Relations: []ast.Relation{{Name: "manager"}}},
}
require.EqualValues(t,
8+72+8+2+ // pointer + Namespace + "Document" + config
8+72+4+ // pointer + Namespace + "User"
48+7, // relation + "manager"
namespace.EstimatedSize(nn))
}