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]>
366 lines
12 KiB
Go
366 lines
12 KiB
Go
// Utility functions for managing HTTPS server certificates and SSH known host
|
|
// entries for ArgoCD
|
|
package cert
|
|
|
|
import (
|
|
"bufio"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"encoding/base64"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
"github.com/hanzoai/deploy/common"
|
|
)
|
|
|
|
// A struct representing an entry in the list of SSH known hosts.
|
|
type SSHKnownHostsEntry struct {
|
|
// Hostname the key is for
|
|
Host string
|
|
// The type of the key
|
|
SubType string
|
|
// The data of the key, including the type
|
|
Data string
|
|
// The SHA256 fingerprint of the key
|
|
Fingerprint string
|
|
}
|
|
|
|
// A representation of a TLS certificate
|
|
type TLSCertificate struct {
|
|
// Subject of the certificate
|
|
Subject string
|
|
// Issuer of the certificate
|
|
Issuer string
|
|
// Certificate data
|
|
Data string
|
|
}
|
|
|
|
// Helper struct for certificate selection
|
|
type CertificateListSelector struct {
|
|
// Pattern to match the hostname with
|
|
HostNamePattern string
|
|
// Type of certificate to match
|
|
CertType string
|
|
// Subtype of certificate to match
|
|
CertSubType string
|
|
}
|
|
|
|
const (
|
|
// Text marker indicating start of certificate in PEM format
|
|
CertificateBeginMarker = "-----BEGIN CERTIFICATE-----"
|
|
// Text marker indicating end of certificate in PEM format
|
|
CertificateEndMarker = "-----END CERTIFICATE-----"
|
|
// Maximum number of lines for a single certificate
|
|
CertificateMaxLines = 128
|
|
// Maximum number of certificates or known host entries in a stream
|
|
CertificateMaxEntriesPerStream = 256
|
|
)
|
|
|
|
// Regular expression that matches a valid hostname
|
|
var validHostNameRegexp = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9_][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9_])(\.([a-zA-Z0-9]|[a-zA-Z0-9_][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]))*(\.){0,1}$`)
|
|
|
|
// Regular expression that matches all kind of IPv6 addresses
|
|
// See https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
|
|
var validIPv6Regexp = regexp.MustCompile(`(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))`)
|
|
|
|
// Regular expression that matches a valid FQDN
|
|
var validFQDNRegexp = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*(\.){1}$`)
|
|
|
|
// Can be used to test whether a given string represents a valid hostname
|
|
// If fqdn is true, given string must also be a FQDN representation.
|
|
func IsValidHostname(hostname string, fqdn bool) bool {
|
|
if !fqdn {
|
|
return validHostNameRegexp.MatchString(hostname) || validIPv6Regexp.MatchString(hostname)
|
|
}
|
|
return validFQDNRegexp.MatchString(hostname)
|
|
}
|
|
|
|
// Get the configured path to where TLS certificates are stored on the local
|
|
// filesystem. If ARGOCD_TLS_DATA_PATH environment is set, path is taken from
|
|
// there, otherwise the default will be returned.
|
|
func GetTLSCertificateDataPath() string {
|
|
if envPath := os.Getenv(common.EnvVarTLSDataPath); envPath != "" {
|
|
return envPath
|
|
}
|
|
return common.DefaultPathTLSConfig
|
|
}
|
|
|
|
// Get the configured path to where SSH certificates are stored on the local
|
|
// filesystem. If ARGOCD_SSH_DATA_PATH environment is set, path is taken from
|
|
// there, otherwise the default will be returned.
|
|
func GetSSHKnownHostsDataPath() string {
|
|
if envPath := os.Getenv(common.EnvVarSSHDataPath); envPath != "" {
|
|
return filepath.Join(envPath, common.DefaultSSHKnownHostsName)
|
|
}
|
|
return filepath.Join(common.DefaultPathSSHConfig, common.DefaultSSHKnownHostsName)
|
|
}
|
|
|
|
// Decode a certificate in PEM format to X509 data structure
|
|
func DecodePEMCertificateToX509(pemData string) (*x509.Certificate, error) {
|
|
decodedData, _ := pem.Decode([]byte(pemData))
|
|
if decodedData == nil {
|
|
return nil, errors.New("could not decode PEM data from input")
|
|
}
|
|
x509Cert, err := x509.ParseCertificate(decodedData.Bytes)
|
|
if err != nil {
|
|
return nil, errors.New("could not parse X509 data from input")
|
|
}
|
|
return x509Cert, nil
|
|
}
|
|
|
|
// Parse TLS certificates from a multiline string
|
|
func ParseTLSCertificatesFromData(data string) ([]string, error) {
|
|
return ParseTLSCertificatesFromStream(strings.NewReader(data))
|
|
}
|
|
|
|
// Parse TLS certificates from a file
|
|
func ParseTLSCertificatesFromPath(sourceFile string) ([]string, error) {
|
|
fileHandle, err := os.Open(sourceFile)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() {
|
|
if err = fileHandle.Close(); err != nil {
|
|
log.WithFields(log.Fields{
|
|
common.SecurityField: common.SecurityMedium,
|
|
common.SecurityCWEField: common.SecurityCWEMissingReleaseOfFileDescriptor,
|
|
}).Errorf("error closing file %q: %v", fileHandle.Name(), err)
|
|
}
|
|
}()
|
|
return ParseTLSCertificatesFromStream(fileHandle)
|
|
}
|
|
|
|
// Parse TLS certificate data from a data stream. The stream may contain more
|
|
// than one certificate. Each found certificate will generate a unique entry
|
|
// in the returned slice, so the length of the slice indicates how many
|
|
// certificates have been found.
|
|
func ParseTLSCertificatesFromStream(stream io.Reader) ([]string, error) {
|
|
scanner := bufio.NewScanner(stream)
|
|
inCertData := false
|
|
pemData := ""
|
|
curLine := 0
|
|
certLine := 0
|
|
|
|
certificateList := make([]string, 0)
|
|
|
|
// TODO: Implement error heuristics
|
|
|
|
for scanner.Scan() {
|
|
curLine++
|
|
if !inCertData {
|
|
if strings.HasPrefix(scanner.Text(), CertificateBeginMarker) {
|
|
certLine = 1
|
|
inCertData = true
|
|
pemData += scanner.Text() + "\n"
|
|
}
|
|
} else {
|
|
certLine++
|
|
pemData += scanner.Text() + "\n"
|
|
if strings.HasPrefix(scanner.Text(), CertificateEndMarker) {
|
|
inCertData = false
|
|
certificateList = append(certificateList, pemData)
|
|
if len(certificateList) > CertificateMaxEntriesPerStream {
|
|
return nil, errors.New("limit exceeded")
|
|
}
|
|
pemData = ""
|
|
}
|
|
}
|
|
|
|
if certLine > CertificateMaxLines {
|
|
return nil, errors.New("maximum number of lines exceeded during certificate parsing")
|
|
}
|
|
}
|
|
|
|
return certificateList, nil
|
|
}
|
|
|
|
// Parse SSH Known Hosts data from a multiline string
|
|
func ParseSSHKnownHostsFromData(data string) ([]string, error) {
|
|
return ParseSSHKnownHostsFromStream(strings.NewReader(data))
|
|
}
|
|
|
|
// Parse SSH Known Hosts data from a file
|
|
func ParseSSHKnownHostsFromPath(sourceFile string) ([]string, error) {
|
|
fileHandle, err := os.Open(sourceFile)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() {
|
|
if err = fileHandle.Close(); err != nil {
|
|
log.WithFields(log.Fields{
|
|
common.SecurityField: common.SecurityMedium,
|
|
common.SecurityCWEField: common.SecurityCWEMissingReleaseOfFileDescriptor,
|
|
}).Errorf("error closing file %q: %v", fileHandle.Name(), err)
|
|
}
|
|
}()
|
|
return ParseSSHKnownHostsFromStream(fileHandle)
|
|
}
|
|
|
|
// Parses a list of strings in SSH's known host data format from a stream and
|
|
// returns the valid entries in an array.
|
|
func ParseSSHKnownHostsFromStream(stream io.Reader) ([]string, error) {
|
|
scanner := bufio.NewScanner(stream)
|
|
knownHostsLists := make([]string, 0)
|
|
curLine := 0
|
|
numEntries := 0
|
|
|
|
for scanner.Scan() {
|
|
curLine++
|
|
lineData := scanner.Text()
|
|
if IsValidSSHKnownHostsEntry(lineData) {
|
|
numEntries++
|
|
knownHostsLists = append(knownHostsLists, lineData)
|
|
if len(knownHostsLists) > CertificateMaxEntriesPerStream {
|
|
return nil, errors.New("limit exceeded")
|
|
}
|
|
}
|
|
}
|
|
|
|
return knownHostsLists, nil
|
|
}
|
|
|
|
// Checks whether we can use a line from ssh_known_hosts data as an actual data
|
|
// source for a RepoCertificate object. This function only checks for syntactic
|
|
// validity, not if the data in the line is valid.
|
|
func IsValidSSHKnownHostsEntry(line string) bool {
|
|
trimmedEntry := strings.TrimSpace(line)
|
|
// We ignore commented out lines - usually happens when copy and pasting
|
|
// to the ConfigMap from a known_hosts file or from ssh-keyscan output.
|
|
if trimmedEntry == "" || trimmedEntry[0] == '#' {
|
|
return false
|
|
}
|
|
|
|
// Each line should consist of three fields: host, type, data
|
|
keyData := strings.SplitN(trimmedEntry, " ", 3)
|
|
return len(keyData) == 3
|
|
}
|
|
|
|
// Tokenize a known_hosts entry into hostname, key sub type and actual key data
|
|
func TokenizeSSHKnownHostsEntry(knownHostsEntry string) (string, string, []byte, error) {
|
|
knownHostsToken := strings.SplitN(knownHostsEntry, " ", 3)
|
|
if len(knownHostsToken) != 3 {
|
|
return "", "", nil, errors.New("error while tokenizing input data")
|
|
}
|
|
return knownHostsToken[0], knownHostsToken[1], []byte(knownHostsToken[2]), nil
|
|
}
|
|
|
|
// Parse a raw known hosts line into a PublicKey object and a list of hosts the
|
|
// key would be valid for.
|
|
func KnownHostsLineToPublicKey(line string) ([]string, ssh.PublicKey, error) {
|
|
_, hostnames, keyData, _, _, err := ssh.ParseKnownHosts([]byte(line))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return hostnames, keyData, nil
|
|
}
|
|
|
|
func TokenizedDataToPublicKey(hostname string, subType string, rawKeyData string) ([]string, ssh.PublicKey, error) {
|
|
hostnames, keyData, err := KnownHostsLineToPublicKey(fmt.Sprintf("%s %s %s", hostname, subType, rawKeyData))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return hostnames, keyData, nil
|
|
}
|
|
|
|
// Returns the requested pattern with all possible square brackets escaped
|
|
func nonBracketedPattern(pattern string) string {
|
|
ret := strings.ReplaceAll(pattern, "[", `\[`)
|
|
return strings.ReplaceAll(ret, "]", `\]`)
|
|
}
|
|
|
|
// We do not use full fledged regular expression for matching the hostname.
|
|
// Instead, we use a less expensive file system glob, which should be fully
|
|
// sufficient for our use case.
|
|
func MatchHostName(hostname, pattern string) bool {
|
|
// If pattern is empty, we always return a match
|
|
if pattern == "" {
|
|
return true
|
|
}
|
|
match, err := filepath.Match(nonBracketedPattern(pattern), hostname)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return match
|
|
}
|
|
|
|
// Convenience wrapper around SSHFingerprintSHA256
|
|
func SSHFingerprintSHA256FromString(key string) string {
|
|
pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return SSHFingerprintSHA256(pubKey)
|
|
}
|
|
|
|
// base64 sha256 hash with the trailing equal sign removed
|
|
func SSHFingerprintSHA256(key ssh.PublicKey) string {
|
|
hash := sha256.Sum256(key.Marshal())
|
|
b64hash := base64.StdEncoding.EncodeToString(hash[:])
|
|
return strings.TrimRight(b64hash, "=")
|
|
}
|
|
|
|
// Remove possible port number from hostname and return just the FQDN
|
|
func ServerNameWithoutPort(serverName string) string {
|
|
return strings.Split(serverName, ":")[0]
|
|
}
|
|
|
|
// Load certificate data from a file. If the file does not exist, we do not
|
|
// consider it an error and just return empty data.
|
|
func GetCertificateForConnect(serverName string) ([]string, error) {
|
|
dataPath := GetTLSCertificateDataPath()
|
|
certPath, err := filepath.Abs(filepath.Join(dataPath, ServerNameWithoutPort(serverName)))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !strings.HasPrefix(certPath, dataPath) {
|
|
return nil, fmt.Errorf("could not get certificate for host %s", serverName)
|
|
}
|
|
certificates, err := ParseTLSCertificatesFromPath(certPath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
if len(certificates) == 0 {
|
|
return nil, errors.New("no certificates found in existing file")
|
|
}
|
|
|
|
return certificates, nil
|
|
}
|
|
|
|
// Gets the full path for a certificate bundle configured from a ConfigMap
|
|
// mount. This function makes sure that the path returned actually contain
|
|
// at least one valid certificate, and no invalid data.
|
|
func GetCertBundlePathForRepository(serverName string) (string, error) {
|
|
certPath := filepath.Join(GetTLSCertificateDataPath(), ServerNameWithoutPort(serverName))
|
|
certs, err := GetCertificateForConnect(serverName)
|
|
if err != nil {
|
|
return "", nil
|
|
}
|
|
if len(certs) == 0 {
|
|
return "", nil
|
|
}
|
|
return certPath, nil
|
|
}
|
|
|
|
// Convert a list of certificates in PEM format to a x509.CertPool object,
|
|
// usable for most golang TLS functions.
|
|
func GetCertPoolFromPEMData(pemData []string) *x509.CertPool {
|
|
certPool := x509.NewCertPool()
|
|
for _, pem := range pemData {
|
|
certPool.AppendCertsFromPEM([]byte(pem))
|
|
}
|
|
return certPool
|
|
}
|