-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #745 from nats-io/fix-sha256
[BREAKING] [FIX] replace sha256 library used by the client for objectstore entries and migration tool
- Loading branch information
Showing
9 changed files
with
723 additions
and
384 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,189 @@ | ||
/* | ||
* Copyright 2025 The NATS Authors | ||
* 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. | ||
*/ | ||
import { parse } from "https://deno.land/[email protected]/flags/mod.ts"; | ||
import { ObjectStoreImpl, ServerObjectInfo } from "../jetstream/objectstore.ts"; | ||
import { | ||
connect, | ||
ConnectionOptions, | ||
credsAuthenticator, | ||
} from "https://raw.githubusercontent.com/nats-io/nats.deno/main/src/mod.ts"; | ||
import { Base64UrlPaddedCodec } from "../nats-base-client/base64.ts"; | ||
import { | ||
SHA256 as BAD_SHA256, | ||
} from "https://raw.githubusercontent.com/nats-io/nats.deno/refs/tags/v1.29.1/nats-base-client/sha256.js"; | ||
import { consumerOpts } from "../jetstream/mod.ts"; | ||
import { sha256 } from "https://raw.githubusercontent.com/nats-io/nats.deno/refs/tags/v1.29.1/nats-base-client/sha256.js"; | ||
import { checkSha256, parseSha256 } from "../jetstream/sha_digest.parser.ts"; | ||
|
||
const argv = parse( | ||
Deno.args, | ||
{ | ||
alias: { | ||
"s": ["server"], | ||
"f": ["creds"], | ||
"b": ["bucket"], | ||
}, | ||
default: { | ||
s: "127.0.0.1:4222", | ||
c: 1, | ||
i: 0, | ||
}, | ||
boolean: ["check"], | ||
string: ["server", "creds", "bucket"], | ||
}, | ||
); | ||
|
||
const copts = { servers: argv.s } as ConnectionOptions; | ||
|
||
if (argv.h || argv.help) { | ||
console.log( | ||
"Usage: fix-os [-s server] [--creds=/path/file.creds] [--check] --bucket=name", | ||
); | ||
console.log( | ||
"\nThis tool fixes metadata entries in an object store that were written", | ||
); | ||
console.log( | ||
"with hashes that were calculated incorrectly due to a bug in the sha256 library.", | ||
); | ||
console.log("Please backup your object stores before using this tool."); | ||
|
||
Deno.exit(1); | ||
} | ||
|
||
if (argv.creds) { | ||
const data = await Deno.readFile(argv.creds); | ||
copts.authenticator = credsAuthenticator(data); | ||
} | ||
|
||
if (!argv.bucket) { | ||
console.log("--bucket is required"); | ||
Deno.exit(1); | ||
} | ||
|
||
const nc = await connect(copts); | ||
|
||
const js = nc.jetstream(); | ||
const jsm = await nc.jetstreamManager(); | ||
const lister = jsm.streams.listObjectStores(); | ||
let found = false; | ||
const streamName = `OBJ_${argv.bucket}`; | ||
for await (const oss of lister) { | ||
if (oss.streamInfo.config.name === streamName) { | ||
found = true; | ||
break; | ||
} | ||
} | ||
if (!found) { | ||
console.log(`bucket '${argv.bucket}' was not found`); | ||
Deno.exit(1); | ||
} | ||
const os = await js.views.os(argv.bucket) as ObjectStoreImpl; | ||
await fixDigests(os); | ||
|
||
async function fixDigests(os: ObjectStoreImpl): Promise<void> { | ||
let fixes = 0; | ||
const entries = await os.list(); | ||
for (const entry of entries) { | ||
if (!entry.digest.startsWith("SHA-256=")) { | ||
console.error( | ||
`ignoring entry ${entry.name} - unknown objectstore digest:`, | ||
entry.digest, | ||
); | ||
continue; | ||
} | ||
// plain digest string | ||
const digest = entry.digest.substring(8); | ||
const parsedDigest = parseSha256(digest); | ||
if (parsedDigest === null) { | ||
console.error( | ||
`ignoring entry ${entry.name} - unable to parse digest:`, | ||
digest, | ||
); | ||
continue; | ||
} | ||
|
||
const badSha = new BAD_SHA256(); | ||
const sha = sha256.create(); | ||
let badHash = new Uint8Array(0); | ||
let hash = new Uint8Array(0); | ||
|
||
const oc = consumerOpts(); | ||
oc.orderedConsumer(); | ||
|
||
const subj = `$O.${os.name}.C.${entry.nuid}`; | ||
let needsFixing = false; | ||
|
||
const sub = await js.subscribe(subj, oc); | ||
for await (const m of sub) { | ||
if (m.data.length > 0) { | ||
badSha.update(m.data); | ||
sha.update(m.data); | ||
} | ||
if (m.info.pending === 0) { | ||
badHash = badSha.digest(); | ||
hash = sha.digest(); | ||
break; | ||
} | ||
} | ||
sub.unsubscribe(); | ||
|
||
if (checkSha256(parsedDigest, badHash)) { | ||
// this one could be bad | ||
if (!checkSha256(badHash, hash)) { | ||
console.log( | ||
`[WARN] entry ${entry.name} has a bad hash: ${ | ||
Base64UrlPaddedCodec.encode(badHash) | ||
} - should be ${Base64UrlPaddedCodec.encode(hash)}`, | ||
); | ||
needsFixing = true; | ||
fixes++; | ||
} | ||
} | ||
|
||
if (argv.check) { | ||
continue; | ||
} | ||
if (needsFixing) { | ||
const metaSubject = os._metaSubject(entry.name); | ||
const m = await os.jsm.streams.getMessage(os.stream, { | ||
last_by_subj: metaSubject, | ||
}); | ||
const info = m.json<ServerObjectInfo>(); | ||
const digest = Base64UrlPaddedCodec.encode(hash); | ||
info.digest = `SHA-256=${digest}`; | ||
try { | ||
await js.publish(metaSubject, JSON.stringify(info)); | ||
} catch (err) { | ||
console.error(`[ERR] failed to update ${metaSubject}: ${err.message}`); | ||
continue; | ||
} | ||
try { | ||
const seq = m.seq; | ||
await jsm.streams.deleteMessage(os.stream, seq); | ||
} catch (err) { | ||
console.error( | ||
`[WARN] failed to delete bad entry ${metaSubject}: ${err.message} - new entry was added`, | ||
); | ||
} | ||
} | ||
} | ||
|
||
const verb = argv.check ? "are" : "were"; | ||
console.log( | ||
`${fixes} digest fixes ${verb} required on bucket ${argv.bucket}`, | ||
); | ||
} | ||
|
||
await nc.drain(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
/* | ||
* Copyright 2025 The NATS Authors | ||
* 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. | ||
*/ | ||
|
||
export function parseSha256(s: string): Uint8Array | null { | ||
return toByteArray(s); | ||
} | ||
|
||
function isHex(s: string): boolean { | ||
// contains valid hex characters only | ||
const hexRegex = /^[0-9A-Fa-f]+$/; | ||
if (!hexRegex.test(s)) { | ||
// non-hex characters | ||
return false; | ||
} | ||
|
||
// check for mixed-case strings - paranoid base64 sneaked in | ||
const isAllUpperCase = /^[0-9A-F]+$/.test(s); | ||
const isAllLowerCase = /^[0-9a-f]+$/.test(s); | ||
if (!(isAllUpperCase || isAllLowerCase)) { | ||
return false; | ||
} | ||
|
||
// ensure the input string length is even | ||
return s.length % 2 === 0; | ||
} | ||
|
||
function isBase64(s: string): boolean { | ||
// test for padded or normal base64 | ||
return /^[A-Za-z0-9\-_]*(={0,2})?$/.test(s) || | ||
/^[A-Za-z0-9+/]*(={0,2})?$/.test(s); | ||
} | ||
|
||
function detectEncoding(input: string): "hex" | "b64" | "" { | ||
// hex is more reliable to flush out... | ||
if (isHex(input)) { | ||
return "hex"; | ||
} else if (isBase64(input)) { | ||
return "b64"; | ||
} | ||
return ""; | ||
} | ||
|
||
function hexToByteArray(s: string): Uint8Array { | ||
if (s.length % 2 !== 0) { | ||
throw new Error("hex string must have an even length"); | ||
} | ||
const a = new Uint8Array(s.length / 2); | ||
for (let i = 0; i < s.length; i += 2) { | ||
// parse hex two chars at a time | ||
a[i / 2] = parseInt(s.substring(i, i + 2), 16); | ||
} | ||
return a; | ||
} | ||
|
||
function base64ToByteArray(s: string): Uint8Array { | ||
// could be url friendly | ||
s = s.replace(/-/g, "+"); | ||
s = s.replace(/_/g, "/"); | ||
const sbin = atob(s); | ||
return Uint8Array.from(sbin, (c) => c.charCodeAt(0)); | ||
} | ||
|
||
function toByteArray(input: string): Uint8Array | null { | ||
const encoding = detectEncoding(input); | ||
switch (encoding) { | ||
case "hex": | ||
return hexToByteArray(input); | ||
case "b64": | ||
return base64ToByteArray(input); | ||
} | ||
return null; | ||
} | ||
|
||
export function checkSha256( | ||
a: string | Uint8Array, | ||
b: string | Uint8Array, | ||
): boolean { | ||
const aBytes = typeof a === "string" ? parseSha256(a) : a; | ||
const bBytes = typeof b === "string" ? parseSha256(b) : b; | ||
if (aBytes === null || bBytes === null) { | ||
return false; | ||
} | ||
if (aBytes.length !== bBytes.length) { | ||
return false; | ||
} | ||
for (let i = 0; i < aBytes.length; i++) { | ||
if (aBytes[i] !== bBytes[i]) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.