Skip to content
Draft
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
35 changes: 23 additions & 12 deletions src/background-safari/services/NativeAppService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import { NativeRequest } from "@web-eid.js/models/message/NativeRequest";
import NativeUnavailableError from "@web-eid.js/errors/NativeUnavailableError";
import { SerializedError } from "@web-eid.js/errors/SerializedError";
import { deserializeError } from "@web-eid.js/utils/errorSerializer";
import libraryConfig from "@web-eid.js/config";

Expand All @@ -30,9 +31,11 @@ import calculateJsonSize from "../../shared/utils/calculateJsonSize";
import config from "../../config";

type NativeAppPendingRequest =
| { resolve?: (value: PromiseLike<any>) => void; reject?: (reason?: any) => void }
| { reject?: (reason?: unknown) => void }
| null;

type NativeAppResponse<T extends object> = T | { error: SerializedError };

export enum NativeAppState {
UNINITIALIZED,
CONNECTING,
Expand Down Expand Up @@ -61,10 +64,10 @@ export default class NativeAppService {
libraryConfig.NATIVE_APP_HANDSHAKE_TIMEOUT,
);

browser.runtime.sendNativeMessage(
void browser.runtime.sendNativeMessage(
"application.id",
{ command: "status" },
(response) => resolve(response),
(response) => resolve(response as { version: string }),
);
});

Expand All @@ -90,45 +93,53 @@ export default class NativeAppService {
}
}

