Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
76 changes: 76 additions & 0 deletions cmd/reconcile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package cmd

import (
"fmt"
"os"

"github.com/MakeNowJust/heredoc"
"github.com/raystack/frontier/internal/reconcile"
cli "github.com/spf13/cobra"
)

func ReconcileCommand(cliConfig *Config) *cli.Command {
var (
filePath string
dryRun bool
header string
)
cmd := &cli.Command{
Use: "reconcile",
Short: "Reconcile declarative platform configuration to a desired-state file",
Long: heredoc.Doc(`
Converge platform resources to a declarative YAML spec via the admin API.

Currently supports the PlatformUser kind (platform admins/members). The file
is the source of truth: entries present are ensured, entries absent are removed.
Authenticate as a superuser (e.g. the bootstrap service account) via --header.
`),
Example: heredoc.Doc(`
$ frontier reconcile -f platform-users.yaml --dry-run -H "Authorization:Basic <base64>"
$ frontier reconcile -f platform-users.yaml -H "Authorization:Basic <base64>"
`),
Annotations: map[string]string{
"group": "core",
"client": "true",
},
RunE: func(cmd *cli.Command, args []string) error {
data, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("read desired-state file: %w", err)
}
adminClient, err := createAdminClient(cliConfig.Host)
if err != nil {
return err
}
registry := map[string]reconcile.Reconciler{
reconcile.KindPlatformUser: reconcile.NewPlatformUserReconciler(adminClient, header),
}
reports, runErr := reconcile.Run(cmd.Context(), registry, data, dryRun)
for _, rep := range reports {
printReconcileReport(cmd, rep)
}
return runErr
},
}
cmd.Flags().StringVarP(&filePath, "file", "f", "", "Path to the desired-state YAML file")
cmd.MarkFlagRequired("file")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the plan without applying changes")
cmd.Flags().StringVarP(&header, "header", "H", "", "Header <key>:<value> for auth, e.g. 'Authorization:Basic <base64>'")
bindFlagsFromClientConfig(cmd)
return cmd
}

