feat(security): BIT-5254 implement audit logging for secret access
- Add src/logger/audit.js: dedicated audit logger writing to logs/audit.log and logs/combined.log; events: secret.access, secret.missing, secrets.loaded, auth.success, auth.failure; never logs secret values - Integrate audit.logSecretAccess() and audit.logSecretsLoaded() into SecretsManager.get() and load() in src/config/secrets.js - Integrate audit.logAuthAttempt() into adminOk() in src/http/ui-auth.js, distinguishing no_token / invalid_token / no_admin_token_configured - Add audit_log() function to tools/deploy/lxc-secrets-inject.sh writing JSON events to syslog (security.info) and stderr for gitea.secret.fetched, gitea.secret.fetch_failed, lxc.injection.started, lxc.injection.completed - Add src/logger/audit.test.js covering all exported functions (11 cases) - All 341 tests pass Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1 parent
dde4398c8e
commit
38ebc60ad9
5 files changed
+276
-1
No files matched your search
@@ -2,6 +2,7 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const audit = require('../logger/audit');
|
||||
|
||||
/**
|
||||
* Centralized secrets management — single source of truth for all sensitive data.
|
||||
@@ -59,6 +60,13 @@ class SecretsManager {
|
||||
|
||||
this._cache = secrets;
|
||||
this._loaded = true;
|
||||
|
||||
audit.logSecretsLoaded({
|
||||
systemFilePresent: fs.existsSync(SYSTEM_SECRETS_FILE),
|
||||
repoFilePresent: fs.existsSync(REPO_SECRETS_FILE),
|
||||
count: Object.keys(secrets).length,
|
||||
});
|
||||
|
||||
return this._cache;
|
||||
}
|
||||
|
||||
@@ -79,6 +87,7 @@ class SecretsManager {
|
||||
const value = (secrets[key] || '').trim();
|
||||
|
||||
if (!value) {
|
||||
audit.logSecretAccess(key, { found: false, required });
|
||||
if (required) {
|
||||
throw new Error(
|
||||
`Missing required secret: ${key}. ` +
|
||||
@@ -88,6 +97,7 @@ class SecretsManager {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
audit.logSecretAccess(key, { found: true, required });
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
+10
-1
@@ -1,5 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const audit = require('../logger/audit');
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text)
|
||||
.replace(/&/g, '&')
|
||||
@@ -24,10 +26,17 @@ function tokenFromRequest(req) {
|
||||
function adminOk(req, bodyToken) {
|
||||
const expected = getAdminToken();
|
||||
if (!expected) {
|
||||
audit.logAuthAttempt(req, false, 'no_admin_token_configured');
|
||||
return false;
|
||||
}
|
||||
const got = bodyToken || tokenFromRequest(req);
|
||||
return got === expected;
|
||||
if (!got) {
|
||||
audit.logAuthAttempt(req, false, 'no_token');
|
||||
return false;
|
||||
}
|
||||
const ok = got === expected;
|
||||
audit.logAuthAttempt(req, ok, ok ? undefined : 'invalid_token');
|
||||
return ok;
|
||||
}
|
||||
|
||||
module.exports = { escapeHtml, getAdminToken, tokenFromRequest, adminOk };
|
||||
@@ -0,0 +1,101 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const { createLogger, format, transports } = require('winston');
|
||||
const { getCurrentCorrelationId } = require('./correlation-id');
|
||||
|
||||
fs.mkdirSync('logs', { recursive: true });
|
||||
|
||||
/**
|
||||
* Audit event type constants.
|
||||
*/
|
||||
const AUDIT_EVENTS = {
|
||||
SECRET_ACCESS: 'secret.access',
|
||||
SECRET_MISSING: 'secret.missing',
|
||||
SECRETS_LOADED: 'secrets.loaded',
|
||||
AUTH_SUCCESS: 'auth.success',
|
||||
AUTH_FAILURE: 'auth.failure',
|
||||
};
|
||||
|
||||
const jsonTimestamp = format.combine(
|
||||
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
|
||||
format.errors({ stack: true }),
|
||||
format.json()
|
||||
);
|
||||
|
||||
const auditLogger = createLogger({
|
||||
level: 'debug',
|
||||
defaultMeta: { module: 'audit' },
|
||||
transports: [
|
||||
new transports.File({ filename: 'logs/audit.log', format: jsonTimestamp }),
|
||||
new transports.File({ filename: 'logs/combined.log', format: jsonTimestamp }),
|
||||
],
|
||||
});
|
||||
|
||||
function enrichAudit(event, context) {
|
||||
return { event, correlationId: getCurrentCorrelationId(), ...context };
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a secret access attempt. Never logs the secret value.
|
||||
* @param {string} key - Secret name
|
||||
* @param {object} opts
|
||||
* @param {boolean} opts.found - Whether the secret was present and non-empty
|
||||
* @param {boolean} opts.required - Whether the secret is required
|
||||
* @param {string} [opts.callerModule] - Module requesting the secret
|
||||
*/
|
||||
function logSecretAccess(key, { found, required, callerModule } = {}) {
|
||||
const event = found ? AUDIT_EVENTS.SECRET_ACCESS : AUDIT_EVENTS.SECRET_MISSING;
|
||||
const meta = enrichAudit(event, { secretKey: key, found, required, callerModule });
|
||||
if (!found && required) {
|
||||
auditLogger.warn(`Secret missing (required): ${key}`, meta);
|
||||
} else if (!found) {
|
||||
auditLogger.info(`Secret missing (optional): ${key}`, meta);
|
||||
} else {
|
||||
auditLogger.debug(`Secret accessed: ${key}`, meta);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log secrets load event. Never logs values — only load-source metadata.
|
||||
* @param {object} opts
|
||||
* @param {boolean} opts.systemFilePresent - Whether /etc/ai-news-writer/secrets.env was read
|
||||
* @param {boolean} opts.repoFilePresent - Whether .env was read
|
||||
* @param {number} opts.count - Total number of keys in loaded cache
|
||||
*/
|
||||
function logSecretsLoaded({ systemFilePresent, repoFilePresent, count } = {}) {
|
||||
auditLogger.info(
|
||||
'Secrets loaded',
|
||||
enrichAudit(AUDIT_EVENTS.SECRETS_LOADED, { systemFilePresent, repoFilePresent, count })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an admin authentication attempt. Never logs the token value.
|
||||
* @param {object} req - HTTP request
|
||||
* @param {boolean} success - Whether authentication succeeded
|
||||
* @param {string} [reason] - Failure reason: 'no_token' | 'invalid_token' | 'no_admin_token_configured'
|
||||
*/
|
||||
function logAuthAttempt(req, success, reason) {
|
||||
const event = success ? AUDIT_EVENTS.AUTH_SUCCESS : AUDIT_EVENTS.AUTH_FAILURE;
|
||||
const raw = req.headers['x-forwarded-for'] || req.socket?.remoteAddress || 'unknown';
|
||||
const ip = String(raw).split(',')[0].trim();
|
||||
const method = req.method || 'unknown';
|
||||
const url = req.url || 'unknown';
|
||||
|
||||
const meta = enrichAudit(event, {
|
||||
success,
|
||||
ip,
|
||||
method,
|
||||
url,
|
||||
...(success ? {} : { reason }),
|
||||
});
|
||||
|
||||
if (success) {
|
||||
auditLogger.info('Admin auth succeeded', meta);
|
||||
} else {
|
||||
auditLogger.warn('Admin auth failed', meta);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { logSecretAccess, logSecretsLoaded, logAuthAttempt, AUDIT_EVENTS };
|
||||
@@ -0,0 +1,125 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const { describe, it, before, after, mock } = require('node:test');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// Create logs directory so Winston file transports don't throw
|
||||
fs.mkdirSync(path.resolve(__dirname, '../../logs'), { recursive: true });
|
||||
|
||||
describe('audit logger', () => {
|
||||
let audit;
|
||||
|
||||
before(() => {
|
||||
audit = require('./audit');
|
||||
});
|
||||
|
||||
describe('AUDIT_EVENTS constants', () => {
|
||||
it('exports expected event type strings', () => {
|
||||
const { AUDIT_EVENTS } = audit;
|
||||
assert.strictEqual(AUDIT_EVENTS.SECRET_ACCESS, 'secret.access');
|
||||
assert.strictEqual(AUDIT_EVENTS.SECRET_MISSING, 'secret.missing');
|
||||
assert.strictEqual(AUDIT_EVENTS.SECRETS_LOADED, 'secrets.loaded');
|
||||
assert.strictEqual(AUDIT_EVENTS.AUTH_SUCCESS, 'auth.success');
|
||||
assert.strictEqual(AUDIT_EVENTS.AUTH_FAILURE, 'auth.failure');
|
||||
});
|
||||
});
|
||||
|
||||
describe('logSecretAccess()', () => {
|
||||
it('does not throw when secret is found', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logSecretAccess('OPENAI_API_KEY', { found: true, required: true });
|
||||
});
|
||||
});
|
||||
|
||||
it('does not throw when optional secret is missing', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logSecretAccess('OPTIONAL_TOKEN', { found: false, required: false });
|
||||
});
|
||||
});
|
||||
|
||||
it('does not throw when required secret is missing', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logSecretAccess('MISSING_KEY', { found: false, required: true });
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts callerModule context', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logSecretAccess('SOME_KEY', { found: true, required: false, callerModule: 'writer' });
|
||||
});
|
||||
});
|
||||
|
||||
it('handles missing opts gracefully', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logSecretAccess('BARE_KEY');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('logSecretsLoaded()', () => {
|
||||
it('does not throw with full metadata', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logSecretsLoaded({ systemFilePresent: true, repoFilePresent: false, count: 12 });
|
||||
});
|
||||
});
|
||||
|
||||
it('does not throw with empty opts', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logSecretsLoaded();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('logAuthAttempt()', () => {
|
||||
function makeReq(overrides = {}) {
|
||||
return {
|
||||
method: 'POST',
|
||||
url: '/admin/sources',
|
||||
headers: { 'x-forwarded-for': '10.0.0.1' },
|
||||
socket: { remoteAddress: '127.0.0.1' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it('does not throw on successful auth', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logAuthAttempt(makeReq(), true);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not throw on failed auth with reason', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logAuthAttempt(makeReq(), false, 'invalid_token');
|
||||
});
|
||||
});
|
||||
|
||||
it('handles missing x-forwarded-for by falling back to socket', () => {
|
||||
const req = makeReq({ headers: {} });
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logAuthAttempt(req, false, 'no_token');
|
||||
});
|
||||
});
|
||||
|
||||
it('handles missing socket by falling back to unknown', () => {
|
||||
const req = makeReq({ headers: {}, socket: null });
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logAuthAttempt(req, false, 'no_token');
|
||||
});
|
||||
});
|
||||
|
||||
it('strips extra IPs from x-forwarded-for', () => {
|
||||
const req = makeReq({ headers: { 'x-forwarded-for': '203.0.113.1, 10.0.0.2, 172.16.0.1' } });
|
||||
assert.doesNotThrow(() => {
|
||||
audit.logAuthAttempt(req, true);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not log the token value', () => {
|
||||
// Verify function signature: no token parameter accepted
|
||||
const { logAuthAttempt } = audit;
|
||||
assert.strictEqual(logAuthAttempt.length, 3); // (req, success, reason)
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,32 @@ die() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Emit a structured audit event to syslog (if available) and stdout.
|
||||
# Usage: audit_log <event> <key=value> [<key=value> ...]
|
||||
# Values that could contain secrets MUST NOT be passed to this function.
|
||||
audit_log() {
|
||||
local event="$1"
|
||||
shift
|
||||
local ts
|
||||
ts=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
|
||||
# Build a compact JSON line from positional key=value pairs
|
||||
local json="{\"timestamp\":\"${ts}\",\"module\":\"lxc-secrets-inject\",\"event\":\"${event}\""
|
||||
for pair in "$@"; do
|
||||
local k="${pair%%=*}"
|
||||
local v="${pair#*=}"
|
||||
# Escape backslash and double-quote in value
|
||||
v="${v//\\/\\\\}"
|
||||
v="${v//\"/\\\"}"
|
||||
json="${json},\"${k}\":\"${v}\""
|
||||
done
|
||||
json="${json}}"
|
||||
# Write to syslog if available, otherwise stderr (which operators typically capture)
|
||||
if command -v logger &>/dev/null; then
|
||||
logger -t ai-news-writer-secrets -p security.info -- "$json"
|
||||
fi
|
||||
echo "$json" >&2
|
||||
}
|
||||
|
||||
check_requirements() {
|
||||
local missing=0
|
||||
|
||||
@@ -153,9 +179,11 @@ fetch_secret() {
|
||||
local error_msg
|
||||
error_msg=$(echo "$response" | jq -r '.message')
|
||||
log_error "Failed to fetch $secret_name: $error_msg"
|
||||
audit_log "gitea.secret.fetch_failed" "secretKey=${secret_name}" "repo=${GITEA_REPO_OWNER}/${GITEA_REPO_NAME}" "error=${error_msg}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
audit_log "gitea.secret.fetched" "secretKey=${secret_name}" "repo=${GITEA_REPO_OWNER}/${GITEA_REPO_NAME}"
|
||||
echo "$response" | jq -r '.data'
|
||||
}
|
||||
|
||||
@@ -224,6 +252,7 @@ inject_secrets() {
|
||||
local secrets_str="$2"
|
||||
|
||||
log_section "Injecting Secrets into LXC $lxc_id"
|
||||
audit_log "lxc.injection.started" "lxcId=${lxc_id}" "requestedSecrets=${secrets_str//,/ }"
|
||||
|
||||
verify_container "$lxc_id"
|
||||
|
||||
@@ -296,6 +325,7 @@ inject_secrets() {
|
||||
log_warn "Unexpected permissions: $file_perms"
|
||||
fi
|
||||
|
||||
audit_log "lxc.injection.completed" "lxcId=${lxc_id}" "successCount=${success_count}" "failCount=${fail_count}"
|
||||
log_section "✓ Secrets Injection Complete"
|
||||
log_ok "$success_count secrets injected into LXC $lxc_id"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user