Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
module go.bytebuilders.dev/cli

go 1.25.6
go 1.26.0

require (
connectrpc.com/connect v1.21.1
github.com/cert-manager/cert-manager v1.19.4
github.com/envoyproxy/gateway v1.6.3
github.com/fatih/color v1.18.0
Expand All @@ -12,16 +13,18 @@ require (
github.com/pkg/errors v0.9.1
github.com/rs/xid v1.6.0
github.com/spf13/cobra v1.10.1
go.bytebuilders.dev/b3/apis v0.0.0-20261108173727-9aab4bbcfac7
go.bytebuilders.dev/catalog v0.0.19
go.bytebuilders.dev/client v0.0.4
go.bytebuilders.dev/license-verifier v0.15.0
go.bytebuilders.dev/resource-model v0.3.0
gocloud.dev v0.41.0
gomodules.xyz/blobfs v0.2.2
gomodules.xyz/go-sh v0.2.0
gomodules.xyz/logs v0.0.7
gomodules.xyz/pointer v0.1.0
gomodules.xyz/x v0.0.17
google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101
google.golang.org/protobuf v1.36.12
k8s.io/api v0.34.3
k8s.io/apimachinery v0.34.3
k8s.io/cli-runtime v0.34.3
Expand All @@ -41,6 +44,7 @@ require (
)

require (
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20260415201107-50325440f8f2.1 // indirect
cel.dev/expr v0.24.0 // indirect
cloud.google.com/go v0.120.0 // indirect
cloud.google.com/go/auth v0.17.0 // indirect
Expand Down Expand Up @@ -203,6 +207,7 @@ require (
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/zeebo/errs v1.4.0 // indirect
github.com/zeebo/xxh3 v1.0.2 // indirect
go.bytebuilders.dev/resource-model v0.3.0 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.36.0 // indirect
Expand Down Expand Up @@ -237,9 +242,7 @@ require (
google.golang.org/api v0.256.0 // indirect
google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 // indirect
google.golang.org/grpc v1.76.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
Expand Down Expand Up @@ -278,3 +281,5 @@ replace github.com/Masterminds/sprig/v3 => github.com/gomodules/sprig/v3 v3.2.3-
replace sigs.k8s.io/controller-runtime => github.com/kmodules/controller-runtime v0.22.5-0.20251227114913-f011264689cd

replace k8s.io/apiserver => github.com/kmodules/apiserver v0.34.4-0.20251227112449-07fa35efc6fc

replace go.bytebuilders.dev/b3/apis => github.com/appscode-cloud/b3/apis v0.0.0-20261108173727-9aab4bbcfac7
10 changes: 8 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20260415201107-50325440f8f2.1 h1:s6hzCXtND/ICdGPTMGk7C+/BFlr2Jg5GyH0NKf4XGXg=
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20260415201107-50325440f8f2.1/go.mod h1:tvtbpgaVXZX4g6Pn+AnzFycuRK3MOz5HJfEGeEllXYM=
cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY=
cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw=
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
Expand Down Expand Up @@ -32,6 +34,8 @@ cloud.google.com/go/storage v1.51.0 h1:ZVZ11zCiD7b3k+cH5lQs/qcNaoSz3U9I0jgwVzqDl
cloud.google.com/go/storage v1.51.0/go.mod h1:YEJfu/Ki3i5oHC/7jyTgsGZwdQ8P9hqMqvpi5kRKGgc=
cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4=
cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI=
connectrpc.com/connect v1.21.1 h1:h2kacdlzXpZU2OQFSv98xkjYXNUSr/ptxmGVbS/+CRM=
connectrpc.com/connect v1.21.1/go.mod h1:fhMcVJ5w6r/yTYhnkEbW6+sIF7OZ5Ay7KYgmfebh2ek=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
filippo.io/edwards25519 v1.1.1 h1:YpjwWWlNmGIDyXOn8zLzqiD+9TyIlPhGFG96P39uBpw=
filippo.io/edwards25519 v1.1.1/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
Expand Down Expand Up @@ -79,6 +83,8 @@ github.com/PuerkitoBio/purell v1.2.1 h1:QsZ4TjvwiMpat6gBCBxEQI0rcS9ehtkKtSpiUnd9
github.com/PuerkitoBio/purell v1.2.1/go.mod h1:ZwHcC/82TOaovDi//J/804umJFFmbOHPngi8iYYv/Eo=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/appscode-cloud/b3/apis v0.0.0-20261108173727-9aab4bbcfac7 h1:DUTRqm1J+kuLpmEbqwQQ7zSF86oKD/U3mFj+C3ysq5U=
github.com/appscode-cloud/b3/apis v0.0.0-20261108173727-9aab4bbcfac7/go.mod h1:mfUKXIT8VqyGjS+ecHykxMSLs/0lEkl/OdHPS4pNplI=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/circbuf v0.0.0-20190214190532-5111143e8da2 h1:7Ip0wMmLHLRJdrloDxZfhMm0xrLXZS8+COSu2bXmEQs=
github.com/armon/circbuf v0.0.0-20190214190532-5111143e8da2/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
Expand Down Expand Up @@ -905,8 +911,8 @@ google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
160 changes: 160 additions & 0 deletions pkg/akp/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
Copyright AppsCode Inc. and Contributors

Licensed under the AppsCode Community License 1.0.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://github.com/appscode/licenses/raw/1.0.0/AppsCode-Community-1.0.0.md

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package akp builds the clients of the AKP v2 API, served under /api/v2.
package akp

import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"os"
"strings"

clusterv2 "go.bytebuilders.dev/b3/apis/gen/go/akp/cluster/v2"
"go.bytebuilders.dev/b3/apis/gen/go/akp/cluster/v2/clusterv2connect"
userv2 "go.bytebuilders.dev/b3/apis/gen/go/akp/user/v2"
"go.bytebuilders.dev/b3/apis/gen/go/akp/user/v2/userv2connect"

"connectrpc.com/connect"
"github.com/nats-io/nats.go"
)

const csrfCookie = "_csrf"

// Credentials are what the CLI signs in to AKP with.
type Credentials struct {
Token string
Username string
Password string
Cookies []http.Cookie
}

type Clients struct {
// Organization is the account to act on; empty means the caller's own.
Organization string

Users userv2connect.UserServiceClient
Nats userv2connect.NatsServiceClient
Clusters clusterv2connect.ClusterServiceClient
Lifecycle clusterv2connect.LifecycleServiceClient
}

func NewClients(endpoint, organization string, cred Credentials) *Clients {
baseURL := strings.TrimSuffix(endpoint, "/") + "/api/v2"
hc := http.DefaultClient
opts := []connect.ClientOption{connect.WithInterceptors(credentialsInterceptor(cred), errorInfoInterceptor(endpoint))}
return &Clients{
Organization: organization,
Users: userv2connect.NewUserServiceClient(hc, baseURL, opts...),
Nats: userv2connect.NewNatsServiceClient(hc, baseURL, opts...),
Clusters: clusterv2connect.NewClusterServiceClient(hc, baseURL, opts...),
Lifecycle: clusterv2connect.NewLifecycleServiceClient(hc, baseURL, opts...),
}
}

func credentialsInterceptor(cred Credentials) connect.UnaryInterceptorFunc {
return func(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
if req.Spec().IsClient {
setCredentials(req.Header(), cred)
}
return next(ctx, req)
}
}
}

func setCredentials(h http.Header, cred Credentials) {
if cred.Token != "" {
h.Set("Authorization", "token "+cred.Token)
}
// Basic auth replaces the token, as it did with the AKP v1 API client.
if cred.Username != "" && cred.Password != "" {
h.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(cred.Username+":"+cred.Password)))
}
if len(cred.Cookies) == 0 {
return
}
cookies := make([]string, 0, len(cred.Cookies))
for _, c := range cred.Cookies {
cookies = append(cookies, (&http.Cookie{Name: c.Name, Value: c.Value}).String())
if c.Name == csrfCookie {
// AKP checks the CSRF token of a session caller.
h.Set("X-Csrf-Token", c.Value)
}
}
h.Set("Cookie", strings.Join(cookies, "; "))
}

// Owner is the account the CLI acts on: the chosen organization, else the caller.
func (c *Clients) Owner(ctx context.Context) (string, error) {
if c.Organization != "" {
return c.Organization, nil
}
resp, err := c.Users.GetAuthenticatedUser(ctx, connect.NewRequest(&userv2.GetAuthenticatedUserRequest{}))
if err != nil {
return "", fmt.Errorf("organization name wasn't provided. Automatic user detection failed with error: %w", err)
}
return resp.Msg.GetUser().GetUsername(), nil
}

// NatsConnection connects to AKP's NATS with the caller's credentials.
func (c *Clients) NatsConnection(ctx context.Context, name string) (*nats.Conn, error) {
resp, err := c.Nats.GetNatsCredentials(ctx, connect.NewRequest(&userv2.GetNatsCredentialsRequest{}))
if err != nil {
return nil, err
}
if len(resp.Msg.GetEndpoints()) == 0 {
return nil, errors.New("AKP answered no NATS endpoint")
}

credFile, err := os.CreateTemp("", "nats-*.creds")
if err != nil {
return nil, err
}
defer os.Remove(credFile.Name()) // nolint:errcheck
_, err = credFile.Write(resp.Msg.GetCredentials())
if cerr := credFile.Close(); err == nil {
err = cerr
}
if err != nil {
return nil, err
}

return nats.Connect(
resp.Msg.GetEndpoints()[0],
nats.Name(name),
nats.UserCredentials(credFile.Name()),
nats.NoReconnect(),
)
}

// ClusterStatus is a cluster with its live status.
func (c *Clients) ClusterStatus(ctx context.Context, owner, name string) (*clusterv2.Cluster, error) {
resp, err := c.Lifecycle.GetClusterStatus(ctx, connect.NewRequest(&clusterv2.GetClusterStatusRequest{
Cluster: &clusterv2.ClusterRef{Owner: owner, Name: name},
}))
if err != nil {
return nil, err
}
return resp.Msg.GetCluster(), nil
}

func IsNotFound(err error) bool {
return connect.CodeOf(err) == connect.CodeNotFound
}
96 changes: 96 additions & 0 deletions pkg/akp/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
Copyright AppsCode Inc. and Contributors

Licensed under the AppsCode Community License 1.0.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://github.com/appscode/licenses/raw/1.0.0/AppsCode-Community-1.0.0.md

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package akp

import (
"context"
"errors"
"fmt"
"strings"

"connectrpc.com/connect"
"google.golang.org/genproto/googleapis/rpc/errdetails"
)

// Domain and reasons of the google.rpc.ErrorInfo the AKP v2 API attaches to errors.
const (
errorDomain = "akp"
reasonAccountInactive = "ACCOUNT_INACTIVE"
reasonLoginProhibited = "LOGIN_PROHIBITED"
reasonOrgSSORequired = "ORG_SSO_REQUIRED"
)

// errorInfoInterceptor adds to an AKP v2 API error the page where the user can resolve it.
func errorInfoInterceptor(endpoint string) connect.UnaryInterceptorFunc {
return func(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
resp, err := next(ctx, req)
if err != nil {
err = withErrorInfo(err, endpoint)
}
return resp, err
}
}
}