func printReconcileReport(cmd *cli.Command, rep reconcile.Report) {
if len(rep.Planned) == 0 {
cmd.Printf("%s: no changes\n", rep.Kind)
return
}
verb := "applied"
if rep.DryRun {
verb = "planned"
}
cmd.Printf("%s (%s %d):\n", rep.Kind, verb, len(rep.Planned))
Comment thread
rohilsurana marked this conversation as resolved.
Outdated
for _, p := range rep.Planned {
cmd.Printf(" - %s\n", p)
}
}
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ func New(cliConfig *Config) *cli.Command {
cmd.AddCommand(PermissionCommand(cliConfig))
cmd.AddCommand(PolicyCommand(cliConfig))
cmd.AddCommand(SeedCommand(cliConfig))
cmd.AddCommand(ReconcileCommand(cliConfig))
cmd.AddCommand(configCommand())
cmd.AddCommand(versionCommand())
cmd.AddCommand(PreferencesCommand(cliConfig))
Expand Down
9 changes: 6 additions & 3 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,9 @@ func StartServer(logger *slog.Logger, cfg *config.Frontier) error {
if err = deps.BootstrapService.MigrateRoles(ctx); err != nil {
return err
}
// promote normal users to superusers
if err = deps.BootstrapService.MakeSuperUsers(ctx); err != nil {
// ensure the config-seeded bootstrap superuser service account (for automation/GitOps).
// all other platform-user management is handled out-of-band via the GitOps reconcile flow.
if err = deps.BootstrapService.EnsureBootstrapSuperUser(ctx); err != nil {
return err
}

Expand Down Expand Up @@ -569,14 +570,16 @@ func buildAPIDependencies(
namespaceService,
roleService,
permissionService,
userService,
authzSchemaRepository,
relationService,
policyService,
svUserRepo,
cfg.App.PAT.DeniedPermissionsSet(),
planService,
planBlobRepository,
svUserRepo,
scUserCredRepo,
serviceUserService,
)

cascadeDeleter := deleter.NewCascadeDeleter(organizationService, projectService, resourceService,
Expand Down
18 changes: 12 additions & 6 deletions config/sample.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,18 @@ app:

# platform level administration
admin:
# Email list of users which needs to be converted as superusers
# if the user is already present in the system, it is promoted to su
# if not, a new account is created with provided email id and promoted to su.
# UUIDs/slugs of existing users can also be provided instead of email ids
# but in that case a new user will not be created.
users: []
# bootstrap seeds a superuser SERVICE ACCOUNT from config (a username/password-style
# client_id + client_secret) so automation like the GitOps reconcile flow has a
# guaranteed superuser identity without a chicken-and-egg. The account is ensured and
# promoted to superuser on every boot (idempotent); the secret is rotated if it changes
# here. Authenticate with: Authorization: Basic base64(client_id:client_secret).
# Leave client_id/client_secret empty to disable.
# client_id must be a UUID (it is the service-account credential id); generate one
# (e.g. uuidgen) and keep it stable. client_secret is your chosen password.
bootstrap:
Comment thread
rohilsurana marked this conversation as resolved.
client_id: ""
client_secret: ""
# title: "GitOps Bootstrap Superuser"
# smtp configuration for sending emails
mailer:
smtp_host: smtp.example.com
Expand Down
11 changes: 11 additions & 0 deletions internal/api/v1beta1connect/platform.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package v1beta1connect
import (
"context"
"fmt"
"log/slog"
"sort"
"strings"

Expand Down Expand Up @@ -55,6 +56,16 @@ func (h *ConnectHandler) RemovePlatformUser(ctx context.Context, req *connect.Re
}
}
} else if req.Msg.GetServiceuserId() != "" {
// Protect the config-bootstrapped break-glass SA (well-known id). It is
// seeded and managed at boot, not via this API, while reconcile is
// authoritative over service accounts — without this guard an apply (or a
// stray call) would strip its superuser access until the next restart.
// Respond with the generic permission error (don't reveal that this id is the
// protected SA); the specific reason is logged only.
Comment thread
rohilsurana marked this conversation as resolved.
Outdated
if req.Msg.GetServiceuserId() == schema.BootstrapServiceUserID {
slog.WarnContext(ctx, "refused removal of the bootstrap superuser service account", "service_user_id", req.Msg.GetServiceuserId())
return nil, connect.NewError(connect.CodePermissionDenied, ErrUnauthorized)
}
for _, relationName := range platformRelations {
if err := h.serviceUserService.UnSudo(ctx, req.Msg.GetServiceuserId(), relationName); err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("RemovePlatformUser.ServiceUserUnSudo: service_user_id=%s relation=%s: %w", req.Msg.GetServiceuserId(), relationName, err))
Expand Down
15 changes: 15 additions & 0 deletions internal/api/v1beta1connect/platform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ func TestHandler_RemovePlatformUser(t *testing.T) {
assert.NotNil(t, resp)
})

t.Run("refuses to remove the bootstrap superuser service account", func(t *testing.T) {
serviceUserSvc := mocks.NewServiceUserService(t)
// the target is the well-known bootstrap SA -> reject before any UnSudo.
h := &ConnectHandler{serviceUserService: serviceUserSvc}
resp, err := h.RemovePlatformUser(context.Background(), connect.NewRequest(&frontierv1beta1.RemovePlatformUserRequest{
ServiceuserId: schema.BootstrapServiceUserID,
}))
assert.Error(t, err)
assert.Nil(t, resp)
assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
// must not reveal that this id is the protected bootstrap SA.
assert.NotContains(t, err.Error(), "bootstrap")
serviceUserSvc.AssertNotCalled(t, "UnSudo", mock.Anything, mock.Anything, mock.Anything)
})

t.Run("removes only the specified relation when relation is set", func(t *testing.T) {
userSvc := mocks.NewUserService(t)
// only the admin relation is stripped; an UnSudo for member would be an
Expand Down
33 changes: 33 additions & 0 deletions internal/api/v1beta1connect/serviceuser.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log/slog"

"connectrpc.com/connect"
"github.com/lestrrat-go/jwx/v2/jwk"
Expand Down Expand Up @@ -168,11 +169,31 @@ func (h *ConnectHandler) CreateServiceUser(ctx context.Context, request *connect
}), nil
}

// errBootstrapSAImmutable returns a PermissionDenied error when id is the
// config-bootstrapped break-glass SA (well-known id). That account is managed
// only via app.admin.bootstrap at boot — the API must never delete it or mint
// credentials/keys/tokens for it (which would create a persistent, rotation-proof
// superuser backdoor). Not even platform superusers are allowed.
//
// The response is the generic permission error so it doesn't reveal that this id
// is the protected SA; the specific reason is logged only.
func errBootstrapSAImmutable(ctx context.Context, id string) error {
Comment thread
rohilsurana marked this conversation as resolved.
if id == schema.BootstrapServiceUserID {
slog.WarnContext(ctx, "refused API mutation of the bootstrap superuser service account", "service_user_id", id)
return connect.NewError(connect.CodePermissionDenied, ErrUnauthorized)
}
return nil
}

func (h *ConnectHandler) DeleteServiceUser(ctx context.Context, request *connect.Request[frontierv1beta1.DeleteServiceUserRequest]) (*connect.Response[frontierv1beta1.DeleteServiceUserResponse], error) {
errorLogger := NewErrorLogger()
serviceUserID := request.Msg.GetId()
orgID := request.Msg.GetOrgId()

if err := errBootstrapSAImmutable(ctx, serviceUserID); err != nil {
return nil, err
}

err := h.serviceUserService.Delete(ctx, serviceUserID)
if err != nil {
errorLogger.LogServiceError(ctx, request, "DeleteServiceUser", err,
Expand All @@ -198,6 +219,10 @@ func (h *ConnectHandler) CreateServiceUserJWK(ctx context.Context, request *conn
serviceUserID := request.Msg.GetId()
title := request.Msg.GetTitle()

if err := errBootstrapSAImmutable(ctx, serviceUserID); err != nil {
return nil, err
}

svCred, err := h.serviceUserService.CreateKey(ctx, serviceuser.Credential{
ServiceUserID: serviceUserID,
Title: title,
Expand Down Expand Up @@ -312,6 +337,10 @@ func (h *ConnectHandler) CreateServiceUserCredential(ctx context.Context, reques
serviceUserID := request.Msg.GetId()
title := request.Msg.GetTitle()

if err := errBootstrapSAImmutable(ctx, serviceUserID); err != nil {
return nil, err
}

secret, err := h.serviceUserService.CreateSecret(ctx, serviceuser.Credential{
ServiceUserID: serviceUserID,
Title: title,
Expand Down Expand Up @@ -364,6 +393,10 @@ func (h *ConnectHandler) CreateServiceUserToken(ctx context.Context, request *co
serviceUserID := request.Msg.GetId()
title := request.Msg.GetTitle()

if err := errBootstrapSAImmutable(ctx, serviceUserID); err != nil {
return nil, err
}

secret, err := h.serviceUserService.CreateToken(ctx, serviceuser.Credential{
ServiceUserID: serviceUserID,
Title: title,
Expand Down
53 changes: 53 additions & 0 deletions internal/api/v1beta1connect/serviceuser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,59 @@ func TestHandler_ListServiceUserCredentials(t *testing.T) {
}
}

func TestHandler_BootstrapSAImmutable(t *testing.T) {
// The bootstrap SA (well-known id) must be immutable via the API: no delete and
// no minting of credentials/keys/tokens (which would be a rotation-proof
// superuser backdoor). Each guard must reject before touching the service.
t.Run("DeleteServiceUser is refused", func(t *testing.T) {
su := new(mocks.ServiceUserService)
h := &ConnectHandler{serviceUserService: su}
resp, err := h.DeleteServiceUser(context.Background(), connect.NewRequest(&frontierv1beta1.DeleteServiceUserRequest{
Id: schema.BootstrapServiceUserID,
}))
assert.Nil(t, resp)
assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
assert.NotContains(t, err.Error(), "bootstrap") // must not reveal the protected SA
su.AssertNotCalled(t, "Delete", mock.Anything, mock.Anything)
})

t.Run("CreateServiceUserCredential is refused", func(t *testing.T) {
su := new(mocks.ServiceUserService)
h := &ConnectHandler{serviceUserService: su}
resp, err := h.CreateServiceUserCredential(context.Background(), connect.NewRequest(&frontierv1beta1.CreateServiceUserCredentialRequest{
Id: schema.BootstrapServiceUserID,
}))
assert.Nil(t, resp)
assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
assert.NotContains(t, err.Error(), "bootstrap") // must not reveal the protected SA
su.AssertNotCalled(t, "CreateSecret", mock.Anything, mock.Anything)
})

t.Run("CreateServiceUserToken is refused", func(t *testing.T) {
su := new(mocks.ServiceUserService)
h := &ConnectHandler{serviceUserService: su}
resp, err := h.CreateServiceUserToken(context.Background(), connect.NewRequest(&frontierv1beta1.CreateServiceUserTokenRequest{
Id: schema.BootstrapServiceUserID,
}))
assert.Nil(t, resp)
assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
assert.NotContains(t, err.Error(), "bootstrap") // must not reveal the protected SA
su.AssertNotCalled(t, "CreateToken", mock.Anything, mock.Anything)
})

t.Run("CreateServiceUserJWK is refused", func(t *testing.T) {
su := new(mocks.ServiceUserService)
h := &ConnectHandler{serviceUserService: su}
resp, err := h.CreateServiceUserJWK(context.Background(), connect.NewRequest(&frontierv1beta1.CreateServiceUserJWKRequest{
Id: schema.BootstrapServiceUserID,
}))
assert.Nil(t, resp)
assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
assert.NotContains(t, err.Error(), "bootstrap") // must not reveal the protected SA
su.AssertNotCalled(t, "CreateKey", mock.Anything, mock.Anything)
})
}

func TestHandler_DeleteServiceUserCredential(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading
Loading