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

feat(app/api): add mock auth on backend side #340

Merged
merged 5 commits into from
Aug 24, 2022
Merged
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: 7 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,13 @@ jobs:
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_codeimage
DOMAIN_AUTH0: https://example.it
CLIENT_SECRET_AUTH: <client-secret-auth>
AUDIENCE_AUTH0: <audience>
CLIENT_ID_AUTH0: <client-id-auth>
CLIENT_SECRET_AUTH0: <client-secret-auth>
AUTH0_CLIENT_CLAIMS: https://example.com
AUDIENCE_AUTH0: https://example.com
GRANT_TYPE_AUTH0: client_credentials
MOCK_AUTH: false
MOCK_AUTH_EMAIL: dev@example.it


steps:
Expand Down
16 changes: 16 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ declare module 'fastify' {
interface FastifyInstance {
config: {
DATABASE_URL: string;
MOCK_AUTH: boolean;
MOCK_AUTH_EMAIL?: string;
CLIENT_ID_AUTH0?: string;
CLIENT_SECRET_AUTH0?: string;
DOMAIN_AUTH0?: string;
AUTH0_CLIENT_CLAIMS?: string;
AUDIENCE_AUTH0?: string;
CLIENT_SECRET_AUTH?: string;
GRANT_TYPE_AUTH0?: string;
};
}
}
Expand All @@ -27,6 +36,13 @@ const app: FastifyPluginAsync<AppOptions> = async (
dotenv: true,
schema: Type.Object({
DATABASE_URL: Type.String(),
MOCK_AUTH: Type.Boolean(),
CLIENT_ID_AUTH0: Type.String(),
CLIENT_SECRET_AUTH0: Type.String(),
DOMAIN_AUTH0: Type.String(),
AUTH0_CLIENT_CLAIMS: Type.RegEx(/^https?:/),
AUDIENCE_AUTH0: Type.RegEx(/^https?:/),
GRANT_TYPE_AUTH0: Type.String(),
}),
});

Expand Down
41 changes: 34 additions & 7 deletions apps/api/src/plugins/auth0.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import {User} from '@codeimage/prisma-models';
import {FastifyPluginAsync, FastifyReply, FastifyRequest} from 'fastify';
import fastifyAuth0Verify from 'fastify-auth0-verify';
import {
FastifyInstance,
FastifyPluginAsync,
FastifyReply,
FastifyRequest,
} from 'fastify';
import fastifyAuth0Verify, {Authenticate} from 'fastify-auth0-verify';
import fp from 'fastify-plugin';