// withErrorInfo wraps err, so connect.CodeOf still sees its code.
func withErrorInfo(err error, endpoint string) error {
info := errorInfo(err)
if info == nil {
return err
}
md := info.GetMetadata()
page := func(key string) string {
if md[key] == "" {
return ""
}
return strings.TrimSuffix(endpoint, "/") + md[key]
}

switch info.GetReason() {
case reasonAccountInactive:
if url := page("activation_path"); url != "" {
return fmt.Errorf("%w; activate the account at %s", err, url)
}
case reasonLoginProhibited:
if url := page("prohibit_login_path"); url != "" {
return fmt.Errorf("%w; the account may not sign in, see %s", err, url)
}
case reasonOrgSSORequired:
if url := page("oauth_callback_path"); url != "" {
return fmt.Errorf("%w; organization %s requires signing in through its SSO at %s", err, md["organization"], url)
}
}
return err
}

func errorInfo(err error) *errdetails.ErrorInfo {
var ce *connect.Error
if !errors.As(err, &ce) {
return nil
}
for _, d := range ce.Details() {
v, err := d.Value()
if err != nil {
continue
}
if info, ok := v.(*errdetails.ErrorInfo); ok && info.GetDomain() == errorDomain {
return info
}
}
return nil
}
Loading
Loading