認証情報の Cloud Storage 権限を制限する

このページでは、認証情報アクセス境界を使用して、有効期間が短い認証情報で使用できる Identity and Access Management(IAM)権限の範囲を限定する方法について説明します。

認証情報アクセス境界を使用して、サービス アカウントを表しながら、サービス アカウントよりも権限が少ない OAuth 2.0 アクセス トークンを生成できます。たとえば、あるお客様が、管理している Cloud Storage データにアクセスする必要がある場合、次のようにします。

  1. 所有するすべての Cloud Storage バケットにアクセスできるサービス アカウントを作成します。
  2. 作成したサービス アカウントに OAuth 2.0 アクセス トークンを生成します。
  3. お客様のデータを含むバケットに対するアクセスのみを許可する認証情報アクセス境界を適用します。

認証情報アクセス境界の仕組み

権限の範囲を限定するには、各リソースで使用できる権限の上限と、有効期間が短い認証情報でアクセスできるリソースを指定する認証情報アクセス境界を定義します。その後、有効期間が短い認証情報を作成し、認証情報アクセス境界を遵守する新しい認証情報に交換できます。

プリンシパルにセッションごとに異なる権限セットを割り当てる必要がある場合は、サービス アカウントを多数作成して各サービス アカウントに異なるロールセットを付与するよりも、認証情報アクセス境界を使用する方が効率的な場合があります。

認証情報アクセス境界の例

以降のセクションでは、一般的なユースケースの認証情報アクセス境界の例を示します。OAuth 2.0 アクセス トークンをスコープが限定されたトークンと交換する場合は、認証情報アクセス境界を使用します。

バケットの権限を制限する

次の例は、シンプルな認証情報アクセス境界を示しています。これは Cloud Storage バケット example-bucket に適用され、ストレージ オブジェクト閲覧者ロール(roles/storage.objectViewer)に含まれる権限の上限を設定します。

{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket"
      }
    ]
  }
}

複数のバケットの権限を制限する

次の例は、複数のバケットのルールを含む認証情報アクセス境界を示しています。

  • Cloud Storage バケット example-bucket-1: このバケットの場合、ストレージ オブジェクト閲覧者のロール(roles/storage.objectViewer)の権限のみが使用できます。
  • Cloud Storage バケット example-bucket-2: このバケットの場合、ストレージ オブジェクト作成者のロール(roles/storage.objectCreator)の権限のみが使用できます。
{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket-1"
      },
      {
        "availablePermissions": [
          "inRole:roles/storage.objectCreator"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket-2"
      }
    ]
  }
}

特定のオブジェクトの権限を制限する

IAM Conditions を使用して、プリンシパルがアクセスできる Cloud Storage オブジェクトを指定することもできます。たとえば、名前が customer-a で始まるオブジェクトにアクセスできるようにする条件を追加できます。

{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket",
        "availabilityCondition": {
          "expression" : "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a')"
        }
      }
    ]
  }
}

オブジェクトを一覧表示するときに権限を制限する

Cloud Storage バケット内のオブジェクトを一覧表示すると、オブジェクト リソースではなく、バケット リソースでメソッドが呼び出されます。そのため、条件が一覧表示のリクエストに関して評価され、その条件がリソース名を参照する場合、リソース名はバケット内のオブジェクトではなく、バケットを表します。たとえば、example-bucket のオブジェクトを一覧表示する場合、リソース名は projects/_/buckets/example-bucket になります。

この命名規則により、オブジェクトを一覧表示するときに予期しない動作が発生することがあります。たとえば、接頭辞 customer-a/invoices/ を持つ example-bucket のオブジェクトに対する表示権限を許可する認証情報アクセス境界があるとします。この認証情報アクセス境界で、次の条件を試した場合を考えます。

不完全な条件: リソース名のみを確認する条件

resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a/invoices/')

この条件はオブジェクトを読み取りには使用できますが、オブジェクトの一覧表示には使用できません。

  • プリンシパルが接頭辞 customer-a/invoices/ を持つ example-bucket のオブジェクトを読み取ろうとすると、条件は true と評価されます。
  • プリンシパルがその接頭辞を持つオブジェクトを一覧表示しようとすると、条件は false と評価されます。resource.name の値は projects/_/buckets/example-bucket となり、projects/_/buckets/example-bucket/objects/customer-a/invoices/ で始まりません。

