I have an application deployed on cloud run, and I created a cloud scheduler job that calls an endpoint on this application.
I created a service account and use it for the cloud task token. Below is a screenshot of the cloud scheduler task configuration (I ensured multiple time the right service account is selected).
I have a middleware on my application to prevent unauthorized access to the endpoint (simplified version):
import (
"fmt"
"github.com/gin-gonic/gin"
"google.golang.org/api/oauth2/v2"
"net/http"
"strings"
)
func ForceCloudScheduler(c *gin.Context) {
if c.Request.UserAgent() != "Google-Cloud-Scheduler" {
c.AbortWithStatus(http.StatusForbidden)
return
}
// https://stackoverflow.com/questions/53181297/verify-http-request-from-google-cloud-scheduler
token := c.GetHeader("Authorization")
if token == "" {
c.AbortWithStatus(http.StatusForbidden)
return
}
idToken := strings.Split(token, "Bearer ")[0]
authenticator, err := oauth2.NewService(c)
if err != nil {
_ = c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("failed to acquire authenticator: %w", err))
return
}
info, err := authenticator.Tokeninfo().IdToken(idToken).Do()
if err != nil {
_ = c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("failed to retrieve token information: %w", err))
return
}
// This is the line where the job fails.
if info.Email != "agora-job-scheduler-account@agoradesecrivains.iam.gserviceaccount.com" {
c.AbortWithStatus(http.StatusForbidden)
return
}
c.Next()
}
When I run the job, the request fails with a 403. I have added some logs to check the content of the token sent by cloud scheduler. Here is the logs explorer output:
{
"audience": "107655128939031897672"
"email": "970356934135-compute@developer.gserviceaccount.com"
"expires_in": 1644
"issued_to": "107655128939031897672"
"scope": "openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
"user_id": "107655128939031897672"
"verified_email": true
}
For some reason (maybe a bug?), the email in the token payload does not match the one I set in cloud scheduler. Is this expected and can I fix that ?