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

Fix: Changing SAML2 return URL, fixing deprecated usages, fixing proxy on binaries file and adding logs #67

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
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
9 changes: 5 additions & 4 deletions .env.dist
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,12 @@ PHPMYADMIN_ROUTER_RULE="Host(`${PHPMYADMIN_DOMAIN}`)"
APP_SSO_SERVICEPROVIDER_X509CERT="MIICkDCCAfmgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBlMQswCQYDVQQGEwJmcjEOMAwGA1UECAwFUEFSSVMxDDAKBgNVBAoMA1RDTTEaMBgGA1UEAwwRZnJvbnQuc29jb3RlYy5kZXYxDjAMBgNVBAcMBVBBUklTMQwwCgYDVQQLDANUQ00wHhcNMTcwOTA4MTUyNzM0WhcNMTgwOTA4MTUyNzM0WjBlMQswCQYDVQQGEwJmcjEOMAwGA1UECAwFUEFSSVMxDDAKBgNVBAoMA1RDTTEaMBgGA1UEAwwRZnJvbnQuc29jb3RlYy5kZXYxDjAMBgNVBAcMBVBBUklTMQwwCgYDVQQLDANUQ00wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMKCd0hnMKX40MYR+fZNRqMJjSiDpTPTkV9A0bfQKESZ9esPjNt8Janq+2MGLrm6cRcMXRx8yo/x7pfoCmdiu9D7VNhk69nFsNKH0PQp/jf2+vLPHXgKvlcCFvlaOB/Cvg9UnK9mq83H88LPwvrpaNRl4qDrLS5TTByEIohjFUJrAgMBAAGjUDBOMB0GA1UdDgQWBBSk8/zuzxKBEwpusxRAva7oY7MkrDAfBgNVHSM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7yapFzlYSJLGoVE+OHEu8g5SlNACUEfkXw+5Eghh+KzlIN7R6Q7r2ixWNFBC/jWf7NKUfJyX8qIG5md1YUeT6GBW9Bm2/1/RiO24JTaYlfLdKK9TYb8sG5B+OLab2DImG99CJ25RkAcSobWNF5zD0O6lgOo3cEdB/ksCq3hmtlC/DlLZ/D8CJ+7VuZnS1rR2naQ=="
APP_SSO_IDENTITYPROVIDER_ENTITYID="http://samltest.${BASE_DOMAIN}/simplesaml/saml2/idp/metadata.php"
APP_SSO_IDENTITYPROVIDER_LOGINURL="http://samltest.${BASE_DOMAIN}/simplesaml/saml2/idp/SSOService.php"
APP_SSO_IDENTITYPROVIDER_LOGOUTURL="http://samltest.${BASE_DOMAIN}/simplesaml/saml2/idp/SSOService.php"
APP_SSO_IDENTITYPROVIDER_X509CERT=MIIDXTCCAkWgAwIBAgIJALmVVuDWu4NYMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwHhcNMTYxMjMxMTQzNDQ3WhcNNDgwNjI1MTQzNDQ3WjBFMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzUCFozgNb1h1M0jzNRSCjhOBnR+uVbVpaWfXYIR+AhWDdEe5ryY+CgavOg8bfLybyzFdehlYdDRgkedEB/GjG8aJw06l0qF4jDOAw0kEygWCu2mcH7XOxRt+YAH3TVHa/Hu1W3WjzkobqqqLQ8gkKWWM27fOgAZ6GieaJBN6VBSMMcPey3HWLBmc+TYJmv1dbaO2jHhKh8pfKw0W12VM8P1PIO8gv4Phu/uuJYieBWKixBEyy0lHjyixYFCR12xdh4CA47q958ZRGnnDUGFVE1QhgRacJCOZ9bd5t9mr8KLaVBYTCJo5ERE8jymab5dPqe5qKfJsCZiqWglbjUo9twIDAQABo1AwTjAdBgNVHQ4EFgQUxpuwcs/CYQOyui+r1G+3KxBNhxkwHwYDVR0jBBgwFoAUxpuwcs/CYQOyui+r1G+3KxBNhxkwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAAiWUKs/2x/viNCKi3Y6blEuCtAGhzOOZ9EjrvJ8+COH3Rag3tVBWrcBZ3/uhhPq5gy9lqw4OkvEws99/5jFsX1FJ6MKBgqfuy7yh5s1YfM0ANHYczMmYpZeAcQf2CGAaVfwTTfSlzNLsF2lW/ly7yapFzlYSJLGoVE+OHEu8g5SlNACUEfkXw+5Eghh+KzlIN7R6Q7r2ixWNFBC/jWf7NKUfJyX8qIG5md1YUeT6GBW9Bm2/1/RiO24JTaYlfLdKK9TYb8sG5B+OLab2DImG99CJ25RkAcSobWNF5zD0O6lgOo3cEdB/ksCq3hmtlC/DlLZ/D8CJ+7VuZnS1rR2naQ==
APP_SSO_IDENTITYPROVIDER_ENTITYID=${PROTOCOL}://samltest.${BASE_DOMAIN}/simplesaml/saml2/idp/metadata.php
APP_SSO_IDENTITYPROVIDER_LOGINURL=${PROTOCOL}://samltest.${BASE_DOMAIN}/simplesaml/saml2/idp/SSOService.php
APP_SSO_IDENTITYPROVIDER_LOGOUTURL=${PROTOCOL}://samltest.${BASE_DOMAIN}/simplesaml/saml2/idp/SSOService.php

