Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2be9fc21db | ||
|
|
47ba7b3f9a
|
||
|
|
478bd4363b | ||
|
|
4ef8a6293f
|
||
|
|
c58324bccf
|
||
|
|
06b766d516
|
||
|
|
5c32e3c5f3
|
||
|
|
1de785328e
|
||
|
|
dbcfd85da8
|
||
|
|
ff76412d80
|
||
|
|
76ac13c14f
|
||
|
|
7ba2740283
|
||
|
|
c82c847b35
|
||
|
|
dc69ffe245
|
||
|
|
66fd64e1c4
|
||
|
|
895727acbb | ||
|
|
886e76b333 | ||
|
|
603f0c9d82 | ||
|
|
bdf79eae09 |
No files matched your search
@@ -1,12 +1,12 @@
|
||||
version: 2.1
|
||||
setup: true
|
||||
orbs:
|
||||
qqq-orb: kingsrook/qqq-orb@0.7.12
|
||||
qqq-orb: kingsrook/qqq-orb@0.8
|
||||
workflows:
|
||||
setup:
|
||||
jobs:
|
||||
- qqq-orb/generate_pipeline:
|
||||
orb_version: 0.7.12
|
||||
orb_version: '0.8'
|
||||
filters:
|
||||
branches:
|
||||
ignore: automation/qbit-rc-pending
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
name: build
|
||||
on:
|
||||
push:
|
||||
jobs:
|
||||
maven:
|
||||
uses: self:KofTwentyTwo/ci-workflows/.gitea/workflows/maven.yaml@v1
|
||||
secrets: inherit
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
profile: qbit
|
||||
orb_version: 0.7.12
|
||||
orb_version: '0.8'
|
||||
default_branch: develop
|
||||
java_version: '21'
|
||||
browsers: true
|
||||
|
||||
@@ -5,6 +5,9 @@ All notable changes to this project are documented here. The format follows Keep
|
||||
## [0.1.0] - Unreleased
|
||||
|
||||
### Added
|
||||
- Plans run on their schedule in an application with no scheduled jobs table. `backupRunDuePlans` (`BackupDuePlansProcess`), once a minute on the qbit's scheduler, starts every active plan whose cron has come due since it last started and every verification that has come due; missed times collapse into one run. Where the application has scheduled jobs it starts nothing. Before, the sync to scheduled jobs logged "ScheduledJob table not found" and no plan ever ran on its schedule unless the host built a scheduler of its own.
|
||||
- Alert `backups.prune.failed`: a plan the daily prune could not prune, cleared by its next good prune.
|
||||
- Client-side encryption (`CLIENT_AES256_GCM`, spec 11.2) works. `BackupsQBitConfig.withKeyProvider(QKeyProviderInterface)` installs the streaming cipher of the QQQ crypto package (`StreamingCipherTransform`: Tink streaming AEAD, a fresh data key per object, wrapped by the referenced key). A plan that asks for encryption is encrypted by its run without the host handing it a cipher, a plan is refused when the provider has no key for its reference, verification and restore read through the same provider, and a rotated key still reads what its older version wrote. A run records the key reference and a fingerprint (`v<version>:<16 hex>`), never the key. Without a key a run is refused and nothing is written in the clear.
|
||||
- Central `backups.sla` and per-active-plan `backups.destination.<planId>` health checks, with bounded read-only destination diagnostics and secret-free status details.
|
||||
- Always-durable backup, resume, scheduled backup, restore and verify processes with conservative `NONE` idempotency and stable backup identities on explicit job retry.
|
||||
- Weighted backup phases, table/file counts, stored bytes, safe per-table/artifact logs, warnings, failures and resume notices through QQQ `JobProgress`.
|
||||
@@ -16,6 +19,9 @@ All notable changes to this project are documented here. The format follows Keep
|
||||
- Repository scaffold: `BackupsQBitConfig` and `BackupsQBitProducer` (table prefix `backups_`, permissions `backups.*`), build, CI and repository standard files.
|
||||
|
||||
### Changed
|
||||
- **The daily prune prunes.** It is a process of its own, `backupPruneScheduled` (`BackupScheduledPruneProcess`), which prunes every active plan with nobody selecting anything. The schedule used to be on "Prune per retention" (`backupPrune`), an action for a person that needs plans selected and a review: started by a scheduler it answered "No records were selected", the scheduler logged a warning, and no old backup was ever deleted by the schedule. `backupPrune` has no schedule now. A host that scheduled it itself should stop.
|
||||
- The file index of an encrypted run (`files/index-00001.jsonl.gz`: tables, record keys and where each file came from) is encrypted like every other object of the run. It was written in the clear while the catalog recorded it as encrypted, and a restore from an encrypted run could not read it. No release could encrypt before this one, so no stored run is affected.
|
||||
- A plan that asks for encryption without a key provider is refused with "no key provider is configured" (was "not available in this version"); a refused run names the key reference.
|
||||
- Tables whose backend module has no query interface (storage-only modules such as qbit-edi `edi_preview_download`) are classified EXTERNAL and always left out of a backup with the reason `NOT_QUERYABLE`, even when selected by name or role; the Run backup review lists them. Before, such a table was read as DATA and the whole run FAILED with "Query is not implemented in this module".
|
||||
- Failed runs persist an actionable `error_message` ("Backup failed: Class: message") and fill `error_detail` with the exception class, the cause chain and the top root-cause frames (bounded to 8 KB). Both go through `FailureText.sanitize`, which redacts URL user-info, presigned query parameters, key=value secrets, Authorization/Bearer values, AWS access key ids, PEM blocks and Postgres row values while keeping object keys and bucket names.
|
||||
- Multi-node deployments: the cached Prometheus text (`BackupsMetrics`) is registered with QQQ `ClusterCaches` as `qbit-backups.metrics` and cleared on every node when a run finishes or a plan is inserted, updated or deleted; the 60 s TTL remains the safety net. `SlaChecker`'s manifest-head and bucket-audit throttles and `BackupsRuntime`'s process-permission map are registered as node-local, with reasons. `BackupsClusterCachesTest` audits the package for unregistered static caches and covers a remote invalidation.
|
||||
|
||||
@@ -62,6 +62,33 @@ checks empty-state, widget and possible-value-source coverage. Run it with
|
||||
|
||||
Always use the Maven wrapper (Maven 3.9.11); Maven 3.10 cannot read the parent POM.
|
||||
|
||||
## Schedules
|
||||
|
||||
Give the qbit a scheduler (`BackupsQBitConfig.withSchedulerName`) and it runs by itself:
|
||||
|
||||
- **Backups and verifications** run on each plan's cron. In an application with QQQ's scheduled jobs table every plan has a scheduled job of its own, kept in sync as the plan changes. In an application without that table, `backupRunDuePlans` starts what is due, once a minute. Either way a host builds nothing.
|
||||
- **Pruning** runs once a day (`backupPruneScheduled`): every active plan is pruned to its retention. A plan that cannot be pruned raises `backups.prune.failed`.
|
||||
- **The SLA check** runs every `slaCheckIntervalSeconds` (`backupCheckSla`).
|
||||
|
||||
Without a scheduler nothing is scheduled, and plans run only by hand.
|
||||
|
||||
|
||||
## Encryption
|
||||
|
||||
Backup objects are encrypted before they leave the application when a plan's encryption mode is `CLIENT_AES256_GCM` and the host has given the qbit a key provider:
|
||||
|
||||
```java
|
||||
new BackupsQBitProducer().withQBitConfig(config.withKeyProvider(new EnvKeyProvider())).produce(qInstance);
|
||||
```
|
||||
|
||||
- The plan's **encryption key reference** names a key of the provider. For `EnvKeyProvider` it is the name of an environment variable that holds 32 random bytes as base64, which is how a secret manager hands a key to a process. `AwsSecretsManagerKeyProvider` reads the same from AWS Secrets Manager. The key is never in a table, a log, a manifest or a message; a run records the reference and a fingerprint.
|
||||
- Table parts, the file index and the copies of referenced files are encrypted (Tink streaming AEAD, a fresh data key per object). The manifest and the checksum list stay readable without the key: they hold table names, row counts and checksums (of the stored bytes, and of each part before it was encrypted, which is how a verification knows it read the right content), and no row.
|
||||
- A plan cannot be saved, and a run does not start, when the provider has no key for the reference. Nothing is written in the clear instead.
|
||||
- **Rotation** (the convention of the QQQ key providers, for a reference `NAME`): keep the old key as `NAME_V<old version>`, put the new key in `NAME`, set `NAME_VERSION` to the new version. New runs are written under the new version; older runs are read with the version in each object's header for as long as that version is kept.
|
||||
- **Losing the key loses every backup it wrote.** Keep it where the application's database is not, and keep an old version until every run written under it has been pruned.
|
||||
- The sensitive field policy `INCLUDE_ENCRYPTED_ONLY` needs this mode.
|
||||
|
||||
|
||||
## Durable jobs and progress
|
||||
|
||||
Run backup now, Resume, scheduled backups, both Restore actions, and Verify backup
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<properties>
|
||||
<qqq.version>4.1.0-RC.26</qqq.version> <!-- feeds qbit-build-parent's qqq-bom-pom import -->
|
||||
<qbit.guardrails.enforce>true</qbit.guardrails.enforce>
|
||||
<qbit.guardrails.strictUiApiRoutes>true</qbit.guardrails.strictUiApiRoutes>
|
||||
<revision>0.1.0-SNAPSHOT</revision>
|
||||
@@ -29,7 +30,7 @@
|
||||
<parent>
|
||||
<groupId>com.kingsrook</groupId>
|
||||
<artifactId>qbit-build-parent</artifactId>
|
||||
<version>2.1.0</version>
|
||||
<version>2.2.1</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
@@ -86,7 +87,7 @@
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-object-storage</artifactId>
|
||||
<version>0.1.0-RC.2</version>
|
||||
<version>0.1.0-RC.10</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
@@ -106,7 +107,7 @@
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-frontend-next</artifactId>
|
||||
<version>1.0.0-RC.14</version>
|
||||
<version>1.0.0-RC.38</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -216,7 +217,7 @@
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
<properties>
|
||||
<qqq.snapshot.version>4.1.0-RC.14</qqq.snapshot.version>
|
||||
<qqq.snapshot.version>4.1.0-RC.26</qqq.snapshot.version>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
||||
@@ -21,8 +21,10 @@ import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import com.kingsrook.qbits.backups.codec.ArtifactTransform;
|
||||
import com.kingsrook.qbits.backups.codec.StreamingCipherTransform;
|
||||
import com.kingsrook.qbits.backups.verify.ScratchTarget;
|
||||
import com.kingsrook.qbits.backups.storage.BackupStorage;
|
||||
import com.kingsrook.qqq.backend.core.crypto.QKeyProviderInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
@@ -417,7 +419,23 @@ public class BackupsQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for artifactTransformResolver (the decrypt hook for verify)
|
||||
** Turn client-side encryption on: plans may ask for CLIENT_AES256_GCM with an
|
||||
** encryption key reference, which names a key of this provider (for the
|
||||
** environment provider, the variable that holds it). The same provider reads
|
||||
** what it wrote, for verification and restore. Losing the key loses the
|
||||
** backups it wrote: the provider's store is what has to be kept safe.
|
||||
*******************************************************************************/
|
||||
public BackupsQBitConfig withKeyProvider(QKeyProviderInterface keyProvider)
|
||||
{
|
||||
this.artifactTransformResolver = keyProvider == null ? null : keyRef -> StreamingCipherTransform.forKey(keyProvider, keyRef);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for artifactTransformResolver: the cipher for an encryption key
|
||||
** reference, for writing, verifying and restoring (null: no encryption)
|
||||
*******************************************************************************/
|
||||
public Function<String, ArtifactTransform> getArtifactTransformResolver()
|
||||
{
|
||||
@@ -428,7 +446,9 @@ public class BackupsQBitConfig implements QBitConfig
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for artifactTransformResolver: encryption key reference (the name
|
||||
** of a key in a key provider) to the transform that decrypts what that key wrote.
|
||||
** of a key in a key provider) to the transform that encrypts with that key and
|
||||
** decrypts what it wrote, or null when there is no such key. withKeyProvider
|
||||
** sets the one built on the QQQ crypto package; this is for a host with its own.
|
||||
*******************************************************************************/
|
||||
public BackupsQBitConfig withArtifactTransformResolver(Function<String, ArtifactTransform> artifactTransformResolver)
|
||||
{
|
||||
|
||||
@@ -43,6 +43,7 @@ public final class BackupAlerts
|
||||
public static final String PLAN_OWNER_INVALID = "backups.plan.owner-invalid";
|
||||
public static final String STORAGE_DEBRIS = "backups.storage.debris";
|
||||
public static final String RESTORE_COMPLETED = "backups.restore.completed";
|
||||
public static final String PRUNE_FAILED = "backups.prune.failed";
|
||||
|
||||
/** The prefix of the heartbeat monitor key of a plan. */
|
||||
public static final String HEARTBEAT_PREFIX = "backups.plan:";
|
||||
@@ -95,7 +96,9 @@ public final class BackupAlerts
|
||||
new AlertType(STORAGE_DEBRIS, "Backup storage has debris or orphans", BackupAlertSink.Severity.INFO,
|
||||
"Prune clears debris. Orphan prefixes can be imported into the catalog or deleted."),
|
||||
new AlertType(RESTORE_COMPLETED, "A restore finished", BackupAlertSink.Severity.INFO,
|
||||
"Nothing to fix unless the restore failed. Open the restore run.")));
|
||||
"Nothing to fix unless the restore failed. Open the restore run."),
|
||||
new AlertType(PRUNE_FAILED, "Old backups could not be deleted", BackupAlertSink.Severity.WARNING,
|
||||
"The daily prune could not prune this plan, so its backups are kept past the plan's retention and storage grows. Run Prune per retention on the plan to see why.")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -83,4 +83,15 @@ public interface ArtifactTransform
|
||||
{
|
||||
return ("");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
** What a run records to say which key wrote its objects (never the key),
|
||||
** or null for a transform that has no key.
|
||||
***************************************************************************/
|
||||
default String keyFingerprint()
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.backups.codec;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import com.kingsrook.qqq.backend.core.crypto.QKeyMaterial;
|
||||
import com.kingsrook.qqq.backend.core.crypto.QKeyProviderInterface;
|
||||
import com.kingsrook.qqq.backend.core.crypto.StreamingArtifactCipher;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Client-side encryption of a backup's objects (the plan's CLIENT_AES256_GCM,
|
||||
** spec 11.2): the streaming cipher of the QQQ crypto package, keyed by a
|
||||
** reference into a key provider.
|
||||
**
|
||||
** Every object gets a fresh data key, wrapped by the current version of the
|
||||
** referenced key; the object's own header names the key and the version that
|
||||
** wrapped it, so an object written before a rotation is read with the version
|
||||
** it was written under for as long as the provider still has it.
|
||||
**
|
||||
** The key never leaves the provider and the cipher: it is in no table, log,
|
||||
** manifest or message. What is recorded is the reference and a fingerprint.
|
||||
*******************************************************************************/
|
||||
public final class StreamingCipherTransform implements ArtifactTransform
|
||||
{
|
||||
/** The scheme a manifest records for objects this transform wrote. */
|
||||
public static final String SCHEME = "tink-streaming-aead-AES256_GCM_HKDF_1MB";
|
||||
|
||||
private static final String FINGERPRINT_DOMAIN = "qbit-backups key fingerprint v1";
|
||||
private static final int FINGERPRINT_HEX = 16;
|
||||
|
||||
private final StreamingArtifactCipher cipher;
|
||||
private final String keyRef;
|
||||
private final String fingerprint;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private StreamingCipherTransform(QKeyProviderInterface keyProvider, String keyRef, String fingerprint)
|
||||
{
|
||||
this.cipher = new StreamingArtifactCipher(keyProvider);
|
||||
this.keyRef = keyRef;
|
||||
this.fingerprint = fingerprint;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The transform for a key reference, or null when the provider has no usable
|
||||
** key of that name (so that a plan, a run, a verification and a restore each
|
||||
** say "no key for this reference" in their own words, and nothing is written
|
||||
** or read in the clear instead).
|
||||
*******************************************************************************/
|
||||
public static StreamingCipherTransform forKey(QKeyProviderInterface keyProvider, String keyRef)
|
||||
{
|
||||
if(keyProvider == null || keyRef == null || keyRef.isBlank())
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
try
|
||||
{
|
||||
QKeyMaterial current = keyProvider.getKey(keyRef);
|
||||
return (current == null ? null : new StreamingCipherTransform(keyProvider, keyRef, fingerprint(current)));
|
||||
}
|
||||
catch(QException e)
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// the provider's message names the setting, never the key; the callers //
|
||||
// say which reference has no key, so nothing of it is carried further //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
return (null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What a run records to say which key (and which version of it) wrote its
|
||||
** objects: the version, and the start of a hash over the key under a label of
|
||||
** this qbit's own. Two keys do not share one, and the key cannot be had from it.
|
||||
*******************************************************************************/
|
||||
static String fingerprint(QKeyMaterial key)
|
||||
{
|
||||
try
|
||||
{
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
digest.update(FINGERPRINT_DOMAIN.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] keyBytes = key.getKeyBytes();
|
||||
try
|
||||
{
|
||||
digest.update(keyBytes);
|
||||
}
|
||||
finally
|
||||
{
|
||||
java.util.Arrays.fill(keyBytes, (byte) 0);
|
||||
}
|
||||
return ("v" + key.getVersion() + ":" + HexFormat.of().formatHex(digest.digest()).substring(0, FINGERPRINT_HEX));
|
||||
}
|
||||
catch(NoSuchAlgorithmException e)
|
||||
{
|
||||
throw (new IllegalStateException("SHA-256 is not available", e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** {@inheritDoc}
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public OutputStream wrap(OutputStream out) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
return (cipher.newEncryptingStream(keyRef, out));
|
||||
}
|
||||
catch(QException e)
|
||||
{
|
||||
throw (new IOException("An object could not be encrypted with the key " + keyRef + ": the key provider did not supply it"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** {@inheritDoc}
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public InputStream unwrap(InputStream in) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
return (cipher.newDecryptingStream(in));
|
||||
}
|
||||
catch(QException e)
|
||||
{
|
||||
throw (new IOException("An object could not be decrypted: it is not an encrypted backup object, or the key provider has no key of the version that wrote it (key " + keyRef + ")"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** {@inheritDoc}
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public boolean encrypts()
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** {@inheritDoc}
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String keySuffix()
|
||||
{
|
||||
return (".tink");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** {@inheritDoc}
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String keyFingerprint()
|
||||
{
|
||||
return (fingerprint);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ public final class BackupPlanValidator
|
||||
private static final Set<String> COMPRESSIONS = Set.of("GZIP", "NONE");
|
||||
private static final Set<String> LOCK_MODES = Set.of("NONE", "GOVERNANCE", "COMPLIANCE");
|
||||
|
||||
/** Replace with the real check when client-side encryption ships (spec 11.2). */
|
||||
/** For a host that installs a cipher of its own outside the config; a configured key provider needs no switch. */
|
||||
private static volatile boolean encryptionAvailable = false;
|
||||
|
||||
|
||||
@@ -69,8 +69,9 @@ public final class BackupPlanValidator
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Tell the validator that client-side encryption is available (the encryption
|
||||
** work calls this when it installs a cipher).
|
||||
** Tell the validator that client-side encryption is available although the
|
||||
** config has no key provider (a host with a cipher of its own). With a key
|
||||
** provider on the config it is available, and a plan's key is checked too.
|
||||
*******************************************************************************/
|
||||
public static void setEncryptionAvailable(boolean available)
|
||||
{
|
||||
@@ -193,14 +194,21 @@ public final class BackupPlanValidator
|
||||
String policy = settings.string("sensitiveFieldPolicy", "EXCLUDE");
|
||||
if("CLIENT_AES256_GCM".equals(mode))
|
||||
{
|
||||
if(!encryptionAvailable)
|
||||
var config = BackupsRuntime.getConfig();
|
||||
var resolver = config == null ? null : config.getArtifactTransformResolver();
|
||||
String keyRef = settings.string("encryptionKeyRef", null);
|
||||
if(!encryptionAvailable && resolver == null)
|
||||
{
|
||||
errors.add("Client-side encryption is not available in this version. Use NONE (and keep the sensitive field policy at EXCLUDE).");
|
||||
errors.add("Client-side encryption is not set up for this application: no key provider is configured. Use NONE (and keep the sensitive field policy at EXCLUDE).");
|
||||
}
|
||||
else if(settings.string("encryptionKeyRef", null) == null)
|
||||
else if(keyRef == null)
|
||||
{
|
||||
errors.add("Client-side encryption needs an encryption key reference (the name of the key, never the key itself).");
|
||||
}
|
||||
else if(resolver != null && resolver.apply(keyRef) == null)
|
||||
{
|
||||
errors.add("No key is available for the encryption key reference " + keyRef + ": the key provider has no usable key of that name. Nothing could be encrypted, so the plan was not saved.");
|
||||
}
|
||||
}
|
||||
if("INCLUDE_ENCRYPTED_ONLY".equals(policy) && !"CLIENT_AES256_GCM".equals(mode))
|
||||
{
|
||||
|
||||
@@ -60,6 +60,8 @@ public final class LifecycleProcesses
|
||||
processes.addAll(PruneProcess.processes());
|
||||
|
||||
BackupsQBitConfig config = BackupsRuntime.getConfig();
|
||||
processes.add(com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.processMetaData(config));
|
||||
processes.add(com.kingsrook.qbits.backups.schedule.BackupDuePlansProcess.processMetaData(config));
|
||||
if(config != null && StringUtils.hasContent(config.getSchedulerName()))
|
||||
{
|
||||
try
|
||||
|
||||
@@ -22,8 +22,6 @@ import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.backups.BackupsQBitConfig;
|
||||
import com.kingsrook.qbits.backups.BackupsRuntime;
|
||||
import com.kingsrook.qbits.backups.model.BackupsTables;
|
||||
import com.kingsrook.qbits.backups.permissions.BackupsPermissions;
|
||||
import com.kingsrook.qbits.backups.prune.BackupPruner;
|
||||
@@ -37,7 +35,6 @@ import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutp
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
|
||||
@@ -46,8 +43,9 @@ import static com.kingsrook.qbits.backups.processes.BackupsProcesses.line;
|
||||
|
||||
/*******************************************************************************
|
||||
** Prune per retention (spec 9, 10.3). A record action on backups_plan, and a
|
||||
** table action on backups_run (which prunes the plans of the selected runs); the
|
||||
** plan one also runs daily when the qbit has a scheduler.
|
||||
** table action on backups_run (which prunes the plans of the selected runs).
|
||||
** Both are for a person: they show what will be deleted and wait. The daily
|
||||
** prune of every active plan is BackupScheduledPruneProcess.
|
||||
**
|
||||
** Review shows exactly what Result will do: the runs to delete, the runs kept by
|
||||
** class, the runs kept because an object is still locked (with the date), the
|
||||
@@ -80,12 +78,6 @@ public final class PruneProcess
|
||||
QProcessMetaData onPlans = BackupsProcesses.permission(BackupsProcesses.etl(NAME, "Prune per retention", BackupsTables.PLAN, PlanTransform.class, Load.class,
|
||||
"This is a preview of what Prune will delete. Nothing is deleted until you continue."), BackupsPermissions.ADMIN);
|
||||
|
||||
BackupsQBitConfig config = BackupsRuntime.getConfig();
|
||||
if(config != null && config.getSchedulerName() != null && !config.getSchedulerName().isBlank())
|
||||
{
|
||||
onPlans.withSchedule(new QScheduleMetaData().withSchedulerName(config.getSchedulerName()).withRepeatSeconds(24 * 3600).withInitialDelaySeconds(3600));
|
||||
}
|
||||
|
||||
QProcessMetaData onRuns = BackupsProcesses.permission(BackupsProcesses.etl(NAME_RUNS, "Prune per retention", BackupsTables.RUN, RunTransform.class, Load.class,
|
||||
"This is a preview of what Prune will delete for the plans of the selected runs. Nothing is deleted until you continue."), BackupsPermissions.ADMIN);
|
||||
return (List.of(onPlans, onRuns));
|
||||
|
||||
@@ -153,6 +153,14 @@ public final class BackupSource
|
||||
}
|
||||
Function<BackupManifest.EncryptionInfo, ArtifactTransform> resolver = transformResolver;
|
||||
ArtifactTransform resolved = resolver == null ? null : resolver.apply(encryption);
|
||||
if(resolver == null && BackupsRuntime.getConfig() != null && BackupsRuntime.getConfig().getArtifactTransformResolver() != null)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// the configured key provider reads what it wrote; a resolver set here //
|
||||
// (by a host with a cipher of its own) takes its place //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
resolved = BackupsRuntime.getConfig().getArtifactTransformResolver().apply(encryption.keyRef());
|
||||
}
|
||||
if(resolved == null)
|
||||
{
|
||||
throw (new QException("This backup is encrypted (key " + encryption.keyRef() + "), and no key provider is available to restore it"));
|
||||
|
||||
@@ -41,6 +41,8 @@ import com.kingsrook.qbits.backups.BackupsRuntime;
|
||||
import com.kingsrook.qbits.backups.alerts.BackupAlertSink;
|
||||
import com.kingsrook.qbits.backups.codec.HashingOutputStream;
|
||||
import com.kingsrook.qbits.backups.codec.TableArtifactWriter;
|
||||
import com.kingsrook.qbits.backups.codec.ArtifactTransform;
|
||||
import com.kingsrook.qbits.backups.codec.StreamingCipherTransform;
|
||||
import com.kingsrook.qbits.backups.events.BackupEvents;
|
||||
import com.kingsrook.qbits.backups.files.FileCopier;
|
||||
import com.kingsrook.qbits.backups.files.FileReference;
|
||||
@@ -454,7 +456,7 @@ public class BackupEngine
|
||||
checkJob();
|
||||
if(indexWriter == null)
|
||||
{
|
||||
indexWriter = new FileIndexWriter(storage, runPrefix + "files/index-00001.jsonl.gz", result.getRunKey(), fileLockMode, fileRetainUntil);
|
||||
indexWriter = new FileIndexWriter(storage, runPrefix + "files/index-00001.jsonl.gz", result.getRunKey(), fileLockMode, fileRetainUntil, request.getTransform());
|
||||
}
|
||||
FileCopier.IndexEntry entry = copier.process(ref);
|
||||
indexWriter.write(entry);
|
||||
@@ -530,7 +532,7 @@ public class BackupEngine
|
||||
started.toString(), finished.toString(), request.getRequestedBy(), request.getSecurityScope(),
|
||||
new BackupManifest.ConsistencyInfo(result.getConsistencyAchieved(), List.of()),
|
||||
request.getTransform().encrypts()
|
||||
? new BackupManifest.EncryptionInfo("CLIENT_AES256_GCM", "tink-streaming-aead-AES256_GCM_HKDF_1MB", request.getEncryptionKeyRef(), request.getEncryptionKeyFingerprint())
|
||||
? new BackupManifest.EncryptionInfo("CLIENT_AES256_GCM", StreamingCipherTransform.SCHEME, request.getEncryptionKeyRef(), request.getEncryptionKeyFingerprint())
|
||||
: new BackupManifest.EncryptionInfo("NONE", null, null, null),
|
||||
manifestTables, order,
|
||||
new BackupManifest.FilesInfo(settings.fileObjectPolicy(), indexKeys, copied + deduplicated, fileBytes + fileBytesRef, missing),
|
||||
@@ -1085,9 +1087,11 @@ public class BackupEngine
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
** Constructor. The index names tables, record keys and where each file came
|
||||
** from, so in an encrypted run it is encrypted like the rows are: compressed,
|
||||
** then through the run's transform, then stored.
|
||||
*******************************************************************************/
|
||||
FileIndexWriter(BackupStorage storage, String key, String runKey, String lockMode, Instant retainUntil) throws IOException
|
||||
FileIndexWriter(BackupStorage storage, String key, String runKey, String lockMode, Instant retainUntil, ArtifactTransform transform) throws IOException
|
||||
{
|
||||
WriteOptions options = WriteOptions.create().withMetadata("qqq-backup-run", runKey);
|
||||
if(lockMode != null)
|
||||
@@ -1095,7 +1099,7 @@ public class BackupEngine
|
||||
options.withObjectLock(lockMode, retainUntil);
|
||||
}
|
||||
stored = new HashingOutputStream(storage.openWrite(key, options));
|
||||
raw = new HashingOutputStream(new GZIPOutputStream(stored));
|
||||
raw = new HashingOutputStream(new GZIPOutputStream((transform == null ? ArtifactTransform.IDENTITY : transform).wrap(stored)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -448,7 +448,8 @@ public class BackupRunCoordinator
|
||||
String mode = plan.getValueString("encryptionMode");
|
||||
if(mode != null && !"NONE".equals(mode) && !request.getTransform().encrypts())
|
||||
{
|
||||
return ("The plan asks for " + mode + " encryption, but no cipher is available in this version. Nothing was written.");
|
||||
return ("The plan asks for " + mode + " encryption, but no key is available for its encryption key reference"
|
||||
+ (plan.getValueString("encryptionKeyRef") == null ? "" : " " + plan.getValueString("encryptionKeyRef")) + " (no key provider is configured, or it has no key of that name). Nothing was written.");
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.backups.BackupsQBitConfig;
|
||||
import com.kingsrook.qbits.backups.BackupsRuntime;
|
||||
import com.kingsrook.qbits.backups.codec.ArtifactTransform;
|
||||
import com.kingsrook.qbits.backups.model.BackupsTables;
|
||||
import com.kingsrook.qbits.backups.scope.PlanSettings;
|
||||
import com.kingsrook.qbits.backups.scope.ScopeResolver;
|
||||
@@ -82,7 +83,7 @@ public final class BackupRunFactory
|
||||
QSession session = QContext.getQSession();
|
||||
String user = session == null || session.getUser() == null ? "system:scheduler" : session.getUser().getIdReference();
|
||||
|
||||
return (new BackupRunRequest()
|
||||
BackupRunRequest request = new BackupRunRequest()
|
||||
.withSettings(settings)
|
||||
.withScope(resolveScope(plan))
|
||||
.withTrigger(trigger)
|
||||
@@ -93,6 +94,23 @@ public final class BackupRunFactory
|
||||
.withSourceResolver(BackupsRuntime::storageFor)
|
||||
.withInstanceName(config.getInstanceName() != null ? config.getInstanceName() : "qqq")
|
||||
.withPlanName(plan.getValueString("name"))
|
||||
.withClock(BackupsRuntime.getClock()));
|
||||
.withClock(BackupsRuntime.getClock());
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// a plan that asks for client-side encryption gets the cipher for its key //
|
||||
// reference. When there is none (no key provider, or no key of that name), //
|
||||
// the request stays without one and the coordinator refuses the run: nothing //
|
||||
// is ever written in the clear for a plan that asked for encryption //
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
String keyRef = settings.string("encryptionKeyRef", null);
|
||||
if("CLIENT_AES256_GCM".equals(settings.string("encryptionMode", "NONE")) && keyRef != null && config.getArtifactTransformResolver() != null)
|
||||
{
|
||||
ArtifactTransform transform = config.getArtifactTransformResolver().apply(keyRef);
|
||||
if(transform != null && transform.encrypts())
|
||||
{
|
||||
request.withTransform(transform, keyRef, transform.keyFingerprint());
|
||||
}
|
||||
}
|
||||
return (request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.backups.schedule;
|
||||
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import com.kingsrook.qbits.backups.BackupsQBitConfig;
|
||||
import com.kingsrook.qbits.backups.BackupsRuntime;
|
||||
import com.kingsrook.qbits.backups.model.BackupsTables;
|
||||
import com.kingsrook.qbits.backups.permissions.BackupsPermissions;
|
||||
import com.kingsrook.qbits.backups.processes.BackupsProcesses;
|
||||
import com.kingsrook.qbits.backups.run.BackupCatalog;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.scheduledjobs.ScheduledJob;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import org.quartz.CronExpression;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Runs the backups and the verifications that are due, in an application that
|
||||
** has no scheduled-jobs table.
|
||||
**
|
||||
** A plan's schedule is its own cron fields. Where the application has QQQ's
|
||||
** scheduled-jobs table, each plan is kept in sync with a scheduled job of its
|
||||
** own (BackupPlanSyncToScheduledJobProcess), which is what starts it. Where it
|
||||
** has none, that sync quietly did nothing and no plan ever ran on its schedule
|
||||
** unless the host built a scheduler of its own. This process is that scheduler,
|
||||
** on the qbit's own: once a minute it starts every active plan whose cron has
|
||||
** come due since the plan last started (or was created), and every
|
||||
** verification that has come due since the plan was last verified.
|
||||
**
|
||||
** Times that were missed (the application was down) collapse into one run. A
|
||||
** run that fails counts as a start, so an outage is not followed by a retry
|
||||
** every minute. The run itself is BackupScheduledRunProcess: the owner check,
|
||||
** the one-run-per-plan lease, the alerts and the SLA are its, unchanged.
|
||||
**
|
||||
** Only the scheduler may run it: it starts work with a full view of the
|
||||
** application, which no request from a browser may ask for.
|
||||
*******************************************************************************/
|
||||
public class BackupDuePlansProcess implements BackendStep
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(BackupDuePlansProcess.class);
|
||||
|
||||
public static final String NAME = "backupRunDuePlans";
|
||||
|
||||
private static final int EVERY_SECONDS = 60;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The process metadata: not in the nav; on the qbit's scheduler once a minute
|
||||
** when it has one.
|
||||
*******************************************************************************/
|
||||
public static QProcessMetaData processMetaData(BackupsQBitConfig config)
|
||||
{
|
||||
QProcessMetaData process = new QProcessMetaData()
|
||||
.withName(NAME)
|
||||
.withLabel("Run due backup plans")
|
||||
.withIsHidden(true)
|
||||
.withStep(new QBackendStepMetaData().withName("tick").withCode(new QCodeReference(BackupDuePlansProcess.class)));
|
||||
process.setPermissionRules(BackupsTables.permissionRules());
|
||||
if(config != null && StringUtils.hasContent(config.getSchedulerName()))
|
||||
{
|
||||
process.setSchedule(new QScheduleMetaData()
|
||||
.withSchedulerName(config.getSchedulerName())
|
||||
.withRepeatSeconds(EVERY_SECONDS)
|
||||
.withInitialDelaySeconds(EVERY_SECONDS)
|
||||
.withDescription("Start the backups and verifications whose plan schedule has come due"));
|
||||
}
|
||||
return (BackupsProcesses.permission(process, BackupsPermissions.ADMIN));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Start what is due.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
if(!(QContext.getQSession() instanceof QSystemUserSession))
|
||||
{
|
||||
throw (new QPermissionDeniedException("Backup plans are started by the scheduler."));
|
||||
}
|
||||
if(QContext.getQInstance().getTable(ScheduledJob.TABLE_NAME) != null)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// the application's scheduled jobs start the plans: starting them here //
|
||||
// too would run every backup twice //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
output.addValue("startedBy", "scheduledJobs");
|
||||
return;
|
||||
}
|
||||
|
||||
BackupCatalog catalog = new BackupCatalog();
|
||||
Instant now = BackupsRuntime.getClock().instant();
|
||||
int backups = 0;
|
||||
int verifies = 0;
|
||||
for(QRecord plan : catalog.where(BackupsTables.PLAN, "isActive", true))
|
||||
{
|
||||
try
|
||||
{
|
||||
if(isDue(plan.getValueString("cronExpression"), plan.getValueString("cronTimeZoneId"), lastStart(catalog, plan), now))
|
||||
{
|
||||
new BackupScheduledRunProcess().run(new RunBackendStepInput().withRecords(List.of(plan)), new RunBackendStepOutput());
|
||||
backups++;
|
||||
}
|
||||
Instant verified = plan.getValueInstant("lastVerifiedDate");
|
||||
if(isDue(plan.getValueString("verifyCronExpression"), plan.getValueString("cronTimeZoneId"), verified == null ? plan.getValueInstant("createDate") : verified, now)
|
||||
&& BackupScheduledRunProcess.ownerProblem(plan) == null)
|
||||
{
|
||||
new BackupScheduledVerifyProcess().run(new RunBackendStepInput().withRecords(List.of(plan)), new RunBackendStepOutput());
|
||||
verifies++;
|
||||
}
|
||||
}
|
||||
catch(QException | ParseException | RuntimeException e)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// the run and the verification record their own failure, with detail, //
|
||||
// and alert. One plan's trouble must not keep the others from starting //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
LOG.warn("A scheduled backup plan could not complete", logPair("plan", plan.getValueString("planKey")), logPair("failure", e.getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
output.addValue("startedBy", "plans");
|
||||
output.addValue("backupsStarted", backups);
|
||||
output.addValue("verificationsStarted", verifies);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** When the plan last started a run, successful or not; for a plan that has
|
||||
** never run, when it was created.
|
||||
*******************************************************************************/
|
||||
private static Instant lastStart(BackupCatalog catalog, QRecord plan) throws QException
|
||||
{
|
||||
List<QRecord> runs = catalog.query(BackupsTables.RUN, new QQueryFilter()
|
||||
.withCriteria(new QFilterCriteria("backupPlanId", QCriteriaOperator.EQUALS, plan.getValueInteger("id")))
|
||||
.withOrderBy(new QFilterOrderBy("id", false)).withLimit(1));
|
||||
Instant start = runs.isEmpty() ? null : runs.get(0).getValueInstant("startDate");
|
||||
return (start == null ? plan.getValueInstant("createDate") : start);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the cron has a time after "since" that is not after "now". A zone
|
||||
** that is not a zone fails; it does not quietly become GMT.
|
||||
*******************************************************************************/
|
||||
static boolean isDue(String cron, String zone, Instant since, Instant now) throws ParseException
|
||||
{
|
||||
if(!StringUtils.hasContent(cron) || since == null)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
CronExpression expression = new CronExpression(cron);
|
||||
expression.setTimeZone(TimeZone.getTimeZone(ZoneId.of(StringUtils.hasContent(zone) ? zone : "UTC")));
|
||||
Date next = expression.getNextValidTimeAfter(Date.from(since));
|
||||
return (next != null && !next.toInstant().isAfter(now));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.backups.schedule;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.backups.BackupsQBitConfig;
|
||||
import com.kingsrook.qbits.backups.alerts.BackupAlertSink;
|
||||
import com.kingsrook.qbits.backups.alerts.BackupAlerts;
|
||||
import com.kingsrook.qbits.backups.model.BackupsTables;
|
||||
import com.kingsrook.qbits.backups.permissions.BackupsPermissions;
|
||||
import com.kingsrook.qbits.backups.processes.BackupsProcesses;
|
||||
import com.kingsrook.qbits.backups.prune.BackupPruner;
|
||||
import com.kingsrook.qbits.backups.run.BackupCatalog;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The daily prune: every plan that is switched on is pruned to its retention
|
||||
** (spec 10.3), with nobody there to pick plans or read a review screen.
|
||||
**
|
||||
** "Prune per retention" (backupPrune) is the action a person runs on the plans
|
||||
** they select; it shows what it will delete and waits. It used to carry the
|
||||
** daily schedule too, and a scheduler that started it selected nothing, was
|
||||
** told "No records were selected", logged a warning and went on: no old backup
|
||||
** was ever deleted by the schedule. This process is what the schedule runs.
|
||||
**
|
||||
** A plan that cannot be pruned raises backups.prune.failed (resolved by its
|
||||
** next good prune) and does not stop the others. A plan that is switched off
|
||||
** is left alone: its backups stay until a person prunes or deletes them.
|
||||
*******************************************************************************/
|
||||
public class BackupScheduledPruneProcess implements BackendStep
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(BackupScheduledPruneProcess.class);
|
||||
|
||||
public static final String NAME = "backupPruneScheduled";
|
||||
|
||||
private static final int EVERY_SECONDS = 24 * 3600;
|
||||
private static final int FIRST_AFTER = 3600;
|
||||
private static final long BYTES_PER_MEBI = 1024L * 1024L;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The process metadata: not in the nav; on the qbit's scheduler once a day
|
||||
** when it has one.
|
||||
*******************************************************************************/
|
||||
public static QProcessMetaData processMetaData(BackupsQBitConfig config)
|
||||
{
|
||||
QProcessMetaData process = new QProcessMetaData()
|
||||
.withName(NAME)
|
||||
.withLabel("Prune every backup plan")
|
||||
.withIsHidden(true)
|
||||
.withStep(new QBackendStepMetaData().withName("prune").withCode(new QCodeReference(BackupScheduledPruneProcess.class)));
|
||||
process.setPermissionRules(BackupsTables.permissionRules());
|
||||
if(config != null && StringUtils.hasContent(config.getSchedulerName()))
|
||||
{
|
||||
process.setSchedule(new QScheduleMetaData()
|
||||
.withSchedulerName(config.getSchedulerName())
|
||||
.withRepeatSeconds(EVERY_SECONDS)
|
||||
.withInitialDelaySeconds(FIRST_AFTER)
|
||||
.withDescription("Prune every active backup plan to its retention"));
|
||||
}
|
||||
return (BackupsProcesses.permission(process, BackupsPermissions.ADMIN));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Prune every active plan; say what was done.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
QSession session = QContext.getQSession();
|
||||
String user = session == null || session.getUser() == null || session.getUser().getIdReference() == null ? "system:scheduler" : session.getUser().getIdReference();
|
||||
|
||||
List<QRecord> plans = new BackupCatalog().where(BackupsTables.PLAN, "isActive", true);
|
||||
int pruned = 0;
|
||||
int failed = 0;
|
||||
int runsDeleted = 0;
|
||||
int filesSwept = 0;
|
||||
long bytesFreed = 0;
|
||||
for(QRecord plan : plans)
|
||||
{
|
||||
String planKey = plan.getValueString("planKey");
|
||||
try
|
||||
{
|
||||
BackupPruner.Outcome outcome = new BackupPruner().prune(plan, user);
|
||||
pruned++;
|
||||
runsDeleted += outcome.runsDeleted() + outcome.debrisPrefixesDeleted();
|
||||
filesSwept += outcome.filesSwept();
|
||||
bytesFreed += outcome.bytesFreed();
|
||||
BackupAlerts.resolve(BackupAlerts.PRUNE_FAILED, planKey);
|
||||
}
|
||||
catch(QException | RuntimeException e)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// one plan's trouble (a bucket that cannot be listed, a locked object) //
|
||||
// must not leave the others unpruned. The class says what kind of //
|
||||
// failure it was; a message could carry a key or an endpoint //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
failed++;
|
||||
LOG.warn("A backup plan could not be pruned", logPair("plan", planKey), logPair("failure", e.getClass().getSimpleName()));
|
||||
BackupAlerts.raise(BackupAlerts.PRUNE_FAILED, planKey, BackupAlertSink.Severity.WARNING, "Old backups of " + plan.getValueString("name") + " could not be deleted",
|
||||
"plan", planKey, "failure", e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
LOG.info("Scheduled prune finished", logPair("plansPruned", pruned), logPair("plansFailed", failed), logPair("runsDeleted", runsDeleted), logPair("filesSwept", filesSwept));
|
||||
output.addValue("plansPruned", pruned);
|
||||
output.addValue("plansFailed", failed);
|
||||
output.addValue("runsDeleted", runsDeleted);
|
||||
output.addValue("filesSwept", filesSwept);
|
||||
output.addValue("mebibytesFreed", bytesFreed / BYTES_PER_MEBI);
|
||||
}
|
||||
}
|
||||
@@ -609,6 +609,14 @@ entries:
|
||||
Use **Create default plan** on **Backup plans** and enter a **Storage bucket alias** provided by your application. Review the proposed plan before continuing. The action adds **Nightly full** for data and audit tables with JSONL, gzip and copied files, scheduled at 02:00 UTC with content verification on Sundays at 04:00 UTC.
|
||||
|
||||
You can edit the settings afterward. The action creates a plan only when its plan key does not already exist; it does not change an existing plan. Scheduled execution requires your application's scheduler integration.
|
||||
- key: process:backupPruneScheduled;slot:help
|
||||
summary: 'Delete, once a day, the backups that every active plan no longer keeps.'
|
||||
content: |
|
||||
This background action prunes every **Backup Plan** that is switched on to its retention: the daily, weekly, monthly and yearly copies the plan keeps, and its minimum. Nobody selects plans or reads a review for it. A plan that is switched off is left alone. A plan that cannot be pruned raises the alert **Old backups could not be deleted**, which its next successful prune clears, and does not stop the others. To see what a prune would delete before it happens, use **Prune per retention** on the plan.
|
||||
- key: process:backupRunDuePlans;slot:help
|
||||
summary: 'Start the backups and verifications whose plan schedule has come due.'
|
||||
content: |
|
||||
This background action is how plans run on their own schedule in an application that has no scheduled jobs table. Once a minute it starts every active **Backup Plan** whose schedule has come due since the plan last started, and every verification that has come due. Times missed while the application was down become one run. Where the application has scheduled jobs, each plan has a scheduled job of its own and this action starts nothing. Only the scheduler can run it.
|
||||
- key: process:backupVerifyPlan;slot:help
|
||||
summary: Verify the latest successful backup of a scheduled plan.
|
||||
content: |
|
||||
|
||||
@@ -191,10 +191,10 @@ class AlertsQBitAlertSinkTest
|
||||
AlertsQBitAlertSink sink = new AlertsQBitAlertSink();
|
||||
int added = sink.registerAlertTypes(instance);
|
||||
var types = new ArrayList<>(AlertsInstanceMetaData.of(instance).getAlertTypes().values());
|
||||
assertThat(added).isEqualTo(BackupAlerts.alertTypes().size()).isEqualTo(9);
|
||||
assertThat(added).isEqualTo(BackupAlerts.alertTypes().size()).isEqualTo(10);
|
||||
assertThat(types).extracting(t -> t.getName()).containsExactly(
|
||||
"backups.plan.missed", "backups.run.failed", "backups.run.missing-in-storage", "backups.files.missing", "backups.verify.failed",
|
||||
"backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed");
|
||||
"backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed", "backups.prune.failed");
|
||||
assertThat(types).allSatisfy(t ->
|
||||
{
|
||||
assertThat(t.getGroupName()).isEqualTo("Backups");
|
||||
|
||||
@@ -71,7 +71,7 @@ class BackupAlertsTest
|
||||
{
|
||||
Set<String> names = BackupAlerts.alertTypes().stream().map(BackupAlerts.AlertType::name).collect(Collectors.toSet());
|
||||
assertThat(names).containsExactlyInAnyOrder("backups.plan.missed", "backups.run.failed", "backups.run.missing-in-storage", "backups.files.missing",
|
||||
"backups.verify.failed", "backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed");
|
||||
"backups.verify.failed", "backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed", "backups.prune.failed");
|
||||
assertThat(BackupAlerts.alertTypes()).allSatisfy(t -> assertThat(t.howToFix()).isNotBlank());
|
||||
assertThat(BackupAlerts.alertTypes().stream().filter(t -> t.name().equals(BackupAlerts.RUN_MISSING)).findFirst().orElseThrow().defaultSeverity())
|
||||
.isEqualTo(BackupAlertSink.Severity.CRITICAL);
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.backups.codec;
|
||||
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The transform that encrypts a backup's objects: what it writes can be read
|
||||
** back with the key and with nothing else, a changed or cut-off object is
|
||||
** refused, a rotated key still reads what its older version wrote, and what a
|
||||
** run records about the key is not the key.
|
||||
**
|
||||
** Every key here is random and made for the test.
|
||||
*******************************************************************************/
|
||||
class StreamingCipherTransformTest
|
||||
{
|
||||
private static final String KEY_REF = "BACKUPS_TEST_KEK";
|
||||
private static final byte[] PLAIN = ("{\"id\":1,\"title\":\"a row of a backup\"}\n".repeat(4000)).getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A new random key, as the text an environment variable would hold.
|
||||
*******************************************************************************/
|
||||
private static String newKey()
|
||||
{
|
||||
byte[] key = new byte[32];
|
||||
new SecureRandom().nextBytes(key);
|
||||
return (Base64.getEncoder().encodeToString(key));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static byte[] encrypt(ArtifactTransform transform, byte[] plain) throws IOException
|
||||
{
|
||||
ByteArrayOutputStream stored = new ByteArrayOutputStream();
|
||||
try(OutputStream out = transform.wrap(stored))
|
||||
{
|
||||
out.write(plain);
|
||||
}
|
||||
return (stored.toByteArray());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static byte[] decrypt(ArtifactTransform transform, byte[] stored) throws IOException
|
||||
{
|
||||
try(InputStream in = transform.unwrap(new ByteArrayInputStream(stored)))
|
||||
{
|
||||
return (in.readAllBytes());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What is stored is not what was written, and the key reads it back exactly.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testWhatIsStoredIsCiphertextAndTheKeyReadsItBack() throws Exception
|
||||
{
|
||||
Map<String, String> env = new HashMap<>(Map.of(KEY_REF, newKey()));
|
||||
ArtifactTransform transform = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
|
||||
|
||||
assertThat(transform).isNotNull();
|
||||
assertThat(transform.encrypts()).isTrue();
|
||||
assertThat(transform.keySuffix()).isEqualTo(".tink");
|
||||
|
||||
byte[] stored = encrypt(transform, PLAIN);
|
||||
assertThat(new String(stored, StandardCharsets.ISO_8859_1)).doesNotContain("a row of a backup");
|
||||
assertThat(stored.length).isGreaterThan(PLAIN.length);
|
||||
assertThat(decrypt(transform, stored)).isEqualTo(PLAIN);
|
||||
assertThat(encrypt(transform, PLAIN)).as("a fresh data key for every object").isNotEqualTo(stored);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A flipped byte, and an object cut short, are refused: nothing altered is
|
||||
** ever handed back as if it were the backup.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testAChangedOrCutOffObjectIsRefused() throws Exception
|
||||
{
|
||||
Map<String, String> env = new HashMap<>(Map.of(KEY_REF, newKey()));
|
||||
ArtifactTransform transform = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
|
||||
byte[] stored = encrypt(transform, PLAIN);
|
||||
|
||||
byte[] flipped = stored.clone();
|
||||
flipped[flipped.length / 2] ^= 0x01;
|
||||
assertThatThrownBy(() -> decrypt(transform, flipped)).isInstanceOf(IOException.class);
|
||||
|
||||
byte[] cut = java.util.Arrays.copyOf(stored, stored.length - 100);
|
||||
assertThatThrownBy(() -> decrypt(transform, cut)).isInstanceOf(IOException.class);
|
||||
|
||||
assertThatThrownBy(() -> decrypt(transform, PLAIN)).as("an object that was never encrypted").isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Another key does not read it, and its message says nothing of either key.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testAnotherKeyDoesNotReadIt() throws Exception
|
||||
{
|
||||
String rightKey = newKey();
|
||||
String wrongKey = newKey();
|
||||
byte[] stored = encrypt(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, rightKey)::get), KEY_REF), PLAIN);
|
||||
|
||||
ArtifactTransform wrong = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, wrongKey)::get), KEY_REF);
|
||||
assertThatThrownBy(() -> decrypt(wrong, stored)).isInstanceOf(IOException.class)
|
||||
.satisfies(e -> assertThat(String.valueOf(e.getMessage())).doesNotContain(rightKey).doesNotContain(wrongKey));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A reference with no key, or a key that is not a key, gives no transform: the
|
||||
** caller then refuses, and nothing is written in the clear instead.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testNoKeyGivesNoTransform()
|
||||
{
|
||||
assertThat(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.<String, String>of()::get), KEY_REF)).isNull();
|
||||
assertThat(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, "not-a-key")::get), KEY_REF)).isNull();
|
||||
assertThat(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, newKey())::get), " ")).isNull();
|
||||
assertThat(StreamingCipherTransform.forKey(null, KEY_REF)).isNull();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After a rotation the new version writes, and what the old version wrote is
|
||||
** still read for as long as the provider keeps that version; without it, it is
|
||||
** refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testARotatedKeyStillReadsWhatItsOlderVersionWrote() throws Exception
|
||||
{
|
||||
Map<String, String> env = new HashMap<>();
|
||||
String first = newKey();
|
||||
env.put(KEY_REF, first);
|
||||
ArtifactTransform before = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
|
||||
byte[] oldObject = encrypt(before, PLAIN);
|
||||
|
||||
env.put(KEY_REF + "_V1", first);
|
||||
env.put(KEY_REF, newKey());
|
||||
env.put(KEY_REF + "_VERSION", "2");
|
||||
ArtifactTransform after = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
|
||||
|
||||
assertThat(after.keyFingerprint()).startsWith("v2:").isNotEqualTo(before.keyFingerprint());
|
||||
assertThat(decrypt(after, oldObject)).as("written under version 1, read after the rotation").isEqualTo(PLAIN);
|
||||
assertThat(decrypt(after, encrypt(after, PLAIN))).isEqualTo(PLAIN);
|
||||
|
||||
env.remove(KEY_REF + "_V1");
|
||||
ArtifactTransform withoutTheOldVersion = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
|
||||
assertThatThrownBy(() -> decrypt(withoutTheOldVersion, oldObject)).isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The fingerprint a run records names the version, is the same every time for
|
||||
** one key, differs between keys, and holds nothing of the key.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testTheFingerprintIsNotTheKey()
|
||||
{
|
||||
String keyText = newKey();
|
||||
String one = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, keyText)::get), KEY_REF).keyFingerprint();
|
||||
String again = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, keyText)::get), KEY_REF).keyFingerprint();
|
||||
String another = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, newKey())::get), KEY_REF).keyFingerprint();
|
||||
String keyAsHex = java.util.HexFormat.of().formatHex(Base64.getDecoder().decode(keyText));
|
||||
|
||||
assertThat(one).matches("v1:[0-9a-f]{16}").isEqualTo(again).isNotEqualTo(another);
|
||||
assertThat(keyAsHex).doesNotContain(one.substring(3));
|
||||
assertThat(keyText).doesNotContain(one.substring(3));
|
||||
}
|
||||
}
|
||||
@@ -160,17 +160,35 @@ class BackupPlanValidationTest
|
||||
/*******************************************************************************
|
||||
** Including sensitive fields only encrypted needs encryption; client-side
|
||||
** encryption is refused until a cipher is installed, and then needs a key name.
|
||||
** With a key provider on the config the key must be one the provider has.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testEncryptionRules() throws Exception
|
||||
{
|
||||
assertThat(errors(save(Map.of("sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY")))).singleElement().asString().contains("requires client-side encryption");
|
||||
assertThat(errors(save(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).singleElement().asString().contains("not available in this version");
|
||||
assertThat(errors(save(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).singleElement().asString().contains("no key provider is configured");
|
||||
assertThat(errors(save(Map.of("sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).hasSize(1);
|
||||
|
||||
BackupPlanValidator.setEncryptionAvailable(true);
|
||||
assertThat(errors(save(Map.of("sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).isEmpty();
|
||||
assertThat(errors(save(Map.of("encryptionMode", "CLIENT_AES256_GCM")))).singleElement().asString().contains("encryption key reference");
|
||||
|
||||
BackupPlanValidator.setEncryptionAvailable(false);
|
||||
byte[] key = new byte[32];
|
||||
new java.security.SecureRandom().nextBytes(key);
|
||||
Map<String, String> env = Map.of("PLAN_TEST_KEK", java.util.Base64.getEncoder().encodeToString(key));
|
||||
com.kingsrook.qbits.backups.BackupsRuntime.getConfig().withKeyProvider(new com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider(env::get));
|
||||
try
|
||||
{
|
||||
assertThat(errors(save(Map.of("planKey", "with-a-key", "sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "PLAN_TEST_KEK"))))
|
||||
.as("the provider has this key").isEmpty();
|
||||
assertThat(errors(save(Map.of("planKey", "without-a-key", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "NO_SUCH_KEK")))).singleElement().asString()
|
||||
.contains("No key is available for the encryption key reference NO_SUCH_KEK");
|
||||
}
|
||||
finally
|
||||
{
|
||||
com.kingsrook.qbits.backups.BackupsRuntime.getConfig().withKeyProvider(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import com.kingsrook.qbits.backups.alerts.BackupAlerts;
|
||||
import com.kingsrook.qbits.backups.BackupsRuntime;
|
||||
import com.kingsrook.qbits.backups.BackupsTestUtils;
|
||||
import com.kingsrook.qbits.backups.LifecycleTestSupport;
|
||||
@@ -262,6 +263,92 @@ class LifecycleProcessesTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The daily prune, started the way the scheduler starts it: no plan selected,
|
||||
** nobody at a review screen. Every plan that is switched on is pruned to its
|
||||
** retention (a plan that is switched off is left alone), so old backups do not
|
||||
** pile up for ever.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testTheScheduledPrunePrunesEveryActivePlanWithNobodyThere() throws Exception
|
||||
{
|
||||
QRecord plan = LifecycleTestSupport.plan(Map.of("retainDaily", 2, "retainWeekly", 0, "retainMonthly", 0, "retainYearly", 0, "retainMinimum", 0));
|
||||
QRecord off = LifecycleTestSupport.plan(Map.of("name", "Switched off", "planKey", "switched-off", "prefix", "switched-off", "retainDaily", 1, "retainWeekly", 0, "retainMonthly", 0,
|
||||
"retainYearly", 0, "retainMinimum", 0));
|
||||
BackupRunResult first = null;
|
||||
BackupRunResult firstOff = null;
|
||||
for(int day = 1; day <= 4; day++)
|
||||
{
|
||||
clock.set(DAY_1.plus(Duration.ofDays(day - 1)));
|
||||
BackupRunResult result = new BackupRunCoordinator().runPlan(plan, "SCHEDULED");
|
||||
first = first == null ? result : first;
|
||||
BackupRunResult other = new BackupRunCoordinator().runPlan(off, "SCHEDULED");
|
||||
firstOff = firstOff == null ? other : firstOff;
|
||||
}
|
||||
new com.kingsrook.qqq.backend.core.actions.tables.UpdateAction().execute(new com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput(BackupsTables.PLAN)
|
||||
.withRecord(new QRecord().withValue("id", off.getValueInteger("id")).withValue("isActive", false)));
|
||||
assertThat(BackupsTestUtils.BACKUPS.list(first.getRunPrefix())).as("the oldest run is there before the prune").isNotEmpty();
|
||||
|
||||
var instance = com.kingsrook.qqq.backend.core.context.QContext.getQInstance();
|
||||
String scheduled = com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.NAME;
|
||||
assertThat(instance.getProcess(PruneProcess.NAME).getSchedule()).as("the action a person runs is not what the schedule runs: it needs plans selected and a review").isNull();
|
||||
assertThat(instance.getProcess(scheduled)).as("the process the schedule runs").isNotNull();
|
||||
assertThat(instance.getProcess(scheduled).getIsHidden()).isTrue();
|
||||
var session = com.kingsrook.qqq.backend.core.context.QContext.getQSession();
|
||||
com.kingsrook.qqq.backend.core.scheduler.SchedulerUtils.runProcess(instance, () -> session, instance.getProcess(scheduled), null, new java.util.HashMap<>());
|
||||
com.kingsrook.qqq.backend.core.context.QContext.init(instance, session);
|
||||
|
||||
assertThat(BackupsTestUtils.BACKUPS.list(first.getRunPrefix())).as("the oldest run of the plan that is on was deleted").isEmpty();
|
||||
assertThat(new BackupCatalog().where(BackupsTables.RUN, "backupPlanId", plan.getValueInteger("id")).stream().filter(run -> !"PRUNED".equals(run.getValueString("status")) && run.getValue("prunedDate") == null))
|
||||
.as("two daily backups are kept").hasSize(2);
|
||||
assertThat(BackupsTestUtils.BACKUPS.list(firstOff.getRunPrefix())).as("a plan that is switched off is not pruned by the schedule").isNotEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** With a scheduler on the config the daily prune is scheduled, once a day, and
|
||||
** the action a person runs is not. A plan whose storage has gone away does
|
||||
** not stop the others, and raises an alert that its next good prune resolves.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testTheScheduledPruneIsOnTheSchedulerAndOnePlansTroubleDoesNotStopTheOthers() throws Exception
|
||||
{
|
||||
var config = new com.kingsrook.qbits.backups.BackupsQBitConfig().withSchedulerName("testScheduler");
|
||||
var meta = com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.processMetaData(config);
|
||||
assertThat(meta.getSchedule()).isNotNull();
|
||||
assertThat(meta.getSchedule().getRepeatSeconds()).isEqualTo(24 * 3600);
|
||||
assertThat(meta.getSchedule().getSchedulerName()).isEqualTo("testScheduler");
|
||||
assertThat(com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.processMetaData(new com.kingsrook.qbits.backups.BackupsQBitConfig()).getSchedule())
|
||||
.as("no scheduler, no schedule").isNull();
|
||||
|
||||
QRecord good = LifecycleTestSupport.plan(Map.of("retainDaily", 1, "retainWeekly", 0, "retainMonthly", 0, "retainYearly", 0, "retainMinimum", 0));
|
||||
QRecord bad = LifecycleTestSupport.plan(Map.of("name", "Storage gone", "planKey", "storage-gone", "prefix", "storage-gone", "storageBucketAlias", "media"));
|
||||
BackupRunResult first = null;
|
||||
for(int day = 1; day <= 3; day++)
|
||||
{
|
||||
clock.set(DAY_1.plus(Duration.ofDays(day - 1)));
|
||||
BackupRunResult result = new BackupRunCoordinator().runPlan(good, "SCHEDULED");
|
||||
first = first == null ? result : first;
|
||||
}
|
||||
|
||||
BackupsRuntime.getConfig().withStorageResolver(alias -> "backups".equals(alias) ? BackupsTestUtils.BACKUPS : null);
|
||||
var sink = new com.kingsrook.qbits.backups.RecordingAlertSink();
|
||||
BackupsRuntime.setAlertSink(sink);
|
||||
var output = new com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput();
|
||||
new com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess().run(new com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput(), output);
|
||||
|
||||
assertThat(output.getValueInteger("plansPruned")).isEqualTo(1);
|
||||
assertThat(output.getValueInteger("plansFailed")).isEqualTo(1);
|
||||
assertThat(output.getValueInteger("runsDeleted")).isEqualTo(2);
|
||||
assertThat(BackupsTestUtils.BACKUPS.list(first.getRunPrefix())).as("the plan that could be pruned was").isEmpty();
|
||||
assertThat(bad.getValueString("planKey")).isEqualTo("storage-gone");
|
||||
assertThat(sink.open.values()).as("the plan that could not be pruned says so").anyMatch(alert -> BackupAlerts.PRUNE_FAILED.equals(alert.type()) && alert.dedupeKey().contains("storage-gone"));
|
||||
assertThat(sink.open.values()).as("and only that plan").noneMatch(alert -> BackupAlerts.PRUNE_FAILED.equals(alert.type()) && alert.dedupeKey().contains("nightly"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The run table action prunes the plans of the selected runs, once each.
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -175,6 +175,47 @@ class RestoreModesTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A restore from an encrypted backup, with the key provider of the config and
|
||||
** nothing else set up: the edited rows are rolled back, and the file that was
|
||||
** removed comes back as it was although its copy in the backup is ciphertext.
|
||||
** Without the key the restore is refused before anything is read or written.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testRestoreFromAnEncryptedBackup() throws Exception
|
||||
{
|
||||
java.util.Map<String, String> env = new java.util.HashMap<>();
|
||||
byte[] key = new byte[32];
|
||||
new java.security.SecureRandom().nextBytes(key);
|
||||
env.put("RESTORE_TEST_KEK", java.util.Base64.getEncoder().encodeToString(key));
|
||||
com.kingsrook.qbits.backups.BackupsRuntime.getConfig().withKeyProvider(new com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider(env::get));
|
||||
|
||||
BackupRunResult run = RestoreTestSupport.backup(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "RESTORE_TEST_KEK", "sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY"));
|
||||
assertThat(RestoreTestSupport.manifest(run).encryption().mode()).isEqualTo("CLIENT_AES256_GCM");
|
||||
assertThat(RestoreTestSupport.manifest(run).encryption().keyFingerprint()).startsWith("v1:");
|
||||
assertThat(BackupsTestUtils.BACKUPS.list("").stream().filter(o -> o.key().contains("_files/sha256/")).map(o -> new String(BackupsTestUtils.BACKUPS.getBytes(o.key()))))
|
||||
.as("the copies of the files are ciphertext too").isNotEmpty().noneMatch(content -> content.contains("photo bytes"));
|
||||
byte[] index = BackupsTestUtils.BACKUPS.list("").stream().filter(o -> o.key().endsWith("files/index-00001.jsonl.gz")).map(o -> BackupsTestUtils.BACKUPS.getBytes(o.key())).findFirst().orElseThrow();
|
||||
assertThat(new String(index, 0, 4, java.nio.charset.StandardCharsets.US_ASCII)).as("the file index names record keys and where files came from: it is encrypted too").isEqualTo("QSC1");
|
||||
|
||||
RestoreTestSupport.mutate();
|
||||
BackupsTestUtils.MEDIA.removeIgnoringLock("media/photo-1.jpg");
|
||||
|
||||
RestoreOutcome outcome = new RestoreEngine().execute(RestoreTestSupport.request(run, RestoreRequest.MODE_UPSERT, "blogPost"));
|
||||
assertThat(outcome.getErrors()).isEmpty();
|
||||
assertThat(outcome.getTables().get("blogPost").getUpdated()).isEqualTo(10);
|
||||
assertThat(outcome.getTables().get("blogPost").getFilesRestored()).isEqualTo(1);
|
||||
assertThat(RestoreTestSupport.rows("blogPost").stream().filter(r -> r.getValueInteger("id") == 15).findFirst().orElseThrow().getValueString("title")).isEqualTo("Post 15");
|
||||
assertThat(new String(BackupsTestUtils.MEDIA.getBytes("media/photo-1.jpg"))).isEqualTo("photo bytes 1");
|
||||
|
||||
env.clear();
|
||||
RestoreOutcome refused = new RestoreEngine().review(RestoreTestSupport.request(run, RestoreRequest.MODE_UPSERT, "blogPost"));
|
||||
assertThat(refused.getErrors()).singleElement().asString().contains("This backup is encrypted (key RESTORE_TEST_KEK), and no key provider is available to restore it");
|
||||
assertThat(refused.getTables()).as("nothing was read").isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** REPLACE needs the typed confirmation, deletes what is not in the backup, takes a
|
||||
** pre-restore backup first, brings the table back to exactly the backed up rows
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.backups.schedule;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.backups.BackupsQBitConfig;
|
||||
import com.kingsrook.qbits.backups.BackupsTestUtils;
|
||||
import com.kingsrook.qbits.backups.VerifyTestSupport;
|
||||
import com.kingsrook.qbits.backups.model.BackupsTables;
|
||||
import com.kingsrook.qbits.backups.run.BackupCatalog;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.scheduledjobs.ScheduledJobsMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Plans run on their own schedule in an application that has no scheduled-jobs
|
||||
** table: the qbit starts what is due, once, and nothing that is not.
|
||||
*******************************************************************************/
|
||||
class BackupDuePlansProcessTest
|
||||
{
|
||||
private static final Map<String, java.io.Serializable> NIGHTLY = Map.of("cronExpression", "0 0 2 * * ?", "cronTimeZoneId", "UTC", "ownerUserId", "jmaes");
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An application with the qbit and no scheduled-jobs table, a clock that can be
|
||||
** moved, and the scheduler's session.
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws Exception
|
||||
{
|
||||
VerifyTestSupport.setUp(5);
|
||||
QContext.setQSession(new QSystemUserSession());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static RunBackendStepOutput tick() throws Exception
|
||||
{
|
||||
RunBackendStepOutput output = new RunBackendStepOutput();
|
||||
new BackupDuePlansProcess().run(new RunBackendStepInput(), output);
|
||||
return (output);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static List<QRecord> runsOf(QRecord plan) throws Exception
|
||||
{
|
||||
return (new BackupCatalog().where(BackupsTables.RUN, "backupPlanId", plan.getValueInteger("id")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A cron is due when it has a time after the last start that is not after now,
|
||||
** in the plan's zone. A cron or a zone that is not one fails; it is not guessed.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testDueTimesRespectZonesAndMissedTimesCollapse() throws Exception
|
||||
{
|
||||
Instant since = Instant.parse("2026-11-04T00:00:00Z");
|
||||
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", "America/Chicago", since, Instant.parse("2026-11-04T13:59:59Z"))).isFalse();
|
||||
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", "America/Chicago", since, Instant.parse("2026-11-04T14:00:00Z"))).isTrue();
|
||||
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", "UTC", since, since.plusSeconds(172800))).as("two missed nights are one due time").isTrue();
|
||||
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", null, since, Instant.parse("2026-11-04T08:00:00Z"))).as("no zone is UTC").isTrue();
|
||||
assertThat(BackupDuePlansProcess.isDue(null, "UTC", since, since.plusSeconds(172800))).as("a plan with no cron is run by hand only").isFalse();
|
||||
assertThat(BackupDuePlansProcess.isDue("0 * * * * ?", "UTC", since, since)).isFalse();
|
||||
assertThat(BackupDuePlansProcess.isDue("0 * * * * ?", "UTC", null, since)).isFalse();
|
||||
assertThatThrownBy(() -> BackupDuePlansProcess.isDue("invalid", "UTC", since, since)).isInstanceOf(java.text.ParseException.class);
|
||||
assertThatThrownBy(() -> BackupDuePlansProcess.isDue("0 * * * * ?", "Fake/Zone", since, since)).isInstanceOf(java.time.DateTimeException.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Only the scheduler starts plans: a person's request is refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testAPersonCannotRunIt() throws Exception
|
||||
{
|
||||
QContext.setQSession(new QSession().withPermissions("backups.admin"));
|
||||
assertThatThrownBy(BackupDuePlansProcessTest::tick).hasMessageContaining("started by the scheduler");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A plan that is on and has a cron is started when its time has come, once: not
|
||||
** before, not again in the next minute, and once for several missed nights. A
|
||||
** plan that is off, and a plan with no cron, are never started.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testADuePlanIsStartedOnceAndOthersAreNot() throws Exception
|
||||
{
|
||||
QRecord nightly = VerifyTestSupport.plan(NIGHTLY);
|
||||
QRecord off = VerifyTestSupport.plan(Map.of("name", "Off", "planKey", "off", "prefix", "off", "isActive", false, "cronExpression", "0 0 2 * * ?", "cronTimeZoneId", "UTC", "ownerUserId", "jmaes"));
|
||||
QRecord byHand = VerifyTestSupport.plan(Map.of("name", "By hand", "planKey", "by-hand", "prefix", "by-hand", "ownerUserId", "jmaes"));
|
||||
|
||||
assertThat(tick().getValueInteger("backupsStarted")).as("created just now: its first time has not come").isZero();
|
||||
assertThat(runsOf(nightly)).isEmpty();
|
||||
|
||||
VerifyTestSupport.clock.advance(Duration.ofDays(1));
|
||||
RunBackendStepOutput first = tick();
|
||||
assertThat(first.getValueString("startedBy")).isEqualTo("plans");
|
||||
assertThat(first.getValueInteger("backupsStarted")).isEqualTo(1);
|
||||
assertThat(runsOf(nightly)).singleElement().satisfies(run ->
|
||||
{
|
||||
assertThat(run.getValueString("trigger")).isEqualTo("SCHEDULED");
|
||||
assertThat(run.getValueString("requestedByUserId")).isEqualTo("system:scheduler");
|
||||
assertThat(run.getValueString("status")).startsWith("SUCCEEDED");
|
||||
});
|
||||
|
||||
VerifyTestSupport.clock.advance(Duration.ofMinutes(1));
|
||||
assertThat(tick().getValueInteger("backupsStarted")).as("a minute later it is not due again").isZero();
|
||||
|
||||
VerifyTestSupport.clock.advance(Duration.ofDays(3));
|
||||
assertThat(tick().getValueInteger("backupsStarted")).as("three missed nights are one run").isEqualTo(1);
|
||||
assertThat(runsOf(nightly)).hasSize(2);
|
||||
assertThat(runsOf(off)).as("a plan that is switched off").isEmpty();
|
||||
assertThat(runsOf(byHand)).as("a plan with no cron").isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The verification cron is started the same way, after the plan has a backup.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testADueVerificationIsStarted() throws Exception
|
||||
{
|
||||
QRecord plan = VerifyTestSupport.plan(Map.of("cronExpression", "0 0 2 * * ?", "verifyCronExpression", "0 0 4 * * ?", "cronTimeZoneId", "UTC", "ownerUserId", "jmaes"));
|
||||
|
||||
VerifyTestSupport.clock.advance(Duration.ofDays(1));
|
||||
RunBackendStepOutput output = tick();
|
||||
assertThat(output.getValueInteger("backupsStarted")).isEqualTo(1);
|
||||
assertThat(output.getValueInteger("verificationsStarted")).isEqualTo(1);
|
||||
assertThat(new BackupCatalog().where(BackupsTables.VERIFICATION, "backupRunId", runsOf(plan).get(0).getValueInteger("id"))).as("the run was verified").isNotEmpty();
|
||||
assertThat(VerifyTestSupport.reload(plan).getValueInstant("lastVerifiedDate")).isNotNull();
|
||||
|
||||
VerifyTestSupport.clock.advance(Duration.ofMinutes(1));
|
||||
assertThat(tick().getValueInteger("verificationsStarted")).as("a minute later it is not due again").isZero();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Where the application has the scheduled-jobs table, its scheduled jobs start
|
||||
** the plans, and this process starts nothing: no backup runs twice.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testItStandsAsideWhereScheduledJobsStartThePlans() throws Exception
|
||||
{
|
||||
QRecord plan = VerifyTestSupport.plan(NIGHTLY);
|
||||
new ScheduledJobsMetaDataProvider().defineAll(QContext.getQInstance(), BackupsTestUtils.BACKEND, null);
|
||||
|
||||
VerifyTestSupport.clock.advance(Duration.ofDays(1));
|
||||
RunBackendStepOutput output = tick();
|
||||
assertThat(output.getValueString("startedBy")).isEqualTo("scheduledJobs");
|
||||
assertThat(runsOf(plan)).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** With a scheduler on the config it is on that scheduler, once a minute; with
|
||||
** none it is not scheduled. It is not in the navigation.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testItIsOnTheQbitsScheduler()
|
||||
{
|
||||
var scheduled = BackupDuePlansProcess.processMetaData(new BackupsQBitConfig().withSchedulerName("testScheduler"));
|
||||
assertThat(scheduled.getSchedule().getSchedulerName()).isEqualTo("testScheduler");
|
||||
assertThat(scheduled.getSchedule().getRepeatSeconds()).isEqualTo(60);
|
||||
assertThat(scheduled.getIsHidden()).isTrue();
|
||||
assertThat(BackupDuePlansProcess.processMetaData(new BackupsQBitConfig()).getSchedule()).isNull();
|
||||
assertThat(QContext.getQInstance().getProcess(BackupDuePlansProcess.NAME)).as("produced with the qbit").isNotNull();
|
||||
}
|
||||
}
|
||||
@@ -323,6 +323,65 @@ class BackupVerifierTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The real thing, from the plan: a key provider on the config, a plan that asks
|
||||
** for client-side encryption with a key reference. Its run is encrypted without
|
||||
** anybody handing it a cipher: the objects are ciphertext, the run and its
|
||||
** manifest record the reference and a fingerprint (never the key), and it
|
||||
** passes verification by content and a test restore. After a rotation the old
|
||||
** run still verifies and a new run is written under the new version. When the
|
||||
** key is gone the old run cannot be verified, and a new run is refused with
|
||||
** nothing written.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testAPlanThatAsksForEncryptionIsEncryptedByTheKeyProvider() throws Exception
|
||||
{
|
||||
java.util.Map<String, String> env = new java.util.HashMap<>();
|
||||
byte[] first = new byte[32];
|
||||
new java.security.SecureRandom().nextBytes(first);
|
||||
env.put("RUN_TEST_KEK", java.util.Base64.getEncoder().encodeToString(first));
|
||||
BackupsRuntime.getConfig().withKeyProvider(new com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider(env::get));
|
||||
|
||||
QRecord plan = plan(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "RUN_TEST_KEK", "sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY"));
|
||||
BackupRunResult result = new com.kingsrook.qbits.backups.run.BackupRunCoordinator().runPlan(plan, "MANUAL");
|
||||
assertThat(result.isUsable()).as(String.valueOf(result.getErrorMessage())).isTrue();
|
||||
|
||||
QRecord stored = run(result.getRunId());
|
||||
assertThat(stored.getValueString("encryptionKeyRef")).isEqualTo("RUN_TEST_KEK");
|
||||
assertThat(stored.getValueString("encryptionKeyFingerprint")).matches("v1:[0-9a-f]{16}");
|
||||
|
||||
String key = VerifyTestSupport.firstPartKey(result, "blogPost");
|
||||
assertThat(key).endsWith(".tink");
|
||||
byte[] object = BackupsTestUtils.BACKUPS.getBytes(key);
|
||||
assertThat(new String(object, 0, 4, java.nio.charset.StandardCharsets.US_ASCII)).as("the cipher's header, not a gzip stream").isEqualTo("QSC1");
|
||||
assertThat(new BackupCatalog().where(BackupsTables.ARTIFACT, "backupRunId", result.getRunId()).stream().filter(a -> "TABLE_DATA".equals(a.getValueString("artifactType"))))
|
||||
.isNotEmpty().allSatisfy(a -> assertThat(a.getValueBoolean("encrypted")).isTrue());
|
||||
|
||||
List<VerificationOutcome> good = new BackupVerifier().verifyThrough(result.getRunId(), BackupVerifier.TEST_RESTORE, "MANUAL", "t");
|
||||
assertThat(good).extracting(VerificationOutcome::status).containsExactly("PASSED", "PASSED", "PASSED");
|
||||
|
||||
env.put("RUN_TEST_KEK_V1", env.get("RUN_TEST_KEK"));
|
||||
byte[] second = new byte[32];
|
||||
new java.security.SecureRandom().nextBytes(second);
|
||||
env.put("RUN_TEST_KEK", java.util.Base64.getEncoder().encodeToString(second));
|
||||
env.put("RUN_TEST_KEK_VERSION", "2");
|
||||
assertThat(new BackupVerifier().verify(result.getRunId(), BackupVerifier.CONTENT, "MANUAL", "t").status()).as("written under version 1, verified after the rotation").isEqualTo("PASSED");
|
||||
VerifyTestSupport.clock.advance(java.time.Duration.ofHours(1));
|
||||
BackupRunResult rotated = new com.kingsrook.qbits.backups.run.BackupRunCoordinator().runPlan(reload(plan), "MANUAL");
|
||||
assertThat(rotated.isUsable()).as(String.valueOf(rotated.getErrorMessage())).isTrue();
|
||||
assertThat(run(rotated.getRunId()).getValueString("encryptionKeyFingerprint")).startsWith("v2:");
|
||||
|
||||
env.clear();
|
||||
assertThat(new BackupVerifier().verify(result.getRunId(), BackupVerifier.CONTENT, "MANUAL", "t").messages()).anyMatch(m -> m.contains("No key is available for the key reference RUN_TEST_KEK"));
|
||||
int objects = BackupsTestUtils.BACKUPS.list("").size();
|
||||
BackupRunResult refused = new com.kingsrook.qbits.backups.run.BackupRunCoordinator().runPlan(reload(plan), "MANUAL");
|
||||
assertThat(refused.getStatus()).isEqualTo("FAILED");
|
||||
assertThat(refused.getErrorMessage()).contains("no key is available for its encryption key reference RUN_TEST_KEK").contains("Nothing was written");
|
||||
assertThat(BackupsTestUtils.BACKUPS.list("")).as("nothing was written in the clear instead").hasSize(objects);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Encrypted runs verify through the decrypt hook; a wrong key fails clearly; no
|
||||
** hook at all is an ERROR that says what to configure.
|
||||
|
||||
Reference in new issue
Block a user