認可と完全性

一般向けアプリケーションを構築する場合、そのデータを保護し、 システムに保存されたデータですLLM に関しては、特に注意を払うことが 必要なデータのみにモデルがアクセスするように制限する必要がある場合、 LLM を呼び出すユーザーに適切なスコープが設定され、フローが呼び出されている 検証されたクライアント アプリケーションによってのみアクセスできます。

Firebase Genkit には、認証ポリシーとリソースを管理するメカニズムが 学びます。Cloud Functions for Firebase で実行されるフローでは、デベロッパーは 認証ポリシーを提供するか、または認証ポリシーがないことを明示的に認める 1 です。Functions 以外のフローでは、auth も管理、設定できますが、 手動の統合が必要になります

基本的なフロー認証

すべてのフローは、構成で authPolicy を定義できます。認証ポリシーは、ユーザーが定義した特定の基準が満たされているかテストし、いずれかのテストが失敗した場合に例外をスローする関数です。 このフィールドが設定されている場合、フローが呼び出される前に実行されます。

import { defineFlow, runFlow } from '@genkit-ai/flow';

export const selfSummaryFlow = defineFlow(
  {
    name: 'selfSummaryFlow',
    inputSchema: z.object({uid: z.string()}),
    outputSchema: z.string(),
    authPolicy: (auth, input) => {
      if (!auth) {
        throw new Error('Authorization required.');
      }
      if (input.uid !== auth.uid) {
        throw new Error('You may only summarize your own profile data.');
      }
    }
  },
  async (input) => { ... });

このフローを実行するときは、withLocalAuthContext を使用して認証オブジェクトを提供する必要があります。そうしないと、 次のエラーが発生します。

// Error: Authorization required.
await runFlow(selfSummaryFlow, { uid: 'abc-def' });

// Error: You may only summarize your own profile data.
await runFlow(
  selfSummaryFlow,
  { uid: 'abc-def' },
  {
    withLocalAuthContext: { uid: 'hij-klm' },
  }
);

// Success
await runFlow(
  selfSummaryFlow,
  { uid: 'abc-def' },
  {
    withLocalAuthContext: { uid: 'abc-def' },
  }
);

Genkit 開発 UI で実行する場合、次のコマンドで Auth オブジェクトを渡すことができます。 [Auth JSON] に JSON を入力し、タブ: {"uid": "abc-def"}

また、フロー内でいつでもフローの認証コンテキストを取得することもできます。 (フローによって呼び出される関数内も含めて)getFlowAuth() を呼び出してください。

import { getFlowAuth, defineFlow } from '@genkit-ai/flow';

async function readDatabase(uid: string) {
  if (getFlowAuth().admin) {
    // Do something special if the user is an admin:
    ...
  } else {
    // Otherwise, use the `uid` variable to retrieve the relevant document
    ...
  }
}

export const selfSummaryFlow = defineFlow(
  {
    name: 'selfSummaryFlow',
    inputSchema: z.object({uid: z.string()}),
    outputSchema: z.string(),
    authPolicy: ...
  },
  async (input) => {
    ...
    await readDatabase(input.uid);
  });

Genkit の開発ツールでフローをテストする場合、この認証を指定できる UI で、またはコマンドラインで --auth フラグを指定します。

genkit flow:run selfSummaryFlow '{"uid": "abc-def"}' --auth '{"uid": "abc-def"}'

Cloud Functions for Firebase の統合

Firebase プラグインは、Firebase Auth / Google Cloud Identity Platform と組み込みの Firebase App Check サポート。

承認

Firebase プラグインが提供する onFlow() ラッパーは、 Cloud Functions for Firebase クライアント SDK。 SDK を使用する場合は、Firebase Auth ヘッダーが自動的に ただし、アプリ クライアントが Firebase Auth SDK。 Firebase Auth を使用して、onFlow() で定義されたフローを保護できます。

import {firebaseAuth} from "@genkit-ai/firebase/auth";
import {onFlow} from "@genkit-ai/firebase/functions";

