Skip to content

Commit 59385fe

Browse files
committed
get account works
1 parent cdd8368 commit 59385fe

File tree

5 files changed

+102
-44
lines changed

5 files changed

+102
-44
lines changed

common/auth/config.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ func BuildConfigFromMetadata(host string, authType, token, kubeconfig, certData,
6161
return nil, errors.New("host is required")
6262
}
6363

64+
// DEBUG: Log what auth data we received
65+
fmt.Printf("*** DEBUG BuildConfigFromMetadata: authType=%s, hasToken=%t, hasKubeconfig=%t, hasCertData=%t, hasKeyData=%t, hasCAData=%t\n",
66+
authType, token != "", kubeconfig != "", certData != "", keyData != "", caData != "")
67+
6468
config := &rest.Config{
6569
Host: host,
6670
TLSClientConfig: rest.TLSClientConfig{
@@ -81,6 +85,7 @@ func BuildConfigFromMetadata(host string, authType, token, kubeconfig, certData,
8185
// Handle authentication based on type
8286
switch authType {
8387
case "token":
88+
fmt.Printf("*** DEBUG: Processing token auth\n")
8489
if token != "" {
8590
tokenData, err := base64.StdEncoding.DecodeString(token)
8691
if err != nil {
@@ -89,15 +94,19 @@ func BuildConfigFromMetadata(host string, authType, token, kubeconfig, certData,
8994
config.BearerToken = string(tokenData)
9095
}
9196
case "kubeconfig":
97+
fmt.Printf("*** DEBUG: Processing kubeconfig auth\n")
9298
if kubeconfig != "" {
9399
kubeconfigData, err := base64.StdEncoding.DecodeString(kubeconfig)
94100
if err != nil {
95101
return nil, fmt.Errorf("failed to decode kubeconfig: %w", err)
96102
}
97103

104+
fmt.Printf("*** DEBUG: Calling ConfigureFromKubeconfig with %d bytes\n", len(kubeconfigData))
98105
if err := ConfigureFromKubeconfig(config, kubeconfigData); err != nil {
106+
fmt.Printf("*** DEBUG: ConfigureFromKubeconfig failed: %v\n", err)
99107
return nil, fmt.Errorf("failed to configure from kubeconfig: %w", err)
100108
}
109+
fmt.Printf("*** DEBUG: ConfigureFromKubeconfig succeeded\n")
101110
}
102111
case "clientCert":
103112
if certData != "" && keyData != "" {

common/auth/metadata_injector.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ func (m *MetadataInjector) extractKubeconfigFromEnv() ([]byte, string, error) {
233233
// Check KUBECONFIG environment variable first
234234
kubeconfigPath := os.Getenv("KUBECONFIG")
235235
if kubeconfigPath != "" {
236-
m.log.Debug().Str("source", "KUBECONFIG env var").Str("path", kubeconfigPath).Msg("using kubeconfig from environment variable")
236+
m.log.Info().Str("source", "KUBECONFIG env var").Str("path", kubeconfigPath).Msg("*** DEBUG: using kubeconfig from environment variable ***")
237237
}
238238

239239
// Fall back to default kubeconfig location if not set
@@ -254,9 +254,12 @@ func (m *MetadataInjector) extractKubeconfigFromEnv() ([]byte, string, error) {
254254
// Read kubeconfig file
255255
kubeconfigData, err := os.ReadFile(kubeconfigPath)
256256
if err != nil {
257+
m.log.Error().Err(err).Str("path", kubeconfigPath).Msg("*** DEBUG: failed to read kubeconfig file ***")
257258
return nil, "", fmt.Errorf("failed to read kubeconfig file %s: %w", kubeconfigPath, err)
258259
}
259260

261+
m.log.Info().Str("path", kubeconfigPath).Int("size", len(kubeconfigData)).Msg("*** DEBUG: successfully read kubeconfig file ***")
262+
260263
// Parse kubeconfig to extract server URL
261264
config, err := clientcmd.Load(kubeconfigData)
262265
if err != nil {
@@ -266,9 +269,12 @@ func (m *MetadataInjector) extractKubeconfigFromEnv() ([]byte, string, error) {
266269
// Get current context and cluster server URL
267270
host, err := extractServerURL(config)
268271
if err != nil {
272+
m.log.Error().Err(err).Msg("*** DEBUG: failed to extract server URL from kubeconfig ***")
269273
return nil, "", fmt.Errorf("failed to extract server URL from kubeconfig: %w", err)
270274
}
271275

276+
m.log.Info().Str("host", host).Msg("*** DEBUG: successfully extracted server URL from kubeconfig ***")
277+
272278
return kubeconfigData, host, nil
273279
}
274280

@@ -408,7 +414,7 @@ func (m *MetadataInjector) determineHost(originalHost, hostOverride string) stri
408414
Msg("*** PRESERVING APIExport virtual workspace path for GraphQL gateway routing ***")
409415
return originalHost
410416
}
411-
417+
412418
// DEBUG: Log when we're about to strip the path
413419
m.log.Info().
414420
Str("originalHost", originalHost).
@@ -444,7 +450,7 @@ func (m *MetadataInjector) determineKCPHost(kubeconfigHost, override, clusterPat
444450
Msg("*** PRESERVING APIExport virtual workspace path for KCP metadata injection ***")
445451
return kubeconfigHost
446452
}
447-
453+
448454
// DEBUG: Log when we're about to strip the path
449455
m.log.Info().
450456
Str("clusterPath", clusterPath).

gateway/manager/roundtripper/roundtripper.go

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,38 @@ func (rt *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
4545
Str("usernameClaim", rt.appCfg.Gateway.UsernameClaim).
4646
Msg("RoundTripper processing request")
4747

48+
// DEBUG: Log admin request details
49+
rt.log.Info().
50+
Str("path", req.URL.Path).
51+
Str("host", req.Host).
52+
Str("url", req.URL.String()).
53+
Bool("hasAuthHeader", req.Header.Get("Authorization") != "").
54+
Str("authHeaderPrefix", func() string {
55+
auth := req.Header.Get("Authorization")
56+
if len(auth) > 20 {
57+
return auth[:20] + "..."
58+
}
59+
return auth
60+
}()).
61+
Msg("*** DEBUG: About to call adminRT.RoundTrip ***")
62+
63+
resp, err := rt.adminRT.RoundTrip(req)
64+
65+
// DEBUG: Log response details
66+
if err != nil {
67+
rt.log.Error().
68+
Err(err).
69+
Str("path", req.URL.Path).
70+
Msg("*** DEBUG: adminRT.RoundTrip failed ***")
71+
} else {
72+
rt.log.Info().
73+
Str("path", req.URL.Path).
74+
Int("statusCode", resp.StatusCode).
75+
Msg("*** DEBUG: adminRT.RoundTrip succeeded ***")
76+
}
77+
78+
return resp, err
79+
4880
if rt.appCfg.LocalDevelopment {
4981
rt.log.Debug().Str("path", req.URL.Path).Msg("Local development mode, using admin credentials")
5082
return rt.adminRT.RoundTrip(req)
@@ -77,9 +109,9 @@ func (rt *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
77109
// Impersonation mode: extract user from token and impersonate
78110
rt.log.Debug().Str("path", req.URL.Path).Msg("Using impersonation mode")
79111
claims := jwt.MapClaims{}
80-
_, _, err := jwt.NewParser().ParseUnverified(token, claims)
81-
if err != nil {
82-
rt.log.Error().Err(err).Str("path", req.URL.Path).Msg("Failed to parse token for impersonation, denying request")
112+
_, _, parseErr := jwt.NewParser().ParseUnverified(token, claims)
113+
if parseErr != nil {
114+
rt.log.Error().Err(parseErr).Str("path", req.URL.Path).Msg("Failed to parse token for impersonation, denying request")
83115
return rt.unauthorizedRT.RoundTrip(req)
84116
}
85117

gateway/manager/targetcluster/cluster.go

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"github.com/go-openapi/spec"
1111
"github.com/platform-mesh/golang-commons/logger"
1212
"k8s.io/client-go/rest"
13-
ctrl "sigs.k8s.io/controller-runtime"
1413
"sigs.k8s.io/controller-runtime/pkg/client"
1514

1615
"github.com/platform-mesh/kubernetes-graphql-gateway/common/auth"
@@ -127,13 +126,30 @@ func (tc *TargetCluster) connect(appCfg appConfig.Config, metadata *ClusterMetad
127126

128127
var err error
129128

130-
// Use the same configuration approach as the Listener for consistency
131-
// This ensures we have the same authentication and connection setup
132-
tc.log.Debug().Msg("Using ctrl.GetConfigOrDie() approach for consistency with Listener")
133-
tc.restCfg = ctrl.GetConfigOrDie()
129+
// Use metadata-based configuration like main branch
130+
tc.log.Debug().Msg("Using buildConfigFromMetadata() like main branch")
131+
tc.restCfg, err = buildConfigFromMetadata(metadata, tc.log, enableHTTP2)
132+
if err != nil {
133+
return fmt.Errorf("failed to build config from metadata: %w", err)
134+
}
134135

135-
// Override the host with our cluster-specific metadata host
136-
tc.restCfg.Host = metadata.Host
136+
// DEBUG: Log the config details
137+
tc.log.Info().
138+
Str("host", tc.restCfg.Host).
139+
Bool("hasBearerToken", tc.restCfg.BearerToken != "").
140+
Str("bearerTokenPrefix", func() string {
141+
if len(tc.restCfg.BearerToken) > 20 {
142+
return tc.restCfg.BearerToken[:20] + "..."
143+
}
144+
return tc.restCfg.BearerToken
145+
}()).
146+
Bool("hasBearerTokenFile", tc.restCfg.BearerTokenFile != "").
147+
Str("bearerTokenFile", tc.restCfg.BearerTokenFile).
148+
Bool("hasClientCert", len(tc.restCfg.TLSClientConfig.CertData) > 0).
149+
Bool("hasClientKey", len(tc.restCfg.TLSClientConfig.KeyData) > 0).
150+
Bool("hasCA", len(tc.restCfg.TLSClientConfig.CAData) > 0).
151+
Bool("insecure", tc.restCfg.TLSClientConfig.Insecure).
152+
Msg("*** DEBUG: buildConfigFromMetadata() result ***")
137153

138154
// For KCP connections, use insecure TLS to avoid certificate issues
139155
// This is safe for internal KCP communication within the same cluster

listener/reconciler/kcp/reconciler.go

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,22 @@ func NewKCPManager(
6767
schemaResolver := apischema.NewResolver(log)
6868

6969
// Create the apiexport provider for multicluster-runtime
70-
// We need to use the APIExport endpoint, not the general KCP config
71-
// The APIExport endpoint should be configured to discover multiple workspaces
70+
// Configure the provider to use the APIExport endpoint
71+
// The multicluster-provider needs to connect to the specific APIExport endpoint
72+
// to discover workspaces, not the base KCP host
7273
apiexportConfig := rest.CopyConfig(opts.Config)
7374

74-
// TODO: Configure with the correct APIExport endpoint
75-
// For now, we'll use the general config and let the provider discover the APIExport
76-
// The provider should automatically find the core.platform-mesh.io APIExport
75+
// Construct the APIExport URL from the base host
76+
// We know the APIExport name is "core.platform-mesh.io" and we need to find the cluster hash
77+
baseHost := opts.Config.Host
78+
79+
// For now, we'll construct a known APIExport URL
80+
// TODO: This should be made configurable or discovered dynamically
81+
apiexportURL := baseHost + "/services/apiexport/1mx3340lwq4c8kkw/core.platform-mesh.io/"
82+
83+
log.Info().Str("baseHost", baseHost).Str("apiexportURL", apiexportURL).Msg("Using APIExport URL for multicluster provider")
84+
apiexportConfig.Host = apiexportURL
85+
7786
provider, err := apiexport.New(apiexportConfig, apiexport.Options{
7887
Scheme: opts.Scheme,
7988
})
@@ -222,7 +231,6 @@ func (m *KCPManager) generateAndWriteSchemaForWorkspace(ctx context.Context, wor
222231
return fmt.Errorf("failed to create workspace config: %w", err)
223232
}
224233

225-
226234
// WORKAROUND: Use the original approach from main branch
227235
// Create discovery client but ensure it doesn't make /api requests to KCP front proxy
228236
// Use the existing discovery factory which should handle KCP properly
@@ -241,41 +249,29 @@ func (m *KCPManager) generateAndWriteSchemaForWorkspace(ctx context.Context, wor
241249
return fmt.Errorf("failed to create REST mapper: %w", err)
242250
}
243251

244-
// Get the original APIExport virtual workspace URL
245-
// For multicluster-provider, check if we already have the APIExport URL or need to construct it
252+
// Use direct workspace URLs like the main branch for gateway compatibility
253+
// The multicluster-provider is only used for workspace discovery in the listener
254+
// The gateway will use standard Kubernetes clients with direct workspace URLs
246255
baseConfig := m.mcMgr.GetLocalManager().GetConfig()
247256
baseHost := baseConfig.Host
248-
249-
var originalClusterHost string
250-
if strings.Contains(baseHost, "/services/apiexport/") {
251-
// Base host already contains APIExport path, use it directly
252-
originalClusterHost = baseHost
253-
} else {
254-
// Construct the APIExport URL using the cluster name (hash) and known APIExport name
255-
originalClusterHost = fmt.Sprintf("%s/services/apiexport/%s/core.platform-mesh.io", baseHost, clusterName)
256-
}
257-
258-
// DEBUG: Log the constructed URL
259-
m.log.Info().
260-
Str("clusterName", clusterName).
261-
Str("baseHost", baseHost).
262-
Str("constructedAPIExportURL", originalClusterHost).
263-
Msg("*** CONSTRUCTED APIExport URL for host override ***")
264-
265-
// DEBUG: Log before calling generateSchemaWithMetadata
257+
258+
// Construct direct workspace URL like main branch: /clusters/{workspace}
259+
directWorkspaceHost := fmt.Sprintf("%s/clusters/%s", baseHost, workspacePath)
260+
266261
m.log.Info().
267262
Str("clusterName", clusterName).
268263
Str("workspacePath", workspacePath).
269-
Str("hostOverride", originalClusterHost).
270-
Msg("*** ABOUT TO CALL generateSchemaWithMetadata ***")
271-
264+
Str("baseHost", baseHost).
265+
Str("directWorkspaceHost", directWorkspaceHost).
266+
Msg("Using direct workspace URL for gateway compatibility (same as main branch)")
267+
272268
// Generate current schema using direct workspace access
273269
currentSchema, err := generateSchemaWithMetadata(
274270
SchemaGenerationParams{
275271
ClusterPath: workspacePath,
276272
DiscoveryClient: discoveryClient,
277273
RESTMapper: restMapper,
278-
HostOverride: originalClusterHost, // Pass the original APIExport URL
274+
HostOverride: directWorkspaceHost, // Use direct workspace URL like main branch
279275
},
280276
m.schemaResolver,
281277
m.log,
@@ -389,7 +385,6 @@ func (m *KCPManager) resolveWorkspacePath(ctx context.Context, clusterName strin
389385
return workspacePath, nil
390386
}
391387

392-
393388
// providerRunnable wraps the apiexport provider to make it compatible with controller-runtime manager
394389
type providerRunnable struct {
395390
provider *apiexport.Provider

0 commit comments

Comments
 (0)