אבטחת האפליקציה באמצעות כותרות חתומות

בדף הזה מוסבר איך לאבטח את האפליקציה באמצעות כותרות חתומות של רכישות מתוך האפליקציה (IAP). כשמוגדר שרת proxy לאימות זהויות (IAP), הוא משתמש באסימוני אינטרנט מסוג JSON‏ (JWT) כדי לוודא שהבקשה לאפליקציה מורשית. ההגנה הזו עוזרת להגן על האפליקציה מפני הסיכונים הבאים:

  • השבתה של רכישות מתוך האפליקציה בטעות
  • חומות אש שהוגדרו באופן שגוי
  • גישה לא מורשית מתוך הפרויקט

כדי לאבטח את האפליקציה, צריך להשתמש בכותרות חתומות לכל סוגי האפליקציות.

לחלופין, אם יש לכם אפליקציה בסביבה הרגילה של App Engine, אתם יכולים להשתמש ב-Users API.

בבדיקות תקינות של Compute Engine ו-GKE לא נכללות כותרות JWT, ו-IAP לא מעבד בדיקות תקינות. אם בדיקת התקינות מחזירה שגיאות גישה, צריך לוודא שבדיקת התקינות מוגדרת בצורה נכונה במסוף Google Cloud ושאימות הכותרת של ה-JWT מאפשר את הנתיב של בדיקת התקינות. מידע נוסף מופיע במאמר יצירת חריגה מבדיקת תקינות.

לפני שמתחילים

כדי לאבטח את האפליקציה באמצעות כותרות חתומות, תצטרכו את הדברים הבאים:

אבטחת האפליקציה באמצעות כותרות IAP

כדי לאבטח את האפליקציה באמצעות ה-JWT של הרכישה מתוך האפליקציה, צריך לאמת את הכותרת, את מטען הייעודי (payload) ואת החתימה של ה-JWT. ה-JWT נמצא בכותרת בקשת ה-HTTP‏ x-goog-iap-jwt-assertion. אם תוקף עוקף את IAP, הוא יכול לזייף את כותרות הזהות הלא חתומות של IAP,‏ x-goog-authenticated-user-{email,id}. ה-JWT של IAP מספק חלופה מאובטחת יותר.

כותרות חתומות מספקות אבטחה משנית במקרה שמישהו עוקף את IAP. כש-IAP מופעל, הוא מסיר את הכותרות x-goog-* שסופקו על ידי הלקוח כשהבקשה עוברת דרך תשתית ההגשה של IAP.

אימות כותרת ה-JWT

מוודאים שהכותרת של ה-JWT עומדת בהגבלות הבאות:

הצהרות בכותרת של JWT
alg אלגוריתם ES256
kid מזהה המפתח חייב להתאים לאחד מהמפתחות הציבוריים שמופיעים בקובץ המפתחות של IAP, שזמין בשני פורמטים שונים: https://www.gstatic.com/iap/verify/public_key ו- https://www.gstatic.com/iap/verify/public_key-jwk

מוודאים שה-JWT נחתם על ידי המפתח הפרטי שתואם לטענת kid של האסימון. קודם כל, מאחזרים את המפתח הציבורי מאחד משני מקומות:

  • https://www.gstatic.com/iap/verify/public_key. כתובת ה-URL הזו מכילה מילון JSON שממפה את ההצהרות kid לערכים של המפתח הציבורי.
  • https://www.gstatic.com/iap/verify/public_key-jwk. כתובת ה-URL הזו מכילה את המפתחות הציבוריים של IAP בפורמט JWK.

אחרי שמקבלים את המפתח הציבורי, משתמשים בספריית JWT כדי לאמת את החתימה.

שירות IAP מבצע רוטציה של המפתחות הציבוריים שלו באופן תקופתי. כדי לוודא שתמיד תוכלו לאמת את ה-JWT, כדאי לעיין במאמר בנושא אוטומציה של שמירת מפתחות ציבוריים במטמון.

אימות מטען הייעודי (payload) של ה-JWT

מוודאים שהמטען הייעודי (payload) של ה-JWT עומד באילוצים הבאים:

הצהרות במטען הייעודי (payload) של JWT
exp שעת התפוגה התאריך חייב להיות בעתיד. הזמן נמדד בשניות מאז ראשית זמן יוניקס (Unix epoch). מחכים 30 שניות עד שההטיה תתבצע. משך החיים המקסימלי של אסימון הוא 10 דקות + 2 * הטיה.
iat השעה שבה הונפק התאריך צריך להיות בעבר. הזמן נמדד בשניות מאז ראשית זמן יוניקס (Unix epoch). מחכים 30 שניות עד שההטיה תתבצע.
aud קהל הערך חייב להיות מחרוזת עם הערכים הבאים:
  • ‫App Engine: /projects/PROJECT_NUMBER/apps/PROJECT_ID
  • ‫Compute Engine ו-GKE: /projects/PROJECT_NUMBER/global/backendServices/SERVICE_ID
  • Cloud Run: /projects/PROJECT_NUMBER/locations/REGION/services/SERVICE_NAME