この問題を回避するには、条件が storage.googleapis.com/objectListPrefix という名前の API 属性を確認できるよう resource.name.startsWith() を使用します。この属性には、オブジェクトのリストをフィルタするために使用された prefix パラメータの値が含まれています。これにより、prefix パラメータの値を参照する条件を記述できます。

次の例は、条件で API 属性を使用する方法を示しています。これにより、接頭辞 customer-a/invoices/ を持つ example-bucket のオブジェクトの読み取りと一覧表示ができます。

完全な条件: リソース名と、接頭辞を確認する条件

resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a/invoices/')  ||
    api.getAttribute('storage.googleapis.com/objectListPrefix', '')
                     .startsWith('customer-a/invoices/')

この条件は認証情報アクセス境界で使用できます。

{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket",
        "availabilityCondition": {
          "expression":
            "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a/invoices/') || api.getAttribute('storage.googleapis.com/objectListPrefix', '').startsWith('customer-a/invoices/')"
        }
      }
    ]
  }
}

始める前に

認証情報アクセス境界を使用する前に、次の要件を満たしていることを確認してください。

  • Cloud Storage の権限のみ範囲を限定する必要があります。他の Google Cloud サービスには必要ありません。

    追加の Google Cloud サービスの権限の範囲を限定する必要がある場合は、複数のサービス アカウントを作成し、各サービス アカウントに異なるロールを付与できます。

  • 認証には OAuth 2.0 アクセス トークンを使用できます。他のタイプの有効期間が短い認証情報は、認証情報アクセス境界をサポートしません。

また、必要な API を有効にする必要があります。

  • IAM and Security Token Service API を有効にします。

    API を有効にする

範囲が限定された有効期間の短い認証情報を作成する

範囲が限定された OAuth 2.0 アクセス トークンを作成する方法は次のとおりです。

  1. ユーザーまたはサービス アカウントに、適切な IAM ロールを付与します。
  2. ユーザーまたはサービス アカウントが使用できる権限の上限を設定する、認証情報アクセス境界を定義します。
  3. ユーザーまたはサービス アカウントの OAuth 2.0 アクセス トークンを作成します。
  4. 認証情報アクセス境界を遵守する新しい認証トークンと OAuth 2.0 アクセス トークンを交換します。

範囲が限定された新しい OAuth 2.0 アクセス トークンを使用して、Cloud Storage へのリクエストを認証できます。

IAM ロールを付与する

認証情報アクセス境界は、リソースで使用可能な権限の上限を設定します。プリンシパルから権限を削除することはできますが、プリンシパルに付与されていない権限は追加できません。

そのため、必要な権限を付与するプリンシパルにも Cloud Storage バケットまたはプロジェクトなどより高いレベルのリソースでロールを付与する必要があります。

たとえば、サービス アカウントがバケット内にオブジェクトを作成することを許可する、範囲が限定された有効期間の短い認証情報を作成するとします。

  • サービス アカウントには、少なくともストレージのオブジェクト作成者ロール(roles/storage.objectCreator)などの storage.objects.create 権限を付与する必要があります。認証情報アクセス境界には、この権限も含める必要があります。
  • また、ストレージ オブジェクト管理者ロール(roles/storage.objectAdmin)など、より多くの権限を含むロールを付与することもできます。サービス アカウントで使用できるのは、ロール付与と認証情報アクセス境界の両方に表示される権限のみです。

Cloud Storage の事前定義ロールについては、Cloud Storage のロールをご覧ください。

認証情報アクセス境界のコンポーネント

認証情報アクセス境界は、アクセス境界ルールのリストを含むオブジェクトです。各ルールには次の情報が含まれます。

  • ルールが適用されるリソース
  • そのリソースで使用できる権限の上限
  • 省略可: 権限をさらに制限する条件。条件には次のものが含まれます。
    • true または false で評価される条件式。true と評価された場合にアクセスが許可され、そうでない場合はアクセスが拒否されます。
    • 省略可: 条件を識別するためのタイトル。
    • 省略可: 条件についての詳しい説明。

