Skip to content

Commit ff90bbb

Browse files
committed
Send X-Organization-ID so cluster register uses the provider tenant.
OAuth binds to the home (often client) org, which made ListAgents return 403. --organization-id and NR_ORGANIZATION_ID now set the header; register also selects a provider org when the flag is omitted.
1 parent b1bf622 commit ff90bbb

10 files changed

Lines changed: 338 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
## [1.0.1] - 2026-08-27
11+
12+
### Added
13+
14+
- `--organization-id` / `NR_ORGANIZATION_ID` sends `X-Organization-ID` so OAuth logins hit the provider tenant, not the default client org. `nr cluster register` lists provider orgs and selects when the flag is omitted.
15+
16+
## [1.0.0]
17+
1018
### Added
1119

1220
- `nr` CLI for provider authentication, agents, service accounts, and cluster registration

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,14 @@ nr cluster register \
5252
--name edge-ams-01 \
5353
--agent-ip 203.0.113.10 \
5454
--gateway-region AMS01 \
55-
--hypervisor-driver proxmox
55+
--hypervisor-driver proxmox \
56+
--organization-id <provider-org-uuid>
5657
```
5758

5859
Supported `--hypervisor-driver` values: `proxmox` (default), `virtfusion`, `solusvm`.
5960

61+
`--organization-id` is the provider organization UUID. The UI copies it into the command. OAuth login otherwise uses your default (often client) org, and listing agents is denied. You can also `export NR_ORGANIZATION_ID=...`.
62+
6063
The CLI prompts for hypervisor credentials unless you pass an instances file:
6164

6265
| Driver | Flag |

‎docs/TROUBLESHOOTING.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ Login succeeded; the provider organization is not marketplace-approved yet. Iden
3131
- Use a dedicated Ubuntu 22.04+ VM with free ports including `6443`.
3232
- Use `--skip-prechecks` only when you understand the risk.
3333

34+
**`You are not allowed to perform this action.` on register**
35+
36+
OAuth sessions bind to the user's home organization, which may be a client org. Pass the provider org UUID:
37+
38+
```bash
39+
nr cluster register --organization-id <provider-org-uuid> ...
40+
```
41+
42+
The UI **Install with NR CLI** command includes this flag. Also accepted: `NR_ORGANIZATION_ID`.
43+
3444
**Resume after failure**
3545

3646
```bash

‎internal/api/client.go‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,20 @@ type TokenRefreshFunc func(ctx context.Context) (string, error)
2727
// refreshWaitTimeout bounds how long a request waits for another goroutine's token refresh.
2828
const refreshWaitTimeout = 30 * time.Second
2929

30+
// OrganizationIDHeader is the gateway tenant header. OAuth sessions bind to the
31+
// user's home org (often a client org); provider APIs require this header.
32+
const OrganizationIDHeader = "X-Organization-ID"
33+
3034
// Client is the API client wrapper for the platform API
3135
// It wraps the generated oapi-codegen client with token authentication, retry logic, and error handling
3236
type Client struct {
33-
generated *generated.Client
34-
config *Config
35-
tokenMu sync.RWMutex // guards token; request editors read it per request
36-
token string
37-
refreshFunc TokenRefreshFunc
38-
refreshMutex chan struct{} // Mutex to prevent concurrent refresh attempts
37+
generated *generated.Client
38+
config *Config
39+
tokenMu sync.RWMutex // guards token and organizationID; request editors read them per request
40+
token string
41+
organizationID string
42+
refreshFunc TokenRefreshFunc
43+
refreshMutex chan struct{} // Mutex to prevent concurrent refresh attempts
3944
}
4045

4146
// Config holds API client configuration
@@ -99,12 +104,29 @@ func (c *Client) SetToken(token string) {
99104
if current := c.GetToken(); current != "" {
100105
req.Header.Set("Authorization", "Bearer "+current)
101106
}
107+
if orgID := c.GetOrganizationID(); orgID != "" {
108+
req.Header.Set(OrganizationIDHeader, orgID)
109+
}
102110
return nil
103111
},
104112
}
105113
}
106114
}
107115

