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(license-service): Barcode session #17541

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions apps/api/infra/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,8 @@ export const serviceSetup = (services: {
staging: 'island-is-assistant-feedback',
prod: 'island-is-assistant-feedback',
},
BARCODE_EXPIRE_TIME_IN_SEC: '60',
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800',
magnearun marked this conversation as resolved.
Show resolved Hide resolved
})

.secrets({
Expand Down
2 changes: 2 additions & 0 deletions apps/services/license-api/infra/license-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export const serviceSetup = (): ServiceBuilder<'license-api'> =>
staging: '1da72d52-a93a-4d0f-8463-1933a2bd210b',
prod: 'd4ecf781-3764-4063-a4e1-9c3e17cebfba',
},
BARCODE_EXPIRE_TIME_IN_SEC: '60',
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800',
})
.secrets({
SMART_SOLUTIONS_API_URL: '/k8s/api/SMART_SOLUTIONS_API_URL',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import { Cache } from 'cache-manager'
import * as faker from 'faker'

import ShortUniqueId from 'short-unique-id'
import { BARCODE_EXPIRE_TIME_IN_SEC } from '@island.is/services/license'
import { VerifyInputData } from '../dto/verifyLicense.input'
import { LicenseService } from '../license.service'
import {
Expand Down Expand Up @@ -226,6 +225,7 @@ export class MockUpdateClient extends BaseLicenseUpdateClient {
describe('LicenseService', () => {
let licenseService: LicenseService
let barcodeService: BarcodeService
let config: ConfigType<typeof LicenseConfig>

beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
Expand Down Expand Up @@ -294,6 +294,8 @@ describe('LicenseService', () => {

licenseService = moduleRef.get<LicenseService>(LicenseService)
barcodeService = moduleRef.get<BarcodeService>(BarcodeService)
config = moduleRef.get(LicenseConfig.KEY)

})

describe.each(licenseIds)('given %s license type id', (licenseId) => {
Expand Down Expand Up @@ -376,7 +378,7 @@ describe('LicenseService', () => {
await barcodeService.setCache(code, data)

// Let the token expire
jest.advanceTimersByTime(BARCODE_EXPIRE_TIME_IN_SEC * 1000)
jest.advanceTimersByTime(config.barcodeExpireTimeInSec * 1000)

// Assert
const result = await licenseService.verifyLicense({
Expand Down
2 changes: 2 additions & 0 deletions charts/islandis-services/api/values.dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ env:
AUTH_DELEGATION_API_URL: 'http://web-services-auth-delegation-api.identity-server-delegation.svc.cluster.local'
AUTH_IDS_API_URL: 'https://identity-server.dev01.devland.is'
AUTH_PUBLIC_API_URL: 'https://identity-server.dev01.devland.is/api'
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
magnearun marked this conversation as resolved.
Show resolved Hide resolved
COMPANY_REGISTRY_REDIS_NODES: '["clustercfg.general-redis-cluster-group.5fzau3.euw1.cache.amazonaws.com:6379"]'
COMPANY_REGISTRY_XROAD_PROVIDER_ID: 'IS-DEV/GOV/10006/Skatturinn/ft-v1'
CONSULTATION_PORTAL_CLIENT_BASE_PATH: 'https://samradapi-test.devland.is'
Expand Down
2 changes: 2 additions & 0 deletions charts/islandis-services/api/values.prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ env:
AUTH_DELEGATION_API_URL: 'https://auth-delegation-api.internal.innskra.island.is'
AUTH_IDS_API_URL: 'https://innskra.island.is'
AUTH_PUBLIC_API_URL: 'https://innskra.island.is/api'
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
COMPANY_REGISTRY_REDIS_NODES: '["clustercfg.general-redis-cluster-group.whakos.euw1.cache.amazonaws.com:6379"]'
COMPANY_REGISTRY_XROAD_PROVIDER_ID: 'IS/GOV/5402696029/Skatturinn/ft-v1'
CONSULTATION_PORTAL_CLIENT_BASE_PATH: 'https://samradapi.island.is'
Expand Down
2 changes: 2 additions & 0 deletions charts/islandis-services/api/values.staging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ env:
AUTH_DELEGATION_API_URL: 'http://web-services-auth-delegation-api.identity-server-delegation.svc.cluster.local'
AUTH_IDS_API_URL: 'https://identity-server.staging01.devland.is'
AUTH_PUBLIC_API_URL: 'https://identity-server.staging01.devland.is/api'
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
COMPANY_REGISTRY_REDIS_NODES: '["clustercfg.general-redis-cluster-group.ab9ckb.euw1.cache.amazonaws.com:6379"]'
COMPANY_REGISTRY_XROAD_PROVIDER_ID: 'IS-TEST/GOV/5402696029/Skatturinn/ft-v1'
CONSULTATION_PORTAL_CLIENT_BASE_PATH: 'https://samradapi-test.devland.is'
Expand Down
2 changes: 2 additions & 0 deletions charts/islandis-services/license-api/values.dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ global:
name: 'license-api'
enabled: true
env:
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
CODE_OWNER: 'hugsmidjan'
HUNTING_LICENSE_PASS_TEMPLATE_ID: '1da72d52-a93a-4d0f-8463-1933a2bd210b'
IDENTITY_SERVER_ISSUER_URL: 'https://identity-server.dev01.devland.is'
Expand Down
2 changes: 2 additions & 0 deletions charts/islandis-services/license-api/values.prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ global:
name: 'license-api'
enabled: true
env:
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
CODE_OWNER: 'hugsmidjan'
HUNTING_LICENSE_PASS_TEMPLATE_ID: 'd4ecf781-3764-4063-a4e1-9c3e17cebfba'
IDENTITY_SERVER_ISSUER_URL: 'https://innskra.island.is'
Expand Down
2 changes: 2 additions & 0 deletions charts/islandis-services/license-api/values.staging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ global:
name: 'license-api'
enabled: true
env:
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
CODE_OWNER: 'hugsmidjan'
HUNTING_LICENSE_PASS_TEMPLATE_ID: '1da72d52-a93a-4d0f-8463-1933a2bd210b'
IDENTITY_SERVER_ISSUER_URL: 'https://identity-server.staging01.devland.is'
Expand Down
4 changes: 4 additions & 0 deletions charts/islandis/values.dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@ api:
AUTH_DELEGATION_API_URL: 'http://web-services-auth-delegation-api.identity-server-delegation.svc.cluster.local'
AUTH_IDS_API_URL: 'https://identity-server.dev01.devland.is'
AUTH_PUBLIC_API_URL: 'https://identity-server.dev01.devland.is/api'
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
COMPANY_REGISTRY_REDIS_NODES: '["clustercfg.general-redis-cluster-group.5fzau3.euw1.cache.amazonaws.com:6379"]'
COMPANY_REGISTRY_XROAD_PROVIDER_ID: 'IS-DEV/GOV/10006/Skatturinn/ft-v1'
CONSULTATION_PORTAL_CLIENT_BASE_PATH: 'https://samradapi-test.devland.is'
Expand Down Expand Up @@ -1693,6 +1695,8 @@ island-ui-storybook:
license-api:
enabled: true
env:
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
CODE_OWNER: 'hugsmidjan'
HUNTING_LICENSE_PASS_TEMPLATE_ID: '1da72d52-a93a-4d0f-8463-1933a2bd210b'
IDENTITY_SERVER_ISSUER_URL: 'https://identity-server.dev01.devland.is'
Expand Down
4 changes: 4 additions & 0 deletions charts/islandis/values.prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,8 @@ api:
AUTH_DELEGATION_API_URL: 'https://auth-delegation-api.internal.innskra.island.is'
AUTH_IDS_API_URL: 'https://innskra.island.is'
AUTH_PUBLIC_API_URL: 'https://innskra.island.is/api'
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
COMPANY_REGISTRY_REDIS_NODES: '["clustercfg.general-redis-cluster-group.whakos.euw1.cache.amazonaws.com:6379"]'
COMPANY_REGISTRY_XROAD_PROVIDER_ID: 'IS/GOV/5402696029/Skatturinn/ft-v1'
CONSULTATION_PORTAL_CLIENT_BASE_PATH: 'https://samradapi.island.is'
Expand Down Expand Up @@ -1559,6 +1561,8 @@ island-ui-storybook:
license-api:
enabled: true
env:
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
CODE_OWNER: 'hugsmidjan'
HUNTING_LICENSE_PASS_TEMPLATE_ID: 'd4ecf781-3764-4063-a4e1-9c3e17cebfba'
IDENTITY_SERVER_ISSUER_URL: 'https://innskra.island.is'
Expand Down
4 changes: 4 additions & 0 deletions charts/islandis/values.staging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@ api:
AUTH_DELEGATION_API_URL: 'http://web-services-auth-delegation-api.identity-server-delegation.svc.cluster.local'
AUTH_IDS_API_URL: 'https://identity-server.staging01.devland.is'
AUTH_PUBLIC_API_URL: 'https://identity-server.staging01.devland.is/api'
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
COMPANY_REGISTRY_REDIS_NODES: '["clustercfg.general-redis-cluster-group.ab9ckb.euw1.cache.amazonaws.com:6379"]'
COMPANY_REGISTRY_XROAD_PROVIDER_ID: 'IS-TEST/GOV/5402696029/Skatturinn/ft-v1'
CONSULTATION_PORTAL_CLIENT_BASE_PATH: 'https://samradapi-test.devland.is'
Expand Down Expand Up @@ -1435,6 +1437,8 @@ island-ui-storybook:
license-api:
enabled: true
env:
BARCODE_EXPIRE_TIME_IN_SEC: '60'
BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
CODE_OWNER: 'hugsmidjan'
HUNTING_LICENSE_PASS_TEMPLATE_ID: '1da72d52-a93a-4d0f-8463-1933a2bd210b'
IDENTITY_SERVER_ISSUER_URL: 'https://identity-server.staging01.devland.is'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ import {
TOKEN_EXPIRED_ERROR,
} from '@island.is/services/license'
import { UserAgent } from '@island.is/nest/core'
import { ProblemError } from '@island.is/nest/problem'
import { ProblemType } from '@island.is/shared/problem'

const LOG_CATEGORY = 'license-service'

Expand Down Expand Up @@ -469,6 +471,30 @@ export class LicenseService {
)
}

getBarcodeSessionKey(licenseType: LicenseType, sub: string) {
return `${licenseType}-${sub}`
}
magnearun marked this conversation as resolved.
Show resolved Hide resolved

async checkBarcodeSession(barcodeSessionKey: string | undefined, user: User, licenseType: LicenseType) {
if (barcodeSessionKey) {
const activeBarcodeSession = await this.barcodeService.getSessionCache(
barcodeSessionKey,
)

if (activeBarcodeSession && activeBarcodeSession !== user.sid) {
// If the user has an active session for the license type, we should not create a new barcode
this.logger.info(
`User has an active session for license: ${licenseType}`,
)
magnearun marked this conversation as resolved.
Show resolved Hide resolved

throw new ProblemError({
type: ProblemType.BAD_SESSION,
title: `User has an active session for license type: ${licenseType}`,
})
}
}
}

async createBarcode(
user: User,
genericUserLicense: GenericUserLicense,
Expand All @@ -478,6 +504,12 @@ export class LicenseService {
const licenseType = this.mapLicenseType(genericUserLicenseType)
const client = await this.getClient<typeof licenseType>(licenseType)

const barcodeSessionKey = user.sub
? this.getBarcodeSessionKey(licenseType, user.sub)
: undefined

await this.checkBarcodeSession(barcodeSessionKey, user, licenseType)

if (
genericUserLicense.license.pkpassStatus !==
GenericUserLicensePkPassStatus.Available
Expand Down Expand Up @@ -518,6 +550,9 @@ export class LicenseService {
licenseType,
extraData,
}),
barcodeSessionKey &&
user.sid &&
this.barcodeService.setSessionCache(barcodeSessionKey, user.sid),
])

return tokenPayload
Expand Down
1 change: 1 addition & 0 deletions libs/auth-nest-tools/src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {

export interface Auth {
sub?: string
sid?: string
nationalId?: string
scope: string[]
authorization: string
Expand Down
1 change: 1 addition & 0 deletions libs/auth-nest-tools/src/lib/current-actor.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const getCurrentActor = (context: ExecutionContext): User => {
: {
...user.actor,
sub: user.sub,
sid: user.sid,
client: user.client,
authorization: user.authorization,
ip: user.ip,
Expand Down
1 change: 1 addition & 0 deletions libs/auth-nest-tools/src/lib/jwt.payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface JwtAct {

export interface JwtPayload {
sub?: string
sid?: string
nationalId?: string
scope: string | string[]
client_id: string
Expand Down
2 changes: 2 additions & 0 deletions libs/auth-nest-tools/src/lib/jwt.strategy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ describe('JwtStrategy#validate', () => {

fakePayload = {
nationalId: '1234567890',
sub: 'sub',
sid: 'sid',
scope: ['test-scope-1'],
client_id: 'test-client',
delegationType: [AuthDelegationType.Custom],
Expand Down
1 change: 1 addition & 0 deletions libs/auth-nest-tools/src/lib/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {

return {
sub: payload.sub,
sid: payload.sid,
nationalId: payload.nationalId,
scope: this.parseScopes(payload.scope),
client: payload.client_id,
Expand Down
1 change: 0 additions & 1 deletion libs/services/license/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ export {
BarcodeData,
LicenseTokenData,
TOKEN_EXPIRED_ERROR,
BARCODE_EXPIRE_TIME_IN_SEC,
} from './lib/barcode.service'
export { LicenseConfig } from './lib/license.config'
export { LICENSE_SERVICE_CACHE_MANAGER_PROVIDER } from './lib/licenseCache.provider'
23 changes: 18 additions & 5 deletions libs/services/license/src/lib/barcode.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import {
} from '@island.is/clients/license-client'
import { ConfigType } from '@nestjs/config'
import { Inject, Injectable } from '@nestjs/common'
import { Cache as CacheManager } from 'cache-manager'
import { Cache as CacheManager, Milliseconds } from 'cache-manager'
import { sign, VerifyOptions, verify } from 'jsonwebtoken'
import { LICENSE_SERVICE_CACHE_MANAGER_PROVIDER } from './licenseCache.provider'
import { LicenseConfig } from './license.config'

export const BARCODE_EXPIRE_TIME_IN_SEC = 60
export const TOKEN_EXPIRED_ERROR = 'TokenExpiredError'
export const BARCODE_ACTIVE_SESSION_KEY = 'activeSession'

/**
* License token data used to generate a license token
* The reason for the one letter fields is to keep the token as small as possible, since it will be used to generate barcodes
Expand Down Expand Up @@ -65,7 +66,7 @@ export class BarcodeService {
expiresIn: number
}> {
// jsonwebtoken uses seconds for expiration time
const exp = Math.floor(Date.now() / 1000) + BARCODE_EXPIRE_TIME_IN_SEC
const exp = Math.floor(Date.now() / 1000) + this.config.barcodeExpireTimeInSec

return new Promise((resolve, reject) =>
sign(
Expand All @@ -82,7 +83,7 @@ export class BarcodeService {

return resolve({
token: encoded,
expiresIn: BARCODE_EXPIRE_TIME_IN_SEC,
expiresIn: this.config.barcodeExpireTimeInSec,
})
},
),
Expand All @@ -93,7 +94,19 @@ export class BarcodeService {
key: string,
value: BarcodeData<Type>,
) {
return this.cacheManager.set(key, value, BARCODE_EXPIRE_TIME_IN_SEC * 1000)
return this.cacheManager.set(key, value, this.config.barcodeExpireTimeInSec * 1000)
}

async setSessionCache(key: string, value: string) {
return this.cacheManager.set(
`${BARCODE_ACTIVE_SESSION_KEY}:${key}`,
value,
this.config.barcodeSessionExpireTimeInSec * 1000,
)
}

async getSessionCache(key: string): Promise<string | undefined> {
return this.cacheManager.get(`${BARCODE_ACTIVE_SESSION_KEY}:${key}`)
}

async getCache<Type extends LicenseType>(
Expand Down
4 changes: 4 additions & 0 deletions libs/services/license/src/lib/license.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export const DEFAULT_CACHE_TTL = 1 * 1000 // 1 minute

const LicenseServiceConfigSchema = z.object({
barcodeSecretKey: z.string(),
barcodeExpireTimeInSec: z.number(),
barcodeSessionExpireTimeInSec: z.number(),
redis: z.object({
nodes: z.array(z.string()),
ssl: z.boolean(),
Expand All @@ -17,6 +19,8 @@ export const LicenseConfig = defineConfig({
schema: LicenseServiceConfigSchema,
load: (env) => ({
barcodeSecretKey: env.required('LICENSE_SERVICE_BARCODE_SECRET_KEY', ''),
barcodeExpireTimeInSec: env.requiredJSON('BARCODE_EXPIRE_TIME_IN_SEC', 60),
barcodeSessionExpireTimeInSec: env.requiredJSON('BARCODE_SESSION_EXPIRE_TIME_IN_SEC', 1800),
redis: {
nodes: env.requiredJSON('LICENSE_SERVICE_REDIS_NODES', [
'localhost:7000',
Expand Down
2 changes: 2 additions & 0 deletions libs/shared/problem/src/Problem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
BadSubjectProblem,
TemplateApiErrorProblem,
AttemptFailedProblem,
BadSessionProblem
} from './problems'

export type Problem =
Expand All @@ -14,3 +15,4 @@ export type Problem =
| BadSubjectProblem
| TemplateApiErrorProblem
| AttemptFailedProblem
| BadSessionProblem
1 change: 1 addition & 0 deletions libs/shared/problem/src/ProblemType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ export enum ProblemType {
BAD_SUBJECT = 'https://docs.devland.is/reference/problems/bad-subject',
TEMPLATE_API_ERROR = 'https://docs.devland.is/reference/problems/template-api-error',
ATTEMPT_FAILED = 'https://docs.devland.is/reference/problems/attempt-failed',
BAD_SESSION = 'https://docs.devland.is/reference/problems/bad-session',
}
3 changes: 3 additions & 0 deletions libs/shared/problem/src/problems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ export interface BadSubjectProblem extends BaseProblem {
type: ProblemType.BAD_SUBJECT
alternativeSubjects?: AlternativeSubject[]
}
export interface BadSessionProblem extends BaseProblem {
type: ProblemType.BAD_SESSION,
}

export interface AttemptFailedProblem extends BaseProblem {
type: ProblemType.ATTEMPT_FAILED
Expand Down
Loading