認証情報アクセス境界を有効期間の短い認証情報に適用すると、認証情報は認証情報アクセス境界内のリソースにのみアクセスできます。他のリソースでは権限は使用できません。

認証情報アクセス境界には、最大 10 個のアクセス境界ルールを含めることができます。有効期間の短い認証情報ごとに適用できる認証情報アクセス境界は 1 つのみです。

JSON オブジェクトとして表現される場合、認証情報アクセス境界には次のフィールドが含まれます。

フィールド
accessBoundary

object

認証情報アクセス境界のラッパー。

accessBoundary.accessBoundaryRules[]

object

有効期間の短い認証情報に適用されるアクセス境界ルールのリスト。

accessBoundary.accessBoundaryRules[].availablePermissions[]

string

リソースに対して使用可能な権限の上限を定義するリスト。

接頭辞 inRole: の付いた各値は、IAM の事前定義ロールまたはカスタムロールの識別子です。例: inRole:roles/storage.objectViewer。こうしたロールに含まれる権限のみが使用できます。

accessBoundary.accessBoundaryRules[].availableResource

string

ルールが適用される Cloud Storage バケットの完全なリソース名。形式 //storage.googleapis.com/projects/_/buckets/bucket-name を使用します。

accessBoundary.accessBoundaryRules[].availabilityCondition

object

省略可。特定の Cloud Storage オブジェクトに対する権限の利用を制限する条件。

このフィールドは、Cloud Storage バケット内のすべてのオブジェクトではなく特定のオブジェクトに対して権限を使用可能にする場合に使用します。

accessBoundary.accessBoundaryRules[].availabilityCondition.expression

string

権限を使用できる Cloud Storage オブジェクトを指定する条件式

条件式で特定のオブジェクトを参照する方法については、resource.name 属性をご覧ください。

accessBoundary.accessBoundaryRules[].availabilityCondition.title

string

省略可。条件の目的を示す短い文字列。

accessBoundary.accessBoundaryRules[].availabilityCondition.description

string

省略可。条件の目的に関する詳細。

JSON 形式の例については、このページの認証情報アクセス境界の例をご覧ください。

OAuth 2.0 アクセス トークンの作成

範囲が限定された有効期間の短い認証情報を作成する前に、通常の OAuth 2.0 アクセス トークンを作成する必要があります。その後、通常の認証情報を範囲が限定された認証情報と交換できます。アクセス トークンを作成する際は、OAuth 2.0 スコープ https://www.googleapis.com/auth/cloud-platform を使用します。

サービス アカウントのアクセス トークンを作成するには、サーバー間の OAuth 2.0 フローを完了するか、Service Account Credentials API を使用して OAuth 2.0 アクセス トークンを生成します。

ユーザーのアクセス トークンを作成する方法については、OAuth 2.0 アクセス トークンの取得をご覧ください。OAuth 2.0 Playground を使用して、ご自分の Google アカウントのアクセス トークンを作成することもできます。

OAuth 2.0 アクセス トークンの交換

作成した OAuth 2.0 アクセス トークンは、認証情報アクセス境界を遵守する範囲が限定された認証トークンと交換できます。このプロセスには通常、トークン ブローカーとトークン コンシューマーが含まれます。

  • トークン ブローカーは、認証情報アクセス境界を定義し、アクセス トークンを範囲の限定されたトークンと交換します。

    トークン ブローカーは、サポートされている認証ライブラリを使用してアクセス トークンを自動的に交換できます。また、セキュリティ トークン サービスを呼び出して、トークンを手動で交換することもできます。

  • トークン コンシューマーは、トークン ブローカーに範囲が限定されたアクセス トークンをリクエストし、範囲が限定されたアクセス トークンを使用して別のアクションを実行します。

    トークン コンシューマーは、サポートされている認証ライブラリを使用して、期限切れになる前にアクセス トークンを自動的に更新できます。あるいは、トークンを手動で更新することも、トークンを更新せずに期限切れにすることもできます。

アクセス トークンを自動的に交換して更新する

次のいずれかの言語でトークン ブローカーとトークン コンシューマーを作成する場合は、Google の認証ライブラリを使用して自動的にトークンを交換および更新できます。

Go