iss מנפיק חייב להיות https://cloud.google.com/iap.
hd הדומיין של החשבון אם חשבון שייך לדומיין מארח, הטענה hd מסופקת כדי להבדיל בין הדומיין שהחשבון משויך אליו.
google תלונה של Google אם אחת או יותר מרמות הגישה חלות על הבקשה, השמות שלהן מאוחסנים באובייקט ה-JSON של התביעה google, במפתח access_levels, כמערך של מחרוזות.

כשמציינים מדיניות מכשירים ולארגון יש גישה לנתוני המכשיר, גם DeviceId נשמר באובייקט JSON. שימו לב: יכול להיות שלבקשה שנשלחת לארגון אחר לא תהיה הרשאה לצפייה בנתוני המכשיר.

כדי לקבל את הערכים של המחרוזת aud שצוינה למעלה, אפשר להיכנס למסוףGoogle Cloud או להשתמש בכלי שורת הפקודה של Google Cloud.

כדי לקבל ערכי מחרוזת של aud מהקונסולה, עוברים אל ההגדרות של שרת proxy לאימות זהויות בפרויקט, לוחצים על עוד לצד משאב איזון העומסים, ואז בוחרים באפשרות קהל JWT של כותרת חתומה. Google Cloud בתיבת הדו-שיח Signed Header JWT שמופיעה, מוצגת טענת aud של המשאב שנבחר.

אם רוצים להשתמש ב-CLI של gcloud, כלי שורת הפקודה של gcloud, כדי לקבל את ערכי המחרוזת aud, צריך לדעת את מזהה הפרויקט. אפשר למצוא את מזהה הפרויקט בכרטיס Project info בGoogle Cloud מסוף, ואז להריץ את הפקודות שצוינו לכל ערך.

מספר הפרויקט

כדי לקבל את מספר הפרויקט באמצעות כלי שורת הפקודה של Google Cloud, מריצים את הפקודה הבאה:

gcloud projects describe PROJECT_ID

הפלט של הפקודה אמור להיראות כך:

createTime: '2016-10-13T16:44:28.170Z'
lifecycleState: ACTIVE
name: project_name
parent:
  id: '433637338589'
  type: organization
projectId: PROJECT_ID
projectNumber: 'PROJECT_NUMBER'

מזהה שירות

כדי לקבל את מזהה השירות באמצעות כלי שורת הפקודה של Google Cloud, מריצים את הפקודה הבאה:

gcloud compute backend-services describe SERVICE_NAME --project=PROJECT_ID --global

הפלט של הפקודה אמור להיראות כך:

affinityCookieTtlSec: 0
backends:
- balancingMode: UTILIZATION
  capacityScaler: 1.0
  group: https://www.googleapis.com/compute/v1/projects/project_name/regions/us-central1/instanceGroups/my-group
connectionDraining:
  drainingTimeoutSec: 0
creationTimestamp: '2017-04-03T14:01:35.687-07:00'
description: ''
enableCDN: false
fingerprint: zaOnO4k56Cw=
healthChecks:
- https://www.googleapis.com/compute/v1/projects/project_name/global/httpsHealthChecks/my-hc
id: 'SERVICE_ID'
kind: compute#backendService
loadBalancingScheme: EXTERNAL
name: my-service
port: 8443
portName: https
protocol: HTTPS
selfLink: https://www.googleapis.com/compute/v1/projects/project_name/global/backendServices/my-service
sessionAffinity: NONE
timeoutSec: 3610

אחזור זהות המשתמש

אם כל האימותים הקודמים בוצעו בהצלחה, מאחזרים את זהות המשתמש. המטען הייעודי (payload) של הטוקן המזהה מכיל את פרטי המשתמש הבאים:

מטען ייעודי (payload) של טוקן ID – זהות המשתמש
sub נושא מזהה ייחודי ויציב של המשתמש. במקום זאת, צריך להשתמש בערך הזה במקום בכותרת x-goog-authenticated-user-id.
email כתובת האימייל של המשתמש כתובת האימייל של המשתמש.
  • במקום זאת, צריך להשתמש בערך הזה במקום בכותרת x-goog-authenticated-user-email.
  • בניגוד לכותרת הזו ולטענת ה-sub, הערך הזה לא כולל קידומת של מרחב שמות.

בהמשך מופיע קוד לדוגמה לאבטחת אפליקציה באמצעות כותרות חתומות של רכישות מתוך האפליקציה:

C#


using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using System;
using System.Threading;
using System.Threading.Tasks;

