@backstage/backend-test-utils
Version:
Test helpers library for Backstage backends
88 lines (84 loc) • 2.88 kB
JavaScript
;
var cookie = require('cookie');
var MockAuthService = require('./MockAuthService.cjs.js');
var errors = require('@backstage/errors');
var mockCredentials = require('./mockCredentials.cjs.js');
class MockHttpAuthService {
#auth;
#defaultCredentials;
constructor(pluginId, defaultCredentials) {
this.#auth = new MockAuthService.MockAuthService({
pluginId,
disableDefaultAuthPolicy: false
});
this.#defaultCredentials = defaultCredentials;
}
async #getCredentials(req, allowLimitedAccess) {
const header = req.headers.authorization;
const token = typeof header === "string" ? header.match(/^Bearer[ ]+(\S+)$/i)?.[1] : void 0;
if (token) {
if (token === mockCredentials.MOCK_NONE_TOKEN) {
return this.#auth.getNoneCredentials();
}
return await this.#auth.authenticate(token, {
allowLimitedAccess
});
}
if (allowLimitedAccess) {
const cookieHeader = req.headers.cookie;
if (cookieHeader) {
const cookies = cookie.parse(cookieHeader);
const cookie$1 = cookies[mockCredentials.MOCK_AUTH_COOKIE];
if (cookie$1) {
return await this.#auth.authenticate(cookie$1, {
allowLimitedAccess: true
});
}
}
}
return this.#defaultCredentials;
}
async credentials(req, options) {
const credentials = await this.#getCredentials(
req,
options?.allowLimitedAccess ?? false
);
const allowedPrincipalTypes = options?.allow;
if (!allowedPrincipalTypes) {
return credentials;
}
if (this.#auth.isPrincipal(credentials, "none")) {
if (allowedPrincipalTypes.includes("none")) {
return credentials;
}
throw new errors.AuthenticationError("Missing credentials");
} else if (this.#auth.isPrincipal(credentials, "user")) {
if (allowedPrincipalTypes.includes("user")) {
return credentials;
}
throw new errors.NotAllowedError(
`This endpoint does not allow 'user' credentials`
);
} else if (this.#auth.isPrincipal(credentials, "service")) {
if (allowedPrincipalTypes.includes("service")) {
return credentials;
}
throw new errors.NotAllowedError(
`This endpoint does not allow 'service' credentials`
);
}
throw new errors.NotAllowedError(
"Unknown principal type, this should never happen"
);
}
async issueUserCookie(res, options) {
const credentials = options?.credentials ?? await this.credentials(res.req, { allow: ["user"] });
res.setHeader(
"Set-Cookie",
mockCredentials.mockCredentials.limitedUser.cookie(credentials.principal.userEntityRef)
);
return { expiresAt: new Date(Date.now() + 36e5) };
}
}
exports.MockHttpAuthService = MockHttpAuthService;
//# sourceMappingURL=MockHttpAuthService.cjs.js.map