Go の場合、バージョン v0.0.0-20210819190943-2bc19b11175f 以降の golang.org/x/oauth2 パッケージを使用してトークンを自動的に交換して更新できます。

使用しているパッケージのバージョンを確認するには、アプリケーション ディレクトリで次のコマンドを実行します。

go list -m golang.org/x/oauth2

次の例は、トークン ブローカーが範囲の限定されたトークンを生成する方法を示しています。


import (
	"context"
	"fmt"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"golang.org/x/oauth2/google/downscope"
)

// createDownscopedToken would be run on the token broker in order to generate
// a downscoped access token that only grants access to objects whose name begins with prefix.
// The token broker would then pass the newly created token to the requesting token consumer for use.
func createDownscopedToken(bucketName string, prefix string) error {
	// bucketName := "foo"
	// prefix := "profile-picture-"

	ctx := context.Background()
	// A condition can optionally be provided to further restrict access permissions.
	condition := downscope.AvailabilityCondition{
		Expression:  "resource.name.startsWith('projects/_/buckets/" + bucketName + "/objects/" + prefix + "')",
		Title:       prefix + " Only",
		Description: "Restricts a token to only be able to access objects that start with `" + prefix + "`",
	}
	// Initializes an accessBoundary with one Rule which restricts the downscoped
	// token to only be able to access the bucket "bucketName" and only grants it the
	// permission "storage.objectViewer".
	accessBoundary := []downscope.AccessBoundaryRule{
		{
			AvailableResource:    "//storage.googleapis.com/projects/_/buckets/" + bucketName,
			AvailablePermissions: []string{"inRole:roles/storage.objectViewer"},
			Condition:            &condition, // Optional
		},
	}

	// This Source can be initialized in multiple ways; the following example uses
	// Application Default Credentials.
	var rootSource oauth2.TokenSource

	// You must provide the "https://www.googleapis.com/auth/cloud-platform" scope.
	rootSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform")
	if err != nil {
		return fmt.Errorf("failed to generate rootSource: %w", err)
	}

	// downscope.NewTokenSource constructs the token source with the configuration provided.
	dts, err := downscope.NewTokenSource(ctx, downscope.DownscopingConfig{RootSource: rootSource, Rules: accessBoundary})
	if err != nil {
		return fmt.Errorf("failed to generate downscoped token source: %w", err)
	}
	// Token() uses the previously declared TokenSource to generate a downscoped token.
	tok, err := dts.Token()
	if err != nil {
		return fmt.Errorf("failed to generate token: %w", err)
	}
	// Pass this token back to the token consumer.
	_ = tok
	return nil
}

トークン コンシューマーが更新ハンドラを使用して、範囲の限定されたトークンを自動的に取得して更新する方法を次に示します。


import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	"golang.org/x/oauth2/google"
	"golang.org/x/oauth2/google/downscope"

	"cloud.google.com/go/storage"
	"golang.org/x/oauth2"
	"google.golang.org/api/option"
)

// A token consumer should define their own tokenSource. In the Token() method,
// it should send a query to a token broker requesting a downscoped token.
// The token broker holds the root credential that is used to generate the
// downscoped token.
type localTokenSource struct {
	ctx        context.Context
	bucketName string
	brokerURL  string
}

func (lts localTokenSource) Token() (*oauth2.Token, error) {
	var remoteToken *oauth2.Token
	// Usually you would now retrieve remoteToken, an oauth2.Token, from token broker.
	// This snippet performs the same functionality locally.
	accessBoundary := []downscope.AccessBoundaryRule{
		{
			AvailableResource:    "//storage.googleapis.com/projects/_/buckets/" + lts.bucketName,
			AvailablePermissions: []string{"inRole:roles/storage.objectViewer"},
		},
	}
	rootSource, err := google.DefaultTokenSource(lts.ctx, "https://www.googleapis.com/auth/cloud-platform")
	if err != nil {
		return nil, fmt.Errorf("failed to generate rootSource: %w", err)
	}
	dts, err := downscope.NewTokenSource(lts.ctx, downscope.DownscopingConfig{RootSource: rootSource, Rules: accessBoundary})
	if err != nil {
		return nil, fmt.Errorf("failed to generate downscoped token source: %w", err)
	}
	// Token() uses the previously declared TokenSource to generate a downscoped token.
	remoteToken, err = dts.Token()
	if err != nil {
		return nil, fmt.Errorf("failed to generate token: %w", err)
	}

	return remoteToken, nil
}