116+
// SetOrganizationID sets the tenant sent as X-Organization-ID on every request.
117+
func (c *Client) SetOrganizationID(id string) {
118+
c.tokenMu.Lock()
119+
c.organizationID = strings.TrimSpace(id)
120+
c.tokenMu.Unlock()
121+
}
122+
123+
// GetOrganizationID returns the tenant UUID sent as X-Organization-ID, if any.
124+
func (c *Client) GetOrganizationID() string {
125+
c.tokenMu.RLock()
126+
defer c.tokenMu.RUnlock()
127+
return c.organizationID
128+
}
129+
108130
// SetTokenRefreshFunc sets the function to call when token needs to be refreshed
109131
func (c *Client) SetTokenRefreshFunc(fn TokenRefreshFunc) {
110132
c.refreshFunc = fn

‎internal/api/client_org_test.go‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package api
2+
3+
import (
4+
"context"
5+
"net/http"
6+
"testing"
7+
)
8+
9+
func TestSetOrganizationIDSetsHeader(t *testing.T) {
10+
c, err := NewClient(&Config{BaseURL: "https://example.invalid"})
11+
if err != nil {
12+
t.Fatal(err)
13+
}
14+
c.SetToken("tok")
15+
c.SetOrganizationID("526ad533-9fef-47ee-9cd6-354c9b9e5cc5")
16+
17+
req, err := http.NewRequest(http.MethodGet, "https://example.invalid/v1/agents", nil)
18+
if err != nil {
19+
t.Fatal(err)
20+
}
21+
for _, editor := range c.GetGeneratedClient().RequestEditors {
22+
if err := editor(context.Background(), req); err != nil {
23+
t.Fatal(err)
24+
}
25+
}
26+
if got := req.Header.Get("Authorization"); got != "Bearer tok" {
27+
t.Fatalf("Authorization=%q", got)
28+
}
29+
if got := req.Header.Get(OrganizationIDHeader); got != "526ad533-9fef-47ee-9cd6-354c9b9e5cc5" {
30+
t.Fatalf("%s=%q", OrganizationIDHeader, got)
31+
}
32+
33+
c.SetOrganizationID("")
34+
req, err = http.NewRequest(http.MethodGet, "https://example.invalid/v1/agents", nil)
35+
if err != nil {
36+
t.Fatal(err)
37+
}
38+
for _, editor := range c.GetGeneratedClient().RequestEditors {
39+
if err := editor(context.Background(), req); err != nil {
40+
t.Fatal(err)
41+
}
42+
}
43+
if req.Header.Get(OrganizationIDHeader) != "" {
44+
t.Fatalf("empty org id should omit %s, got %q", OrganizationIDHeader, req.Header.Get(OrganizationIDHeader))
45+
}
46+
}

‎internal/cli/agent.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,13 @@ func getAuthenticatedAPIClient(cmd *cobra.Command, opts ...apiClientOption) (*ap
175175
// Set authentication token
176176
apiClient.SetToken(tokenInfo.Token)
177177

178+
if orgID := organizationIDFromCmd(cmd); orgID != "" {
179+
if !uuidPattern.MatchString(orgID) {
180+
return nil, UsageErrorf("--organization-id must be a UUID")
181+
}
182+
apiClient.SetOrganizationID(orgID)
183+
}
184+
178185
// Set up automatic token refresh on 401 (only for OAuth tokens)
179186
if tokenInfo.IsOAuthToken {
180187
apiClient.SetTokenRefreshFunc(func(ctx context.Context) (string, error) {

‎internal/cli/cluster.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@ func runClusterRegister(cmd *cobra.Command, args []string) error {
8585
return err
8686
}
8787

88+
yes, _ := cmd.Flags().GetBool("yes")
89+
if err := ensureProviderOrganization(ctx, apiClient, yes); err != nil {
90+
return err
91+
}
92+
8893
// Get config directory
8994
configDir, _ := cmd.Flags().GetString("config-dir")
9095
if configDir == "" {
@@ -106,7 +111,6 @@ func runClusterRegister(cmd *cobra.Command, args []string) error {
106111
description, _ := cmd.Flags().GetString("description")
107112
resume, _ := cmd.Flags().GetBool("resume")
108113
force, _ := cmd.Flags().GetBool("force")
109-
yes, _ := cmd.Flags().GetBool("yes")
110114
skipPrechecks, _ := cmd.Flags().GetBool("skip-prechecks")
111115
dryRun, _ := cmd.Flags().GetBool("dry-run")
112116
offline, _ := cmd.Flags().GetBool("offline")

‎internal/cli/cluster_org.go‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
package cli
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"io"
8+
"net/http"
9+
"os"
10+
"strconv"
11+
"strings"
12+
13+
"github.com/spf13/cobra"
14+
15+
"github.com/noderings/cli/internal/api"
16+
generated "github.com/noderings/cli/internal/api/generated"
17+
)
18+
19+
type providerOrg struct {
20+
id string
21+
name string
22+
}
23+
24+
func organizationIDFromCmd(cmd *cobra.Command) string {
25+
if cmd != nil {
26+
if f := cmd.Flag("organization-id"); f != nil {
27+
if v := strings.TrimSpace(f.Value.String()); v != "" {
28+
return v
29+
}
30+
}
31+
}
32+
for _, key := range []string{"NR_ORGANIZATION_ID", "NODERINGS_ORGANIZATION_ID"} {
33+
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
34+
return v
35+
}
36+
}
37+
return ""
38+
}
39+
40+
// ensureProviderOrganization sets X-Organization-ID so provider APIs (ListAgents,
41+
// CreateAgent) run against the provider tenant instead of the OAuth home org.
42+
func ensureProviderOrganization(ctx context.Context, client *api.Client, yes bool) error {
43+
if client == nil {
44+
return nil
45+
}
46+
if id := strings.TrimSpace(client.GetOrganizationID()); id != "" {
47+
return nil
48+
}
49+
50+
orgs, err := listProviderOrganizations(ctx, client)
51+
if err != nil {
52+
return fmt.Errorf("list organizations: %w\nPass --organization-id from the UI install command", err)
53+
}
54+
id, err := chooseProviderOrganization(orgs, yes)
55+
if err != nil {
56+
return err
57+
}
58+
client.SetOrganizationID(id)
59+
fmt.Fprintf(os.Stderr, "Using provider organization %s (%s)\n", orgNameByID(orgs, id), id)
60+
return nil
61+
}
62+
63+
func listProviderOrganizations(ctx context.Context, client *api.Client) ([]providerOrg, error) {
64+
pageSize := int32(-1)
65+
resp, err := client.DoWithAutoRefresh(ctx, 3, func() (*http.Response, error) {
66+
return client.GetGeneratedClient().OrganizationServiceListOrganizations(ctx,
67+
&generated.OrganizationServiceListOrganizationsParams{PageSize: &pageSize})
68+
})
69+
if err != nil {
70+
return nil, err
71+
}
72+
defer func() { _ = resp.Body.Close() }()
73+
if resp.StatusCode >= 400 {
74+
return nil, api.ParseError(resp)
75+
}
76+
body, err := io.ReadAll(resp.Body)
77+
if err != nil {
78+
return nil, err
79+
}
80+
return providerOrgsFromListJSON(body), nil
81+
}
82+
83+
func providerOrgsFromListJSON(body []byte) []providerOrg {
84+
var list generated.V1ListOrganizationsResponse
85+
if err := json.Unmarshal(body, &list); err != nil || list.Organizations == nil {
86+
return nil
87+
}
88+
out := make([]providerOrg, 0, len(*list.Organizations))
89+
for _, org := range *list.Organizations {
90+
if org.Type == nil || *org.Type != generated.ORGANIZATIONTYPEPROVIDER {
91+
continue
92+
}
93+
id := ""
94+
if org.Id != nil {
95+
id = strings.TrimSpace(*org.Id)
96+
}
97+
if id == "" {
98+
continue
99+
}
100+
name := id
101+
if org.Name != nil && strings.TrimSpace(*org.Name) != "" {
102+
name = strings.TrimSpace(*org.Name)
103+
}
104+
out = append(out, providerOrg{id: id, name: name})
105+
}
106+
return out
107+
}
108+
109+
func chooseProviderOrganization(orgs []providerOrg, yes bool) (string, error) {
110+
if len(orgs) == 0 {
111+
return "", fmt.Errorf("no provider organization found for this account. Pass --organization-id from the UI install command")
112+
}
113+
if len(orgs) == 1 && (yes || !isStdinTerminal()) {
114+
return orgs[0].id, nil
115+
}
116+
if !isStdinTerminal() {
117+
return "", fmt.Errorf("pass --organization-id <uuid> (provider organization). The UI install command includes this flag")
118+
}
119+
120+
fmt.Fprintln(os.Stderr, "Provider organizations:")
121+
for i, org := range orgs {
122+
fmt.Fprintf(os.Stderr, " %d) %s (%s)\n", i+1, org.name, org.id)
123+
}
124+
raw, err := promptString("Select a provider organization", "1")
125+
if err != nil {
126+
return "", err
127+
}
128+
n, err := strconv.Atoi(strings.TrimSpace(raw))
129+
if err != nil || n < 1 || n > len(orgs) {
130+
return "", fmt.Errorf("invalid selection %q (enter 1-%d)", raw, len(orgs))
131+
}
132+
return orgs[n-1].id, nil
133+
}
134+
135+
func orgNameByID(orgs []providerOrg, id string) string {
136+
for _, org := range orgs {
137+
if org.id == id {
138+
return org.name
139+
}
140+
}
141+
return id
142+
}

0 commit comments

Comments
 (0)