mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
feat(native): client certificates for servers behind mutual TLS
A proxy in front of TREK (Cloudflare, nginx, Caddy, Traefik, HAProxy) can let in only devices that show a client certificate. The apps could not, so such a server was unusable from them. - Address screen: the server check runs natively and notices when the server asks for a certificate. Instead of "no server answered" it says so and offers to add a .p12/.pfx file; a wrong password asks again, an expired, not yet valid or keyless file is named as such. - The certificate is shown only to the host and port it was added for. iOS keeps it in the keychain (this device only), Android seals the key with an Android Keystore key. The file's password is never stored. - The web view answers the server's certificate request on both platforms; WebSocket, service worker and API requests go through with it. The offline copy, watch requests and the check use it too. - When the server stops letting the app in (certificate removed, expired or no longer trusted) while the page still comes from the service worker or the offline copy, a native check sends the app to the address screen, which offers to add another. A server that only asks and lets everyone in is left alone. - Cloudflare-style 403 and nginx-style 400 refusals without a certificate lead to the same screen instead of staying up as an error page. - Settings, Account: a Client certificate card (only with one stored) shows subject, issuer, server and expiry, with Replace and Remove. - Wiki: Native-Apps "Client certificates (mTLS)" with Cloudflare, nginx, Caddy and Traefik setup and how to make a certificate for the app. - The app icon on the unreachable screen is black on the light surface.
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import {
|
||||
certificateTarget,
|
||||
clientCertificateSupported,
|
||||
removeClientCertificate,
|
||||
replaceClientCertificate,
|
||||
storedClientCertificate,
|
||||
} from './clientCertificate';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() }));
|
||||
vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() }));
|
||||
vi.mock('./trekShell', () => ({
|
||||
TrekShell: {
|
||||
clientCertificate: vi.fn(),
|
||||
importClientCertificate: vi.fn(),
|
||||
removeClientCertificate: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const info = { host: 'trek.example.com', port: 443, subject: 'phone', issuer: 'Home CA', notAfter: 1 };
|
||||
const labels = { title: 't', message: 'm', placeholder: 'p', ok: 'o', cancel: 'c', wrongPassword: 'w' };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(true);
|
||||
});
|
||||
|
||||
describe('clientCertificate', () => {
|
||||
it('asks the binary only where it can hold a certificate', async () => {
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(false);
|
||||
expect(clientCertificateSupported()).toBe(false);
|
||||
expect(await storedClientCertificate()).toBeNull();
|
||||
expect(TrekShell.clientCertificate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns the stored certificate, and none when the binary fails', async () => {
|
||||
vi.mocked(TrekShell.clientCertificate).mockResolvedValueOnce({ certificate: info });
|
||||
expect(await storedClientCertificate()).toEqual(info);
|
||||
vi.mocked(TrekShell.clientCertificate).mockRejectedValueOnce(new Error('gone'));
|
||||
expect(await storedClientCertificate()).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a certificate for the https host and port of the server, never for plain http', () => {
|
||||
expect(certificateTarget('https://Trek.Example.com/')).toEqual({ host: 'trek.example.com', port: 443 });
|
||||
expect(certificateTarget('https://nas.local:8443/trek')).toEqual({ host: 'nas.local', port: 8443 });
|
||||
expect(certificateTarget('http://nas.local:3001')).toBeNull();
|
||||
expect(certificateTarget('not a url')).toBeNull();
|
||||
});
|
||||
|
||||
it('imports for the server shown and reports a failed call as a store failure', async () => {
|
||||
vi.mocked(TrekShell.importClientCertificate).mockResolvedValueOnce({ result: 'imported', certificate: info });
|
||||
await replaceClientCertificate('https://trek.example.com:8443', labels);
|
||||
expect(TrekShell.importClientCertificate).toHaveBeenCalledWith({ host: 'trek.example.com', port: 8443, labels });
|
||||
|
||||
vi.mocked(TrekShell.importClientCertificate).mockRejectedValueOnce(new Error('no picker'));
|
||||
expect(await replaceClientCertificate('https://trek.example.com', labels)).toEqual({
|
||||
result: 'failed',
|
||||
failure: 'store',
|
||||
});
|
||||
expect(await replaceClientCertificate('http://trek.example.com', labels)).toEqual({
|
||||
result: 'failed',
|
||||
failure: 'format',
|
||||
});
|
||||
});
|
||||
|
||||
it('says whether removing worked', async () => {
|
||||
vi.mocked(TrekShell.removeClientCertificate).mockResolvedValueOnce();
|
||||
expect(await removeClientCertificate()).toBe(true);
|
||||
vi.mocked(TrekShell.removeClientCertificate).mockRejectedValueOnce(new Error('keychain'));
|
||||
expect(await removeClientCertificate()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import {
|
||||
TrekShell,
|
||||
type ClientCertificateImport,
|
||||
type ClientCertificateInfo,
|
||||
type ClientCertificateLabels,
|
||||
} from './trekShell';
|
||||
|
||||
/**
|
||||
* The client certificate the app shows to a server behind mutual TLS (a proxy
|
||||
* such as Cloudflare, nginx, Caddy or Traefik that lets in only devices with
|
||||
* one). The address screen adds it when the server asks; the settings show,
|
||||
* replace and remove it. The binary keeps it (TrekClientIdentity on iOS and
|
||||
* Android) and shows it to the one host and port it was added for.
|
||||
*/
|
||||
|
||||
export function clientCertificateSupported(): boolean {
|
||||
return hasNativeFeature('clientCertificate');
|
||||
}
|
||||
|
||||
/** The stored certificate, or null when there is none or the binary cannot hold one. */
|
||||
export async function storedClientCertificate(): Promise<ClientCertificateInfo | null> {
|
||||
if (!clientCertificateSupported()) return null;
|
||||
try {
|
||||
const { certificate } = await TrekShell.clientCertificate();
|
||||
return certificate ?? null;
|
||||
} catch (err) {
|
||||
reportNativeFailure(err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Host and port a certificate for this server address is kept for; null for a plain http server. */
|
||||
export function certificateTarget(serverUrl: string): { host: string; port: number } | null {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(serverUrl);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (url.protocol !== 'https:' || !url.hostname) return null;
|
||||
return { host: url.hostname.toLowerCase(), port: url.port ? Number(url.port) : 443 };
|
||||
}
|
||||
|
||||
/** Picks a certificate file for the server the app shows and keeps it in place of the stored one. */
|
||||
export async function replaceClientCertificate(
|
||||
serverUrl: string,
|
||||
labels: ClientCertificateLabels
|
||||
): Promise<ClientCertificateImport> {
|
||||
const target = certificateTarget(serverUrl);
|
||||
if (!target) return { result: 'failed', failure: 'format' };
|
||||
try {
|
||||
return await TrekShell.importClientCertificate({ ...target, labels });
|
||||
} catch (err) {
|
||||
reportNativeFailure(err);
|
||||
return { result: 'failed', failure: 'store' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeClientCertificate(): Promise<boolean> {
|
||||
try {
|
||||
await TrekShell.removeClientCertificate();
|
||||
return true;
|
||||
} catch (err) {
|
||||
reportNativeFailure(err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,9 @@ export const SERVER_DOCS_URL = 'https://github.com/liketrek/TREK#readme';
|
||||
/** Running the app with a sign-in proxy (Cloudflare Access, Pangolin and the like) in front of TREK. */
|
||||
export const AUTH_PROXY_DOCS_URL = 'https://github.com/liketrek/TREK/wiki/Native-Apps#behind-a-sign-in-proxy';
|
||||
|
||||
/** Adding a client certificate for a server behind mutual TLS (Cloudflare, nginx, Caddy, Traefik). */
|
||||
export const CLIENT_CERT_DOCS_URL = 'https://github.com/liketrek/TREK/wiki/Native-Apps#client-certificates-mtls';
|
||||
|
||||
/** The public demo the address screen offers to someone without a server. */
|
||||
export const DEMO_SERVER_URL = 'https://demo.liketrek.com';
|
||||
|
||||
|
||||
@@ -141,3 +141,53 @@ describe('probeServer behind a sign-in proxy', () => {
|
||||
expect(await probeServer('https://x.example.com', get)).toEqual({ ok: false, reason: 'notTrek' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeServer behind mutual TLS', () => {
|
||||
const asked = (status: number, sent: boolean, data: unknown = ''): ProbeResponse => ({
|
||||
status,
|
||||
data,
|
||||
url: 'https://trek.example.com/api/health/features',
|
||||
clientCert: { requested: true, sent },
|
||||
});
|
||||
|
||||
it('names a handshake the proxy broke off for want of a certificate, with the host to add one for', async () => {
|
||||
const get = vi.fn().mockResolvedValue(asked(0, false));
|
||||
expect(await probeServer('trek.example.com', get)).toEqual({
|
||||
ok: false,
|
||||
reason: 'clientCert',
|
||||
url: 'https://trek.example.com',
|
||||
cert: { host: 'trek.example.com', port: 443, sent: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("names Cloudflare's 403 without a certificate the same way, port included", async () => {
|
||||
const get = vi.fn().mockResolvedValue(asked(403, false, 'Access denied'));
|
||||
const result = await probeServer('https://Trek.Example.com:8443', get);
|
||||
expect(result.reason).toBe('clientCert');
|
||||
expect(result.cert).toEqual({ host: 'trek.example.com', port: 8443, sent: false });
|
||||
});
|
||||
|
||||
it('says the proxy refused the certificate the app showed', async () => {
|
||||
const get = vi.fn().mockResolvedValue(asked(400, true, '400 The SSL certificate error'));
|
||||
expect((await probeServer('https://trek.example.com', get)).cert?.sent).toBe(true);
|
||||
});
|
||||
|
||||
it('connects where the proxy asked and TREK answered, with or without a certificate', async () => {
|
||||
const trek = { bookingImport: false, nativeApp: true, nativeApi: 1 };
|
||||
for (const sent of [true, false]) {
|
||||
const get = vi.fn().mockResolvedValue(asked(200, sent, trek));
|
||||
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a failed connection without an ask unreachable, and ranks the ask above it', async () => {
|
||||
const down = vi.fn().mockResolvedValue({ status: 0, data: '', url: 'https://trek.example.com' });
|
||||
expect(await probeServer('https://trek.example.com', down)).toEqual({ ok: false, reason: 'unreachable' });
|
||||
|
||||
const mixed = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(asked(0, false))
|
||||
.mockResolvedValueOnce({ status: 0, data: '', url: 'http://trek.example.com' });
|
||||
expect((await probeServer('trek.example.com', mixed)).reason).toBe('clientCert');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,14 +6,27 @@ import { DEMO_SERVER_URL } from './links';
|
||||
* can load, or a reason it cannot.
|
||||
*/
|
||||
|
||||
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'authGate' | 'tooOld';
|
||||
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'authGate' | 'clientCert' | 'tooOld';
|
||||
|
||||
/**
|
||||
* A proxy in front of the server asked for a client certificate (mutual TLS)
|
||||
* and let the check through without one. `sent`: the app showed its stored
|
||||
* certificate and the proxy refused it all the same.
|
||||
*/
|
||||
export interface ClientCertDemand {
|
||||
host: string;
|
||||
port: number;
|
||||
sent: boolean;
|
||||
}
|
||||
|
||||
type ProbeResult =
|
||||
| { ok: true; url: string; reason?: undefined; gate?: undefined }
|
||||
| { ok: true; url: string; reason?: undefined; gate?: undefined; cert?: undefined }
|
||||
/**
|
||||
* `authGate`: a sign-in page of the user's own stands in front of TREK
|
||||
* (authGate.ts); `url` is the server address it guards.
|
||||
* (authGate.ts); `url` is the server address it guards. `clientCert`: a proxy
|
||||
* wants a client certificate, `cert` says for which host and whether one was shown.
|
||||
*/
|
||||
| { ok: false; reason: ProbeFailure; url?: string; gate?: AuthGate };
|
||||
| { ok: false; reason: ProbeFailure; url?: string; gate?: AuthGate; cert?: ClientCertDemand };
|
||||
|
||||
export interface ProbeResponse {
|
||||
status: number;
|
||||
@@ -21,6 +34,8 @@ export interface ProbeResponse {
|
||||
/** The URL after redirects. */
|
||||
url: string;
|
||||
headers?: Record<string, string>;
|
||||
/** Whether the server asked for a client certificate, and whether the app showed one (native requests only). */
|
||||
clientCert?: { requested: boolean; sent: boolean };
|
||||
}
|
||||
export type ProbeGet = (url: string) => Promise<ProbeResponse>;
|
||||
|
||||
@@ -74,7 +89,25 @@ function judge(response: ProbeResponse): ProbeResult {
|
||||
return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' };
|
||||
}
|
||||
|
||||
const FAILURE_RANK: Record<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, authGate: 3, tooOld: 4 };
|
||||
const FAILURE_RANK: Record<ProbeFailure, number> = {
|
||||
invalid: 0,
|
||||
unreachable: 1,
|
||||
notTrek: 2,
|
||||
authGate: 3,
|
||||
clientCert: 4,
|
||||
tooOld: 5,
|
||||
};
|
||||
|
||||
/**
|
||||
* A server that asked for a client certificate and did not answer with TREK:
|
||||
* the TLS handshake failed (status 0, as nginx, Caddy and Traefik do), or the
|
||||
* proxy answered with its own refusal (Cloudflare's 403, nginx's 400).
|
||||
*/
|
||||
function clientCertDemand(candidate: string, response: ProbeResponse): ClientCertDemand | null {
|
||||
if (!response.clientCert?.requested) return null;
|
||||
const url = new URL(candidate);
|
||||
return { host: url.hostname.toLowerCase(), port: url.port ? Number(url.port) : 443, sent: response.clientCert.sent };
|
||||
}
|
||||
|
||||
/**
|
||||
* A gate that did not send the check to its sign-in page (an API path can get a
|
||||
@@ -105,9 +138,12 @@ export async function probeServer(input: string, get: ProbeGet): Promise<ProbeRe
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
let verdict = judge(response);
|
||||
const cert = clientCertDemand(candidate, response);
|
||||
let verdict = response.status === 0 && !cert ? ({ ok: false, reason: 'unreachable' } as const) : judge(response);
|
||||
if (verdict.ok) return { ok: true, url: verdict.url || candidate };
|
||||
if (verdict.reason === 'notTrek') {
|
||||
if (cert) {
|
||||
verdict = { ok: false, reason: 'clientCert', url: candidate, cert };
|
||||
} else if (verdict.reason === 'notTrek') {
|
||||
const gate = detectAuthGate(candidate + FEATURES_PATH, response);
|
||||
if (gate)
|
||||
verdict = { ok: false, reason: 'authGate', url: candidate, gate: await withLoginHost(candidate, gate, get) };
|
||||
|
||||
@@ -119,6 +119,33 @@ export interface TrekShellPlugin {
|
||||
addToGoogleWallet(options: { url: string }): Promise<{ result: 'opened' }>;
|
||||
/** Android, feature windowLayout: the window's size classes and a foldable's posture and hinge. */
|
||||
getWindowLayout(): Promise<NativeWindowLayout>;
|
||||
/**
|
||||
* Feature clientCertificate: a GET against the user's server for the address
|
||||
* screen, made natively. It shows the stored client certificate to that server
|
||||
* when asked and reports whether the server asked (`certRequested`) and got
|
||||
* one (`certSent`). A failed connection resolves with status 0.
|
||||
*/
|
||||
requestServer(options: { url: string; timeoutMs?: number }): Promise<NativeServerResponse>;
|
||||
/**
|
||||
* Feature clientCertificate: the stored client certificate, or null, and the
|
||||
* last server that asked for one while the app ran (`served`: it got one).
|
||||
*/
|
||||
clientCertificate(): Promise<{
|
||||
certificate: ClientCertificateInfo | null;
|
||||
request?: { host: string; port: number; served: boolean };
|
||||
}>;
|
||||
/**
|
||||
* Feature clientCertificate: picks a .p12/.pfx file, asks for its password
|
||||
* (with `labels`, the UI's words) until it opens, and keeps it for the server
|
||||
* at host and port, replacing any other.
|
||||
*/
|
||||
importClientCertificate(options: {
|
||||
host: string;
|
||||
port: number;
|
||||
labels: ClientCertificateLabels;
|
||||
}): Promise<ClientCertificateImport>;
|
||||
/** Feature clientCertificate: forgets the stored client certificate. */
|
||||
removeClientCertificate(): Promise<void>;
|
||||
addListener(
|
||||
event: 'windowLayout',
|
||||
listener: (payload: NativeWindowLayout) => void
|
||||
@@ -229,6 +256,47 @@ export type NativeLocationPayload =
|
||||
}
|
||||
| { error: { code: number; message: string } };
|
||||
|
||||
interface NativeServerResponse {
|
||||
status: number;
|
||||
data: unknown;
|
||||
url: string;
|
||||
headers?: Record<string, string>;
|
||||
certRequested: boolean;
|
||||
certSent: boolean;
|
||||
/** host:port of the server that asked. */
|
||||
certHost?: string;
|
||||
/** Why the connection failed, when status is 0. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ClientCertificateInfo {
|
||||
host: string;
|
||||
port: number;
|
||||
/** The certificate's common name. */
|
||||
subject: string;
|
||||
/** The issuer's common name. */
|
||||
issuer: string;
|
||||
/** Expiry, in milliseconds since 1970. */
|
||||
notAfter: number;
|
||||
}
|
||||
|
||||
export interface ClientCertificateLabels {
|
||||
title: string;
|
||||
message: string;
|
||||
placeholder: string;
|
||||
ok: string;
|
||||
cancel: string;
|
||||
wrongPassword: string;
|
||||
}
|
||||
|
||||
export type ClientCertificateFailure = 'format' | 'no_key' | 'expired' | 'not_yet_valid' | 'store';
|
||||
|
||||
export interface ClientCertificateImport {
|
||||
result: 'imported' | 'cancelled' | 'failed';
|
||||
failure?: ClientCertificateFailure;
|
||||
certificate?: ClientCertificateInfo;
|
||||
}
|
||||
|
||||
export const TrekShell = registerPlugin<TrekShellPlugin>('TrekShell');
|
||||
|
||||
export const APP_URL_SCHEME = 'com.liketrek.trek';
|
||||
|
||||
Reference in New Issue
Block a user