// getObjectContents will read the contents of an object in Google Storage
// named objectName, contained in the bucket "bucketName".
func getObjectContents(output io.Writer, bucketName string, objectName string) error {
	// bucketName := "foo"
	// prefix := "profile-picture-"

	ctx := context.Background()

	thisTokenSource := localTokenSource{
		ctx:        ctx,
		bucketName: bucketName,
		brokerURL:  "yourURL.com/internal/broker",
	}

	// Wrap the TokenSource in an oauth2.ReuseTokenSource to enable automatic refreshing.
	refreshableTS := oauth2.ReuseTokenSource(nil, thisTokenSource)
	// You can now use the token source to access Google Cloud Storage resources as follows.
	storageClient, err := storage.NewClient(ctx, option.WithTokenSource(refreshableTS))
	if err != nil {
		return fmt.Errorf("failed to create the storage client: %w", err)
	}
	defer storageClient.Close()
	bkt := storageClient.Bucket(bucketName)
	obj := bkt.Object(objectName)
	rc, err := obj.NewReader(ctx)
	if err != nil {
		return fmt.Errorf("failed to retrieve the object: %w", err)
	}
	defer rc.Close()
	data, err := ioutil.ReadAll(rc)
	if err != nil {
		return fmt.Errorf("could not read the object's contents: %w", err)
	}
	// Data now contains the contents of the requested object.
	output.Write(data)
	return nil
}

Java

Java の場合、バージョン 1.1.0 以降の com.google.auth:google-auth-library-oauth2-http アーティファクトを使用してトークンを自動的に交換して更新できます。

使用しているアーティファクトのバージョンを確認するには、アプリケーション ディレクトリで次の Maven コマンドを実行します。

mvn dependency:list -DincludeArtifactIds=google-auth-library-oauth2-http

次の例は、トークン ブローカーが範囲の限定されたトークンを生成する方法を示しています。

public static AccessToken getTokenFromBroker(String bucketName, String objectPrefix)
    throws IOException {
  // Retrieve the source credentials from ADC.
  GoogleCredentials sourceCredentials =
      GoogleCredentials.getApplicationDefault()
          .createScoped("https://www.googleapis.com/auth/cloud-platform");

  // Initialize the Credential Access Boundary rules.
  String availableResource = "//storage.googleapis.com/projects/_/buckets/" + bucketName;

  // Downscoped credentials will have readonly access to the resource.
  String availablePermission = "inRole:roles/storage.objectViewer";

  // Only objects starting with the specified prefix string in the object name will be allowed
  // read access.
  String expression =
      "resource.name.startsWith('projects/_/buckets/"
          + bucketName
          + "/objects/"
          + objectPrefix
          + "')";

  // Build the AvailabilityCondition.
  CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition availabilityCondition =
      CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition.newBuilder()
          .setExpression(expression)
          .build();

  // Define the single access boundary rule using the above properties.
  CredentialAccessBoundary.AccessBoundaryRule rule =
      CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
          .setAvailableResource(availableResource)
          .addAvailablePermission(availablePermission)
          .setAvailabilityCondition(availabilityCondition)
          .build();

  // Define the Credential Access Boundary with all the relevant rules.
  CredentialAccessBoundary credentialAccessBoundary =
      CredentialAccessBoundary.newBuilder().addRule(rule).build();

  // Create the downscoped credentials.
  DownscopedCredentials downscopedCredentials =
      DownscopedCredentials.newBuilder()
          .setSourceCredential(sourceCredentials)
          .setCredentialAccessBoundary(credentialAccessBoundary)
          .build();

  // Retrieve the token.
  // This will need to be passed to the Token Consumer.
  AccessToken accessToken = downscopedCredentials.refreshAccessToken();
  return accessToken;
}

トークン コンシューマーが更新ハンドラを使用して、範囲の限定されたトークンを自動的に取得して更新する方法を次に示します。