public class IAPTokenVerification
{
    /// <summary>
    /// Verifies a signed jwt token and returns its payload.
    /// </summary>
    /// <param name="signedJwt">The token to verify.</param>
    /// <param name="expectedAudience">The audience that the token should be meant for.
    /// Validation will fail if that's not the case.</param>
    /// <param name="cancellationToken">The cancellation token to propagate cancellation requests.</param>
    /// <returns>A task that when completed will have as its result the payload of the verified token.</returns>
    /// <exception cref="InvalidJwtException">If verification failed. The message of the exception will contain
    /// information as to why the token failed.</exception>
    public async Task<JsonWebSignature.Payload> VerifyTokenAsync(
        string signedJwt, string expectedAudience, CancellationToken cancellationToken = default)
    {
        SignedTokenVerificationOptions options = new SignedTokenVerificationOptions
        {
            // Use clock tolerance to account for possible clock differences
            // between the issuer and the verifier.
            IssuedAtClockTolerance = TimeSpan.FromMinutes(1),
            ExpiryClockTolerance = TimeSpan.FromMinutes(1),
            TrustedAudiences = { expectedAudience },
            TrustedIssuers = { "https://cloud.google.com/iap" },
            CertificatesUrl = GoogleAuthConsts.IapKeySetUrl,
        };

        return await JsonWebSignature.VerifySignedTokenAsync(signedJwt, options, cancellationToken: cancellationToken);
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/api/idtoken"
)

// validateJWTFromAppEngine validates a JWT found in the
// "x-goog-iap-jwt-assertion" header.
func validateJWTFromAppEngine(w io.Writer, iapJWT, projectNumber, projectID string) error {
	// iapJWT := "YmFzZQ==.ZW5jb2RlZA==.and0" // req.Header.Get("X-Goog-IAP-JWT-Assertion")
	// projectNumber := "123456789"
	// projectID := "your-project-id"
	ctx := context.Background()
	aud := fmt.Sprintf("/projects/%s/apps/%s", projectNumber, projectID)

	payload, err := idtoken.Validate(ctx, iapJWT, aud)
	if err != nil {
		return fmt.Errorf("idtoken.Validate: %w", err)
	}

	// payload contains the JWT claims for further inspection or validation
	fmt.Fprintf(w, "payload: %v", payload)

	return nil
}

// validateJWTFromComputeEngine validates a JWT found in the
// "x-goog-iap-jwt-assertion" header.
func validateJWTFromComputeEngine(w io.Writer, iapJWT, projectNumber, backendServiceID string) error {
	// iapJWT := "YmFzZQ==.ZW5jb2RlZA==.and0" // req.Header.Get("X-Goog-IAP-JWT-Assertion")
	// projectNumber := "123456789"
	// backendServiceID := "backend-service-id"
	ctx := context.Background()
	aud := fmt.Sprintf("/projects/%s/global/backendServices/%s", projectNumber, backendServiceID)

	payload, err := idtoken.Validate(ctx, iapJWT, aud)
	if err != nil {
		return fmt.Errorf("idtoken.Validate: %w", err)
	}

	// payload contains the JWT claims for further inspection or validation
	fmt.Fprintf(w, "payload: %v", payload)

	return nil
}

Java


import com.google.api.client.http.HttpRequest;
import com.google.api.client.json.webtoken.JsonWebToken;
import com.google.auth.oauth2.TokenVerifier;

/** Verify IAP authorization JWT token in incoming request. */
public class VerifyIapRequestHeader {

  private static final String IAP_ISSUER_URL = "https://cloud.google.com/iap";

  // Verify jwt tokens addressed to IAP protected resources on App Engine.
  // The project *number* for your Google Cloud project via 'gcloud projects describe $PROJECT_ID'
  // The project *number* can also be retrieved from the Project Info card in Cloud Console.
  // projectId is The project *ID* for your Google Cloud Project.
  boolean verifyJwtForAppEngine(HttpRequest request, long projectNumber, String projectId)
      throws Exception {
    // Check for iap jwt header in incoming request
    String jwt = request.getHeaders().getFirstHeaderStringValue("x-goog-iap-jwt-assertion");
    if (jwt == null) {
      return false;
    }
    return verifyJwt(
        jwt,
        String.format("/projects/%s/apps/%s", Long.toUnsignedString(projectNumber), projectId));
  }

  boolean verifyJwtForComputeEngine(HttpRequest request, long projectNumber, long backendServiceId)
      throws Exception {
    // Check for iap jwt header in incoming request
    String jwtToken = request.getHeaders().getFirstHeaderStringValue("x-goog-iap-jwt-assertion");
    if (jwtToken == null) {
      return false;
    }
    return verifyJwt(
        jwtToken,
        String.format(
            "/projects/%s/global/backendServices/%s",
            Long.toUnsignedString(projectNumber), Long.toUnsignedString(backendServiceId)));
  }

