mirror of
https://github.com/hanzoai/deploy.git
synced 2026-10-07 08:44:50 +00:00
* feat(api): hard-fork CRD API group argoproj.io -> deploy.hanzo.ai
Hanzo CD hard-fork, phase 1.1. Single source of truth is
pkg/apis/application/register.go's Group constant (Application/AppProject/
ApplicationSet all derive their FullName from it); every other Go call-site
that hardcoded the literal group string is updated to match: the 3 generated
informer GVRs, the app-of-apps nested-Application detector in types.go, the
resource-tree Application-kind cache populator, the 3 NotFound error
constructors in server/application, and the applicationset-controller's
leader-election Lease name/ID (kept in lockstep across Go source + RBAC
resourceNames, or leader election would get RBAC-denied on startup).
CRD YAMLs (application/appproject/applicationset) and every RBAC apiGroups
rule that actually governs our 3 CRDs are repointed to deploy.hanzo.ai, across
both manifests/base/* (namespaced Roles) and manifests/cluster-rbac/* (cluster
scope). Two adjacent things that share the "argoproj.io" string but are NOT
ours are deliberately left untouched: gitops-engine's health-check dispatch
for Argo Workflows' `Workflow` kind, and argocd-server-clusterrole's second
apiGroups block granting read on Argo Workflows' `workflows` resource — both
belong to a separate, unrelated Argoproj-family project we are not forking.
Also untouched, per explicit scope: annotation/label keys (argocd.argoproj.io/*)
and finalizers (*.argoproj.io) that track already-applied live resources, and
argocd-cm.yaml's resource.customizations.ignoreResourceUpdates keys (a narrow
app-of-apps diffing nicety, not build- or RBAC-relevant).
CGO_ENABLED=0 go build ./... verified green.
* ci: wire canonical hanzo.yml + cicd.yml (Hanzo CD image build)
Phase 1.3. Follows the same one-way pattern every hanzo/lux/zoo repo uses:
hanzo.yml declares the image (root Dockerfile -> ghcr.io/hanzoai/deploy) and a
fast go-build sanity test (the multi-stage Dockerfile build is the slow, real
gate); cicd.yml is the ~10-line trigger shim importing hanzoai/ci's reusable
build workflow on the arc pool, secrets from KMS only.
No `deploy:` block yet, matching the hanzoai/cms build-only-first-cutover
pattern: this repo's own live hanzo-cd namespace runs the whole Hanzo fleet's
GitOps, so the prod image/CRD swap is a deliberate separate action (see the
[HELD] universe PR), never an automatic rollout on merge. Every PR/push still
builds and pushes an immutable ghcr.io/hanzoai/deploy:sha-<7>-amd64 image.
* feat(ui): rebrand Argo CD -> Hanzo CD (title, favicon, logo, sidebar)
Phase 1.2. User-facing "Argo CD"/"ArgoCD" text replaced with "Hanzo CD"
across the login page, help modal, settings screens, version-info panel,
sync-options warning, fullscreen-logs title, app.tsx page titles, and
index.html's <title>/noscript text (dropped the now-wrong upstream CLI
doc link rather than invent a hanzo.ai URL that doesn't exist).
Logo/favicon assets replaced with the canonical Hanzo mark (never
hand-drawn, copied from ~/work/hanzo/logo/dist): the two real usages of
Argo's logo collapse onto one Hanzo glyph (mono + white variants) at the
same 5 call sites (login icon + footer, login.scss $logoPath/
$logoNegativePath, sidebar text-logo), preserving the existing CSS
invert() filters so both the light login panel and dark sidebar still
render correctly. Old argologo.svg/argo_o.svg/argo.png deleted (no
longer referenced). favicon-{16x16,32x32}.png added at
ui/src/assets/favicon/ (index.html's links to that path were previously
dead - the directory didn't exist in this checkout). package.json name
argo-cd-ui -> hanzo-cd-ui.
Left alone, deliberately: the two Kubernetes resource-kind icon sets
under ui/src/assets/images/resources/ (unrelated to branding), and
upstream doc/project links (argoproj.io, argo-cd.readthedocs.io) since
we have no equivalent hanzo.ai docs to point to yet - except the login
footer logo's outbound link, which now points to hanzo.ai instead of
argoproj.io (a Hanzo-branded mark linking to the upstream project it
was forked from read as an obvious leftover).
* feat(module): rename Go module github.com/argoproj/argo-cd/v3 -> github.com/hanzoai/deploy
Phase 2. No version suffix on the new path (org policy: never publish our
own Go modules above v1.x.x / with a v2+ suffix) — this fork starts a fresh
v0/v1 module identity rather than carrying the v3 the upstream fork point
had reached.
Mechanical, symmetric rewrite: 704 .go files (import statements only; two
disjoint substitutions applied specific-first so the nested gitops-engine
module path never double-matches), plus go.mod (module line, the
gitops-engine require+replace pair, version reset to v0.0.0-... since a
suffix-less path can't carry a v3 semver), gitops-engine/go.mod, Makefile
(ldflags PACKAGE + 2 TEST_MODULE filters), .golangci.yaml, .goreleaser.yaml,
.mockery.yaml (+ gitops-engine's), Procfile, the codegen/proto generation
scripts (hack/generate-proto.sh, update-codegen.sh, update-openapi.sh), and
20 .proto files' go_package options. Also one OpenTelemetry tracer name
string in gitops-engine/pkg/sync/sync_context.go (a cosmestic label, not an
import, but worth keeping consistent).
CGO_ENABLED=0 go build ./... verified green for both the root module and
the nested gitops-engine module; go vet clean on both; go mod tidy run
(network available) to reconcile go.sum, dependency set unchanged.
Left alone, deliberately: doc-only mentions (docs/snyk/*.html scan reports,
gitops-engine/README.md), a comment-only reference in
.github/workflows/release.yaml, and one Renovate bot config line — none are
build- or codegen-load-bearing. Also left alone: comments citing upstream
GitHub issue URLs (github.com/argoproj/argo-cd/issues/NNNNN) and a handful
of test fixtures using "https://github.com/argoproj/argo-cd.git" as a
representative example repo URL — both are accurate historical/test-data
references, not stale self-references.
---------
Co-authored-by: Hanzo Dev <[email protected]>
283 lines
9.6 KiB
Go
283 lines
9.6 KiB
Go
package account
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
log "github.com/sirupsen/logrus"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
|
|
"github.com/hanzoai/deploy/common"
|
|
"github.com/hanzoai/deploy/pkg/apiclient/account"
|
|
"github.com/hanzoai/deploy/server/rbacpolicy"
|
|
"github.com/hanzoai/deploy/util/password"
|
|
"github.com/hanzoai/deploy/util/rbac"
|
|
"github.com/hanzoai/deploy/util/security"
|
|
"github.com/hanzoai/deploy/util/session"
|
|
"github.com/hanzoai/deploy/util/settings"
|
|
)
|
|
|
|
// Server provides a Session service
|
|
type Server struct {
|
|
sessionMgr *session.SessionManager
|
|
settingsMgr *settings.SettingsManager
|
|
enf *rbac.Enforcer
|
|
namespace string
|
|
}
|
|
|
|
// NewServer returns a new instance of the Session service
|
|
func NewServer(sessionMgr *session.SessionManager, settingsMgr *settings.SettingsManager, enf *rbac.Enforcer, namespace string) *Server {
|
|
return &Server{sessionMgr, settingsMgr, enf, namespace}
|
|
}
|
|
|
|
// UpdatePassword updates the password of the currently authenticated account or the account specified in the request.
|
|
func (s *Server) UpdatePassword(ctx context.Context, q *account.UpdatePasswordRequest) (*account.UpdatePasswordResponse, error) {
|
|
username := session.GetUserIdentifier(ctx)
|
|
|
|
updatedUsername := username
|
|
if q.Name != "" {
|
|
updatedUsername = q.Name
|
|
}
|
|
|
|
// check for permission is user is trying to change someone else's password
|
|
// assuming user is trying to update someone else if username is different or issuer is not Argo CD
|
|
issuer := session.Iss(ctx)
|
|
if updatedUsername != username || issuer != session.SessionManagerClaimsIssuer {
|
|
if err := s.enf.EnforceErr(ctx.Value("claims"), rbac.ResourceAccounts, rbac.ActionUpdate, q.Name); err != nil {
|
|
return nil, fmt.Errorf("permission denied: %w", err)
|
|
}
|
|
}
|
|
|
|
if issuer == session.SessionManagerClaimsIssuer {
|
|
// local user is changing own password or another user password
|
|
|
|
// user is changing own password.
|
|
// ensure token belongs to a user, not project
|
|
if q.Name == "" && rbacpolicy.IsProjectSubject(username) {
|
|
return nil, status.Errorf(codes.InvalidArgument, "password can only be changed for local users, not user %q", username)
|
|
}
|
|
|
|
err := s.sessionMgr.VerifyUsernamePassword(username, q.CurrentPassword)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "current password does not match")
|
|
}
|
|
} else {
|
|
// SSO user is changing or local user password
|
|
|
|
iat, err := session.Iat(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get issue time: %w", err)
|
|
}
|
|
if time.Since(iat) > common.ChangePasswordSSOTokenMaxAge {
|
|
return nil, errors.New("SSO token is too old. Please use 'argocd relogin' to get a new token")
|
|
}
|
|
}
|
|
|
|
// Need to validate password complexity with regular expression
|
|
passwordPattern, err := s.settingsMgr.GetPasswordPattern()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get password pattern: %w", err)
|
|
}
|
|
|
|
validPasswordRegexp, err := regexp.Compile(passwordPattern)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to compile password regex: %w", err)
|
|
}
|
|
|
|
if !validPasswordRegexp.MatchString(q.NewPassword) {
|
|
err := fmt.Errorf("new password does not match the following expression: %s", passwordPattern)
|
|
return nil, err
|
|
}
|
|
|
|
hashedPassword, err := password.HashPassword(q.NewPassword)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to hash password: %w", err)
|
|
}
|
|
|
|
err = s.settingsMgr.UpdateAccount(updatedUsername, func(acc *settings.Account) error {
|
|
acc.PasswordHash = hashedPassword
|
|
now := time.Now().UTC()
|
|
acc.PasswordMtime = &now
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to update account password: %w", err)
|
|
}
|
|
|
|
if updatedUsername == username {
|
|
log.Infof("user '%s' updated password", username)
|
|
} else {
|
|
log.Infof("user '%s' updated password of user '%s'", username, updatedUsername)
|
|
}
|
|
return &account.UpdatePasswordResponse{}, nil
|
|
}
|
|
|
|
// CanI checks if the current account has permission to perform an action
|
|
func (s *Server) CanI(ctx context.Context, r *account.CanIRequest) (*account.CanIResponse, error) {
|
|
if !slices.Contains(rbac.Actions, r.Action) {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v does not contain %s", rbac.Actions, r.Action)
|
|
}
|
|
if !slices.Contains(rbac.Resources, r.Resource) {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v does not contain %s", rbac.Resources, r.Resource)
|
|
}
|
|
|
|
subresource := r.Subresource
|
|
|
|
// For project-scoped resources, normalize the subresource using security.RBACName
|
|
// This converts "project/defaultNS/name" to "project/name" for backward compatibility
|
|
if rbac.ProjectScoped[r.Resource] && s.namespace != "" && subresource != "" {
|
|
parts := strings.Split(subresource, "/")
|
|
if len(parts) == 3 {
|
|
// 3-part format: project/namespace/name
|
|
// Normalize: if namespace == defaultNS, becomes project/name; otherwise stays project/namespace/name
|
|
subresource = security.RBACName(s.namespace, parts[0], parts[1], parts[2])
|
|
}
|
|
// if 2 parts, always assume the default namespace
|
|
// else: keep as-is (wildcards, etc.)
|
|
}
|
|
|
|
ok := s.enf.Enforce(ctx.Value("claims"), r.Resource, r.Action, subresource)
|
|
if ok {
|
|
return &account.CanIResponse{Value: "yes"}, nil
|
|
}
|
|
return &account.CanIResponse{Value: "no"}, nil
|
|
}
|
|
|
|
func toAPIAccount(name string, a settings.Account) *account.Account {
|
|
var capabilities []string
|
|
for _, c := range a.Capabilities {
|
|
capabilities = append(capabilities, string(c))
|
|
}
|
|
var tokens []*account.Token
|
|
for _, t := range a.Tokens {
|
|
tokens = append(tokens, &account.Token{Id: t.ID, ExpiresAt: t.ExpiresAt, IssuedAt: t.IssuedAt})
|
|
}
|
|
sort.Slice(tokens, func(i, j int) bool {
|
|
return tokens[i].IssuedAt > tokens[j].IssuedAt
|
|
})
|
|
return &account.Account{
|
|
Name: name,
|
|
Enabled: a.Enabled,
|
|
Capabilities: capabilities,
|
|
Tokens: tokens,
|
|
}
|
|
}
|
|
|
|
func (s *Server) ensureHasAccountPermission(ctx context.Context, action string, account string) error {
|
|
id := session.GetUserIdentifier(ctx)
|
|
|
|
// account has always has access to itself
|
|
if id == account && session.Iss(ctx) == session.SessionManagerClaimsIssuer {
|
|
return nil
|
|
}
|
|
if err := s.enf.EnforceErr(ctx.Value("claims"), rbac.ResourceAccounts, action, account); err != nil {
|
|
return fmt.Errorf("permission denied for account %s with action %s: %w", account, action, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ListAccounts returns the list of accounts
|
|
func (s *Server) ListAccounts(ctx context.Context, _ *account.ListAccountRequest) (*account.AccountsList, error) {
|
|
resp := account.AccountsList{}
|
|
accounts, err := s.settingsMgr.GetAccounts()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get accounts: %w", err)
|
|
}
|
|
for name, a := range accounts {
|
|
if err := s.ensureHasAccountPermission(ctx, rbac.ActionGet, name); err == nil {
|
|
resp.Items = append(resp.Items, toAPIAccount(name, a))
|
|
}
|
|
}
|
|
sort.Slice(resp.Items, func(i, j int) bool {
|
|
return resp.Items[i].Name < resp.Items[j].Name
|
|
})
|
|
return &resp, nil
|
|
}
|
|
|
|
// GetAccount returns an account
|
|
func (s *Server) GetAccount(ctx context.Context, r *account.GetAccountRequest) (*account.Account, error) {
|
|
if err := s.ensureHasAccountPermission(ctx, rbac.ActionGet, r.Name); err != nil {
|
|
return nil, fmt.Errorf("permission denied to get account %s: %w", r.Name, err)
|
|
}
|
|
a, err := s.settingsMgr.GetAccount(r.Name)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get account %s: %w", r.Name, err)
|
|
}
|
|
return toAPIAccount(r.Name, *a), nil
|
|
}
|
|
|
|
// CreateToken creates a token
|
|
func (s *Server) CreateToken(ctx context.Context, r *account.CreateTokenRequest) (*account.CreateTokenResponse, error) {
|
|
if err := s.ensureHasAccountPermission(ctx, rbac.ActionUpdate, r.Name); err != nil {
|
|
return nil, fmt.Errorf("permission denied to create token for account %s: %w", r.Name, err)
|
|
}
|
|
|
|
id := r.Id
|
|
if id == "" {
|
|
uniqueId, err := uuid.NewRandom()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate unique ID: %w", err)
|
|
}
|
|
id = uniqueId.String()
|
|
}
|
|
|
|
var tokenString string
|
|
err := s.settingsMgr.UpdateAccount(r.Name, func(account *settings.Account) error {
|
|
if account.TokenIndex(id) > -1 {
|
|
return fmt.Errorf("account already has token with id '%s'", id)
|
|
}
|
|
if !account.HasCapability(settings.AccountCapabilityApiKey) {
|
|
return fmt.Errorf("account '%s' does not have %s capability", r.Name, settings.AccountCapabilityApiKey)
|
|
}
|
|
|
|
now := time.Now()
|
|
var err error
|
|
tokenString, err = s.sessionMgr.Create(fmt.Sprintf("%s:%s", r.Name, settings.AccountCapabilityApiKey), r.ExpiresIn, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var expiresAt int64
|
|
if r.ExpiresIn > 0 {
|
|
expiresAt = now.Add(time.Duration(r.ExpiresIn) * time.Second).Unix()
|
|
}
|
|
account.Tokens = append(account.Tokens, settings.Token{
|
|
ID: id,
|
|
IssuedAt: now.Unix(),
|
|
ExpiresAt: expiresAt,
|
|
})
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to update account with new token: %w", err)
|
|
}
|
|
return &account.CreateTokenResponse{Token: tokenString}, nil
|
|
}
|
|
|
|
// DeleteToken deletes a token
|
|
func (s *Server) DeleteToken(ctx context.Context, r *account.DeleteTokenRequest) (*account.EmptyResponse, error) {
|
|
if err := s.ensureHasAccountPermission(ctx, rbac.ActionUpdate, r.Name); err != nil {
|
|
return nil, fmt.Errorf("permission denied to delete account %s: %w", r.Name, err)
|
|
}
|
|
|
|
err := s.settingsMgr.UpdateAccount(r.Name, func(account *settings.Account) error {
|
|
if index := account.TokenIndex(r.Id); index > -1 {
|
|
account.Tokens = append(account.Tokens[:index], account.Tokens[index+1:]...)
|
|
return nil
|
|
}
|
|
return status.Errorf(codes.NotFound, "token with id '%s' does not exist", r.Id)
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to delete account %s: %w", r.Name, err)
|
|
}
|
|
return &account.EmptyResponse{}, nil
|
|
}
|