-
Notifications
You must be signed in to change notification settings - Fork 9
Implement rotation manager for root token #96
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
drewmullen
wants to merge
13
commits into
hashicorp:main
Choose a base branch
from
drewmullen:f-rotate-root
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f8552bb
initial rotate manager implementation
drewmullen b932338
added new rotate immediately command and old token cleanup working
drewmullen aecb6a4
rotation and revocation working
drewmullen cae1191
rotation tests working
drewmullen 7f96edc
implement immediate rotation
drewmullen 469dbb3
help docs
drewmullen 0b53edc
rm immediate rotation param
drewmullen 9fa5d7c
rename to rotate-root for convention
drewmullen 4e0064e
use account details to fetch token type and entity id
drewmullen f4693fe
agent suggested nits
drewmullen a7153cd
add accoutn details tests
drewmullen 9a8d3c1
reorder token saving and old token delete. use new token to delete ol…
drewmullen 01c9726
utilize testSystemView which implements DeregisterRotationJob
drewmullen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,3 +6,6 @@ bin | |
| tmp | ||
| .idea | ||
| .vscode | ||
| .DS_Store | ||
| config.json | ||
| .bin | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| // Copyright (c) HashiCorp, Inc. | ||
| // SPDX-License-Identifier: MPL-2.0 | ||
|
|
||
| package tfc | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "strings" | ||
| ) | ||
|
|
||
| // accountDetailsResponse represents the JSON response from the TFC/TFE | ||
| // account/details API endpoint. | ||
| type accountDetailsResponse struct { | ||
| Data struct { | ||
| ID string `json:"id"` | ||
| Type string `json:"type"` | ||
| Attributes struct { | ||
| Username string `json:"username"` | ||
| } `json:"attributes"` | ||
| Relationships struct { | ||
| AuthenticatedResource struct { | ||
| Data struct { | ||
| ID string `json:"id"` | ||
| Type string `json:"type"` | ||
| } `json:"data"` | ||
| } `json:"authenticated-resource"` | ||
| } `json:"relationships"` | ||
| } `json:"data"` | ||
| } | ||
|
|
||
| // resolveTokenIdentity calls the TFC/TFE account/details API to determine | ||
| // the token type (organization, team, or user) and the associated entity ID. | ||
| // | ||
| // Organization tokens have usernames starting with "api-org-". The org name | ||
| // is extracted by splitting on "-" and dropping the first two and last parts. | ||
| // | ||
| // Team tokens have usernames starting with "api-team-". The team ID is | ||
| // taken from the authenticated-resource relationship. | ||
| // | ||
| // All other tokens are treated as user tokens, using data.id directly. | ||
| func resolveTokenIdentity(ctx context.Context, address, basePath, token string) (tokenType string, id string, err error) { | ||
| url := strings.TrimRight(address, "/") + "/" + strings.Trim(basePath, "/") + "/account/details" | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "GET", url, nil) | ||
| if err != nil { | ||
| return "", "", fmt.Errorf("error creating account details request: %w", err) | ||
| } | ||
| req.Header.Set("Authorization", "Bearer "+token) | ||
| req.Header.Set("Content-Type", "application/vnd.api+json") | ||
|
|
||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return "", "", fmt.Errorf("error calling account/details: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return "", "", fmt.Errorf("account/details returned status %d", resp.StatusCode) | ||
| } | ||
|
|
||
| var details accountDetailsResponse | ||
| if err := json.NewDecoder(resp.Body).Decode(&details); err != nil { | ||
| return "", "", fmt.Errorf("error decoding account/details response: %w", err) | ||
| } | ||
|
|
||
| username := details.Data.Attributes.Username | ||
|
|
||
| if strings.HasPrefix(username, "api-org-") { | ||
| // Organization token: extract org name from username. | ||
| // Username format: "api-org-<orgname>-<random>" | ||
| // Organization names can contain "-", so we split on "-" and drop | ||
| // the first two parts ("api", "org") and the last part (random suffix). | ||
| parts := strings.Split(username, "-") | ||
| if len(parts) < 4 { | ||
| return "", "", fmt.Errorf("unexpected organization token username format: %s", username) | ||
| } | ||
| orgName := strings.Join(parts[2:len(parts)-1], "-") | ||
| return "organization", orgName, nil | ||
| } | ||
|
|
||
| if strings.HasPrefix(username, "api-team-") { | ||
| // Team token: get team ID from the authenticated-resource relationship. | ||
| teamID := details.Data.Relationships.AuthenticatedResource.Data.ID | ||
| if teamID == "" { | ||
| return "", "", fmt.Errorf("team token detected but authenticated-resource ID is missing") | ||
| } | ||
| return "team", teamID, nil | ||
| } | ||
|
|
||
| // User token: use the user ID directly. | ||
| return "user", details.Data.ID, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| // Copyright (c) HashiCorp, Inc. | ||
| // SPDX-License-Identifier: MPL-2.0 | ||
|
|
||
| package tfc | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestResolveTokenIdentity(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| responseCode int | ||
| responseBody string | ||
| wantTokenType string | ||
| wantID string | ||
| wantErrContain string | ||
| }{ | ||
| { | ||
| name: "organization token - simple name", | ||
| responseCode: http.StatusOK, | ||
| responseBody: `{ | ||
| "data": { | ||
| "id": "user-abc123", | ||
| "type": "users", | ||
| "attributes": { "username": "api-org-mullen-14JAXvyITM" }, | ||
| "relationships": {} | ||
| } | ||
| }`, | ||
| wantTokenType: "organization", | ||
| wantID: "mullen", | ||
| }, | ||
| { | ||
| name: "organization token - hyphenated name", | ||
| responseCode: http.StatusOK, | ||
| responseBody: `{ | ||
| "data": { | ||
| "id": "user-abc123", | ||
| "type": "users", | ||
| "attributes": { "username": "api-org-my-cool-org-14JAXvyITM" }, | ||
| "relationships": {} | ||
| } | ||
| }`, | ||
| wantTokenType: "organization", | ||
| wantID: "my-cool-org", | ||
| }, | ||
| { | ||
| name: "team token", | ||
| responseCode: http.StatusOK, | ||
| responseBody: `{ | ||
| "data": { | ||
| "id": "user-xyz", | ||
| "type": "users", | ||
| "attributes": { "username": "api-team-myteam-abc123" }, | ||
| "relationships": { | ||
| "authenticated-resource": { | ||
| "data": { "id": "team-RGhi7xU4NWWmp1MQ", "type": "teams" } | ||
| } | ||
| } | ||
| } | ||
| }`, | ||
| wantTokenType: "team", | ||
| wantID: "team-RGhi7xU4NWWmp1MQ", | ||
| }, | ||
| { | ||
| name: "user token", | ||
| responseCode: http.StatusOK, | ||
| responseBody: `{ | ||
| "data": { | ||
| "id": "user-V3R563qtqNzY6fA1", | ||
| "type": "users", | ||
| "attributes": { "username": "drew-mullen" }, | ||
| "relationships": {} | ||
| } | ||
| }`, | ||
| wantTokenType: "user", | ||
| wantID: "user-V3R563qtqNzY6fA1", | ||
| }, | ||
| { | ||
| name: "team token - missing relationship", | ||
| responseCode: http.StatusOK, | ||
| responseBody: `{"data":{"id":"user-x","type":"users","attributes":{"username":"api-team-foo-bar"},"relationships":{}}}`, | ||
| wantErrContain: "authenticated-resource ID is missing", | ||
| }, | ||
| { | ||
| name: "org token - username too short", | ||
| responseCode: http.StatusOK, | ||
| responseBody: `{"data":{"id":"user-x","type":"users","attributes":{"username":"api-org-x"},"relationships":{}}}`, | ||
| wantErrContain: "unexpected organization token username format", | ||
| }, | ||
| { | ||
| name: "unauthorized", | ||
| responseCode: http.StatusUnauthorized, | ||
| responseBody: `{"errors":["unauthorized"]}`, | ||
| wantErrContain: "status 401", | ||
| }, | ||
| { | ||
| name: "bad json", | ||
| responseCode: http.StatusOK, | ||
| responseBody: `not json`, | ||
| wantErrContain: "error decoding", | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| assert.Equal(t, "/api/v2/account/details", r.URL.Path) | ||
| assert.Equal(t, "Bearer test-token", r.Header.Get("Authorization")) | ||
| w.WriteHeader(tt.responseCode) | ||
| fmt.Fprint(w, tt.responseBody) | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| tokenType, id, err := resolveTokenIdentity( | ||
| context.Background(), | ||
| srv.URL, | ||
| "/api/v2/", | ||
| "test-token", | ||
| ) | ||
|
|
||
| if tt.wantErrContain != "" { | ||
| require.Error(t, err) | ||
| assert.Contains(t, err.Error(), tt.wantErrContain) | ||
| return | ||
| } | ||
|
|
||
| require.NoError(t, err) | ||
| assert.Equal(t, tt.wantTokenType, tokenType) | ||
| assert.Equal(t, tt.wantID, id) | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
because AuthToken may not come from older versions of tfe the
omitemptymay not work here. may have to rework the struct definition