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

94
cmd/status/root.go Normal file
View File

@@ -0,0 +1,94 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package status
import (
"context"
"errors"
"fmt"
"time"
"github.com/ory/x/cmdx"
"github.com/ory/x/stringsx"
"github.com/spf13/cobra"
"google.golang.org/grpc"
grpcHealthV1 "google.golang.org/grpc/health/grpc_health_v1"
cliclient "github.com/ory/keto/cmd/client"
)
const (
FlagEndpoint = "endpoint"
)
func newStatusCmd() *cobra.Command {
var endpoint string
cmd := &cobra.Command{
Use: "status",
Short: "Get the status of the upstream Keto instance",
Long: "Get a status report about the upstream Keto instance. Can also block until the service is healthy.",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, _ []string) error {
block, err := cmd.Flags().GetBool(cliclient.FlagBlock)
if err != nil {
return err
}
var connect func(*cobra.Command) (*grpc.ClientConn, error)
switch endpoints := stringsx.SwitchExact(endpoint); {
case endpoints.AddCase("read"):
connect = cliclient.GetReadConn
case endpoints.AddCase("write"):
connect = cliclient.GetWriteConn
default:
return endpoints.ToUnknownCaseErr()
}
loudPrinter := cmdx.NewLoudOutPrinter(cmd)
conn, err := connect(cmd)
for block && err != nil {
if !errors.Is(err, context.DeadlineExceeded) {
return err
}
_, _ = loudPrinter.Println("Context deadline exceeded, going to retry.")
conn, err = connect(cmd)
}
if err != nil {
_, _ = fmt.Fprint(cmd.ErrOrStderr(), err.Error())
return cmdx.FailSilently(cmd)
}
c := grpcHealthV1.NewHealthClient(conn)
for {
status, err := c.Check(cmd.Context(), &grpcHealthV1.HealthCheckRequest{})
if err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Unable to get a check response: %+v\n", err)
return cmdx.FailSilently(cmd)
}
if !block || status.GetStatus() == grpcHealthV1.HealthCheckResponse_SERVING {
_, _ = fmt.Fprintln(cmd.OutOrStdout(), status.GetStatus().String())
return nil
}
_, _ = loudPrinter.Printf("Got the status %s, waiting until %s.\n", status.GetStatus(), grpcHealthV1.HealthCheckResponse_SERVING)
time.Sleep(500 * time.Millisecond)
}
},
}
cliclient.RegisterRemoteURLFlags(cmd.Flags())
cmdx.RegisterNoiseFlags(cmd.Flags())
cmd.Flags().StringVar(&endpoint, FlagEndpoint, "read", "which endpoint to use; one of {read, write}")
return cmd
}
func RegisterCommandRecursive(parent *cobra.Command) {
parent.AddCommand(newStatusCmd())
}

153
cmd/status/root_test.go Normal file
View File