public static void tokenConsumer(final String bucketName, final String objectName)
    throws IOException {
  // You can pass an `OAuth2RefreshHandler` to `OAuth2CredentialsWithRefresh` which will allow the
  // library to seamlessly handle downscoped token refreshes on expiration.
  OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler =
      new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() {
        @Override
        public AccessToken refreshAccessToken() throws IOException {
          // The common pattern of usage is to have a token broker pass the downscoped short-lived
          // access tokens to a token consumer via some secure authenticated channel.
          // For illustration purposes, we are generating the downscoped token locally.
          // We want to test the ability to limit access to objects with a certain prefix string
          // in the resource bucket. objectName.substring(0, 3) is the prefix here. This field is
          // not required if access to all bucket resources are allowed. If access to limited
          // resources in the bucket is needed, this mechanism can be used.
          return getTokenFromBroker(bucketName, objectName.substring(0, 3));
        }
      };

  // Downscoped token retrieved from token broker.
  AccessToken downscopedToken = handler.refreshAccessToken();

  // Create the OAuth2CredentialsWithRefresh from the downscoped token and pass a refresh handler
  // which will handle token expiration.
  // This will allow the consumer to seamlessly obtain new downscoped tokens on demand every time
  // token expires.
  OAuth2CredentialsWithRefresh credentials =
      OAuth2CredentialsWithRefresh.newBuilder()
          .setAccessToken(downscopedToken)
          .setRefreshHandler(handler)
          .build();

  // Use the credentials with the Cloud Storage SDK.
  StorageOptions options = StorageOptions.newBuilder().setCredentials(credentials).build();
  Storage storage = options.getService();

  // Call Cloud Storage APIs.
  Blob blob = storage.get(bucketName, objectName);
  String content = new String(blob.getContent());
  System.out.println(
      "Retrieved object, "
          + objectName
          + ", from bucket,"
          + bucketName
          + ", with content: "
          + content);
}

Node.js

Node.js の場合、バージョン 7.9.0 以降の google-auth-library パッケージを使用してトークンを自動的に交換して更新できます。

使用しているパッケージのバージョンを確認するには、アプリケーション ディレクトリで次のコマンドを実行します。

npm list google-auth-library

次の例は、トークン ブローカーが範囲の限定されたトークンを生成する方法を示しています。

// Imports the Google Auth libraries.
const {GoogleAuth, DownscopedClient} = require('google-auth-library');
/**
 * Simulates token broker generating downscoped tokens for specified bucket.
 *
 * @param bucketName The name of the Cloud Storage bucket.
 * @param objectPrefix The prefix string of the object name. This is used
 *        to ensure access is restricted to only objects starting with this
 *        prefix string.
 */
async function getTokenFromBroker(bucketName, objectPrefix) {
  const googleAuth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
  });

  // Define the Credential Access Boundary object.
  const cab = {
    // Define the access boundary.
    accessBoundary: {
      // Define the single access boundary rule.
      accessBoundaryRules: [
        {
          availableResource: `//storage.googleapis.com/projects/_/buckets/${bucketName}`,
          // Downscoped credentials will have readonly access to the resource.
          availablePermissions: ['inRole:roles/storage.objectViewer'],
          // Only objects starting with the specified prefix string in the object name
          // will be allowed read access.
          availabilityCondition: {
            expression:
              "resource.name.startsWith('projects/_/buckets/" +
              `${bucketName}/objects/${objectPrefix}')`,
          },
        },
      ],
    },
  };

  // Obtain an authenticated client via ADC.
  const client = await googleAuth.getClient();

  // Use the client to create a DownscopedClient.
  const cabClient = new DownscopedClient(client, cab);

  // Refresh the tokens.
  const refreshedAccessToken = await cabClient.getAccessToken();

  // This will need to be passed to the token consumer.
  return refreshedAccessToken;
}

次の例は、トークン コンシューマーが、範囲の限定されたトークンを自動的に取得して更新する更新ハンドラを提供する方法を示しています。

// Imports the Google Auth and Google Cloud libraries.
const {OAuth2Client} = require('google-auth-library');
const {Storage} = require('@google-cloud/storage');
/**
 * Simulates token consumer generating calling GCS APIs using generated
 * downscoped tokens for specified bucket.
 *
 * @param bucketName The name of the Cloud Storage bucket.
 * @param objectName The name of the object in the Cloud Storage bucket
 *        to read.
 */
