<commit_before>/*
Copyright 2020 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import '../../olm-loader';
import {
    CrossSigningInfo,
    createCryptoStoreCacheCallbacks,
} from '../../../src/crypto/CrossSigning';
import {
    IndexedDBCryptoStore,
} from '../../../src/crypto/store/indexeddb-crypto-store';
import {MemoryCryptoStore} from '../../../src/crypto/store/memory-crypto-store';
import 'fake-indexeddb/auto';
import 'jest-localstorage-mock';

const userId = "@alice:example.com";

// Private key for tests only
const testKey = new Uint8Array([
    0xda, 0x5a, 0x27, 0x60, 0xe3, 0x3a, 0xc5, 0x82,
    0x9d, 0x12, 0xc3, 0xbe, 0xe8, 0xaa, 0xc2, 0xef,
    0xae, 0xb1, 0x05, 0xc1, 0xe7, 0x62, 0x78, 0xa6,
    0xd7, 0x1f, 0xf8, 0x2c, 0x51, 0x85, 0xf0, 0x1d,
]);

const types = [
    { type: "master", shouldCache: false },
    { type: "self_signing", shouldCache: true },
    { type: "user_signing", shouldCache: true },
    { type: "invalid", shouldCache: false },
];

const badKey = Uint8Array.from(testKey);
badKey[0] ^= 1;

const masterKeyPub = "<KEY>";

describe("CrossSigningInfo.getCrossSigningKey", function() {
    if (!global.Olm) {
        console.warn('Not running megolm backup unit tests: libolm not present');
        return;
    }

    beforeAll(function() {
        return global.Olm.init();
    });

    it("should throw if no callback is provided", async () => {
        const info = new CrossSigningInfo(userId);
        await expect(info.getCrossSigningKey("master")).rejects.toThrow();
    });

    it.each(types)("should throw if the callback returns falsey",
                   async ({type, shouldCache}) => {
        const info = new CrossSigningInfo(userId, {
            getCrossSigningKey: () => false,
        });
        await expect(info.getCrossSigningKey(type)).rejects.toThrow("falsey");
    });

    it("should throw if the expected key doesn't come back", async () => {
        const info = new CrossSigningInfo(userId, {
            getCrossSigningKey: () => masterKeyPub,
        });
        await expect(info.getCrossSigningKey("master", "")).rejects.toThrow();
    });

    it("should return a key from its callback", async () => {
        const info = new CrossSigningInfo(userId, {
            getCrossSigningKey: () => testKey,
        });
        const [pubKey, ab] = await info.getCrossSigningKey("master", masterKeyPub);
        expect(pubKey).toEqual(masterKeyPub);
        expect(ab).toEqual({a: 106712, b: 106712});
    });

    it.each(types)("should request a key from the cache callback (if set)" +
                   " and does not call app if one is found" +
                   `%o`,
                   async ({ type, shouldCache }) => {
        const getCrossSigningKey = jest.fn().mockImplementation(() => {
            if (shouldCache) {
                return Promise.reject(new Error("Regular callback called"));
            } else {
                return Promise.resolve(testKey);
            }
        });
        const getCrossSigningKeyCache = jest.fn().mockResolvedValue(testKey);
        const info = new CrossSigningInfo(
            userId,
            { getCrossSigningKey },
            { getCrossSigningKeyCache },
        );
        const [pubKey] = await info.getCrossSigningKey(type, masterKeyPub);
        expect(pubKey).toEqual(masterKeyPub);
        expect(getCrossSigningKeyCache.mock.calls.length).toBe(shouldCache ? 1 : 0);
        if (shouldCache) {
            expect(getCrossSigningKeyCache.mock.calls[0][0]).toBe(type);
        }
    });
<commit_msg>proper spacing for test output text<commit_after>/*
Copyright 2020 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import '../../olm-loader';
import {
    CrossSigningInfo,
    createCryptoStoreCacheCallbacks,
} from '../../../src/crypto/CrossSigning';
import {
    IndexedDBCryptoStore,
} from '../../../src/crypto/store/indexeddb-crypto-store';
import {MemoryCryptoStore} from '../../../src/crypto/store/memory-crypto-store';
import 'fake-indexeddb/auto';
import 'jest-localstorage-mock';

const userId = "@alice:example.com";

// Private key for tests only
const testKey = new Uint8Array([
    0xda, 0x5a, 0x27, 0x60, 0xe3, 0x3a, 0xc5, 0x82,
    0x9d, 0x12, 0xc3, 0xbe, 0xe8, 0xaa, 0xc2, 0xef,
    0xae, 0xb1, 0x05, 0xc1, 0xe7, 0x62, 0x78, 0xa6,
    0xd7, 0x1f, 0xf8, 0x2c, 0x51, 0x85, 0xf0, 0x1d,
]);

const types = [
    { type: "master", shouldCache: false },
    { type: "self_signing", shouldCache: true },
    { type: "user_signing", shouldCache: true },
    { type: "invalid", shouldCache: false },
];

const badKey = Uint8Array.from(testKey);
badKey[0] ^= 1;

const masterKeyPub = "<KEY>";

describe("CrossSigningInfo.getCrossSigningKey", function() {
    if (!global.Olm) {
        console.warn('Not running megolm backup unit tests: libolm not present');
        return;
    }

    beforeAll(function() {
        return global.Olm.init();
    });

    it("should throw if no callback is provided", async () => {
        const info = new CrossSigningInfo(userId);
        await expect(info.getCrossSigningKey("master")).rejects.toThrow();
    });

    it.each(types)("should throw if the callback returns falsey",
                   async ({type, shouldCache}) => {
        const info = new CrossSigningInfo(userId, {
            getCrossSigningKey: () => false,
        });
        await expect(info.getCrossSigningKey(type)).rejects.toThrow("falsey");
    });

    it("should throw if the expected key doesn't come back", async () => {
        const info = new CrossSigningInfo(userId, {
            getCrossSigningKey: () => masterKeyPub,
        });
        await expect(info.getCrossSigningKey("master", "")).rejects.toThrow();
    });

    it("should return a key from its callback", async () => {
        const info = new CrossSigningInfo(userId, {
            getCrossSigningKey: () => testKey,
        });
        const [pubKey, ab] = await info.getCrossSigningKey("master", masterKeyPub);
        expect(pubKey).toEqual(masterKeyPub);
        expect(ab).toEqual({a: 106712, b: 106712});
    });

    it.each(types)("should request a key from the cache callback (if set)" +
                   " and does not call app if one is found" +
                   " %o",
                   async ({ type, shouldCache }) => {
        const getCrossSigningKey = jest.fn().mockImplementation(() => {
            if (shouldCache) {
                return Promise.reject(new Error("Regular callback called"));
            } else {
                return Promise.resolve(testKey);
            }
        });
        const getCrossSigningKeyCache = jest.fn().mockResolvedValue(testKey);
        const info = new CrossSigningInfo(
            userId,
            { getCrossSigningKey },
            { getCrossSigningKeyCache },
        );
        const [pubKey] = await info.getCrossSigningKey(type, masterKeyPub);
        expect(pubKey).toEqual(masterKeyPub);
        expect(getCrossSigningKeyCache.mock.calls.length).toBe(shouldCache ? 1 : 0);
        if (shouldCache) {
            expect(getCrossSigningKeyCache.mock.calls[0][0]).toBe(type);
        }
    });

{'fraction_non_alphanumeric': 0.12999139943482, 'fraction_numerical': 0.02359012163656469, 'mean_word_length': 2.773759851645804, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6803510', 'n_tokens_mistral': 2584, 'n_tokens_neox': 2471, 'n_words': 655}