@@ -0,0 +1,153 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package status
import (
"bytes"
"context"
"errors"
"net/http/httptest"
"strings"
"testing"
"time"
"connectrpc.com/connect"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
grpcHealthV1 "google.golang.org/grpc/health/grpc_health_v1"
"github.com/ory/x/cmdx"
"github.com/ory/keto/cmd/client"
"github.com/ory/keto/cmd/client/clienttest"
"github.com/ory/keto/internal/driver"
"github.com/ory/keto/internal/namespace"
)
func TestStatusCmd(t *testing.T) {
ts := clienttest.NewTestServer(t, []*namespace.Namespace{{Name: t.Name()}}, newStatusCmd)
for _, serverType := range []clienttest.ServerType{clienttest.ReadServer, clienttest.WriteServer} {
t.Run("server_type="+string(serverType), func(t *testing.T) {
ts.Cmd.PersistentArgs = append(ts.Cmd.PersistentArgs, "--"+cmdx.FlagQuiet, "--"+FlagEndpoint, string(serverType))
t.Run("case=timeout,noblock", func(t *testing.T) {
ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(-time.Second))
defer cancel()
stdErr := cmdx.ExecExpectedErrCtx(ctx, t, newStatusCmd(), "--"+FlagEndpoint, string(serverType))
assert.Contains(t, stdErr, "context deadline exceeded")
})
t.Run("case=noblock", func(t *testing.T) {
stdOut := ts.Cmd.ExecNoErr(t)
assert.Equal(t, grpcHealthV1.HealthCheckResponse_SERVING.String()+"\n", stdOut)
})
t.Run("case=block", func(t *testing.T) {
ctx := context.WithValue(t.Context(), client.ContextKeyTimeout, 100*time.Millisecond)
s := httptest.NewUnstartedServer(ts.NewHandler(t, serverType))
s.EnableHTTP2 = true
startServe := make(chan struct{})
serveErr := &errgroup.Group{}
serveErr.Go(func() error {
// wait until we get the signal to start
<-startServe
s.StartTLS()
return nil
})
var stdIn, stdErr bytes.Buffer
stdOut := cmdx.CallbackWriter{
Callbacks: map[string]func([]byte) error{
// once we get the first retry message, we want to start serving
"Context deadline exceeded, going to retry.": func([]byte) error {
// select ensures we only call this if the chan is not already closed
select {
case <-startServe:
default:
close(startServe)
}
return nil
},
},
}
require.NoError(t,
cmdx.ExecBackgroundCtx(ctx, newStatusCmd(), &stdIn, &stdOut, &stdErr,
"--"+FlagEndpoint, string(serverType),
"--"+serverType.FlagName(), s.Listener.Addr().String(),
"--insecure-skip-hostname-verification=true",
"--"+client.FlagBlock,
).Wait(),
)
fullStdOut := stdOut.String()
assert.True(t, strings.HasSuffix(fullStdOut, "\n"+grpcHealthV1.HealthCheckResponse_SERVING.String()+"\n"), fullStdOut)
require.NoError(t, serveErr.Wait())
})
})
}
}
func authInterceptor(header, validValue string) connect.UnaryInterceptorFunc {
return func(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
val := req.Header().Get(header)
if val == "" {
return nil, errors.New("not authorized, no header values")
}
if val != validValue {
return nil, errors.New("not authorized, incorrect value")
}
return next(ctx, req)
}
}
}
func TestAuthorizedRequest(t *testing.T) {
ts := clienttest.NewTestServer(
t, []*namespace.Namespace{{Name: t.Name()}}, newStatusCmd,
driver.WithHandlerOptions(connect.WithInterceptors(authInterceptor("authorization", "Bearer secret"))),
)
t.Run("case=not authorized", func(t *testing.T) {
out := ts.Cmd.ExecExpectedErr(t)
assert.Contains(t, out, "not authorized")
})
t.Run("case=authorized", func(t *testing.T) {
t.Setenv("KETO_BEARER_TOKEN", "secret")
out := ts.Cmd.ExecNoErr(t)
assert.Contains(t, out, "SERVING")
})
}
func TestAuthorityRequest(t *testing.T) {
ts := clienttest.NewTestServer(
t, []*namespace.Namespace{{Name: t.Name()}}, newStatusCmd,
driver.WithHandlerOptions(connect.WithInterceptors(authInterceptor("Host", "example.com"))),
)
t.Run("case=no authority", func(t *testing.T) {
out := ts.Cmd.ExecExpectedErr(t)
assert.Contains(t, out, "not authorized")
})
t.Run("case=env authority", func(t *testing.T) {
t.Setenv("KETO_AUTHORITY", "example.com")
out := ts.Cmd.ExecNoErr(t)
assert.Contains(t, out, "SERVING")
})
t.Run("case=flag authority", func(t *testing.T) {
out := ts.Cmd.ExecNoErr(t, "--"+client.FlagAuthority, "example.com")
assert.Contains(t, out, "SERVING")
})
}