Skip to content
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

Add List fine-grained personal access tokens with access to organization resources API #3215

Merged
merged 4 commits into from
Jul 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions github/github-accessors.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

84 changes: 84 additions & 0 deletions github/github-accessors_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 63 additions & 0 deletions github/orgs_personal_access_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,69 @@ import (
"net/http"
)

// PersonalAccessToken represents the minimal representation of an organization programmatic access grant.
//
// GitHub API docs: https://docs.github.com/en/rest/orgs/personal-access-tokens?apiVersion=2022-11-28
type PersonalAccessToken struct {
// "Unique identifier of the fine-grained personal access token.
// The `pat_id` used to get details about an approved fine-grained personal access token.
ID *int64 `json:"id"`

// Owner is the GitHub user associated with the token.
Owner *User `json:"owner"`

// RepositorySelection is the type of repository selection requested.
// Possible values are: "none", "all", "subset".
RepositorySelection *string `json:"repository_selection"`

// URL to the list of repositories the fine-grained personal access token can access.
// Only follow when `repository_selection` is `subset`.
RepositoriesURL *string `json:"repositories_url"`

// Permissions are the permissions requested, categorized by type.
Permissions *PersonalAccessTokenPermissions `json:"permissions"`

// Date and time when the fine-grained personal access token was approved to access the organization.
AccessGrantedAt *Timestamp `json:"access_granted_at"`

// Whether the associated fine-grained personal access token has expired.
TokenExpired *bool `json:"token_expired"`

// Date and time when the associated fine-grained personal access token expires.
TokenExpiresAt *Timestamp `json:"token_expires_at"`

// Date and time when the associated fine-grained personal access token was last used for authentication.
TokenLastUsedAt *Timestamp `json:"token_last_used_at"`
}

// ListFineGrainedPersonalAccessTokens lists approved fine-grained personal access tokens owned by organization members that can access organization resources.
// Only GitHub Apps can call this API, using the `Personal access tokens` organization permissions (read).
//
// GitHub API docs: https://docs.github.com/rest/orgs/personal-access-tokens#list-fine-grained-personal-access-tokens-with-access-to-organization-resources
//
//meta:operation GET /orgs/{org}/personal-access-tokens
func (s *OrganizationsService) ListFineGrainedPersonalAccessTokens(ctx context.Context, org string, opts *ListOptions) ([]*PersonalAccessToken, *Response, error) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This endpoint can take a whole bunch more options:

sort stringThe property by which to sort the results.Default: created_atValue: created_at
--
direction stringThe direction to sort the results by.Default: descCan be one of: asc, desc
owner arrayA list of owner usernames to use to filter the results.
repository stringThe name of the repository to use to filter the results.
permission stringThe permission to use to filter the results.
last_used_before stringOnly show fine-grained personal access tokens used before the given time. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
last_used_after stringOnly show fine-grained personal access tokens used after the given time. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.

sort string
The property by which to sort the results.

Default: created_at

Value: created_at

direction string
The direction to sort the results by.

Default: desc

Can be one of: asc, desc

owner array
A list of owner usernames to use to filter the results.

repository string
The name of the repository to use to filter the results.

permission string
The permission to use to filter the results.

last_used_before string
Only show fine-grained personal access tokens used before the given time. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: YYYY-MM-DDTHH:MM:SSZ.

last_used_after string
Only show fine-grained personal access tokens used after the given time. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: YYYY-MM-DDTHH:MM:SSZ.

So let's please create a new type ListFineGrainedPATOptions struct { ... ListOptions } that can take all these parameter, and make sure to add omitempty to each one of them since they are optional.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point and sorry for missing that. I added that on my latest commit.

One thing though, using the owner array as

Owner           []string `url:"owner,omitempty,comma"`

will cause the API to return 422 status code, as it expects the []owner=... format, so I had to create the helper function below.

I tried to find an example on the codebase and I found IssueListOptions, but this one seems to work as that endpoint expects the orgs/{ORG}/issues?labels=bug%2Cfeature format

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@arymoraes - I'm looking all over the GitHub v3 API documentation and can't find []owner=... anywhere.
Where did you find this? It seems incredibly strange syntax to me for a query parameter.

Copy link
Contributor Author

@arymoraes arymoraes Jul 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also found it very strange. I did not find it on the docs, but by trial and error (and by remembering seeing this kind of issue once).
If you run a CURL with:

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: {TOKEN}" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/orgs/{ORG}/personal-access-tokens?owner={username}

It will give you a 422 status code error:

{
  "message": "Invalid request.\n\nInvalid input: `\"{username}\"` is not of type `array`.",
  "documentation_url": "https://docs.github.com/rest/orgs/personal-access-tokens#list-fine-grained-personal-access-tokens-with-access-to-organization-resources",
  "status": "422"
}

However:

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer {TOKEN}" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/orgs/{ORG}/personal-access-tokens?owner[]={username}

Is valid and will indeed return you a list of tokens filtered by that owner

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, wow, that is bizarre... so I was hoping that your unit test would show how multiple owners would appear in the resulting URL, but it doesn't... do they show up as comma-separated values?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly, it gets even weirder if you want multiple owners.

personal-access-tokens?owner[]=owner1,owner2