async function tokenConsumer(bucketName, objectName) {
  // Create the OAuth credentials (the consumer).
  const oauth2Client = new OAuth2Client();
  // We are defining a refresh handler instead of a one-time access
  // token/expiry pair.
  // This will allow the consumer to obtain new downscoped tokens on
  // demand every time a token is expired, without any additional code
  // changes.
  oauth2Client.refreshHandler = async () => {
    // The common pattern of usage is to have a token broker pass the
    // downscoped short-lived access tokens to a token consumer via some
    // secure authenticated channel. For illustration purposes, we are
    // generating the downscoped token locally. We want to test the ability
    // to limit access to objects with a certain prefix string in the
    // resource bucket. objectName.substring(0, 3) is the prefix here. This
    // field is not required if access to all bucket resources are allowed.
    // If access to limited resources in the bucket is needed, this mechanism
    // can be used.
    const refreshedAccessToken = await getTokenFromBroker(
      bucketName,
      objectName.substring(0, 3)
    );
    return {
      access_token: refreshedAccessToken.token,
      expiry_date: refreshedAccessToken.expirationTime,
    };
  };

  const storageOptions = {
    projectId: process.env.GOOGLE_CLOUD_PROJECT,
    authClient: oauth2Client,
  };

  const storage = new Storage(storageOptions);
  const downloadFile = await storage
    .bucket(bucketName)
    .file(objectName)
    .download();
  console.log(downloadFile.toString('utf8'));
}

Python

Python の場合、バージョン 2.0.0 以降の google-auth パッケージを使用してトークンを自動的に交換して更新できます。

使用しているパッケージのバージョンを確認するには、パッケージがインストールされている環境で次のコマンドを実行します。

pip show google-auth

次の例は、トークン ブローカーが範囲の限定されたトークンを生成する方法を示しています。

import google.auth

from google.auth import downscoped
from google.auth.transport import requests

def get_token_from_broker(bucket_name, object_prefix):
    """Simulates token broker generating downscoped tokens for specified bucket.

    Args:
        bucket_name (str): The name of the Cloud Storage bucket.
        object_prefix (str): The prefix string of the object name. This is used
            to ensure access is restricted to only objects starting with this
            prefix string.

    Returns:
        Tuple[str, datetime.datetime]: The downscoped access token and its expiry date.
    """
    # Initialize the Credential Access Boundary rules.
    available_resource = f"//storage.googleapis.com/projects/_/buckets/{bucket_name}"
    # Downscoped credentials will have readonly access to the resource.
    available_permissions = ["inRole:roles/storage.objectViewer"]
    # Only objects starting with the specified prefix string in the object name
    # will be allowed read access.
    availability_expression = (
        "resource.name.startsWith('projects/_/buckets/{}/objects/{}')".format(
            bucket_name, object_prefix
        )
    )
    availability_condition = downscoped.AvailabilityCondition(availability_expression)
    # Define the single access boundary rule using the above properties.
    rule = downscoped.AccessBoundaryRule(
        available_resource=available_resource,
        available_permissions=available_permissions,
        availability_condition=availability_condition,
    )
    # Define the Credential Access Boundary with all the relevant rules.
    credential_access_boundary = downscoped.CredentialAccessBoundary(rules=[rule])

    # Retrieve the source credentials via ADC.
    source_credentials, _ = google.auth.default()
    if source_credentials.requires_scopes:
        source_credentials = source_credentials.with_scopes(
            ["https://www.googleapis.com/auth/cloud-platform"]
        )

    # Create the downscoped credentials.
    downscoped_credentials = downscoped.Credentials(
        source_credentials=source_credentials,
        credential_access_boundary=credential_access_boundary,
    )

    # Refresh the tokens.
    downscoped_credentials.refresh(requests.Request())

    # These values will need to be passed to the token consumer.
    access_token = downscoped_credentials.token
    expiry = downscoped_credentials.expiry
    return (access_token, expiry)

次の例は、トークン コンシューマーが、範囲の限定されたトークンを自動的に取得して更新する更新ハンドラを提供する方法を示しています。

from google.cloud import storage
from google.oauth2 import credentials

