Skip to content

[TECH] Suppression du token d’accès aux résultats de campagne (PIX-16610) #11443

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

Merged
merged 1 commit into from
Feb 18, 2025
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
6 changes: 0 additions & 6 deletions api/sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -706,12 +706,6 @@ REFRESH_TOKEN_LIFESPAN=7d
# default: '7d'
SAML_ACCESS_TOKEN_LIFESPAN=7d

# Campaign result access token lifespan
# presence: optional
# type: string
# default: 1h
#CAMPAIGN_RESULT_ACCESS_TOKEN_LIFESPAN=

# ========
# TESTS
# ========
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import stream from 'node:stream';

import { tokenService } from '../../../shared/domain/services/token-service.js';
import { extractLocaleFromRequest } from '../../../shared/infrastructure/utils/request-response-utils.js';
import { escapeFileName } from '../../../shared/infrastructure/utils/request-response-utils.js';
import { usecases } from '../domain/usecases/index.js';
Expand Down Expand Up @@ -31,16 +30,13 @@ const getById = async function (
_,
dependencies = {
campaignReportSerializer,
tokenService,
},
) {
const { userId } = request.auth.credentials;
const { campaignId } = request.params;

const tokenForCampaignResults = dependencies.tokenService.createTokenForCampaignResults({ userId, campaignId });

const campaign = await usecases.getCampaign({ campaignId, userId });
return dependencies.campaignReportSerializer.serialize(campaign, {}, { tokenForCampaignResults });
return dependencies.campaignReportSerializer.serialize(campaign);
};

