Skip to content

Commit 2a44e55

Browse files
committed
feat(api): load API key from systemd credentials with fallback
If provided, API key is read through systemd credential `api-key` passed to the service and preferred, will fallback to environment var if not present. See: https://systemd.io/CREDENTIALS systemd.system-credentials(7)
1 parent 2fe7253 commit 2a44e55

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

server/lib/settings/index.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -745,19 +745,29 @@ class Settings {
745745
}
746746

747747
public async regenerateApiKey(): Promise<MainSettings> {
748-
this.main.apiKey = this.generateApiKey();
748+
this.main.apiKey = await this.generateApiKey();
749749
await this.save();
750750
return this.main;
751751
}
752752

753-
private generateApiKey(): string {
754-
if (process.env.API_KEY) {
753+
private async apiKeyFromEnvOrCred(): Promise<string | undefined> {
754+
const apiKeyCredential = `${process.env.CREDENTIALS_DIRECTORY}/api-key`;
755+
756+
try {
757+
return fs.readFile(apiKeyCredential, 'utf-8');
758+
} catch {
755759
return process.env.API_KEY;
756-
} else {
757-
return Buffer.from(`${Date.now()}${randomUUID()}`).toString('base64');
758760
}
759761
}
760762

763+
private async generateApiKey(): Promise<string> {
764+
const apiKey = await this.apiKeyFromEnvOrCred();
765+
766+
return (
767+
apiKey || Buffer.from(`${Date.now()}${randomUUID()}`).toString('base64')
768+
);
769+
}
770+
761771
/**
762772
* Settings Load
763773
*
@@ -794,11 +804,12 @@ class Settings {
794804
// generate keys and ids if it's missing
795805
let change = false;
796806
if (!this.data.main.apiKey) {
797-
this.data.main.apiKey = this.generateApiKey();
807+
this.data.main.apiKey = await this.generateApiKey();
798808
change = true;
799-
} else if (process.env.API_KEY) {
800-
if (this.main.apiKey != process.env.API_KEY) {
801-
this.main.apiKey = process.env.API_KEY;
809+
} else {
810+
const apiKey = await this.apiKeyFromEnvOrCred();
811+
if (apiKey && this.main.apiKey != apiKey) {
812+
this.main.apiKey = apiKey;
802813
}
803814
}
804815
if (!this.data.clientId) {

0 commit comments

Comments
 (0)