export const selfSummaryFlow = onFlow({
    name: "selfSummaryFlow",
    inputSchema: z.string(),
    outputSchema: z.string(),
    authPolicy: firebaseAuth((user) => {
      if (!user.email_verified && !user.admin) {
        throw new Error("Email not verified");
      }
    }),
  }, (subject) => {...})

Firebase Auth プラグインを使用すると、userDecodedIdToken。 前述のように、このオブジェクトはいつでも getFlowAuth() を介して取得できます。 ご覧ください。開発中にこのフローを実行する場合は、ユーザー オブジェクトを できます。

genkit flow:run selfSummaryFlow '{"uid": "abc-def"}' --auth '{"admin": true}'

デフォルトでは、Firebase Auth プラグインは、認証ヘッダーを ただし、特別な API キーを使用して未認証アクセスを許可し、 処理(アップセル機能など)を行う場合は、 次のようにポリシーを構成します。

authPolicy: firebaseAuth((user) => {
  if (user && !user.email_verified) {
    throw new Error("Logged in users must have verified emails");
  }
}, {required: false}),

Cloud Functions の関数をインターネットに広く公開する際は、 データ保護のためになんらかの認可メカニズムを使用することが重要です。 顧客のデータを保護できます。とはいえ、データ アナリストが コードベースの認証チェック( 関数はグローバル呼び出し可能ではなく、代わりに Cloud IAM など)。「 onFlow() を使用する場合、authPolicy フィールドは常に必須ですが、 許可チェックを行わないことをライブラリに伝えるには、 noAuth() 関数:

import {onFlow, noAuth} from "@genkit-ai/firebase/functions";

export const selfSummaryFlow = onFlow({
    name: "selfSummaryFlow",
    inputSchema: z.string(),
    outputSchema: z.string(),
    // WARNING: Only do this if you have some other gatekeeping in place, like
    // Cloud IAM!
    authPolicy: noAuth(),
  }, (subject) => {...})

クライアントの完全性

認証自体が、アプリを保護するうえで大いに役立ちます。しかし、 クライアント アプリだけが関数を呼び出すようにすることが重要です。「 genkit 用の Firebase プラグインには、Genkit の Firebase App Check。追加するだけで onFlow() に次の構成オプションを追加します。

import {onFlow} from "@genkit-ai/firebase/functions";

export const selfSummaryFlow = onFlow({
    name: "selfSummaryFlow",
    inputSchema: z.string(),
    outputSchema: z.string(),

    // These two fields for app check. The consumeAppCheckToken option is for
    // replay protection, and requires additional client configuration. See the
    // App Check docs.
    enforceAppCheck: true,
    consumeAppCheckToken: true,

    authPolicy: ...,
  }, (subject) => {...})

Firebase 以外の HTTP 認証

Cloud Functions の外部のサーバー コンテキストにフローをデプロイすると、 Firebase では、認証チェックを独自に設定することをおすすめします。 ネイティブフローと一緒に使用できます次の 2 つのオプションがあります。

  1. 任意のサーバー フレームワークを使用し、 runFlow()

  2. 組み込みの startFlowsServer() を使用して、Express ミドルウェアを提供します。 フロー構成:

    export const selfSummaryFlow = defineFlow(
    {
      name: 'selfSummaryFlow',
      inputSchema: z.object({uid: z.string()}),
      outputSchema: z.string(),
      middleware: [
        (req, res, next) => {
          const token = req.headers['authorization'];
          const user = yourVerificationLibrary(token);
    
          // This is what will get passed to your authPolicy
          req.auth = user;
          next();
        }
      ],
      authPolicy: (auth, input) => {
        if (!auth) {
          throw new Error('Authorization required.');
        }
        if (input.uid !== auth.uid) {
          throw new Error('You may only summarize your own profile data.');
        }
      }
    },
    async (input) => { ... });
    
    startFlowsServer();  // This will register the middleware
    

    Express の使用の詳細については、Cloud Run をご覧ください。 できます。

(1)を選択すると、middleware 構成オプションが runFlow() によって無視されます。