func findToken()

in internal/google/adc.go [50:117]


func findToken(jsonPath string) (string, error) {
	ctx := context.Background()

	// locate application default credentials
	// read in JSON from path
	jsonData, _ := utils.ReadFile(jsonPath)
	adc, err := google.CredentialsFromJSON(ctx, jsonData)

	if err != nil {
		return "", err // can't find adc
	}

	rawToken, err := adc.TokenSource.Token()

	if err != nil {
		return "", err // found adc, but token is likely expired
	}

	// get google signing keys
	fetchedKeys, err := jwk.Fetch(ctx, googleKeys)

	if err != nil {
		return "", errors.New("unable to fetch signing keys from google")
	}

	// Assuming rawToken is of a type that has an Extra method
	// returning an interface{}
	idTokenInterface := rawToken.Extra("id_token")
	if idTokenInterface == nil {
		// Handle the error: id_token is missing or nil
		return "", errors.New("id_token is missing or nil")
	}

	// Safely assert idTokenInterface to a string
	idToken, ok := idTokenInterface.(string)
	if !ok {
		// Handle the error: idTokenInterface is not a string
		return "", errors.New("idTokenInterface is not a string")
	}

	// parse the token
	jwt.ParseWithClaims(
		idToken,
		&userClaim,
		func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return "", errors.New("unexpected token signature method")
			}

			kid, ok := token.Header["kid"].(string)
			if !ok {
				return "", errors.New("could not find key id in token header")
			}

			keys, ok := fetchedKeys.LookupKeyID(kid)
			if !ok {
				return "", errors.New(
					"no keys found matching key id in token header",
				)
			}

			var empty interface{}
			return empty, keys.Raw(&empty)
		},
	)

	return userClaim.Email, nil
}