close(error?: any): void {
config.DEBUG && console.log("Disconnecting from native app");
close(error?: unknown): void {
if (config.DEBUG) {
console.log("Disconnecting from native app");
}
this.state = NativeAppState.DISCONNECTED;

this.pending?.reject?.(error);
this.pending = null;
}

async send<T>(message: NativeRequest, timeout: number, throwAfterTimeout: Error): Promise<T> {
async send<T extends object>(message: NativeRequest, timeout: number, throwAfterTimeout: Error): Promise<T> {
if (message.command == "quit") return {} as T;

switch (this.state) {
case NativeAppState.CONNECTED: {
const releaseLock = await commandMutex.acquire();

const sendPromise = new Promise<T>((resolve, reject) => {
this.pending = { resolve, reject };
this.pending = { reject };

setTimeout(() => { reject(throwAfterTimeout); }, timeout );

const onResponse = (message: any): void => {
const onResponse = (message: NativeAppResponse<T>): void => {
this.pending = null;

if (message.error) {
if ("error" in message) {
reject(deserializeError(message.error));
} else {
resolve(message);
}
};

config.DEBUG && console.log("Sending message to native app", JSON.stringify(message));
if (config.DEBUG) {
console.log("Sending message to native app", JSON.stringify(message));
}

const messageSize = calculateJsonSize(message);

if (messageSize > config.NATIVE_MESSAGE_MAX_BYTES) {
throw new Error(`native application message exceeded ${config.NATIVE_MESSAGE_MAX_BYTES} bytes`);
const error = new Error(`native application message exceeded ${config.NATIVE_MESSAGE_MAX_BYTES} bytes`);

this.close(error);
reject(error);
return;
}

browser.runtime.sendNativeMessage("application.id", message, onResponse);
void browser.runtime.sendNativeMessage("application.id", message, onResponse);
});

return sendPromise.finally(() => releaseLock());
Expand Down
18 changes: 12 additions & 6 deletions src/background/actions/TokenSigning/errorToResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,26 @@
*/

import ErrorCode from "@web-eid.js/errors/ErrorCode";

import { serializeError } from "@web-eid.js/utils/errorSerializer";

import { getErrorCode, toError } from "../../../shared/utils/error";

import { TokenSigningErrorResponse } from "../../../models/TokenSigning/TokenSigningResponse";

import tokenSigningResponse from "../../../shared/tokenSigningResponse";

export default function errorToResponse(nonce: string, error: any): TokenSigningErrorResponse {
if (error.code === ErrorCode.ERR_WEBEID_USER_CANCELLED) {
export default function errorToResponse(nonce: string, error: unknown): TokenSigningErrorResponse {
const errorCode = getErrorCode(error);

if (errorCode === ErrorCode.ERR_WEBEID_USER_CANCELLED) {
return tokenSigningResponse<TokenSigningErrorResponse>("user_cancel", nonce);
} else if (error.code === ErrorCode.ERR_WEBEID_NATIVE_FATAL ||
error.code === ErrorCode.ERR_WEBEID_NATIVE_INVALID_ARGUMENT) {
const nativeException = serializeError(error);
} else if (errorCode === ErrorCode.ERR_WEBEID_NATIVE_FATAL ||
errorCode === ErrorCode.ERR_WEBEID_NATIVE_INVALID_ARGUMENT) {
const nativeException = serializeError(toError(error));

return tokenSigningResponse<TokenSigningErrorResponse>("driver_error", nonce, { nativeException });
} else {
return tokenSigningResponse<TokenSigningErrorResponse>("technical_error", nonce, { error });
return tokenSigningResponse<TokenSigningErrorResponse>("technical_error", nonce, { error: serializeError(toError(error)) });
}
}
4 changes: 3 additions & 1 deletion src/background/actions/TokenSigning/getCertificate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ export default async function getCertificate(
try {
const nativeAppStatus = await nativeAppService.connect();

config.DEBUG && console.log("Get certificate: connected to native", nativeAppStatus);
if (config.DEBUG) {
console.log("Get certificate: connected to native", nativeAppStatus);
}

const message: NativeGetSigningCertificateRequest = {
command: "get-signing-certificate",
Expand Down
4 changes: 3 additions & 1 deletion src/background/actions/TokenSigning/sign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ export default async function sign(
const warnings: Array<string> = [];
const nativeAppStatus = await nativeAppService.connect();

config.DEBUG && console.log("Sign: connected to native", nativeAppStatus);
if (config.DEBUG) {
console.log("Sign: connected to native", nativeAppStatus);
}

let hashFunction = (
Object.keys(digestCommandToHashFunction).includes(algorithm)
Expand Down
223 changes: 223 additions & 0 deletions src/background/actions/__tests__/native-actions-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
/*
* Copyright (c) 2020-2026 Estonian Information System Authority
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import Action from "@web-eid.js/models/Action";
import ErrorCode from "@web-eid.js/errors/ErrorCode";
import UserCancelledError from "@web-eid.js/errors/UserCancelledError";

import {
NativeAuthenticateResponse,
NativeGetSigningCertificateResponse,
NativeSignResponse,
} from "@web-eid.js/models/message/NativeResponse";

import { MessageSender } from "../../../models/Browser/Runtime";
import NativeAppService from "../../services/NativeAppService";
import authenticate from "../authenticate";
import getSigningCertificate from "../getSigningCertificate";
import sign from "../sign";

const SENDER: MessageSender = {
tab: { id: 1 },
url: "https://example.com/path?query=1#fragment",
};

function mockNativeConnect(version = "2.4.1"): jest.SpyInstance {
return jest.spyOn(NativeAppService.prototype, "connect").mockResolvedValue({ version });
}

function mockNativeSend(response: object): jest.SpyInstance {
return jest.spyOn(NativeAppService.prototype, "send").mockResolvedValue(response);
}

describe("background native IPC actions", () => {
let closeSpy: jest.SpyInstance;
let consoleError: jest.SpyInstance;

beforeEach(() => {
closeSpy = jest.spyOn(NativeAppService.prototype, "close").mockImplementation(() => undefined);
consoleError = jest.spyOn(console, "error").mockImplementation(() => undefined);
});

afterEach(() => {
jest.restoreAllMocks();
});

it("sends authenticate request arguments to web-eid-app and maps the response", async () => {
mockNativeConnect("2.9.0+0");
const nativeResponse: NativeAuthenticateResponse = {
algorithm: "ES256",
appVersion: "https://web-eid.eu/web-eid-app/releases/2.9.0+0",
format: "web-eid:1.0",
signature: "base64-signature",
unverifiedCertificate: "base64-auth-certificate",
};
const sendSpy = mockNativeSend(nativeResponse);

const response = await authenticate(
"12345678123456781234567812345678912356789123",
SENDER,
"2.4.1",
12345,
"et"
);

expect(sendSpy).toHaveBeenCalledWith(
{
command: "authenticate",
arguments: {
challengeNonce: "12345678123456781234567812345678912356789123",
lang: "et",
origin: "https://example.com",
},
},
12345,
expect.objectContaining({ code: ErrorCode.ERR_WEBEID_USER_TIMEOUT })
);
expect(response).toEqual({
action: Action.AUTHENTICATE_SUCCESS,
...nativeResponse,
});
expect(closeSpy).toHaveBeenCalledTimes(1);
});

it("sends get-signing-certificate request arguments to web-eid-app and maps the response", async () => {
mockNativeConnect();
const nativeResponse: NativeGetSigningCertificateResponse = {
certificate: "base64-signing-certificate",
supportedSignatureAlgorithms: [
{
cryptoAlgorithm: "ECC",
hashFunction: "SHA-384",
paddingScheme: "NONE",
},
],
};
const sendSpy = mockNativeSend(nativeResponse);

const response = await getSigningCertificate(SENDER, "2.4.1", 12345, "en");

expect(sendSpy).toHaveBeenCalledWith(
{
command: "get-signing-certificate",
arguments: {
lang: "en",
origin: "https://example.com",
},
},
12345,
expect.objectContaining({ code: ErrorCode.ERR_WEBEID_USER_TIMEOUT })
);
expect(response).toEqual({
action: Action.GET_SIGNING_CERTIFICATE_SUCCESS,
...nativeResponse,
});
expect(closeSpy).toHaveBeenCalledTimes(1);
});

it("sends sign request arguments to web-eid-app and maps the response", async () => {
mockNativeConnect();
const nativeResponse: NativeSignResponse = {
signature: "base64-signature",
signatureAlgorithm: {
cryptoAlgorithm: "RSA",
hashFunction: "SHA-384",
paddingScheme: "PSS",
},
};
const sendSpy = mockNativeSend(nativeResponse);

const response = await sign(
"base64-signing-certificate",
"base64-document-hash",
"SHA-384",
SENDER,
"2.4.1",
12345,
"fi"
);

expect(sendSpy).toHaveBeenCalledWith(
{
command: "sign",
arguments: {
certificate: "base64-signing-certificate",
hash: "base64-document-hash",
hashFunction: "SHA-384",
lang: "fi",
origin: "https://example.com",
},
},
12345,
expect.objectContaining({ code: ErrorCode.ERR_WEBEID_USER_TIMEOUT })
);
expect(response).toEqual({
action: Action.SIGN_SUCCESS,
...nativeResponse,
});
expect(closeSpy).toHaveBeenCalledTimes(1);
});

it("maps native user cancellation to an extension failure response", async () => {
mockNativeConnect();
jest.spyOn(NativeAppService.prototype, "send").mockRejectedValue(
new UserCancelledError("User cancelled")
);

const response = await authenticate(
"12345678123456781234567812345678912356789123",
SENDER,
"2.4.1",
12345
);

expect(response).toEqual({
action: Action.AUTHENTICATE_FAILURE,
error: expect.objectContaining({
code: ErrorCode.ERR_WEBEID_USER_CANCELLED,
message: "User cancelled",
name: "UserCancelledError",
}),
});
expect(consoleError).toHaveBeenCalled();
expect(closeSpy).toHaveBeenCalledTimes(1);
});

it("maps native connection failures to extension failure responses before sending a request", async () => {
const connectError = new Error("missing native application port");
jest.spyOn(NativeAppService.prototype, "connect").mockRejectedValue(connectError);
const sendSpy = jest.spyOn(NativeAppService.prototype, "send");

const response = await getSigningCertificate(SENDER, "2.4.1", 12345);

expect(sendSpy).not.toHaveBeenCalled();
expect(response).toEqual({
action: Action.GET_SIGNING_CERTIFICATE_FAILURE,
error: expect.objectContaining({
code: ErrorCode.ERR_WEBEID_UNKNOWN_ERROR,
message: "missing native application port",
}),
});
expect(consoleError).toHaveBeenCalled();
expect(closeSpy).toHaveBeenCalledTimes(1);
});
});
8 changes: 6 additions & 2 deletions src/background/actions/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ export default async function authenticate(
nativeAppService = new NativeAppService();
nativeAppStatus = await nativeAppService.connect();

config.DEBUG && console.log("Authenticate: connected to native", nativeAppStatus);
if (config.DEBUG) {
console.log("Authenticate: connected to native", nativeAppStatus);
}

const message: NativeAuthenticateRequest = {
command: "authenticate",
Expand All @@ -67,7 +69,9 @@ export default async function authenticate(
new UserTimeoutError(),
);

config.DEBUG && console.log("Authenticate: authentication token received");
if (config.DEBUG) {
console.log("Authenticate: authentication token received");
}

const isResponseValid = (
response?.unverifiedCertificate &&
Expand Down
Loading
Loading