doesn't work, it'll just return an empty array of tokens (maybe if thinks the owner name is owner1,owner2?

You have to do

personal-access-tokens?owner[]=owner1&owner[]=owner2

To be able to filter tokens from any of those two owners. This is the one that is generated with addListFineGrainedPATOptions.

I am finding this really weird, but this is the way it works even with curl, so I'm assuming this is indeed the way that GitHub API wants us to send the query param. I tried to search for others with the same question, but could not. I could take another look though.

I should probably improve the comment for addListFineGrainedPATOptions to add the multiple owners scenario, and maybe also test the URL explicitly on the unit test?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, that's amazing... thank you for the details, @arymoraes !

Maybe could you please just add a comment explaining all this weirdness would be extremely helpful for anyone else that comes across this and tries to use it. Thank you!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

I added the comments to the addListFineGrainedPATOptions helper function declaration, as well as inside addListFineGrainedPATOptions when we call addListFineGrainedPATOptions, so whoever runs into that code knows why we are doing this.

u := fmt.Sprintf("orgs/%v/personal-access-tokens", org)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}

req, err := s.client.NewRequest(http.MethodGet, u, &opts)
if err != nil {
return nil, nil, err
}

var pats []*PersonalAccessToken

resp, err := s.client.Do(ctx, req, &pats)
if err != nil {
return nil, resp, err
}

return pats, resp, nil
}

// ReviewPersonalAccessTokenRequestOptions specifies the parameters to the ReviewPersonalAccessTokenRequest method.
type ReviewPersonalAccessTokenRequestOptions struct {
Action string `json:"action"`
Expand Down
116 changes: 116 additions & 0 deletions github/orgs_personal_access_tokens_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,128 @@ package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"

"github.com/google/go-cmp/cmp"
)

func TestOrganizationsService_ListFineGrainedPersonalAccessTokens(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()

mux.HandleFunc("/orgs/o/personal-access-tokens", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"per_page": "2", "page": "2"})
fmt.Fprint(w, `
[
{
"id": 25381,
"owner": {
"login": "octocat",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": false
},
"repository_selection": "all",
"repositories_url": "https://api.github.com/organizations/652551/personal-access-tokens/25381/repositories",
"permissions": {
"organization": {
"members": "read"
},
"repository": {
"metadata": "read"
}
},
"access_granted_at": "2023-05-16T08:47:09.000-07:00",
"token_expired": false,
"token_expires_at": "2023-11-16T08:47:09.000-07:00",
"token_last_used_at": null
}
]`)
})

opts := &ListOptions{Page: 2, PerPage: 2}
ctx := context.Background()
tokens, resp, err := client.Organizations.ListFineGrainedPersonalAccessTokens(ctx, "o", opts)
if err != nil {
t.Errorf("Organizations.ListFineGrainedPersonalAccessTokens returned error: %v", err)
}

want := []*PersonalAccessToken{
{
ID: Int64(25381),
Owner: &User{
Login: String("octocat"),
ID: Int64(1),
NodeID: String("MDQ6VXNlcjE="),
AvatarURL: String("https://github.com/images/error/octocat_happy.gif"),
GravatarID: String(""),
URL: String("https://api.github.com/users/octocat"),
HTMLURL: String("https://github.com/octocat"),
FollowersURL: String("https://api.github.com/users/octocat/followers"),
FollowingURL: String("https://api.github.com/users/octocat/following{/other_user}"),
GistsURL: String("https://api.github.com/users/octocat/gists{/gist_id}"),
StarredURL: String("https://api.github.com/users/octocat/starred{/owner}{/repo}"),
SubscriptionsURL: String("https://api.github.com/users/octocat/subscriptions"),
OrganizationsURL: String("https://api.github.com/users/octocat/orgs"),
ReposURL: String("https://api.github.com/users/octocat/repos"),
EventsURL: String("https://api.github.com/users/octocat/events{/privacy}"),
ReceivedEventsURL: String("https://api.github.com/users/octocat/received_events"),
Type: String("User"),
SiteAdmin: Bool(false),
},
RepositorySelection: String("all"),
RepositoriesURL: String("https://api.github.com/organizations/652551/personal-access-tokens/25381/repositories"),
Permissions: &PersonalAccessTokenPermissions{
Org: map[string]string{"members": "read"},
Repo: map[string]string{"metadata": "read"},
},
AccessGrantedAt: &Timestamp{time.Date(2023, time.May, 16, 8, 47, 9, 0, time.FixedZone("PDT", -7*60*60))},
TokenExpired: Bool(false),
TokenExpiresAt: &Timestamp{time.Date(2023, time.November, 16, 8, 47, 9, 0, time.FixedZone("PDT", -7*60*60))},
TokenLastUsedAt: nil,
},
}
if !cmp.Equal(tokens, want) {
t.Errorf("Organizations.ListFineGrainedPersonalAccessTokens returned %+v, want %+v", tokens, want)
}

if resp == nil {
t.Error("Organizations.ListFineGrainedPersonalAccessTokens returned nil response")
}

const methodName = "ListFineGrainedPersonalAccessTokens"
testBadOptions(t, methodName, func() (err error) {
_, _, err = client.Organizations.ListFineGrainedPersonalAccessTokens(ctx, "\n", opts)
return err
})

testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
got, resp, err := client.Organizations.ListFineGrainedPersonalAccessTokens(ctx, "o", opts)
if got != nil {
t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
}
return resp, err
})
}

func TestOrganizationsService_ReviewPersonalAccessTokenRequest(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
Expand Down
Loading