def token_consumer(bucket_name, object_name):
    """Tests token consumer readonly access to the specified object.

    Args:
        bucket_name (str): The name of the Cloud Storage bucket.
        object_name (str): The name of the object in the Cloud Storage bucket
            to read.
    """

    # Create the OAuth credentials from the downscoped token and pass a
    # refresh handler to handle token expiration. We are passing a
    # refresh_handler instead of a one-time access token/expiry pair.
    # This will allow the consumer to obtain new downscoped tokens on
    # demand every time a token is expired, without any additional code
    # changes.
    def refresh_handler(request, scopes=None):
        # The common pattern of usage is to have a token broker pass the
        # downscoped short-lived access tokens to a token consumer via some
        # secure authenticated channel.
        # For illustration purposes, we are generating the downscoped token
        # locally.
        # We want to test the ability to limit access to objects with a certain
        # prefix string in the resource bucket. object_name[0:3] is the prefix
        # here. This field is not required if access to all bucket resources are
        # allowed. If access to limited resources in the bucket is needed, this
        # mechanism can be used.
        return get_token_from_broker(bucket_name, object_prefix=object_name[0:3])

    creds = credentials.Credentials(
        None,
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
        refresh_handler=refresh_handler,
    )

    # Initialize a Cloud Storage client with the oauth2 credentials.
    storage_client = storage.Client(credentials=creds)
    # The token broker has readonly access to the specified bucket object.
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(object_name)
    print(blob.download_as_bytes().decode("utf-8"))

アクセス トークンを手動で交換して更新する

トークン ブローカーは、Security Token Service API を使用して、アクセス トークンを範囲の限定されたアクセス トークンと交換できます。その後、範囲の限定されたトークンをトークン コンシューマーに提供できます。

アクセス トークンを交換するには、次の HTTP メソッドと URL を使用します。

POST https://sts.googleapis.com/v1/token

リクエストの Content-Type ヘッダーを application/x-www-form-urlencoded に設定します。リクエスト本文に次のフィールドを含めます。

フィールド
grant_type

string

urn:ietf:params:oauth:grant-type:token-exchange を使用します。

options

string

パーセント エンコードでエンコードされた JSON 形式の認証情報アクセス境界。

requested_token_type

string

urn:ietf:params:oauth:token-type:access_token を使用します。

subject_token

string

交換する OAuth 2.0 アクセス トークン。

subject_token_type

string

urn:ietf:params:oauth:token-type:access_token を使用します。

レスポンスは、次のフィールドを含む JSON オブジェクトです。

フィールド
access_token

string

認証情報アクセス境界を遵守する範囲が限定された OAuth 2.0 アクセス トークン。

expires_in

number

範囲が限定されたトークンが期限切れになるまでの秒数。

このフィールドは、元のアクセス トークンがサービス アカウントを表す場合にのみ存在します。このフィールドが存在しない場合、範囲が限定されたトークンの有効期限は元のアクセス トークンと同じになります。

issued_token_type

string

urn:ietf:params:oauth:token-type:access_token という値が含まれます。

token_type

string

Bearer という値が含まれます。

たとえば、JSON 形式の認証情報アクセス境界が ./access-boundary.json ファイルに保存されている場合、次の curl コマンドを使用してアクセス トークンを交換できます。original-token は元のアクセス トークンに置き換えます。

curl -H "Content-Type:application/x-www-form-urlencoded" \
    -X POST \
    https://sts.googleapis.com/v1/token \
    -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange&subject_token_type=urn:ietf:params:oauth:token-type:access_token&requested_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=original-token" \
    --data-urlencode "options=$(cat ./access-boundary.json)"

レスポンスは次の例のようになります。

{
  "access_token": "ya29.dr.AbCDeFg-123456...",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "token_type": "Bearer",
  "expires_in": 3600
}

トークン コンシューマーが範囲の限定されたトークンをリクエストすると、トークン ブローカーは、範囲の限定されたトークンおよび有効期限が切れるまでの秒数の両方を応答する必要があります。範囲の限定されたトークンを更新するには、既存のトークンが期限切れになる前に、コンシューマーは範囲の限定されたトークンをブローカーにリクエストします。

次のステップ