All files / src/lib/db api-token-store.ts

80.95% Statements 51/63
100% Branches 12/12
71.43% Functions 15/21
80.65% Lines 50/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206    69x 69x   69x   69x           69x   69x 69x   69x                                 69x 34x 34x 31x                     34x 34x 8x 5x   8x 8x   34x     69x                 69x 81x 81x     69x               87x 87x 87x 79x                         21x 21x 21x 21x       58x 58x     58x 58x       81x                                     44x 44x         44x   40x     14x         44x 42x           42x                                       11x       23x       2x       2x 2x                                
import { EventEmitter } from 'events';
import { Knex } from 'knex';
import metricsHelper from '../util/metrics-helper';
import { DB_TIME } from '../metric-events';
import { Logger, LogProvider } from '../logger';
import NotFoundError from '../error/notfound-error';
import { IApiTokenStore } from '../types/stores/api-token-store';
import {
    ApiTokenType,
    IApiToken,
    IApiTokenCreate,
    isAllProjects,
} from '../types/models/api-token';
import { ALL_PROJECTS } from '../../lib/services/access-service';
 
const TABLE = 'api_tokens';
const API_LINK_TABLE = 'api_token_project';
 
const ALL = '*';
 
interface ITokenInsert {
    id: number;
    secret: string;
    username: string;
    type: ApiTokenType;
    expires_at?: Date;
    created_at: Date;
    seen_at?: Date;
    environment: string;
}
 
interface ITokenRow extends ITokenInsert {
    project: string;
}
 
const tokenRowReducer = (acc, tokenRow) => {
    const { project, ...token } = tokenRow;
    if (!acc[tokenRow.secret]) {
        acc[tokenRow.secret] = {
            secret: token.secret,
            username: token.username,
            type: token.type,
            project: ALL,
            projects: [ALL],
            environment: token.environment ? token.environment : ALL,
            expiresAt: token.expires_at,
            createdAt: token.created_at,
        };
    }
    const currentToken = acc[tokenRow.secret];
    if (tokenRow.project) {
        if (isAllProjects(currentToken.projects)) {
            currentToken.projects = [];
        }
        currentToken.projects.push(tokenRow.project);
        currentToken.project = currentToken.projects.join(',');
    }
    return acc;
};
 
const toRow = (newToken: IApiTokenCreate) => ({
    username: newToken.username,
    secret: newToken.secret,
    type: newToken.type,
    environment:
        newToken.environment === ALL ? undefined : newToken.environment,
    expires_at: newToken.expiresAt,
});
 
const toTokens = (rows: any[]): IApiToken[] => {
    const tokens = rows.reduce(tokenRowReducer, {});
    return Object.values(tokens);
};
 
export class ApiTokenStore implements IApiTokenStore {
    private logger: Logger;
 
    private timer: Function;
 
    private db: Knex;
 
    constructor(db: Knex, eventBus: EventEmitter, getLogger: LogProvider) {
        this.db = db;
        this.logger = getLogger('api-tokens.js');
        this.timer = (action: string) =>
            metricsHelper.wrapTimer(eventBus, DB_TIME, {
                store: 'api-tokens',
                action,
            });
    }
 
    count(): Promise<number> {
        return this.db(TABLE)
            .count('*')
            .then((res) => Number(res[0].count));
    }
 
    async getAll(): Promise<IApiToken[]> {
        const stopTimer = this.timer('getAll');
        const rows = await this.makeTokenProjectQuery();
        stopTimer();
        return toTokens(rows);
    }
 
    async getAllActive(): Promise<IApiToken[]> {
        const stopTimer = this.timer('getAllActive');
        const rows = await this.makeTokenProjectQuery()
            .where('expires_at', 'IS', null)
            .orWhere('expires_at', '>', 'now()');
        stopTimer();
        return toTokens(rows);
    }
 
    private makeTokenProjectQuery() {
        return this.db<ITokenRow>(`${TABLE} as tokens`)
            .leftJoin(
                `${API_LINK_TABLE} as token_project_link`,
                'tokens.secret',
                'token_project_link.secret',
            )
            .select(
                'tokens.secret',
                'username',
                'type',
                'expires_at',
                'created_at',
                'seen_at',
                'environment',
                'token_project_link.project',
            );
    }
 
    async insert(newToken: IApiTokenCreate): Promise<IApiToken> {
        const response = await this.db.transaction(async (tx) => {
            const [row] = await tx<ITokenInsert>(TABLE).insert(
                toRow(newToken),
                ['created_at'],
            );
 
            const updateProjectTasks = (newToken.projects || [])
                .filter((project) => {
                    return project !== ALL_PROJECTS;
                })
                .map((project) => {
                    return tx.raw(
                        `INSERT INTO ${API_LINK_TABLE} VALUES (?, ?)`,
                        [newToken.secret, project],
                    );
                });
            await Promise.all(updateProjectTasks);
            return {
                ...newToken,
                project: newToken.projects?.join(',') || '*',
                createdAt: row.created_at,
            };
        });
        return response;
    }
 
    destroy(): void {}
 
    async exists(secret: string): Promise<boolean> {
        const result = await this.db.raw(
            `SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE secret = ?) AS present`,
            [secret],
        );
        const { present } = result.rows[0];
        return present;
    }
 
    async get(key: string): Promise<IApiToken> {
        const row = await this.makeTokenProjectQuery().where('secret', key);
        return toTokens(row)[0];
    }
 
    async delete(secret: string): Promise<void> {
        return this.db<ITokenRow>(TABLE).where({ secret }).del();
    }
 
    async deleteAll(): Promise<void> {
        return this.db<ITokenRow>(TABLE).del();
    }
 
    async setExpiry(secret: string, expiresAt: Date): Promise<IApiToken> {
        const rows = await this.makeTokenProjectQuery()
            .update({ expires_at: expiresAt })
            .where({ secret })
            .returning('*');
        if (rows.length > 0) {
            return toTokens(rows)[0];
        }
        throw new NotFoundError('Could not find api-token.');
    }
 
    async markSeenAt(secrets: string[]): Promise<void> {
        const now = new Date();
        try {
            await this.db(TABLE)
                .whereIn('secrets', secrets)
                .update({ seen_at: now });
        } catch (err) {
            this.logger.error('Could not update lastSeen, error: ', err);
        }
    }
}