  private boolean verifyJwt(String jwtToken, String expectedAudience) {
    TokenVerifier tokenVerifier =
        TokenVerifier.newBuilder().setAudience(expectedAudience).setIssuer(IAP_ISSUER_URL).build();
    try {
      JsonWebToken jsonWebToken = tokenVerifier.verify(jwtToken);

      // Verify that the token contain subject and email claims
      JsonWebToken.Payload payload = jsonWebToken.getPayload();
      return payload.getSubject() != null && payload.get("email") != null;
    } catch (TokenVerifier.VerificationException e) {
      System.out.println(e.getMessage());
      return false;
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const iapJwt = 'SOME_ID_TOKEN'; // JWT from the "x-goog-iap-jwt-assertion" header

let expectedAudience = null;
if (projectNumber && projectId) {
  // Expected Audience for App Engine.
  expectedAudience = `/projects/${projectNumber}/apps/${projectId}`;
} else if (projectNumber && backendServiceId) {
  // Expected Audience for Compute Engine
  expectedAudience = `/projects/${projectNumber}/global/backendServices/${backendServiceId}`;
}

const oAuth2Client = new OAuth2Client();

async function verify() {
  // Verify the id_token, and access the claims.
  const response = await oAuth2Client.getIapPublicKeys();
  const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync(
    iapJwt,
    response.pubkeys,
    expectedAudience,
    ['https://cloud.google.com/iap'],
  );
  // Print out the info contained in the IAP ID token
  console.log(ticket);
}

verify().catch(console.error);

PHP

namespace Google\Cloud\Samples\Iap;

# Imports Google auth libraries for IAP validation
use Google\Auth\AccessToken;

/**
 * Validate a JWT passed to your App Engine app by Identity-Aware Proxy.
 *
 * @param string $iapJwt The contents of the X-Goog-IAP-JWT-Assertion header.
 * @param string $cloudProjectNumber The project *number* for your Google
 *     Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID',
 *     or in the Project Info card in Cloud Console.
 * @param string $cloudProjectId Your Google Cloud Project ID.
 */
function validate_jwt_from_app_engine(
    string $iapJwt,
    string $cloudProjectNumber,
    string $cloudProjectId
): void {
    $expectedAudience = sprintf(
        '/projects/%s/apps/%s',
        $cloudProjectNumber,
        $cloudProjectId
    );
    validate_jwt($iapJwt, $expectedAudience);
}

/**
 * Validate a JWT passed to your Compute / Container Engine app by Identity-Aware Proxy.
 *
 * @param string $iapJwt The contents of the X-Goog-IAP-JWT-Assertion header.
 * @param string $cloudProjectNumber The project *number* for your Google
 *     Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID',
 *     or in the Project Info card in Cloud Console.
 * @param string $backendServiceId The ID of the backend service used to access the
 *     application. See https://cloud.google.com/iap/docs/signed-headers-howto
 *     for details on how to get this value.
 */
function validate_jwt_from_compute_engine(
    string $iapJwt,
    string $cloudProjectNumber,
    string $backendServiceId
): void {
    $expectedAudience = sprintf(
        '/projects/%s/global/backendServices/%s',
        $cloudProjectNumber,
        $backendServiceId
    );
    validate_jwt($iapJwt, $expectedAudience);
}

/**
 * Validate a JWT passed to your app by Identity-Aware Proxy.
 *
 * @param string $iapJwt The contents of the X-Goog-IAP-JWT-Assertion header.
 * @param string $expectedAudience The expected audience of the JWT with the following formats:
 *     App Engine:     /projects/{PROJECT_NUMBER}/apps/{PROJECT_ID}
 *     Compute Engine: /projects/{PROJECT_NUMBER}/global/backendServices/{BACKEND_SERVICE_ID}
 */
function validate_jwt(string $iapJwt, string $expectedAudience): void
{
    // Validate the signature using the IAP cert URL.
    $token = new AccessToken();
    $jwt = $token->verify($iapJwt, [
        'certsLocation' => AccessToken::IAP_CERT_URL
    ]);

    if (!$jwt) {
        print('Failed to validate JWT: Invalid JWT');
        return;
    }

    // Validate token by checking issuer and audience fields.
    assert($jwt['iss'] == 'https://cloud.google.com/iap');
    assert($jwt['aud'] == $expectedAudience);

    print('Printing user identity information from ID token payload:');
    printf('sub: %s', $jwt['sub']);
    printf('email: %s', $jwt['email']);
}

Python

from google.auth.transport import requests
from google.oauth2 import id_token


def validate_iap_jwt(iap_jwt, expected_audience):
    """Validate an IAP JWT.

    Args:
      iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header.
      expected_audience: The Signed Header JWT audience. See
          https://cloud.google.com/iap/docs/signed-headers-howto
          for details on how to get this value.

    Returns:
      (user_id, user_email, error_str).
    """

    try:
        decoded_jwt = id_token.verify_token(
            iap_jwt,
            requests.Request(),
            audience=expected_audience,
            certs_url="https://www.gstatic.com/iap/verify/public_key",
        )
        return (decoded_jwt["sub"], decoded_jwt["email"], "")
    except Exception as e:
        return (None, None, f"**ERROR: JWT validation error {e}**")

Ruby

# iap_jwt = "The contents of the X-Goog-Iap-Jwt-Assertion header"
# project_number = "The project *number* for your Google Cloud project"
# project_id = "Your Google Cloud project ID"
# backend_service_id = "Your Compute Engine backend service ID"
require "googleauth"

audience = nil
if project_number && project_id
  # Expected audience for App Engine
  audience = "/projects/#{project_number}/apps/#{project_id}"
elsif project_number && backend_service_id
  # Expected audience for Compute Engine
  audience = "/projects/#{project_number}/global/backendServices/#{backend_service_id}"
end

# The client ID as the target audience for IAP
payload = Google::Auth::IDTokens.verify_iap iap_jwt, aud: audience

puts payload

if audience.nil?
  puts "Audience not verified! Supply a project_number and project_id to verify"
end

בדיקה של קוד האימות

אם תיכנס לאפליקציה באמצעות פרמטרים של שאילתה secure_token_test, מערכת IAP תכלול JWT לא תקין. כדאי להשתמש בזה כדי לוודא שהלוגיקה של אימות ה-JWT מטפלת בכל מקרי הכשל השונים, וכדי לראות איך האפליקציה מתנהגת כשהיא מקבלת JWT לא תקין.

יצירת חריג לבדיקת תקינות

כמו שצוין קודם, בדיקות תקינות ב-Compute Engine וב-GKE לא משתמשות בכותרות JWT, ו-IAP לא מטפל בבדיקות תקינות. תצטרכו להגדיר את בדיקת התקינות ואת האפליקציה כדי לאפשר גישה לבדיקת התקינות.

הגדרת בדיקת התקינות

אם עדיין לא הגדרתם נתיב לבדיקת התקינות, אתם יכולים להשתמש במסוףGoogle Cloud כדי להגדיר נתיב לא רגיש לבדיקת התקינות. חשוב לוודא שאף משאב אחר לא משתף את הנתיב הזה.

  1. נכנסים לדף Health checks במסוף Google Cloud .
    מעבר לדף Health checks
  2. לוחצים על בדיקת התקינות שבה אתם משתמשים לאפליקציה, ואז לוחצים על עריכה.
  3. בקטע נתיב הבקשה מוסיפים שם נתיב לא רגיש. ההגדרה הזו מציינת את נתיב כתובת ה-URL ש Google Cloud משתמש בו כששולח בקשות לבדיקת תקינות. אם לא מציינים כתובת, הבקשה לבדיקת תקינות נשלחת אל /.
  4. לוחצים על Save.

הגדרת אימות ה-JWT

בקוד שקורא לשגרת האימות של JWT, מוסיפים תנאי להצגת סטטוס HTTP‏ 200 עבור נתיב הבקשה של בדיקת תקינות. לדוגמה:

if HttpRequest.path_info = '/HEALTH_CHECK_REQUEST_PATH'
  return HttpResponse(status=200)
else
  VALIDATION_FUNCTION

אוטומציה של שמירת מפתחות ציבוריים במטמון

מערכת IAP מבצעת רוטציה של המפתחות הציבוריים שלה מדי פעם. כדי לוודא שתמיד תוכלו לאמת את ה-JWT של הרכישה מתוך האפליקציה, מומלץ לשמור במטמון את המפתחות כדי להימנע מאחזור שלהם מכתובת ה-URL הציבורית לכל בקשה, וגם להפוך את תהליך העדכון של המפתח ששמור במטמון לאוטומטי. הגישה הזו שימושית במיוחד לאפליקציות שפועלות בסביבה עם הגבלות על הרשת, כמו היקף של VPC Service Controls.

גבולות גזרה של VPC Service Controls יכולים למנוע גישה ישירה לכתובת ה-URL הציבורית של המפתחות. על ידי שמירת המפתחות במטמון בקטגוריה של Cloud Storage, האפליקציות יכולות לאחזר אותם ממיקום בתוך המתחם ההיקפי של VPC-SC.

ההגדרה הבאה של Terraform פורסת פונקציה ב-Cloud Run שמביאה את המפתחות הציבוריים העדכניים של IAP מ-https://www.gstatic.com/iap/verify/public_key-jwk ומאחסנת אותם בקטגוריה של Cloud Storage. משימה של Cloud Scheduler מפעילה את הפונקציה הזו כל 12 שעות כדי לוודא שהמפתחות מעודכנים.

ההגדרה הזו כוללת את הפריטים הבאים:

  • ממשקי API נדרשים מופעלים כדי להשתמש ב-Cloud Run ולאחסן ולשמור במטמון מפתחות Google Cloud
  • קטגוריה של Cloud Storage לאחסון המפתחות הציבוריים של IAP שאוחזרו
  • קטגוריה של Cloud Storage לאחסון זמני של קוד המקור של פונקציות Cloud Run
  • חשבונות שירות לפונקציות של Cloud Run ול-Cloud Scheduler עם הרשאות IAM מתאימות
  • פונקציית Python לאחזור ולאחסון מפתחות
  • משימה ב-Cloud Scheduler להפעלת הפונקציה כל 12 שעות

מבנה הספרייה

├── function_source/
│   ├── main.py
│   └── requirements.txt
├── main.tf
├── outputs.tf
├── variables.tf
└── terraform.tfvars

function_source/main.py

import functions_framework
import requests
from google.cloud import storage
import os

# Environment variables to be set in the function configuration
BUCKET_NAME = os.environ.get("BUCKET_NAME")
OBJECT_NAME = os.environ.get("OBJECT_NAME", "iap_public_keys.jwk")
IAP_KEYS_URL = "https://www.gstatic.com/iap/verify/public_key-jwk"

@functions_framework.http
def update_iap_keys(request):
    """Fetches IAP public keys from the public URL and stores them in a Cloud Storage bucket."""
    if not BUCKET_NAME:
        print("Error: BUCKET_NAME environment variable not set.")
        return "BUCKET_NAME environment variable not set.", 500

    try:
        # Fetch the keys
        response = requests.get(IAP_KEYS_URL)
        response.raise_for_status()  # Raise an exception for bad status codes
        keys_content = response.text
        print(f"Successfully fetched keys from {IAP_KEYS_URL}")

        # Store in Cloud Storage
        storage_client = storage.Client()
        bucket = storage_client.bucket(BUCKET_NAME)
        blob = bucket.blob(OBJECT_NAME)

        blob.upload_from_string(keys_content, content_type='application/json')

        print(f"Successfully wrote IAP keys to gs://{BUCKET_NAME}/{OBJECT_NAME}")
        return f"Successfully updated {OBJECT_NAME} in bucket {BUCKET_NAME}", 200

    except requests.exceptions.RequestException as e:
        print(f"Error fetching keys from {IAP_KEYS_URL}: {e}")
        return f"Error fetching keys: {e}", 500
    except Exception as e:
        print(f"Error interacting with Cloud Storage: {e}")
        return f"Error interacting with Cloud Storage: {e}", 500

מחליפים את מה שכתוב בשדות הבאים:

  • BUCKET_NAME: שם הקטגוריה של Cloud Storage
  • OBJECT_NAME: השם של האובייקט שבו רוצים לאחסן את המפתחות

function_source/requirements.txt

functions-framework==3.*
requests
google-cloud-storage

variables.tf

variable "project_id" {
  description = "The Google Cloud project ID."
  type        = string
  default     = PROJECT_ID
}

variable "region" {
  description = "The Google Cloud region."
  type        = string
  default     = "REGION"
}

variable "iap_keys_bucket_name" {
  description = "The name of the Cloud Storage bucket to store IAP keys."
  type        = string
  default     = BUCKET_NAME"
}

variable "function_source_bucket_name" {
  description = "The name of the Cloud Storage bucket to store the function source code."
  type        = string
  default     = "BUCKET_NAME_FUNCTION"
}

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • REGION: האזור שבו יופעלו המשאבים – לדוגמה, us-central1
  • BUCKET_NAME: השם של קטגוריית Cloud Storage שבה מאוחסנים מפתחות IAP
  • BUCKET_NAME_FUNCTION: השם של קטגוריית Cloud Storage שבה מאוחסן קוד המקור של פונקציות Cloud Run

main.tf

terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = ">= 4.50.0"
    }
    google-beta = {
      source  = "hashicorp/google-beta"
      version = ">= 4.50.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
}

provider "google-beta" {
  project = var.project_id
  region  = var.region
}

# Enable necessary APIs
resource "google_project_service" "services" {
  for_each = toset([
    "storage.googleapis.com",
    "cloudfunctions.googleapis.com",
    "run.googleapis.com", # Cloud Functions v2 uses Cloud Run
    "cloudscheduler.googleapis.com",
    "iamcredentials.googleapis.com",
    "cloudbuild.googleapis.com" # Needed for Cloud Functions deployment
  ])
  service            = each.key
  disable_on_destroy = false
}

# Cloud Storage Bucket to store the IAP public keys
resource "google_storage_bucket" "iap_keys_bucket" {
  name                        = var.iap_keys_bucket_name
  location                    = var.region
  uniform_bucket_level_access = true
  versioning {
    enabled = true
  }
  lifecycle {
    prevent_destroy = false # Set to true in production to prevent accidental deletion
  }
}

# Cloud Storage Bucket to store the Cloud Function source code
resource "google_storage_bucket" "function_source_bucket" {
  name                        = var.function_source_bucket_name
  location                    = var.region
  uniform_bucket_level_access = true
}

# Archive the function source code
data "archive_file" "function_source_zip" {
  type        = "zip"
  source_dir  = "${path.module}/function_source"
  output_path = "${path.module}/function_source.zip"
}

# Upload the zipped source code to the source bucket
resource "google_storage_bucket_object" "function_source_object" {
  name   = "function_source.zip"
  bucket = google_storage_bucket.function_source_bucket.name
  source = data.archive_file.function_source_zip.output_path
}

# Service Account for the Cloud Function
resource "google_service_account" "iap_key_updater_sa" {
  account_id   = "iap-key-updater"
  display_name = "IAP Key Updater Function SA"
}

# Grant the function's SA permission to write to the IAP keys bucket
resource "google_storage_bucket_iam_member" "keys_bucket_writer" {
  bucket = google_storage_bucket.iap_keys_bucket.name
  role   = "roles/storage.objectAdmin"
  member = "serviceAccount:${google_service_account.iap_key_updater_sa.email}"
}

# Cloud Function (v2)
resource "google_cloudfunctions2_function" "update_iap_keys_func" {
  provider = google-beta # CFv2 often has newer features in google-beta
  name     = "update-iap-keys-function"
  location = var.region

  build_config {
    runtime     = "python312"
    entry_point = "update_iap_keys"
    source {
      storage_source {
        bucket = google_storage_bucket.function_source_bucket.name
        object = google_storage_bucket_object.function_source_object.name
      }
    }
  }

  service_config {
    max_instance_count = 1
    available_memory   = "256M"
    timeout_seconds    = 60
    ingress_settings   = "ALLOW_ALL"
    service_account_email = google_service_account.iap_key_updater_sa.email
    environment_variables = {
      BUCKET_NAME = google_storage_bucket.iap_keys_bucket.name
      OBJECT_NAME = "iap_public_keys.jwk"
    }
  }

  depends_on = [
    google_project_service.services,
    google_storage_bucket_iam_member.keys_bucket_writer
  ]
}

# Service Account for the Cloud Scheduler job
resource "google_service_account" "iap_key_scheduler_sa" {
  account_id   = "iap-key-scheduler"
  display_name = "IAP Key Update Scheduler SA"
}

# Grant the Scheduler SA permission to invoke the Cloud Function
resource "google_cloudfunctions2_function_iam_member" "invoker" {
  provider       = google-beta
  project        = google_cloudfunctions2_function.update_iap_keys_func.project
  location       = google_cloudfunctions2_function.update_iap_keys_func.location
  cloud_function = google_cloudfunctions2_function.update_iap_keys_func.name
  role           = "roles/cloudfunctions.invoker"
  member         = "serviceAccount:${google_service_account.iap_key_scheduler_sa.email}"
}

# Cloud Scheduler Job
resource "google_cloud_scheduler_job" "iap_key_update_schedule" {
  name        = "iap-key-update-schedule"
  description = "Fetches IAP public keys and stores them in Cloud Storage every 12 hours"
  schedule    = "0 */12 * * *" # Every 12 hours
  time_zone   = "Etc/UTC"
  region      = var.region

  http_target {
    uri = google_cloudfunctions2_function.update_iap_keys_func.service_config[0].uri
    http_method = "POST"

    oidc_token {
      service_account_email = google_service_account.iap_key_scheduler_sa.email
    }
  }

  depends_on = [
    google_cloudfunctions2_function_iam_member.invoker,
    google_project_service.services
  ]
}

outputs.tf

output "iap_keys_bucket_url" {
  description = "The Cloud Storage bucket URL where IAP public keys are stored."
  value       = "gs://${google_storage_bucket.iap_keys_bucket.name}"
}

output "cloud_function_url" {
  description = "The URL of the Cloud Function endpoint that triggers key updates."
  value       = google_cloudfunctions2_function.update_iap_keys_func.service_config[0].uri
}

terraform.tfvars

יוצרים קובץ terraform.tfvars כדי לציין את מזהה הפרויקט ולהתאים אישית את שמות הקטגוריות, אם צריך:

project_id = "your-gcp-project-id"
# Optional: Customize bucket names
# iap_keys_bucket_name = "custom-iap-keys-bucket"
# function_source_bucket_name = "custom-func-src-bucket"

פריסה באמצעות Terraform

  1. שומרים את הקבצים במבנה הספרייה שמתואר למעלה.
  2. מנווטים לספרייה במסוף ומאתחלים את Terraform:
    terraform init
  3. מתכננים את השינויים:
    terraform plan
  4. מחילים את השינויים:
    terraform apply

הפעולה הזו תפרוס את התשתית. המשימה של Cloud Scheduler מפעילה את הפונקציה כל 12 שעות, מאחזרת את מפתחות ה-IAP ומאחסנת אותם ב-gs://BUCKET_NAME/iap_public_keys.jwk כברירת מחדל. האפליקציות שלכם יכולות עכשיו לאחזר את המפתחות מהמאגר הזה.

לפנות משאבים

כדי להסיר את המשאבים שנוצרו על ידי Terraform, מריצים את הפקודות הבאות:

gsutil rm -a gs://BUCKET_NAME/**

terraform destroy -auto-approve

מחליפים את BUCKET_NAME בקטגוריה של Cloud Storage שבה נמצאים המפתחות.

JWTs for external identities

אם אתם משתמשים ב-IAP עם זהויות חיצוניות, שרת IAP עדיין ינפיק JWT חתום בכל בקשה מאומתת, בדיוק כמו שהוא עושה עם זהויות של Google. עם זאת, יש כמה הבדלים.

פרטי הספק

כשמשתמשים בזהויות חיצוניות, מטען ה-JWT יכיל הצהרה בשם gcip. הטענה הזו מכילה מידע על המשתמש, כמו כתובת האימייל, כתובת ה-URL של התמונה וכל מאפיין נוסף שספציפי לספק.

הנה דוגמה ל-JWT של משתמש שהתחבר באמצעות Facebook:

"gcip": '{
  "auth_time": 1553219869,
  "email": "facebook_user@gmail.com",
  "email_verified": false,
  "firebase": {
    "identities": {
      "email": [
        "facebook_user@gmail.com"
      ],
      "facebook.com": [
        "1234567890"
      ]
    },
    "sign_in_provider": "facebook.com",
  },
  "name": "Facebook User",
  "picture: "https://graph.facebook.com/1234567890/picture",
  "sub": "gZG0yELPypZElTmAT9I55prjHg63"
}',

השדות email ו-sub

אם משתמש אומת על ידי Identity Platform, השדות email ו-sub של ה-JWT יתחילו בקידומת של מנפיק האסימון של Identity Platform ומזהה הדייר שבו נעשה שימוש (אם יש כזה). לדוגמה:

"email": "securetoken.google.com/PROJECT-ID/TENANT-ID:demo_user@gmail.com",
"sub": "securetoken.google.com/PROJECT-ID/TENANT-ID:gZG0yELPypZElTmAT9I55prjHg63"

שליטה בגישה באמצעות sign_in_attributes

מערכת IAM לא תומכת בזהויות חיצוניות, אבל אפשר להשתמש בטענות שמוטמעות בשדה sign_in_attributes כדי לשלוט בגישה. לדוגמה, נניח שמשתמש נכנס לחשבון באמצעות ספק SAML:

{
  "aud": "/projects/project_number/apps/my_project_id",
  "gcip": '{
    "auth_time": 1553219869,
    "email": "demo_user@gmail.com",
    "email_verified": true,
    "firebase": {
      "identities": {
        "email": [
          "demo_user@gmail.com"
        ],
        "saml.myProvider": [
          "demo_user@gmail.com"
        ]
      },
      "sign_in_attributes": {
        "firstname": "John",
        "group": "test group",
        "role": "admin",
        "lastname": "Doe"
      },
      "sign_in_provider": "saml.myProvider",
      "tenant": "my_tenant_id"
    },
    "sub": "gZG0yELPypZElTmAT9I55prjHg63"
  }',
  "email": "securetoken.google.com/my_project_id/my_tenant_id:demo_user@gmail.com",
  "exp": 1553220470,
  "iat": 1553219870,
  "iss": "https://cloud.google.com/iap",
  "sub": "securetoken.google.com/my_project_id/my_tenant_id:gZG0yELPypZElTmAT9I55prjHg63"
}

אפשר להוסיף לאפליקציה לוגיקה שדומה לקוד שבהמשך כדי להגביל את הגישה למשתמשים עם תפקיד תקף:

const gcipClaims = JSON.parse(decodedIapJwtClaims.gcip);
if (gcipClaims &&
    gcipClaims.firebase &&
    gcipClaims.firebase.sign_in_attributes &&
    gcipClaims.firebase.sign_in_attribute.role === 'admin') {
  // Allow access to admin restricted resource.
} else {
  // Block access.
}

אתם יכולים לגשת למאפייני משתמשים נוספים מספקי SAML ו-OIDC של Identity Platform באמצעות gcipClaims.gcip.firebase.sign_in_attributes nested claim.

מגבלות על גודל הטענות של ספק הזהויות

אחרי שמשתמש מתחבר באמצעות Identity Platform, מאפייני המשתמש הנוספים מועברים למטען הייעודי (payload) של טוקן הזהות חסר המצב של Identity Platform, שמועבר בצורה מאובטחת אל IAP. לאחר מכן, מערכת IAP תנפיק קובץ Cookie אטום משלה בלי שמירת מצב, שמכיל גם את אותן הצהרות. מערכת IAP תיצור את הכותרת של ה-JWT החתום על סמך התוכן של קובץ ה-Cookie.

כתוצאה מכך, אם סשן מתחיל עם הרבה תביעות, יכול להיות שהוא יחרוג מהגודל המקסימלי המותר של קובץ Cookie, שהוא בדרך כלל כ-4KB ברוב הדפדפנים. הפעולה הזו תגרום לכך שהכניסה לחשבון תיכשל.

מוודאים שרק הטענות הנכונות (claims) מועברות במאפייני SAML או OIDC של ספק ה-IdP. אפשרות נוספת היא להשתמש בפונקציות חסימה כדי לסנן את הטענות שלא נדרשות לבדיקת ההרשאה.

const gcipCloudFunctions = require('gcip-cloud-functions');

const authFunctions = new gcipCloudFunctions.Auth().functions();

// This function runs before any sign-in operation.
exports.beforeSignIn = authFunctions.beforeSignInHandler((user, context) => {
  if (context.credential &&
      context.credential.providerId === 'saml.my-provider') {
    // Get the original claims.
    const claims = context.credential.claims;
    // Define this function to filter out the unnecessary claims.
    claims.groups = keepNeededClaims(claims.groups);
    // Return only the needed claims. The claims will be propagated to the token
    // payload.
    return {
      sessionClaims: claims,
    };
  }
});