mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
fix(unsplash): tell a server Unsplash turns away that the free key helps
Without an Access Key the image search goes through Unsplash's web endpoint, which refuses datacenter addresses with a 401 or 403 or answers with a challenge page. The search then said only "Unsplash search unavailable", although an admin can already enter a free key in the settings. Such a refusal now answers 502 with that hint and the code unsplash_key_needed, and the cover search shows it in the user's language. Closes #1449
This commit is contained in:
@@ -41,6 +41,16 @@ const MAX_COVER_BYTES = 15 * 1024 * 1024;
|
||||
// Unsplash is a third party on the request path; safeFetch adds no deadline of
|
||||
// its own, so both the search and the cover download carry one.
|
||||
const UNSPLASH_TIMEOUT_MS = 10_000;
|
||||
/**
|
||||
* What a search is told when the keyless web endpoint turns this server away, as it
|
||||
* does a datacenter (VPS) address: the free Access Key is the way out, and the admin
|
||||
* who can enter it is the one to tell (#1449). The code lets the client say it in
|
||||
* the user's language.
|
||||
*/
|
||||
const UNSPLASH_KEY_NEEDED =
|
||||
'Unsplash refused this server. An administrator can add a free Unsplash Access Key in Admin > Settings.';
|
||||
const UNSPLASH_KEY_NEEDED_CODE = 'unsplash_key_needed';
|
||||
|
||||
const COVER_EXT_BY_TYPE: Record<string, string> = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
@@ -120,10 +130,18 @@ export class UnsplashService {
|
||||
'Sec-Fetch-Site': 'same-origin',
|
||||
},
|
||||
});
|
||||
// Turned away without a key: a 401 or 403, or an ok answer that is a challenge page, not JSON.
|
||||
const refused = () =>
|
||||
new DomainError(502, UNSPLASH_KEY_NEEDED, {
|
||||
code: UNSPLASH_KEY_NEEDED_CODE,
|
||||
details: { code: UNSPLASH_KEY_NEEDED_CODE },
|
||||
});
|
||||
if (!accessKey && (response.status === 401 || response.status === 403)) throw refused();
|
||||
let data: UnsplashSearchResponse;
|
||||
try {
|
||||
data = (await response.json()) as UnsplashSearchResponse;
|
||||
} catch {
|
||||
if (!accessKey && response.ok) throw refused();
|
||||
throw new DomainError(response.ok ? 502 : response.status, 'Unsplash search unavailable');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AppSettingsRepository } from '../../../../src/db/repositories/AppSettings.repository';
|
||||
import type { UsersRepository } from '../../../../src/db/repositories/Users.repository';
|
||||
import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { UnsplashService } from '../../../../src/nest/unsplash/unsplash.service';
|
||||
import { asLegacyResult } from '../../../helpers/domain-error';
|
||||
import { makeStorageFixture } from '../../../helpers/storage-fixture';
|
||||
@@ -40,6 +41,9 @@ const getUnsplashKey = svc.getUnsplashKey.bind(svc);
|
||||
const saveUnsplashCover = svc.saveUnsplashCover.bind(svc);
|
||||
const isUnsplashCoverUrl = svc.isUnsplashCoverUrl.bind(svc);
|
||||
|
||||
const KEY_NEEDED =
|
||||
'Unsplash refused this server. An administrator can add a free Unsplash Access Key in Admin > Settings.';
|
||||
|
||||
const ORIGINAL_UNSPLASH_ENV = process.env.UNSPLASH_ACCESS_KEY;
|
||||
|
||||
afterEach(() => {
|
||||
@@ -99,13 +103,33 @@ describe('unsplashService.searchUnsplashPhotos', () => {
|
||||
it('UNSPLASH-016: a 200 carrying unparseable JSON becomes a 502, not a crash', async () => {
|
||||
// The web endpoint answers 200 with an HTML challenge page when it decides the
|
||||
// caller is a datacenter (#1449), so a parse failure on an ok response is an
|
||||
// upstream problem, not the caller's.
|
||||
// upstream problem, not the caller's: without a key, the key is the way out.
|
||||
const bad = fakeRes({ ok: true, type: 'text/html' });
|
||||
(bad as { json: () => Promise<unknown> }).json = async () => {
|
||||
throw new SyntaxError('Unexpected token < in JSON');
|
||||
};
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(bad));
|
||||
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Unsplash search unavailable', status: 502 });
|
||||
expect(await searchUnsplashPhotos('paris')).toMatchObject({ error: KEY_NEEDED, status: 502 });
|
||||
// With a key the official API answered, so no key is named.
|
||||
expect(await searchUnsplashPhotos('paris', 9, 'key')).toEqual({
|
||||
error: 'Unsplash search unavailable',
|
||||
status: 502,
|
||||
});
|
||||
});
|
||||
|
||||
it('UNSPLASH-016b: a keyless search turned away with 401 or 403 says the Access Key is the way out (#1449)', async () => {
|
||||
for (const status of [401, 403]) {
|
||||
const refused = fakeRes({ ok: false, status, type: 'text/plain' });
|
||||
(refused as { json: () => Promise<unknown> }).json = async () => {
|
||||
throw new SyntaxError('Unexpected token A in JSON');
|
||||
};
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(refused));
|
||||
const err = await svc.searchUnsplashPhotos('paris').catch((e: unknown) => e);
|
||||
expect(err).toBeInstanceOf(DomainError);
|
||||
expect((err as DomainError).getStatus()).toBe(502);
|
||||
expect(err).toMatchObject({ publicMessage: KEY_NEEDED, code: 'unsplash_key_needed' });
|
||||
expect((err as DomainError).toBody()).toEqual({ error: KEY_NEEDED, code: 'unsplash_key_needed' });
|
||||
}
|
||||
});
|
||||
|
||||
it('UNSPLASH-017: a failing response with unparseable JSON keeps its own status', async () => {
|
||||
@@ -134,7 +158,8 @@ describe('unsplashService.searchUnsplashPhotos', () => {
|
||||
fakeRes({ ok: false, status: 401, type: 'application/json', json: { error: 'Bad credentials' } }),
|
||||
),
|
||||
);
|
||||
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Bad credentials', status: 401 });
|
||||
// A key the official API refuses is named by Unsplash itself.
|
||||
expect(await searchUnsplashPhotos('paris', 9, 'stale-key')).toEqual({ error: 'Bad credentials', status: 401 });
|
||||
});
|
||||
|
||||
it('UNSPLASH-004: returns normalised photos on success and drops entries missing a url/thumb', async () => {
|
||||
|
||||
Reference in New Issue
Block a user