const getCampaignDetails = async function (request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import jsonapiSerializer from 'jsonapi-serializer';

const { Serializer } = jsonapiSerializer;

const serialize = function (campaignReports, meta, { tokenForCampaignResults } = {}) {
const serialize = function (campaignReports, meta) {
return new Serializer('campaign', {
transform: (record) => {
const campaign = Object.assign({}, record);
campaign.tokenForCampaignResults = tokenForCampaignResults;
campaign.isArchived = record.isArchived;
return campaign;
},
Expand All @@ -18,7 +17,6 @@ const serialize = function (campaignReports, meta, { tokenForCampaignResults } =
'createdAt',
'customLandingPageText',
'isArchived',
'tokenForCampaignResults',
'externalIdLabel',
'externalIdType',
'targetProfileId',
Expand Down
1 change: 0 additions & 1 deletion api/src/shared/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,6 @@ const configuration = (function () {
accessTokenLifespanMs: ms(process.env.ACCESS_TOKEN_LIFESPAN || '20m'),
refreshTokenLifespanMs: ms(process.env.REFRESH_TOKEN_LIFESPAN || '7d'),
revokedUserAccessLifespanMs: ms(process.env.REVOKED_USER_ACCESS_LIFESPAN || '7d'),
tokenForCampaignResultLifespan: process.env.CAMPAIGN_RESULT_ACCESS_TOKEN_LIFESPAN || '1h',
tokenForStudentReconciliationLifespan: '1h',
passwordResetTokenLifespan: '1h',
},
Expand Down
1 change: 0 additions & 1 deletion api/src/shared/config.maddo.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,6 @@ const configuration = (function () {
'pix-admin': ms(process.env.REFRESH_TOKEN_LIFESPAN_PIX_ADMIN || '7d'),
},
revokedUserAccessLifespanMs: ms(process.env.REVOKED_USER_ACCESS_LIFESPAN || '7d'),
tokenForCampaignResultLifespan: process.env.CAMPAIGN_RESULT_ACCESS_TOKEN_LIFESPAN || '1h',
tokenForStudentReconciliationLifespan: '1h',
passwordResetTokenLifespan: '1h',
},
Expand Down
24 changes: 0 additions & 24 deletions api/src/shared/domain/services/token-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import jsonwebtoken from 'jsonwebtoken';

import { config } from '../../../../src/shared/config.js';
import {
ForbiddenAccess,
InvalidExternalUserTokenError,
InvalidResultRecipientTokenError,
InvalidSessionResultTokenError,
Expand Down Expand Up @@ -51,17 +50,6 @@ function createAccessTokenFromApplication(
);
}

function createTokenForCampaignResults({ userId, campaignId }) {
return jsonwebtoken.sign(
{
access_id: userId,
campaign_id: campaignId,
},
config.authentication.secret,
{ expiresIn: config.authentication.tokenForCampaignResultLifespan },
);
}

function createIdTokenForUserReconciliation(externalUser) {
return jsonwebtoken.sign(
{
Expand Down Expand Up @@ -187,14 +175,6 @@ function extractClientId(token, secret = config.authentication.secret) {
return decoded.client_id || null;
}

function extractCampaignResultsTokenContent(token) {
const decoded = getDecodedToken(token);
if (decoded === false) {
throw new ForbiddenAccess();
}
return { userId: decoded.access_id, campaignId: decoded.campaign_id };
}

async function extractExternalUserFromIdToken(token) {
const externalUser = await getDecodedToken(token);

Expand All @@ -215,7 +195,6 @@ const tokenService = {
createAccessTokenForSaml,
createAccessTokenFromApplication,
createAccessTokenFromAnonymousUser,
createTokenForCampaignResults,
createIdTokenForUserReconciliation,
createCertificationResultsByRecipientEmailLinkToken,
createCertificationResultsLinkToken,
Expand All @@ -229,7 +208,6 @@ const tokenService = {
extractTokenFromAuthChain,
extractUserId,
extractClientId,
extractCampaignResultsTokenContent,
};

/**
Expand All @@ -245,9 +223,7 @@ export {
createCertificationResultsLinkToken,
createIdTokenForUserReconciliation,
createPasswordResetToken,
createTokenForCampaignResults,
decodeIfValid,
extractCampaignResultsTokenContent,
extractCertificationResultsByRecipientEmailLink,
extractCertificationResultsLink,
extractClientId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ describe('Unit | Application | Controller | Campaign detail', function () {

let request, campaign;
let campaignReportSerializerStub;
let tokenServiceStub;

beforeEach(function () {
campaign = {
Expand All @@ -62,28 +61,22 @@ describe('Unit | Application | Controller | Campaign detail', function () {
campaignReportSerializerStub = {
serialize: sinon.stub(),
};
tokenServiceStub = { createTokenForCampaignResults: sinon.stub().returns('token') };
usecases.getCampaign.resolves(campaign);
});

it('should return the campaign', async function () {
// given
const expectedResult = Symbol('ok');
const tokenForCampaignResults = 'token';
campaignReportSerializerStub.serialize
.withArgs(campaign, {}, { tokenForCampaignResults })
.returns(expectedResult);
campaignReportSerializerStub.serialize.withArgs(campaign).returns(expectedResult);

const dependencies = {
campaignReportSerializer: campaignReportSerializerStub,
tokenService: tokenServiceStub,
};
// when
const response = await campaignDetailController.getById(request, hFake, dependencies);

// then
expect(usecases.getCampaign).calledWith({ campaignId, userId });
expect(tokenServiceStub.createTokenForCampaignResults).to.have.been.calledWithExactly({ userId, campaignId });
expect(response).to.deep.equal(expectedResult);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ describe('Unit | Serializer | JSONAPI | campaign-report-serializer', function ()
'target-profile-tubes-count': report.targetProfileTubesCount,
'target-profile-thematic-result-count': report.targetProfileThematicResultCount,
'target-profile-are-knowledge-elements-resettable': report.targetProfileAreKnowledgeElementsResettable,
'token-for-campaign-results': report.tokenForCampaignResults,
'participations-count': report.participationsCount,
'shared-participations-count': report.sharedParticipationsCount,
'average-result': report.averageResult,
Expand Down
56 changes: 0 additions & 56 deletions api/tests/shared/unit/domain/services/token-service_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import jsonwebtoken from 'jsonwebtoken';

import { config, config as settings } from '../../../../../src/shared/config.js';
import {
ForbiddenAccess,
InvalidExternalUserTokenError,
InvalidResultRecipientTokenError,
InvalidSessionResultTokenError,
Expand All @@ -14,32 +13,6 @@ import { tokenService } from '../../../../../src/shared/domain/services/token-se
import { catchErr, expect, sinon } from '../../../../test-helper.js';

describe('Unit | Shared | Domain | Services | Token Service', function () {
describe('#createTokenForCampaignResults', function () {
it('should create an access token with user id and campaign id', function () {
// given
const generatedAccessToken = 'Valid-Access-Token';
const userId = 123;
const campaignId = 456;

sinon.stub(settings.authentication, 'secret').value('a secret');
sinon.stub(settings.authentication, 'tokenForCampaignResultLifespan').value(10);
sinon.stub(jsonwebtoken, 'sign').returns(generatedAccessToken);

// when
const accessTokenForCampaignResults = tokenService.createTokenForCampaignResults({ userId, campaignId });

// then
expect(accessTokenForCampaignResults).to.equal(generatedAccessToken);
expect(jsonwebtoken.sign).to.have.been.calledWithExactly(
{ access_id: userId, campaign_id: campaignId },
'a secret',
{
expiresIn: 10,
},
);
});
});

describe('#createAccessTokenFromUser', function () {
it('should create access token with user id and source', function () {
// given
Expand Down Expand Up @@ -169,35 +142,6 @@ describe('Unit | Shared | Domain | Services | Token Service', function () {
});
});

describe('#extractCampaignResultsTokenContent', function () {
context('valid token', function () {
it('should return userId and campaignId if the accessToken is valid', function () {
// given
const accessToken = tokenService.createTokenForCampaignResults({ userId: 123, campaignId: 456 });

// when
const { userId, campaignId } = tokenService.extractCampaignResultsTokenContent(accessToken);

// then
expect(userId).to.equal(123);
expect(campaignId).to.equal(456);
});
});

context('invalid token', function () {
it('should return null', async function () {
// given
const accessToken = 'WRONG_DATA';

// when
const error = await catchErr(tokenService.extractCampaignResultsTokenContent)(accessToken);

// then
expect(error).to.be.an.instanceof(ForbiddenAccess);
});
});
});

describe('#decodeIfValid', function () {
it('should throw an Invalid token error, when token is not valid', async function () {
// given
Expand Down
1 change: 0 additions & 1 deletion orga/app/models/campaign.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export default class Campaign extends Model {
@attr('nullable-string') externalIdLabel;
@attr('string') externalIdType;
@attr('nullable-text') customLandingPageText;
@attr('string') tokenForCampaignResults;
@attr('number') ownerId;
@attr('string') ownerLastName;
@attr('string') ownerFirstName;
Expand Down
2 changes: 0 additions & 2 deletions orga/tests/unit/models/campaign-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ module('Unit | Model | campaign', function (hooks) {
id: '1',
name: 'Fake name',
code: 'ABC123',
tokenForCampaignResults: 'token',
type: 'ASSESSMENT',
});
assert.strictEqual(model.urlToResult, 'http://localhost:3000/api/campaigns/1/csv-assessment-results');
Expand All @@ -35,7 +34,6 @@ module('Unit | Model | campaign', function (hooks) {
id: '1',
name: 'Fake name',
code: 'ABC123',
tokenForCampaignResults: 'token',
type: 'PROFILES_COLLECTION',
});
assert.strictEqual(model.urlToResult, 'http://localhost:3000/api/campaigns/1/csv-profiles-collection-results');
Expand Down