| 1 |
package google |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"net/http" |
| 10 |
"net/url" |
| 11 |
"strings" |
| 12 |
|
| 13 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/idtoken" |
| 14 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/types" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
// Successful API responses are limited to 1 MiB. |
| 19 |
maxResponseBodySize = 1 << 20 |
| 20 |
// Error responses are retained only as a 4 KiB diagnostic excerpt. |
| 21 |
maxErrorResponseBodySize = 4 << 10 |
| 22 |
) |
| 23 |
|
| 24 |
//nolint:tagliatelle // The API response is a JSON object with a dynamic structure. |
| 25 |
type groupMembershipPage struct { |
| 26 |
NextPageToken string `json:"nextPageToken"` |
| 27 |
Memberships []struct { |
| 28 |
Name string `json:"name"` |
| 29 |
} `json:"memberships"` |
| 30 |
} |
| 31 |
|
| 32 |
//nolint:tagliatelle // hasMembership matches the Google Cloud Identity API response field name. |
| 33 |
type checkTransitiveMembershipResponse struct { |
| 34 |
HasMembership bool `json:"hasMembership"` |
| 35 |
} |
| 36 |
|
| 37 |
type apiError struct { |
| 38 |
Error struct { |
| 39 |
Message string `json:"message"` |
| 40 |
} `json:"error"` |
| 41 |
} |
| 42 |
|
| 43 |
// checkGroupMembership fetches the groups from a user using the Google Identity API. |
| 44 |
func (p Provider) checkGroupMembership(ctx context.Context, groupID string, userInfo types.UserInfo, tokens *idtoken.IDToken) (bool, error) { |
| 45 |
// https://cloud.google.com/identity/docs/reference/rest/v1beta1/groups.memberships/searchDirectGroups |
| 46 |
apiURL := &url.URL{ |
| 47 |
Scheme: "https", |
| 48 |
Host: "cloudidentity.googleapis.com", |
| 49 |
Path: fmt.Sprintf("/v1/groups/%s/memberships", groupID), |
| 50 |
} |
| 51 |
|
| 52 |
var ( |
| 53 |
result groupMembershipPage |
| 54 |
err error |
| 55 |
) |
| 56 |
|
| 57 |
for { |
| 58 |
if err = get[groupMembershipPage](ctx, p.httpClient, tokens.AccessToken, apiURL, &result); err != nil { |
| 59 |
return false, err |
| 60 |
} |
| 61 |
|
| 62 |
for _, membership := range result.Memberships { |
| 63 |
if fmt.Sprintf("groups/%s/memberships/%s", groupID, userInfo.Subject) == membership.Name { |
| 64 |
return true, nil |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
if result.NextPageToken == "" { |
| 69 |
break |
| 70 |
} |
| 71 |
|
| 72 |
apiURL.RawQuery = "pageToken=" + result.NextPageToken |
| 73 |
} |
| 74 |
|
| 75 |
return false, nil |
| 76 |
} |
| 77 |
|
| 78 |
// checkTransitiveGroupMembership uses the Cloud Identity API to determine whether the user is a |
| 79 |
// transitive (direct or nested) member of the given group. |
| 80 |
// https://cloud.google.com/identity/docs/reference/rest/v1/groups.memberships/checkTransitiveMembership |
| 81 |
func (p Provider) checkTransitiveGroupMembership(ctx context.Context, groupID string, userInfo types.UserInfo, tokens *idtoken.IDToken) (bool, error) { |
| 82 |
memberKey := userInfo.Email |
| 83 |
if memberKey == "" { |
| 84 |
memberKey = userInfo.Subject |
| 85 |
} |
| 86 |
|
| 87 |
query := url.Values{} |
| 88 |
query.Set("query", fmt.Sprintf("member_key_id == '%s'", memberKey)) |
| 89 |
|
| 90 |
apiURL := &url.URL{ |
| 91 |
Scheme: "https", |
| 92 |
Host: "cloudidentity.googleapis.com", |
| 93 |
Path: fmt.Sprintf("/v1/groups/%s/memberships:checkTransitiveMembership", groupID), |
| 94 |
RawQuery: query.Encode(), |
| 95 |
} |
| 96 |
|
| 97 |
var result checkTransitiveMembershipResponse |
| 98 |
|
| 99 |
if err := get[checkTransitiveMembershipResponse](ctx, p.httpClient, tokens.AccessToken, apiURL, &result); err != nil { |
| 100 |
return false, err |
| 101 |
} |
| 102 |
|
| 103 |
return result.HasMembership, nil |
| 104 |
} |
| 105 |
|
| 106 |
// get calls the Google API and decodes the response into the data struct. |
| 107 |
func get[T any](ctx context.Context, httpClient *http.Client, accessToken string, apiURL *url.URL, data *T) error { |
| 108 |
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL.String(), nil) |
| 109 |
if err != nil { |
| 110 |
return fmt.Errorf("error creating request context with URL %s: %w", apiURL, err) |
| 111 |
} |
| 112 |
|
| 113 |
req.Header.Add("Authorization", "Bearer "+accessToken) |
| 114 |
req.Header.Add("Accept", "application/json") |
| 115 |
|
| 116 |
resp, err := httpClient.Do(req) |
| 117 |
if err != nil { |
| 118 |
return fmt.Errorf("error calling Google API %s: %w", apiURL, err) |
| 119 |
} |
| 120 |
|
| 121 |
defer resp.Body.Close() |
| 122 |
|
| 123 |
bodyLimit := maxResponseBodySize |
| 124 |
if resp.StatusCode != http.StatusOK { |
| 125 |
bodyLimit = maxErrorResponseBodySize |
| 126 |
} |
| 127 |
|
| 128 |
respBody, truncated, err := readResponseBody(resp.Body, bodyLimit) |
| 129 |
if err != nil { |
| 130 |
return fmt.Errorf("unable to read body from Google API %s: http status code: %d; error: %w", apiURL, resp.StatusCode, err) |
| 131 |
} |
| 132 |
|
| 133 |
if resp.StatusCode != http.StatusOK { |
| 134 |
return handleErrorResponse(apiURL, resp.StatusCode, respBody, truncated, data) |
| 135 |
} |
| 136 |
|
| 137 |
if truncated { |
| 138 |
return fmt.Errorf("response body from Google API %s exceeds the %d byte limit", apiURL, maxResponseBodySize) |
| 139 |
} |
| 140 |
|
| 141 |
if err = json.Unmarshal(respBody, data); err != nil { |
| 142 |
return fmt.Errorf("unable to decode JSON from Google API %s: '%s': %w", apiURL, respBody, err) |
| 143 |
} |
| 144 |
|
| 145 |
return nil |
| 146 |
} |
| 147 |
|
| 148 |
func handleErrorResponse[T any](apiURL *url.URL, statusCode int, responseBody []byte, truncated bool, data *T) error { |
| 149 |
var apiErr apiError |
| 150 |
|
| 151 |
if bytes.HasPrefix(responseBody, []byte("{")) { |
| 152 |
_ = json.Unmarshal(responseBody, &apiErr) |
| 153 |
} |
| 154 |
|
| 155 |
if strings.HasPrefix(apiErr.Error.Message, "Error(4001):") { |
| 156 |
// This error indicates that the current user does not have the required permissions to access the group. |
| 157 |
// Clear the data by setting it to zero value |
| 158 |
var zero T |
| 159 |
|
| 160 |
*data = zero |
| 161 |
|
| 162 |
return nil |
| 163 |
} |
| 164 |
|
| 165 |
message := apiErr.Error.Message |
| 166 |
if message == "" { |
| 167 |
message = string(responseBody) |
| 168 |
} |
| 169 |
|
| 170 |
if truncated { |
| 171 |
message += " [truncated]" |
| 172 |
} |
| 173 |
|
| 174 |
return fmt.Errorf("error from Google API %s: http status code: %d; message: %s", apiURL, statusCode, message) |
| 175 |
} |
| 176 |
|
| 177 |
func readResponseBody(body io.Reader, limit int) ([]byte, bool, error) { |
| 178 |
responseBody, err := io.ReadAll(io.LimitReader(body, int64(limit+1))) |
| 179 |
if err != nil { |
| 180 |
return nil, false, fmt.Errorf("read limited response body: %w", err) |
| 181 |
} |
| 182 |
|
| 183 |
if len(responseBody) <= limit { |
| 184 |
return responseBody, false, nil |
| 185 |
} |
| 186 |
|
| 187 |
return responseBody[:limit], true, nil |
| 188 |
} |