Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BREAKING CHANGE(js)!: Reconcile authPolicy. add firebase and api key helpers #1743

Merged
merged 52 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
24c8b08
Checkpoint. Need to remove firebase/functions
inlined Jan 31, 2025
b4f16f2
Revert removal of middleware.ts
inlined Feb 5, 2025
473468e
Merge remote-tracking branch 'origin/main' into inlined.auth
inlined Feb 5, 2025
496dede
firebaseAuth sans integration tests
inlined Feb 5, 2025
5a201d9
Merge remote-tracking branch 'origin' into inlined.auth
inlined Feb 5, 2025
0924ab9
API key module
inlined Feb 5, 2025
c6492ec
Update error type to match Callable protocol
inlined Feb 5, 2025
2e0fa7e
Checkpoint. Merging UserFacingError with GenkitError
inlined Feb 5, 2025
d67b9be
Checkpoint. Refactored policy & error. Updated express. Strange errors
inlined Feb 6, 2025
b68d638
Whoops. Missing files
inlined Feb 6, 2025
dd15fa0
Tests passing again! Onto Next.js
inlined Feb 6, 2025
73afde8
Next.js works! Theres' enough testing I think we can GA it
inlined Feb 6, 2025
118bf91
Fix esm stuff; update docs
inlined Feb 6, 2025
347aa88
Remove last reference to onCallFlow
inlined Feb 6, 2025
042bd45
a few fixes for #1743 (#1880)
pavelgj Feb 6, 2025
4be1e3a
Adding missing files; PR feedback
inlined Feb 6, 2025
dad4a0a
docs: vertexai updates (#1841)
ifielker Feb 5, 2025
4f71804
breaking(js/ai): drop ToolDefinition from ToolArgument (and generate …
pavelgj Feb 5, 2025
5e744c9
chore: bump @genkit-ai/tools-common version to @genkit-ai/tools-commo…
gh-action-bump-version Feb 5, 2025
8a36c92
chore: bump genkit-cli version to [email protected]
gh-action-bump-version Feb 5, 2025
413f82b
chore: bump @genkit-ai/telemetry-server version to @genkit-ai/telemet…
gh-action-bump-version Feb 5, 2025
26ca0d8
chore: bump @genkit-ai/core version to @genkit-ai/[email protected]
gh-action-bump-version Feb 5, 2025
f67f4e5
chore: bump @genkit-ai/ai version to @genkit-ai/[email protected]
gh-action-bump-version Feb 5, 2025
73f8610
chore: bump genkit version to [email protected]
gh-action-bump-version Feb 5, 2025
d289a7d
chore: bump genkitx-chromadb version to [email protected]
gh-action-bump-version Feb 5, 2025
4ac6af2
chore: bump @genkit-ai/dev-local-vectorstore version to @genkit-ai/de…
gh-action-bump-version Feb 5, 2025
306c9a3
chore: bump @genkit-ai/evaluator version to @genkit-ai/[email protected].…
gh-action-bump-version Feb 5, 2025
1631611
chore: bump @genkit-ai/firebase version to @genkit-ai/[email protected]
gh-action-bump-version Feb 5, 2025
74e6b29
chore: bump @genkit-ai/google-cloud version to @genkit-ai/google-clou…
gh-action-bump-version Feb 5, 2025
e08bc1f
chore: bump @genkit-ai/googleai version to @genkit-ai/[email protected]
gh-action-bump-version Feb 5, 2025
c02a8bc
chore: bump genkitx-langchain version to [email protected]
gh-action-bump-version Feb 5, 2025
79f233a
chore: bump genkitx-ollama version to [email protected]
gh-action-bump-version Feb 5, 2025
a75fe7c
chore: bump genkitx-pinecone version to [email protected]
gh-action-bump-version Feb 5, 2025
9298eee
chore: bump @genkit-ai/vertexai version to @genkit-ai/[email protected]
gh-action-bump-version Feb 5, 2025
11663a2
chore: bump @genkit-ai/checks version to @genkit-ai/[email protected]
gh-action-bump-version Feb 5, 2025
7286715
chore: bump genkitx-mcp version to [email protected]
gh-action-bump-version Feb 5, 2025
a2cb532
chore: bump @genkit-ai/express version to @genkit-ai/[email protected]
gh-action-bump-version Feb 5, 2025
d364a19
chore: added next plugin to release script
pavelgj Feb 5, 2025
163ca84
docs: Restructuring of codelab-chat-with-a-pdf.md (#1836)
thedmail Feb 5, 2025
5c7ba1f
docs(js): Adds doc for context. (#1843)
mbleigh Feb 5, 2025
398e1b3
feat: support model validation (#1868)
ssbushi Feb 5, 2025
9552866
docs: 2nd tranche of docs updates for 6 Feb GA release (#1865)
thedmail Feb 5, 2025
a08c69a
fix(js): stream tool message generated by interrupt resume (#1870)
mbleigh Feb 5, 2025
2dcf527
feature(go): add support for multiple model versions (#1575)
hugoaguirre Feb 5, 2025
c3b91ab
docs: Third tranche of docs updates (#1871)
thedmail Feb 6, 2025
39a17bb
feat(js/ai): allow explicit constrained gen option, allow simulation …
pavelgj Feb 6, 2025
961feae
fix: update-samples-to-v17 (#1867)
i2amsam Feb 6, 2025
55e10ab
fix: update js-chatbot to work in IDX preview (#1874)
i2amsam Feb 6, 2025
652a5a6
fix: use correct idx link in js api readme (#1877)
tonybaroneee Feb 6, 2025
72f3ad0
fix: minor fixes in ollama plugin doc (#1875)
shrutip90 Feb 6, 2025
0f2d3f7
PR feedback
inlined Feb 6, 2025
9a07808
PR feedback & merge conflicts. Testing async
inlined Feb 6, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/bump-js-version.yml
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,17 @@ jobs:
preid: ${{ inputs.preid }}
commit-message: 'chore: bump genkitx-langchain version to {{version}}'
tag-prefix: 'genkitx-langchain@'
- name: 'js/plugins/next version bump'
uses: 'phips28/gh-action-bump-version@master'
env:
GITHUB_TOKEN: ${{ secrets.GENKIT_RELEASER_GITHUB_TOKEN }}
PACKAGEJSON_DIR: js/plugins/next
with:
default: ${{ inputs.releaseType }}
version-type: ${{ inputs.releaseType }}
preid: ${{ inputs.preid }}
commit-message: 'chore: bump @genkit-ai/next version to {{version}}'
tag-prefix: '@genkit-ai/next@'
- name: 'js/plugins/ollama version bump'
uses: 'phips28/gh-action-bump-version@master'
env:
Expand Down
136 changes: 78 additions & 58 deletions docs/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Alternatively, Firebase also provides auth context into the flow where it can
do its own checks. For non-Functions flows, auth can be managed and set
through middleware.

## Basic flow authorization
## Authorizing within a Flow

Flows can check authorization in two ways: either the request binding
(e.g. `onCallGenkit` for Cloud Functions for Firebase or `express`) can enforce
Expand All @@ -24,7 +24,7 @@ where the flow has access to the information for auth managed within the
flow.

```ts
import { genkit, z } from 'genkit';
import { genkit, z, UserFacingError } from 'genkit';

const ai = genkit({ ... });

Expand All @@ -34,10 +34,10 @@ export const selfSummaryFlow = ai.defineFlow( {
outputSchema: z.string(),
}, async (input, { context }) => {
if (!context.auth) {
throw new Error('Authorization required.');
throw new UserFacingErrorError('UNAUTHENTICATED', 'Unauthenticated');
}
if (input.uid !== context.auth.uid) {
throw new Error('You may only summarize your own profile data.');
throw new UserFacingError('PERMISSION_DENIED', 'You may only summarize your own profile data.');
}
// Flow logic here...
});
Expand Down Expand Up @@ -112,14 +112,13 @@ object in the UI, or on the command line with the `--context` flag:
genkit flow:run selfSummaryFlow '{"uid": "abc-def"}' --context '{"auth": {"email_verified": true}}'
```

## Cloud Functions for Firebase integration
## Authorizing with Cloud Functions for Firebase

The Cloud Functions for Firebase SDKs support Genkit including
integration with Firebase Auth / Google Cloud Identity Platform, as well as
built-in Firebase App Check support.

### Authorization

### User authentication
The `onCallGenkit()` wrapper provided by the Firebase Functions library works
natively with the Cloud Functions for Firebase
[client SDKs](https://firebase.google.com/docs/functions/callable?gen=2nd#call_the_function).
Expand Down Expand Up @@ -192,7 +191,7 @@ export const selfSummary = onCallGenkit({
}, selfSummaryFlow);
```

### Client integrity
#### Client integrity

Authentication on its own goes a long way to protect your app. But it's also
important to ensure that only your client apps are calling your functions. The
Expand Down Expand Up @@ -228,53 +227,74 @@ export const selfSummary = onCallGenkit({

When deploying flows to a server context outside of Cloud Functions for
Firebase, you'll want to have a way to set up your own authorization checks
alongside the native flows. You have two options:

1. Use whatever server framework you like, and pass the auth context through
using the flow call as noted earlier.

1. Use `startFlowsServer()`, which the `@genkit-ai/express` plugin
exposes, and provide Express auth middleware in the flow server config:

```ts
import { genkit, z } from 'genkit';
import { startFlowServer, withAuth } from '@genkit-ai/express';

const ai = genkit({ ... });;

export const selfSummaryFlow = ai.defineFlow(
{
name: 'selfSummaryFlow',
inputSchema: z.object({ uid: z.string() }),
outputSchema: z.string(),
},
async (input) => {
// Flow logic here...
}
);

const authProvider = (req, res, next) => {
const token = req.headers['authorization'];
const user = yourVerificationLibrary(token);

// Pass auth information to the flow
req.auth = user;
next();
};

startFlowServer({
flows: [
withAuth(selfSummaryFlow, authProvider, ({ auth, action, input, request }) => {
if (!auth) {
throw new Error('Authorization required.');
}
if (input.uid !== auth.uid) {
throw new Error('You may only summarize your own profile data.');
}
})
],
}); // Registers the auth provider middleware and policy
```

For more information about using Express, see the
[Cloud Run](/genkit/cloud-run) instructions.
alongside the native flows.

Use a `ContextProvider`, which both populates context values such as `auth` as well
as allowing you to provide a declarative policy or a policy callback. The genkit
SDK provides `ContextProvider` such as `apiKey`, and plugins may expose them as well,
such as `@genkit-ai/firebase/context` which can be used to build Firebase apps with
backends that are not Cloud Functions for Firebase.

Given the snippet common to all kinds of applications:

```ts
// Express app with a simple API key
import { genkit, z } from 'genkit';

const ai = genkit({ ... });;

export const selfSummaryFlow = ai.defineFlow(
{
name: 'selfSummaryFlow',
inputSchema: z.object({ uid: z.string() }),
outputSchema: z.string(),
},
async (input) => {
// Flow logic here...
}
);
```

You could secure a simple "flow server" express app with:

```ts
import { apiKey } from "genkit";
import { startFlowServer, withContext } from "@genkit-ai/express";

startFlowServer({
flows: [
withContext(selfSummaryFlow, apiKey(process.env.REQUIRED_API_KEY))
],
});
```

Or you can build a custom express application using the same tools:

```ts
import { apiKey } from "genkit";
import * as express from "express";
import { expressHandler } from "@genkit-ai/express;

const app = express();
// Capture but don't validate the API key (or its absence)
app.post('/summary', expressHandler(selfSummaryFlow, { contextProvider: apiKey()}))

app.listen(process.env.PORT, () => {
console.log(`Listening on port ${process.env.PORT}`);
})
```

`ContextProvider`s are intended to be abstract of any web framework, so these
tools work in other frameworks like Next.js as well. Here is an example of a
Firebase app built on Next.js.

```ts
import { appRoute } from "@genkit-ai/express";
import { firebaseContext } from "@genkit-ai/firebase";

export const POST = appRoute(selfSummaryFlow, { contextProvider: firebaseContext })
```

<!-- NOTE: Should we provide more docs? E.g. docs into various web frameworks and hosting services? -->
For more information about using Express, see the
[Cloud Run](/genkit/cloud-run) instructions.
10 changes: 6 additions & 4 deletions docs/cloud-run.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ endpoints.

When you make the call, specify the flows you want to serve:

There is also
```ts
import { startFlowServer } from '@genkit-ai/express';

Expand Down Expand Up @@ -83,13 +84,14 @@ When you deploy your flows with Cloud Run, you have two options for
authorization:

- **Cloud IAM-based authorization**: Use Google Cloud's native access management
facilities to gate access to your endpoints. See
facilities to gate access to your endpoints. For information on providing
these credentials, see
[Authentication](https://cloud.google.com/run/docs/authenticating/overview)
in the Cloud Run docs for information on providing these credentials.
in the Cloud Run docs.

- **Authorization policy defined in code**: Use the authorization policy feature
of Genkit express plugin to verify authorization info using custom code. This is often,
but not necessarily, token-based authorization.
of the Genkit express plugin to verify authorization info using custom code.
This is often, but not necessarily, token-based authorization.

If you want to define an authorization policy in code, use the `authPolicy`
parameter in the flow definition:
Expand Down
Loading
Loading