declare module '@fastify/jwt/jwt' {
Expand All @@ -14,15 +19,37 @@ interface AuthorizeOptions {
mustBeAuthenticated: boolean;
}

export function mockAuthProvider(context: {email: string}) {
return fp(async (fastify: FastifyInstance) => {
const auth0Authenticate: Authenticate = async req => {
const email = context.email;
const clientClaim = fastify.config.AUTH0_CLIENT_CLAIMS;
const emailKey = `${clientClaim}/email`;
req.user = {
[emailKey]: email,
};
};

fastify.decorateRequest('user', null);
fastify.decorate('authenticate', auth0Authenticate);
});
}

export default fp<{authProvider?: FastifyPluginAsync}>(
async (fastify, options) => {
if (options.authProvider) {
if (fastify.config.MOCK_AUTH) {
await fastify.register(
mockAuthProvider({
email: fastify.config.MOCK_AUTH_EMAIL as string,
}),
);
} else if (options.authProvider) {
await fastify.register(options.authProvider);
} else {
await fastify.register(fastifyAuth0Verify, {
domain: process.env.DOMAIN_AUTH0,
secret: process.env.CLIENT_SECRET_AUTH,
audience: process.env.AUDIENCE_AUTH0,
domain: fastify.config.DOMAIN_AUTH0,
secret: fastify.config.CLIENT_SECRET_AUTH,
audience: fastify.config.AUDIENCE_AUTH0,
});
}

Expand All @@ -41,7 +68,7 @@ export default fp<{authProvider?: FastifyPluginAsync}>(
}
}

const emailClaim = `${process.env.AUTH0_CLIENT_CLAIMS}/email`;
const emailClaim = `${fastify.config.AUTH0_CLIENT_CLAIMS}/email`;

if (!req.user) {
req.appUserOptional = null;
Expand Down
19 changes: 2 additions & 17 deletions apps/api/test/helpers/auth0Mock.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,3 @@
import {FastifyInstance} from 'fastify';
import type {Authenticate} from 'fastify-auth0-verify';
import fp from 'fastify-plugin';
import {mockAuthProvider} from '../../src/plugins/auth0';

export const auth0Mock = (t: Tap.Test) =>
fp(async (fastify: FastifyInstance) => {
const user = t.context.user;

const auth0Authenticate: Authenticate = async req => {
const email = user?.email ?? 'test@example.it';
req.user = {
[`${process.env.AUTH0_CLIENT_CLAIMS}/email`]: email,
};
};

fastify.decorateRequest('user', null);
fastify.decorate('authenticate', auth0Authenticate);
});
export const auth0Mock = (t: Tap.Test) => mockAuthProvider(t.context.user);
65 changes: 63 additions & 2 deletions apps/api/test/plugins/auth0.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,34 @@ import auth0 from '../../src/plugins/auth0';
import prisma from '../../src/plugins/prisma';
import sensible from '../../src/plugins/sensible';

async function build(t: Tap.Test) {
interface AppOptions {
mockAuth: boolean;
}

process.env.AUTH0_CLIENT_CLAIMS = 'claims';
process.env.CLIENT_SECRET_AUTH = 'secret';
process.env.DOMAIN_AUTH0 = 'domain';
process.env.AUDIENCE_AUTH0 = 'audience';

async function build(t: Tap.Test, options: AppOptions = {mockAuth: false}) {
if (options.mockAuth) {
process.env.MOCK_AUTH = 'true';
process.env.MOCK_AUTH_EMAIL = 'dev@example.it';
}

const app = Fastify();
await void app.register(
fp(async app => {
await app.register(fastifyEnv, {
schema: Type.Object({DATABASE_URL: Type.String()}),
schema: Type.Object({
DATABASE_URL: Type.String(),
MOCK_AUTH: Type.Boolean(),
MOCK_AUTH_EMAIL: Type.String(),
AUTH0_CLIENT_CLAIMS: Type.String(),
CLIENT_SECRET_AUTH: Type.String(),
DOMAIN_AUTH0: Type.String(),
AUDIENCE_AUTH0: Type.String(),
}),
});
await app.register(sensible);
await app.register(prisma);
Expand All @@ -25,6 +47,7 @@ async function build(t: Tap.Test) {
{preValidation: (req, reply) => app.authorize(req, reply)},
async _ => ({
response: 'ok',
user: _.user,
appUser: _.appUser,
}),
);
Expand Down Expand Up @@ -145,3 +168,41 @@ t.test('should also sync user in db if not exists', async t => {
t.same(resObj.response, 'ok');
t.same(resObj.appUser?.email, 'email@example.it');
});

t.test('should mock auth', async t => {
const app = await build(t, {mockAuth: true});

const response = await app.inject({
method: 'GET',
url: '/',
});

sinon.stub(app.prisma.user, 'findFirst').resolves({
email: 'dev@example.it',
id: 'id',
createdAt: new Date(),
});

t.same(response.statusCode, 200);
t.sameStrict(response.json().user, {'claims/email': 'dev@example.it'});
t.same(response.json().appUser.email, 'dev@example.it');
});

t.test('should mock auth with env fallback', async t => {
const app = await build(t, {mockAuth: true});

const response = await app.inject({
method: 'GET',
url: '/',
});

sinon.stub(app.prisma.user, 'findFirst').resolves({
email: 'dev@example.it',
id: 'id',
createdAt: new Date(),
});

t.same(response.statusCode, 200);
t.sameStrict(response.json().user, {'claims/email': 'dev@example.it'});
t.same(response.json().appUser.email, 'dev@example.it');
});
1 change: 0 additions & 1 deletion apps/codeimage/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import './theme/light-theme.css';
const i18n = createI18nContext(locale);

if (import.meta.env.VITE_ENABLE_MSW) {
console.info('MSW Enabled');
import('./mocks/browser').then(({worker}) => worker.start());
}

Expand Down
20 changes: 20 additions & 0 deletions apps/codeimage/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,26 @@ export default defineConfig(({mode}) => ({
);
},
},
{
name: 'parse-environment-variables',

configResolved(resolvedConfig) {
const config = resolvedConfig as Omit<typeof resolvedConfig, 'env'> & {
env: typeof resolvedConfig['env'];
};
const env = config.env;
config.env = Object.keys(env).reduce((acc, key) => {
let parsed = config.env[key];
try {
parsed = JSON.parse(config.env[key]);
} catch {}
return {
...acc,
[key]: parsed,
};
}, {});
},
},
],
server: {
strictPort: true,
Expand Down
16 changes: 9 additions & 7 deletions scripts/make-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,14 @@ async function buildApiEnv() {

const env = {
DATABASE_URL: defaultDatabase,
CLIENT_ID_AUTH0: '',
CLIENT_SECRET_AUTH0: '',
DOMAIN_AUTH0: '',
AUTH0_CLIENT_CLAIMS: '',
AUDIENCE_AUTH0: '',
CLIENT_ID_AUTH0: 'clientId',
CLIENT_SECRET_AUTH0: 'clientSecret',
DOMAIN_AUTH0: 'dev',
AUTH0_CLIENT_CLAIMS: 'https://example.com/',
AUDIENCE_AUTH0: 'https://example.com/',
GRANT_TYPE_AUTH0: 'client_credentials',
MOCK_AUTH: true,
MOCK_AUTH_EMAIL: 'dev@example.it',
};

if (!runOnCodeSandbox) {
Expand Down Expand Up @@ -134,11 +135,12 @@ async function buildApiTestEnv() {
DATABASE_URL: defaultDatabase,
CLIENT_ID_AUTH0: '<client-id-auth>',
CLIENT_SECRET_AUTH0: '<client-secret-auth>',
DOMAIN_AUTH0: 'https://example.it',
AUTH0_CLIENT_CLAIMS: '',
DOMAIN_AUTH0: 'https://example.com',
AUTH0_CLIENT_CLAIMS: 'https://example.com',
AUDIENCE_AUTH0: '<audience>',
GRANT_TYPE_AUTH0: 'client_credentials',
MOCK_AUTH: false,
MOCK_AUTH_EMAIL: 'dev@example.it',
};

if (!runOnCodeSandbox) {
Expand Down