break identity client into an interface

The interface has changed a little instead of allowing the client to
parse out the authorization header, it takes the request object as is
to extract the identity from it how the implementation decides.

IdentityClient#authenticate is now deprecated, in favor of
IdentityApi#getIdentity.

I am leaving the IdentityClient in place deprecated so that plugins
that use this can migrate away from it.

Signed-off-by: Brian Fletcher <brian@roadie.io>
This commit is contained in:
Brian Fletcher
2022-07-08 16:20:50 +01:00
parent f0e3de54fc
commit 2cbd533426
26 changed files with 753 additions and 213 deletions
+20 -1
View File
@@ -4,6 +4,7 @@
```ts
import { PluginEndpointDiscovery } from '@backstage/backend-common';
import { Request as Request_2 } from 'express';
// @public
export interface BackstageIdentityResponse extends BackstageSignInResult {
@@ -22,21 +23,39 @@ export type BackstageUserIdentity = {
ownershipEntityRefs: string[];
};
// @public
export class DefaultIdentityClient implements IdentityApi {
// @deprecated
authenticate(token: string | undefined): Promise<BackstageIdentityResponse>;
static create(options: IdentityClientOptions): DefaultIdentityClient;
// (undocumented)
getIdentity(req: Request_2): Promise<BackstageIdentityResponse | undefined>;
}
// @public
export function getBearerTokenFromAuthorizationHeader(
authorizationHeader: unknown,
): string | undefined;
// @public
export interface IdentityApi {
getIdentity(
req: Request_2<any>,
): Promise<BackstageIdentityResponse | undefined>;
}
// @public @deprecated
export class IdentityClient {
// @deprecated
authenticate(token: string | undefined): Promise<BackstageIdentityResponse>;
// (undocumented)
static create(options: IdentityClientOptions): IdentityClient;
}
// @public
export type IdentityClientOptions = {
discovery: PluginEndpointDiscovery;
issuer: string;
issuer?: string;
algorithms?: string[];
};
```
+1
View File
@@ -26,6 +26,7 @@
"@backstage/backend-common": "^0.14.1-next.1",
"@backstage/config": "^1.0.1",
"@backstage/errors": "^1.1.0-next.0",
"express": "^4.18.1",
"jose": "^4.6.0",
"node-fetch": "^2.6.7",
"winston": "^3.2.1"
@@ -0,0 +1,369 @@
/*
* Copyright 2020 The Backstage Authors
*
* 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 { PluginEndpointDiscovery } from '@backstage/backend-common';
import {
decodeProtectedHeader,
exportJWK,
generateKeyPair,
SignJWT,
} from 'jose';
import { cloneDeep } from 'lodash';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { v4 as uuid } from 'uuid';
import { DefaultIdentityClient } from './DefaultIdentityClient';
interface AnyJWK extends Record<string, string> {
use: 'sig';
alg: string;
kid: string;
kty: string;
}
// Simplified copy of TokenFactory in @backstage/plugin-auth-backend
class FakeTokenFactory {
private readonly keys = new Array<AnyJWK>();
constructor(
private readonly options: {
issuer: string;
keyDurationSeconds: number;
},
) {}
async issueToken(params: {
claims: {
sub: string;
ent?: string[];
};
}): Promise<string> {
const pair = await generateKeyPair('ES256');
const publicKey = await exportJWK(pair.publicKey);
const kid = uuid();
publicKey.kid = kid;
this.keys.push(publicKey as AnyJWK);
const iss = this.options.issuer;
const sub = params.claims.sub;
const ent = params.claims.ent;
const aud = 'backstage';
const iat = Math.floor(Date.now() / 1000);
const exp = iat + this.options.keyDurationSeconds;
return new SignJWT({ iss, sub, aud, iat, exp, ent, kid })
.setProtectedHeader({ alg: 'ES256', ent: ent, kid: kid })
.setIssuer(iss)
.setAudience(aud)
.setSubject(sub)
.setIssuedAt(iat)
.setExpirationTime(exp)
.sign(pair.privateKey);
}
async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {
return { keys: this.keys };
}
}
function jwtKid(jwt: string): string {
const header = decodeProtectedHeader(jwt);
return header.kid ?? '';
}
const server = setupServer();
const mockBaseUrl = 'http://backstage:9191/i-am-a-mock-base';
const discovery: PluginEndpointDiscovery = {
async getBaseUrl() {
return mockBaseUrl;
},
async getExternalBaseUrl() {
return mockBaseUrl;
},
};
describe('DefaultIdentityClient', () => {
let client: DefaultIdentityClient;
let factory: FakeTokenFactory;
const keyDurationSeconds = 5;
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterAll(() => server.close());
afterEach(() => server.resetHandlers());
beforeEach(() => {
client = DefaultIdentityClient.create({ discovery, issuer: mockBaseUrl });
factory = new FakeTokenFactory({
issuer: mockBaseUrl,
keyDurationSeconds,
});
});
describe('identity client configuration', () => {
beforeEach(() => {
server.use(
rest.get(
`${mockBaseUrl}/.well-known/jwks.json`,
async (_, res, ctx) => {
const keys = await factory.listPublicKeys();
return res(ctx.json(keys));
},
),
);
});
it('should defaults to ES256 when no algorithm is supplied', async () => {
const identityClient = DefaultIdentityClient.create({
discovery,
issuer: mockBaseUrl,
});
const token = await factory.issueToken({ claims: { sub: 'foo' } });
const response = await identityClient.authenticate(token);
// expect that the authenticate is able to validate a token with ES256, which is the one set to FakeTokenFactory.
// This means that IdentityClient set ES256 by default.
expect(response).toEqual({
token: token,
identity: {
type: 'user',
userEntityRef: 'foo',
ownershipEntityRefs: [],
},
});
});
it('should throw error on empty algorithms array', async () => {
const identityClient = DefaultIdentityClient.create({
discovery,
issuer: mockBaseUrl,
algorithms: [''],
});
const token = await factory.issueToken({ claims: { sub: 'foo' } });
return expect(
async () => await identityClient.authenticate(token),
).rejects.toThrow();
});
it('should throw error on empty algorithm string', async () => {
const identityClient = DefaultIdentityClient.create({
discovery,
issuer: mockBaseUrl,
algorithms: [],
});
const token = await factory.issueToken({ claims: { sub: 'foo' } });
return expect(
async () => await identityClient.authenticate(token),
).rejects.toThrow();
});
});
describe('authenticate', () => {
beforeEach(() => {
server.use(
rest.get(
`${mockBaseUrl}/.well-known/jwks.json`,
async (_, res, ctx) => {
const keys = await factory.listPublicKeys();
return res(ctx.json(keys));
},
),
);
});
it('should throw on undefined header', async () => {
return expect(async () => {
await client.authenticate(undefined);
}).rejects.toThrow();
});
it('should accept fresh token', async () => {
const token = await factory.issueToken({ claims: { sub: 'foo' } });
const response = await client.authenticate(token);
expect(response).toEqual({
token: token,
identity: {
type: 'user',
userEntityRef: 'foo',
ownershipEntityRefs: [],
},
});
});
it('should decode claims correctly', async () => {
const token = await factory.issueToken({
claims: { sub: 'foo', ent: ['entity1', 'entity2'] },
});
const response = await client.authenticate(token);
expect(response).toEqual({
token: token,
identity: {
type: 'user',
userEntityRef: 'foo',
ownershipEntityRefs: ['entity1', 'entity2'],
},
});
});
it('should throw on incorrect issuer', async () => {
const hackerFactory = new FakeTokenFactory({
issuer: 'hacker',
keyDurationSeconds,
});
return expect(async () => {
const token = await hackerFactory.issueToken({
claims: { sub: 'foo' },
});
await client.authenticate(token);
}).rejects.toThrow();
});
it('should throw on expired token', async () => {
return expect(async () => {
const fixedTime = Date.now();
jest
.spyOn(Date, 'now')
.mockImplementation(() => fixedTime - keyDurationSeconds * 1000 * 2);
const token = await factory.issueToken({
claims: { sub: 'foo' },
});
jest.spyOn(Date, 'now').mockImplementation(() => fixedTime);
await client.authenticate(token);
}).rejects.toThrow();
});
it('should throw on incorrect signing key', async () => {
const hackerFactory = new FakeTokenFactory({
issuer: mockBaseUrl,
keyDurationSeconds,
});
return expect(async () => {
const token = await hackerFactory.issueToken({
claims: { sub: 'foo' },
});
await client.authenticate(token);
}).rejects.toThrow();
});
it('should accept token from new key', async () => {
const fixedTime = Date.now();
jest
.spyOn(Date, 'now')
.mockImplementation(() => fixedTime - keyDurationSeconds * 1000 * 2);
const token1 = await factory.issueToken({ claims: { sub: 'foo1' } });
try {
// This throws as token has already expired
await client.authenticate(token1);
} catch (_err) {
// Ignore thrown error
}
// Move forward in time where the signing key has been rotated and the
// cooldown period to look up a new public key has elapsed.
jest
.spyOn(Date, 'now')
.mockImplementation(
() => fixedTime + 30 * keyDurationSeconds * 1000 + 2,
);
const token = await factory.issueToken({ claims: { sub: 'foo' } });
const response = await client.authenticate(token);
expect(response).toEqual({
token: token,
identity: {
type: 'user',
userEntityRef: 'foo',
ownershipEntityRefs: [],
},
});
});
it('should not be fooled by the none algorithm', async () => {
return expect(async () => {
const token = await factory.issueToken({ claims: { sub: 'foo' } });
const header = btoa(
JSON.stringify({ alg: 'none', kid: jwtKid(token) }),
);
const payload = btoa(
JSON.stringify({
iss: mockBaseUrl,
sub: 'foo',
aud: 'backstage',
iat: Date.now() / 1000,
exp: Date.now() / 1000 + 60000,
}),
);
const fakeToken = `${header}.${payload}.`;
return await client.authenticate(fakeToken);
}).rejects.toThrow();
});
it('should use an updated endpoint when the key is not found', async () => {
const updatedURL = 'http://backstage:9191/an-updated-base';
const getBaseUrl = discovery.getBaseUrl;
const getExternalBaseUrl = discovery.getExternalBaseUrl;
// Generate a key and sign a token with it
await factory.issueToken({ claims: { sub: 'foo' } });
// Only return the key from a single token
const singleKey = cloneDeep(await factory.listPublicKeys());
server.use(
rest.get(
`${mockBaseUrl}/.well-known/jwks.json`,
async (_, res, ctx) => {
return res(ctx.json(singleKey));
},
),
);
// Update the discovery endpoint to point to a new URL
discovery.getBaseUrl = async () => {
return updatedURL;
};
discovery.getExternalBaseUrl = async () => {
return updatedURL;
};
let calledUpdatedEndpoint = false;
server.use(
rest.get(`${updatedURL}/.well-known/jwks.json`, async (_, res, ctx) => {
const keys = await factory.listPublicKeys();
calledUpdatedEndpoint = true;
return res(ctx.json(keys));
}),
);
// Advance time
const future_11s = Date.now() + 11 * 1000;
const dateSpy = jest
.spyOn(Date, 'now')
.mockImplementation(() => future_11s);
// Issue a new token
const token = await factory.issueToken({ claims: { sub: 'foo2' } });
const response = await client.authenticate(token);
// Verify that the endpoint was updated.
expect(calledUpdatedEndpoint).toBeTruthy();
expect(response).toEqual({
token: token,
identity: {
type: 'user',
userEntityRef: 'foo2',
ownershipEntityRefs: [],
},
});
// Restore the discovery endpoint and time
discovery.getBaseUrl = getBaseUrl;
discovery.getExternalBaseUrl = getExternalBaseUrl;
dateSpy.mockClear();
});
});
});
@@ -0,0 +1,168 @@
/*
* Copyright 2020 The Backstage Authors
*
* 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 { PluginEndpointDiscovery } from '@backstage/backend-common';
import { AuthenticationError } from '@backstage/errors';
import {
createRemoteJWKSet,
decodeJwt,
decodeProtectedHeader,
FlattenedJWSInput,
JWSHeaderParameters,
jwtVerify,
} from 'jose';
import { GetKeyFunction } from 'jose/dist/types/types';
import { BackstageIdentityResponse } from './types';
import { getBearerTokenFromAuthorizationHeader, IdentityApi } from '.';
import { Request } from 'express';
const CLOCK_MARGIN_S = 10;
/**
* An identity client options object which allows extra configurations
*
* @experimental This is not a stable API yet
* @public
*/
export type IdentityClientOptions = {
discovery: PluginEndpointDiscovery;
issuer?: string;
/** JWS "alg" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.
* More info on supported algorithms: https://github.com/panva/jose */
algorithms?: string[];
};
/**
* An identity client to interact with auth-backend and authenticate Backstage
* tokens
*
* @experimental This is not a stable API yet
* @public
*/
export class DefaultIdentityClient implements IdentityApi {
private readonly discovery: PluginEndpointDiscovery;
private readonly issuer?: string;
private readonly algorithms?: string[];
private keyStore?: GetKeyFunction<JWSHeaderParameters, FlattenedJWSInput>;
private keyStoreUpdated: number = 0;
/**
* Create a new {@link DefaultIdentityClient} instance.
*/
static create(options: IdentityClientOptions): DefaultIdentityClient {
return new DefaultIdentityClient(options);
}
private constructor(options: IdentityClientOptions) {
this.discovery = options.discovery;
this.issuer = options.issuer;
this.algorithms = options.hasOwnProperty('algorithms')
? options.algorithms
: ['ES256'];
}
async getIdentity(req: Request) {
try {
return await this.authenticate(
getBearerTokenFromAuthorizationHeader(req.headers.authorization),
);
} catch (e) {
return undefined;
}
}
/**
* Verifies the given backstage identity token
* Returns a BackstageIdentity (user) matching the token.
* The method throws an error if verification fails.
*
* @deprecated You should start to use getIdentity instead of authenticate to retrieve the user
* identity.
*/
async authenticate(
token: string | undefined,
): Promise<BackstageIdentityResponse> {
// Extract token from header
if (!token) {
throw new AuthenticationError('No token specified');
}
// Verify token claims and signature
// Note: Claims must match those set by TokenFactory when issuing tokens
// Note: verify throws if verification fails
// Check if the keystore needs to be updated
await this.refreshKeyStore(token);
if (!this.keyStore) {
throw new AuthenticationError('No keystore exists');
}
const decoded = await jwtVerify(token, this.keyStore, {
algorithms: this.algorithms,
audience: 'backstage',
issuer: this.issuer,
});
// Verified, return the matching user as BackstageIdentity
// TODO: Settle internal user format/properties
if (!decoded.payload.sub) {
throw new AuthenticationError('No user sub found in token');
}
const user: BackstageIdentityResponse = {
token,
identity: {
type: 'user',
userEntityRef: decoded.payload.sub,
ownershipEntityRefs: decoded.payload.ent
? (decoded.payload.ent as string[])
: [],
},
};
return user;
}
/**
* If the last keystore refresh is stale, update the keystore URL to the latest
*/
private async refreshKeyStore(rawJwtToken: string): Promise<void> {
const payload = await decodeJwt(rawJwtToken);
const header = await decodeProtectedHeader(rawJwtToken);
// Refresh public keys if needed
let keyStoreHasKey;
try {
if (this.keyStore) {
// Check if the key is present in the keystore
const [_, rawPayload, rawSignature] = rawJwtToken.split('.');
keyStoreHasKey = await this.keyStore(header, {
payload: rawPayload,
signature: rawSignature,
});
}
} catch (error) {
keyStoreHasKey = false;
}
// Refresh public key URL if needed
// Add a small margin in case clocks are out of sync
const issuedAfterLastRefresh =
payload?.iat && payload.iat > this.keyStoreUpdated - CLOCK_MARGIN_S;
if (!this.keyStore || (!keyStoreHasKey && issuedAfterLastRefresh)) {
const url = await this.discovery.getBaseUrl('auth');
const endpoint = new URL(`${url}/.well-known/jwks.json`);
this.keyStore = createRemoteJWKSet(endpoint);
this.keyStoreUpdated = Date.now() / 1000;
}
}
}
+35
View File
@@ -0,0 +1,35 @@
/*
* Copyright 2020 The Backstage Authors
*
* 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 { Request } from 'express';
import { BackstageIdentityResponse } from './types';
/**
* An identity client api to authenticate Backstage
* tokens
*
* @experimental This is not a stable API yet
* @public
*/
export interface IdentityApi {
/**
* Verifies the given backstage identity token
* Returns a BackstageIdentity (user) matching the token.
* The method throws an error if verification fails.
*/
getIdentity(
req: Request<any>,
): Promise<BackstageIdentityResponse | undefined>;
}
+14 -111
View File
@@ -13,139 +13,42 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { PluginEndpointDiscovery } from '@backstage/backend-common';
import { AuthenticationError } from '@backstage/errors';
import {
createRemoteJWKSet,
decodeJwt,
decodeProtectedHeader,
FlattenedJWSInput,
JWSHeaderParameters,
jwtVerify,
} from 'jose';
import { GetKeyFunction } from 'jose/dist/types/types';
DefaultIdentityClient,
IdentityClientOptions,
} from './DefaultIdentityClient';
import { BackstageIdentityResponse } from './types';
const CLOCK_MARGIN_S = 10;
/**
* An identity client options object which allows extra configurations
*
* @experimental This is not a stable API yet
* @public
*/
export type IdentityClientOptions = {
discovery: PluginEndpointDiscovery;
issuer: string;
/** JWS "alg" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.
* More info on supported algorithms: https://github.com/panva/jose */
algorithms?: string[];
};
/**
* An identity client to interact with auth-backend and authenticate Backstage
* tokens
*
* @experimental This is not a stable API yet
* @public
* @experimental This is not a stable API yet
* @deprecated Please migrate to the DefaultIdentityClient.
*/
export class IdentityClient {
private readonly discovery: PluginEndpointDiscovery;
private readonly issuer: string;
private readonly algorithms: string[];
private keyStore?: GetKeyFunction<JWSHeaderParameters, FlattenedJWSInput>;
private keyStoreUpdated: number = 0;
/**
* Create a new {@link IdentityClient} instance.
*/
private readonly defaultIdentityClient: DefaultIdentityClient;
static create(options: IdentityClientOptions): IdentityClient {
return new IdentityClient(options);
return new IdentityClient(DefaultIdentityClient.create(options));
}
private constructor(options: IdentityClientOptions) {
this.discovery = options.discovery;
this.issuer = options.issuer;
this.algorithms = options.algorithms ?? ['ES256'];
private constructor(defaultIdentityClient: DefaultIdentityClient) {
this.defaultIdentityClient = defaultIdentityClient;
}
/**
* Verifies the given backstage identity token
* Returns a BackstageIdentity (user) matching the token.
* The method throws an error if verification fails.
*
* @deprecated You should start to use IdentityApi#getIdentity instead of authenticate
* to retrieve the user identity.
*/
async authenticate(
token: string | undefined,
): Promise<BackstageIdentityResponse> {
// Extract token from header
if (!token) {
throw new AuthenticationError('No token specified');
}
// Verify token claims and signature
// Note: Claims must match those set by TokenFactory when issuing tokens
// Note: verify throws if verification fails
// Check if the keystore needs to be updated
await this.refreshKeyStore(token);
if (!this.keyStore) {
throw new AuthenticationError('No keystore exists');
}
const decoded = await jwtVerify(token, this.keyStore, {
algorithms: this.algorithms,
audience: 'backstage',
issuer: this.issuer,
});
// Verified, return the matching user as BackstageIdentity
// TODO: Settle internal user format/properties
if (!decoded.payload.sub) {
throw new AuthenticationError('No user sub found in token');
}
const user: BackstageIdentityResponse = {
token,
identity: {
type: 'user',
userEntityRef: decoded.payload.sub,
ownershipEntityRefs: decoded.payload.ent
? (decoded.payload.ent as string[])
: [],
},
};
return user;
}
/**
* If the last keystore refresh is stale, update the keystore URL to the latest
*/
private async refreshKeyStore(rawJwtToken: string): Promise<void> {
const payload = await decodeJwt(rawJwtToken);
const header = await decodeProtectedHeader(rawJwtToken);
// Refresh public keys if needed
let keyStoreHasKey;
try {
if (this.keyStore) {
// Check if the key is present in the keystore
const [_, rawPayload, rawSignature] = rawJwtToken.split('.');
keyStoreHasKey = await this.keyStore(header, {
payload: rawPayload,
signature: rawSignature,
});
}
} catch (error) {
keyStoreHasKey = false;
}
// Refresh public key URL if needed
// Add a small margin in case clocks are out of sync
const issuedAfterLastRefresh =
payload?.iat && payload.iat > this.keyStoreUpdated - CLOCK_MARGIN_S;
if (!this.keyStore || (!keyStoreHasKey && issuedAfterLastRefresh)) {
const url = await this.discovery.getBaseUrl('auth');
const endpoint = new URL(`${url}/.well-known/jwks.json`);
this.keyStore = createRemoteJWKSet(endpoint);
this.keyStoreUpdated = Date.now() / 1000;
}
return await this.defaultIdentityClient.authenticate(token);
}
}
+3 -1
View File
@@ -21,8 +21,10 @@
*/
export { getBearerTokenFromAuthorizationHeader } from './getBearerTokenFromAuthorizationHeader';
export { DefaultIdentityClient } from './DefaultIdentityClient';
export { IdentityClient } from './IdentityClient';
export type { IdentityClientOptions } from './IdentityClient';
export type { IdentityApi } from './IdentityApi';
export type { IdentityClientOptions } from './DefaultIdentityClient';
export type {
BackstageIdentityResponse,
BackstageSignInResult,