###> symfony/mailer ###
MAILER_DSN=smtp://mail:1025
[email protected]
###< symfony/mailer ###
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ restart: down up ## Soft Restart
.PHONY: frestart
frestart: fdown fup ## Hard restart


.PHONY: fbuild
fbuild: ;\
docker compose build --no-cache

.PHONY: stop-front
stop-front: sync-env ## stop front container
DOCKER_BUILDKIT=1 docker compose stop front
Expand Down
1 change: 1 addition & 0 deletions apps/back/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ services:
class: App\Authenticator\Saml2Authenticator
arguments:
$checkPath: 'api_login_saml2'
$returnTo: "%app.url.base%/api/1.0/auth/sso/saml2/login"


OneLogin\Saml2\Auth:
Expand Down
19 changes: 9 additions & 10 deletions apps/back/src/Authenticator/Saml2Authenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace App\Authenticator;

use App\Exception\SsoConsumerAuthNException;
use App\Exception\SsoConsumerException;
use OneLogin\Saml2\Auth;
use Symfony\Component\HttpFoundation\JsonResponse;
Expand All @@ -27,6 +26,8 @@ public function __construct(
private readonly HttpUtils $httpUtils,
private readonly string $checkPath,
private readonly Auth $auth,
private readonly string $returnTo,
private readonly \Psr\Log\LoggerInterface $logger,
) {
}

