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

Keycloak test #612

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 7 additions & 7 deletions examples/kitchensink/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"dev": "nodemon --delay 2500ms --watch '../../packages' --watch '.' -i lib -e js,mjs,json,ts --exec \"npm run dev:run\""
},
"dependencies": {
"@graphql-yoga/plugin-response-cache": "^3.12.3",
"@graphql-yoga/plugin-response-cache": "^3.12.5",
"@paypal/checkout-server-sdk": "^1.0.3",
"@unchainedshop/api": "^3.0.0-alpha4",
"@unchainedshop/core-delivery": "^3.0.0-alpha4",
Expand All @@ -43,12 +43,12 @@
"@unchainedshop/plugins": "^3.0.0-alpha4",
"@unchainedshop/ticketing": "^3.0.0-alpha4",
"bip32": "^4.0.0",
"bitcoinjs-lib": "^6.1.6",
"bitcoinjs-lib": "^6.1.7",
"cookie-parser": "^1.4.7",
"dotenv-extended": "^2.9.0",
"ethers": "^6.13.4",
"event-iterator": "^2.0.0",
"express": "^4.21.1",
"express": "^4.21.2",
"express-session": "^1.18.1",
"graphql": "^16.9.0",
"JSONStream": "^1.3.5",
Expand All @@ -60,15 +60,15 @@
"serve-static": "^1.15.0",
"stripe": "^17.4.0",
"tiny-secp256k1": "^2.2.3",
"twilio": "^5.3.6",
"twilio": "^5.4.0",
"web-push": "^3.6.7",
"xml-js": "^1.6.11"
},
"devDependencies": {
"@types/node": "^22.10.0",
"@types/node": "^22.10.2",
"mongodb-memory-server": "^10.1.2",
"nodemon": "^3.1.7",
"prettier": "^3.4.1",
"nodemon": "^3.1.9",
"prettier": "^3.4.2",
"ts-node": "^10.9.2",
"typescript": "^5.7.2"
}
Expand Down
60 changes: 60 additions & 0 deletions examples/minimal/boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import { log } from '@unchainedshop/logger';
import seed from './seed.js';
import Fastify from 'fastify';
import FastifyOAuth2 from '@fastify/oauth2';

const start = async () => {
const fastify = Fastify({
Expand All @@ -27,6 +28,65 @@
modules: baseModules,
});

fastify.register(FastifyOAuth2, {
name: 'keycloak',
credentials: {
client: {
id: 'unchained-local',
secret: 'n7L0X7Wo7mLkSIfLKvvAqZpNpcOVncKd',
},
},
startRedirectPath: '/login',
scope: ['profile', 'email', 'openid', 'address'],
callbackUri: 'http://localhost:4010/callback',
discovery: { issuer: 'http://localhost:8080/realms/myrealm' },
});

fastify.get('/callback', async function (request, reply) {
const accessToken = await this.keycloak.getAccessTokenFromAuthorizationCodeFlow(request);
try {
const userinfo = await this.keycloak.userinfo(accessToken.token.access_token);
const { sub, email, resource_access, email_verified, name, given_name, family_name } = userinfo;
const roles = resource_access?.['unchained-local']?.roles || [];
const user = await engine.unchainedAPI.modules.users.findUserByUsername(`keycloak:${sub}`);

if (user) {
if (JSON.stringify(user.roles) !== JSON.stringify(roles)) {
await engine.unchainedAPI.modules.users.updateRoles(user._id, roles);
}
request.unchainedContext.login(user);
return reply.redirect('/');
}
// TODO: try to use the preferred_username as the username first
const newUserId = await engine.unchainedAPI.modules.users.createUser(
{
username: `keycloak:${sub}`,
password: null,
email: email_verified ? email : undefined,
profile: {
displayName: name,
address: {
firstName: given_name,
lastName: family_name,
},
},
roles,
},
{ skipMessaging: true, skipPasswordEnrollment: true },
);
const newUser = await engine.unchainedAPI.modules.users.findUserById(newUserId);
request.unchainedContext.login(newUser);
return reply.redirect('/');
} catch (e) {
console.error(e);
}

// if later need to refresh the token this can be used
// const { token: newToken } = await this.getNewAccessTokenUsingRefreshToken(token)

return reply.send({ access_token: token.access_token });
});
Comment on lines +45 to +88

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.

Copilot Autofix AI about 1 month ago

To fix the problem, we need to introduce rate limiting to the Fastify application. We can use the @fastify/rate-limit plugin to achieve this. This plugin allows us to set a maximum number of requests per time window for each IP address, which will help mitigate the risk of denial-of-service attacks.

We will:

  1. Install the @fastify/rate-limit package.
  2. Register the rate limiting plugin with the Fastify instance.
  3. Configure the rate limiting settings to a reasonable default, such as 100 requests per 15 minutes.
Suggested changeset 2
examples/minimal/boot.ts

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/examples/minimal/boot.ts b/examples/minimal/boot.ts
--- a/examples/minimal/boot.ts
+++ b/examples/minimal/boot.ts
@@ -8,2 +8,3 @@
 import FastifyOAuth2 from '@fastify/oauth2';
+import FastifyRateLimit from '@fastify/rate-limit';
 
@@ -25,2 +26,7 @@
   });
+
+  await fastify.register(FastifyRateLimit, {
+    max: 100, // maximum 100 requests per 15 minutes
+    timeWindow: '15 minutes'
+  });
 
EOF
@@ -8,2 +8,3 @@
import FastifyOAuth2 from '@fastify/oauth2';
import FastifyRateLimit from '@fastify/rate-limit';

@@ -25,2 +26,7 @@
});

await fastify.register(FastifyRateLimit, {
max: 100, // maximum 100 requests per 15 minutes
timeWindow: '15 minutes'
});

examples/minimal/package.json
Outside changed files

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/examples/minimal/package.json b/examples/minimal/package.json
--- a/examples/minimal/package.json
+++ b/examples/minimal/package.json
@@ -41,3 +41,4 @@
     "@unchainedshop/plugins": "^3.0.0-alpha4",
-    "fastify": "^5.1.0"
+    "fastify": "^5.1.0",
+    "@fastify/rate-limit": "^10.2.1"
   },
EOF
@@ -41,3 +41,4 @@
"@unchainedshop/plugins": "^3.0.0-alpha4",
"fastify": "^5.1.0"
"fastify": "^5.1.0",
"@fastify/rate-limit": "^10.2.1"
},
This fix introduces these dependencies
Package Version Security advisories
@fastify/rate-limit (npm) 10.2.1 None
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options

await seed(engine.unchainedAPI);
await setAccessToken(engine.unchainedAPI, 'admin', 'secret');

Expand Down
7 changes: 4 additions & 3 deletions examples/minimal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,17 @@
},
"dependencies": {
"@fastify/cookie": "^11.0.1",
"@fastify/oauth2": "^8.1.0",
"@fastify/session": "^11.0.1",
"@unchainedshop/platform": "^3.0.0-alpha4",
"@unchainedshop/plugins": "^3.0.0-alpha4",
"fastify": "^5.1.0"
},
"devDependencies": {
"@types/node": "^22.10.0",
"@types/node": "^22.10.2",
"mongodb-memory-server": "^10.0.0",
"nodemon": "^3.1.7",
"prettier": "^3.4.1",
"nodemon": "^3.1.9",
"prettier": "^3.4.2",
"ts-node": "^10.9.2",
"typescript": "^5.7.2"
}
Expand Down
Loading
Loading