Skip to content

Commit

Permalink
patch identity fetch in mutation for non public queries
Browse files Browse the repository at this point in the history
  • Loading branch information
dbrrt committed Jan 5, 2024
1 parent 4fc38c8 commit 320f085
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 13 deletions.
5 changes: 5 additions & 0 deletions .changeset/eleven-chairs-attack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@authdog/hydra-core": patch
---

patch identity fetch in mutation for non public queries
87 changes: 75 additions & 12 deletions packages/core/src/handlers/hydra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
unauthorizedResponse,
} from "../responses/default";


// TODO: remove duplicated identity fetcher
export const HydraHandler = async (req, env, ctx): Promise<Response> => {
if (ctx.hasOwnProperty("kv") === false) {
throw new Error("Missing KV store");
Expand Down Expand Up @@ -51,13 +53,31 @@ export const HydraHandler = async (req, env, ctx): Promise<Response> => {
requestBody?.query?.indexOf("_schema") > -1;

let extractedQueries = [];
let userId = "";

const directQuery = isIntrospection || skipCache;

if (directQuery) {
return await GraphQLHandler(req, env, ctx);
}

if (isMutation) {
cacheKey = await generateGraphQLCacheKey({
query: requestBody?.query,
userId: "",
variables: JSON.stringify(requestBody?.variables),
});
}

let authorization =
requestHeaders?.get("authorization") ||
requestHeaders?.get("Authorization");

if (authorization) {
authorization = authorization?.replace("Bearer ", "");
authorization = authorization?.replace("bearer ", "");
}

if (!isIntrospection && !isMutation) {
// TODO: fix this, it excludes variables
extractedQueries = extractedAllQueryIdentifiersInRawQuery(
Expand Down Expand Up @@ -139,23 +159,12 @@ export const HydraHandler = async (req, env, ctx): Promise<Response> => {
});
});

let authorization =
requestHeaders?.get("authorization") ||
requestHeaders?.get("Authorization");

if (authorization) {
authorization = authorization?.replace("Bearer ", "");
authorization = authorization?.replace("bearer ", "");
}

if (!requiresAuthorization) {
cacheKey = await generateGraphQLCacheKey({
query: requestBody?.query,
variables,
});
} else if (requiresAuthorization && authorization) {
let userId = "";

if (requiresAuthorization && authorization) {
let sanitizedJwks = null;

Expand Down Expand Up @@ -270,10 +279,65 @@ export const HydraHandler = async (req, env, ctx): Promise<Response> => {
payload = await GraphQLHandler(newRequest, env, ctx);

if (isMutation) {
console.log("isMutation", isMutation);

const { data } = await payload.clone().json();
const aggregatedIds = aggregateTypesWithIds(data);
const allKeys = await kvNamespace.list();
const keysToDelete = [];

// get user from request
let sanitizedJwks = null;

try {
const cachedJwks = await kvNamespace.get(hydraConfig?.jwksUri, {
type: "text",
});

if (cachedJwks) {
sanitizedJwks = JSON.parse(cachedJwks);
} else {
const jwksResponse = await fetch(hydraConfig?.jwksUri);
const jwks = await jwksResponse.json();
sanitizedJwks = jwks?.keys?.map((key) => {
return {
...Object.keys(key).reduce((acc, curr) => {
if (curr !== "x5c" && curr !== "__typename") {
acc[curr] = key[curr];
}
return acc;
}, {}),
};
});
await kvNamespace.put(
hydraConfig?.jwksUri,
JSON.stringify(sanitizedJwks),
{
expirationTtl: 60,
},
);
}
} catch (e) {
//console.log(e);
}

const { ["payload"]: tokenPayload } = await checkTokenValidness(
authorization,
{
adhoc: sanitizedJwks,
},
);

if (tokenPayload) {
userId = tokenPayload?.sub;
}

cacheKey = await generateGraphQLCacheKey({
query: requestBody?.query,
userId,
variables: JSON.stringify(requestBody?.variables),
});

const userKey = cacheKey?.split("_")[0];

const sequenceKeys = [];
Expand Down Expand Up @@ -328,7 +392,6 @@ export const HydraHandler = async (req, env, ctx): Promise<Response> => {
if (!isIntrospection && !isMutation && cacheKey && payload) {
const rawJsonPayload = await payload.clone().json();


if (rawJsonPayload?.errors) {
throw new Error(JSON.stringify(rawJsonPayload?.errors));
}
Expand Down
13 changes: 13 additions & 0 deletions services/itty-hydra/hydra.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export const HydraConfigAcme = {
id: "authz",
uri: "https://authz.auth.dog/graphql",
},
{
id: "notification",
uri: "https://notif.auth.dog/.netlify/functions/graphql",
},
],
rateLimiting: {
default: {
Expand All @@ -31,6 +35,15 @@ export const HydraConfigAcme = {
{
name: "hydraDevQuery",
},
{
name: "applicationEnvironment",
},
// {
// name: "getEnvJwks"
// },
// {
// name: "jwksPayload"
// }
],
jwksUri: "https://id.authdog.com/oidc/.well-known/jwks.json",
};
2 changes: 1 addition & 1 deletion services/itty-hydra/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Router } from "itty-router";
import { createCors } from "itty-cors";
import { NotFound } from "./handlers/notFound";
import { Health } from "./handlers/health";
import {CacheKeysHandler} from "./handlers/cache-keys"
import { CacheKeysHandler } from "./handlers/cache-keys";
import { GraphQLHandler, HydraHandler } from "@authdog/hydra-core";
import { HydraConfigAcme } from "./hydra.config";

Expand Down

0 comments on commit 320f085

Please sign in to comment.