Expand All @@ -43,12 +44,8 @@ public function supports(Request $request): bool|null
public function authenticate(Request $request): Passport
{
$session = $request->getSession();
$authNRequestId = $session->get('AuthNRequestID');
if (! \is_string($authNRequestId)) {
throw new SsoConsumerAuthNException();
}

$auth = $this->auth;
$authNRequestId = $session->get('AuthNRequestID', null);
$auth = $this->auth;
$auth->setStrict(false);
$auth->processResponse($authNRequestId);
$errors = $auth->getErrors();
Expand Down Expand Up @@ -97,11 +94,13 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio
/** @inheritDoc */
public function start(Request $request, AuthenticationException|null $authException = null)
{
$session = $request->getSession();
$auth = $this->auth;
$url = $auth->login(null, [], false, false, true);
$session = $request->getSession();
$this->logger->debug('Starting auth');
$auth = $this->auth;
$url = $auth->login($this->returnTo, [], false, false, true);
$authNRequestId = $auth->getLastRequestID();
$session->set('AuthNRequestID', $authNRequestId);
$this->logger->debug("Need redirect to $url");

return new JsonResponse(['url' => $url], Response::HTTP_UNAUTHORIZED);
}
Expand Down
2 changes: 1 addition & 1 deletion apps/front/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default defineNuxtConfig({
// @see https://getbootstrap.com/docs/5.0/getting-started/introduction/#starter-template
charset: "utf-8",
viewport: "width=device-width, initial-scale=1",
title: "Boilerplate TCM v2",
title: "Boilerplate SF - Nuxt",
meta: [
// <meta name="description" content="My amazing site">
// { name: 'description', content: 'My amazing site.' }
Expand Down
2 changes: 1 addition & 1 deletion apps/front/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"lint": "eslint nuxt.config.ts --fix ; nuxi typecheck ; eslint ./src/"
"lint": "eslint nuxt.config.ts --fix ; nuxi typecheck && eslint ./src/"
},
"devDependencies": {
"@nuxt/eslint-config": "^0.1.1",
Expand Down
18 changes: 14 additions & 4 deletions apps/front/src/app.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<template>
<div>
<NuxtErrorBoundary @error="mHandleError">
<NuxtLayout v-if="!isPendingAuth || authStore.isAuthenticated">
<NuxtLayout v-if="shouldRender">
<NuxtPage />
</NuxtLayout>
</NuxtErrorBoundary>
Expand All @@ -15,19 +15,28 @@ const authStore = useAuthUser();

const route = useRoute();

const mHandleError = (e: unknown) => {
const mHandleError = (e: any) => {
logger.error("Primary error boundary", e);
};
const isPendingAuth = computed(() => authStore.isPending);
const shouldRender = computed(
() => !authStore.isPending || authStore.isAuthenticated
);
// Doing this here instead than in the middleware allow reactivity on the auth user
watchEffect(async () => {
if (isPendingAuth.value) {
logger.info("pending");
if (authStore.isPending) {
return;
}
logger.info("resolved pending");
const shouldRedirectToLogin =
!authStore.isAuthenticated &&
authStore.authUrl &&
route.name !== "auth-login";
logger.info("shouldRedirectToLogin");
logger.info(authStore.isAuthenticated);
logger.info(authStore.authUrl);
logger.info(route.name);
logger.info(shouldRedirectToLogin);
if (shouldRedirectToLogin) {
await navigateTo(authStore.authUrl, { external: true });
}
Expand All @@ -38,3 +47,4 @@ watchEffect(async () => {
}
});
</script>
cd
1 change: 1 addition & 0 deletions apps/front/src/middleware/auth.global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export default defineNuxtRouteMiddleware(async () => {
// We refresh the data information
// If the syncMe result in a 401, the component RedirectToLogin will be triggered,
// so no need to wait the sync
logger.info("------ in middleware");
const mePromise = authStore.syncMe();
/**
* We still wait if the user is not authenticated because that may mean
Expand Down
17 changes: 10 additions & 7 deletions apps/front/src/plugins/appFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@ export default defineNuxtPlugin(() => {
const event = useRequestEvent();
const headers: {
[key: string]: string;
} = useRequestHeaders(["cookie"]) as {
[key: string]: string;
} = {
...(useRequestHeaders(["cookie"]) as {
[key: string]: string;
}),
...{
accept: "application/json",
},
};

const handleException = (e: any) => {
logger.error("An error hapenned during an API call");
logger.error(e);
Expand All @@ -21,10 +25,9 @@ export default defineNuxtPlugin(() => {
logger.error("401 error, removing authentication informations");
store.resetAuth();
}
// HERE the bug
const cookies = e.response.headers.get("set-cookie") || "";
if (process.server && cookies) {
event.res.setHeader("set-cookie", cookies);
event.node.res.setHeader("set-cookie", cookies);
}
throw e;
};
Expand All @@ -40,7 +43,7 @@ export default defineNuxtPlugin(() => {

const cookies = res.headers.get("set-cookie") || "";
if (process.server && cookies) {
event.res.setHeader("set-cookie", cookies);
event.node.res.setHeader("set-cookie", cookies);
}
return res;
};
Expand All @@ -57,7 +60,7 @@ export default defineNuxtPlugin(() => {

const cookies = res.headers.get("set-cookie") || "";
if (process.server && cookies) {
event.res.setHeader("set-cookie", cookies);
event.node.res.setHeader("set-cookie", cookies);
}
return res._data;
};
Expand Down
90 changes: 86 additions & 4 deletions apps/front/src/server/api/[...].ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { defineEventHandler, H3Event, proxyRequest } from "h3";

import {
defineEventHandler,
H3Event,
RequestHeaders,
getMethod,
getRequestHeaders,
sendProxy as _sendProxy,
} from "h3";
/**
* Beware
* Using the SSR, cookies are transmitted to the proxy BUT
Expand All @@ -25,6 +31,81 @@ import { defineEventHandler, H3Event, proxyRequest } from "h3";

import logger from "~/utils/logger";

/**
* This code override proxyRequest from h3
*/

/**
* start - this code is not exported from h3
*/
export interface ProxyOptions {
headers?: RequestHeaders | HeadersInit;
fetchOptions?: RequestInit;
fetch?: typeof fetch;
sendStream?: boolean;
cookieDomainRewrite?: string | Record<string, string>;
cookiePathRewrite?: string | Record<string, string>;
onResponse?: (event: H3Event, response: Response) => void;
}

const ignoredHeaders = new Set([
'transfer-encoding',
'connection',
'keep-alive',
'upgrade',
'expect',
'host',
]);

export function getProxyRequestHeaders(event: H3Event) {
const headers = Object.create(null);
const reqHeaders = getRequestHeaders(event);
// eslint-disable-next-line no-restricted-syntax
for (const name in reqHeaders) {
if (!ignoredHeaders.has(name)) {
headers[name] = reqHeaders[name];
}
}
return headers;
}

/**
* end - this code is not exported from h3
*/

/**
* This code override h3 default behavior:
* Instead of reading the body we send the body as the stream, allowing better memory usage + prevent utf8 decoding
* */
async function proxyRequest(
event: H3Event,
target: string,
opts: ProxyOptions = {},
) {
const method = getMethod(event);

// Headers
const headers = getProxyRequestHeaders(event);
if (opts.fetchOptions?.headers) {
Object.assign(headers, opts.fetchOptions.headers);
}
if (opts.headers) {
Object.assign(headers, opts.headers);
}
return _sendProxy(event, target, {
...opts,
fetchOptions: {
headers,
method,
body: method !== "GET" && method !== "HEAD" ? event.node.req : undefined,
...opts.fetchOptions,
} as RequestInit,
});
}

/**
* Here we use the proxy as a default request
*/
export default defineEventHandler(async (event: H3Event) => {
const { API_URL } = useRuntimeConfig();
const target = new URL(event.req.url as string, API_URL);
Expand All @@ -33,8 +114,9 @@ export default defineEventHandler(async (event: H3Event) => {
headers: {
host: target.host,
},
cookiePathRewrite: {
"/*": "/",
sendStream: true,
fetchOptions: {
redirect: "manual",
},
});
return ret;
Expand Down
2 changes: 1 addition & 1 deletion apps/front/src/store/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ export const useAuthUser = defineStore({
if (this.isPending) {
return;
}
this.startPending();
// Our session is based on the PHPSESSID cookie
const me = useMe();
try {
this.startPending();
const authUser = await me();
this.setAuthUser(authUser);
this.endPending();
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ services:
working_dir: /home/node/app
environment:
# This is used only per the proxy
NUXT_API_URL: http://${API_DOMAIN}/
- NUXT_API_URL=${PROTOCOL}://${API_DOMAIN}/
proxy:
image: traefik:3.0
container_name: tcm_proxy
Expand Down