Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.

Grafbase next #11

Draft
wants to merge 22 commits into
base: grafbase
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ name: CI
on:
pull_request:
branches:
- neon
- master
push:
branches:
- neon
- master

env:
Expand All @@ -17,15 +19,15 @@ jobs:
name: rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: sfackler/actions/rustup@master
- uses: sfackler/actions/rustfmt@master

clippy:
name: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: sfackler/actions/rustup@master
- run: echo "version=$(rustc --version)" >> $GITHUB_OUTPUT
id: rust-version
Expand All @@ -45,15 +47,18 @@ jobs:
with:
path: target
key: clippy-target-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }}y
- run: cargo clippy --all --all-targets
- run: cargo clippy --workspace --all-targets

check-wasm32:
name: check-wasm32
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- run: docker compose up -d
- uses: sfackler/actions/rustup@master
- run: echo "version=$(rustc --version)" >> $GITHUB_OUTPUT
with:
version: 1.67.0
- run: echo "::set-output name=version::$(rustc --version)"
id: rust-version
- run: rustup target add wasm32-unknown-unknown
- uses: actions/cache@v3
Expand Down
2 changes: 2 additions & 0 deletions docker/sql_setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ port = 5433
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
wal_level = logical
EOCONF

cat > "$PGDATA/pg_hba.conf" <<-EOCONF
Expand All @@ -82,6 +83,7 @@ host all ssl_user ::0/0 reject

# IPv4 local connections:
host all postgres 0.0.0.0/0 trust
host replication postgres 0.0.0.0/0 trust
# IPv6 local connections:
host all postgres ::0/0 trust
# Unix socket connections:
Expand Down
61 changes: 61 additions & 0 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
description = "A prisma test project";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/master";
inputs.flake-utils.url = "github:numtide/flake-utils";

outputs = {
self,
nixpkgs,
flake-utils,
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = nixpkgs.legacyPackages.${system};
in {
devShell = pkgs.mkShell {
nativeBuildInputs = [pkgs.bashInteractive];
buildInputs = with pkgs; [
openssl
rustup
pkg-config
];
};
});
}
1 change: 1 addition & 0 deletions postgres-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ byteorder = "1.0"
bytes = "1.0"
fallible-iterator = "0.2"
hmac = "0.12"
lazy_static = "1.4"
md-5 = "0.10"
memchr = "2.0"
rand = "0.8"
Expand Down
110 changes: 74 additions & 36 deletions postgres-protocol/src/authentication/sasl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,32 @@ impl ChannelBinding {
}
}

/// A pair of keys for the SCRAM-SHA-256 mechanism.
/// See <https://datatracker.ietf.org/doc/html/rfc5802#section-3> for details.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScramKeys<const N: usize> {
/// Used by server to authenticate client.
pub client_key: [u8; N],
/// Used by client to verify server's signature.
pub server_key: [u8; N],
}

/// Password or keys which were derived from it.
enum Credentials<const N: usize> {
/// A regular password as a vector of bytes.
Password(Vec<u8>),
/// A precomputed pair of keys.
Keys(Box<ScramKeys<N>>),
}

enum State {
Update {
nonce: String,
password: Vec<u8>,
password: Credentials<32>,
channel_binding: ChannelBinding,
},
Finish {
salted_password: [u8; 32],
server_key: [u8; 32],
auth_message: String,
},
Done,
Expand All @@ -132,30 +150,43 @@ pub struct ScramSha256 {
state: State,
}

fn nonce() -> String {
// rand 0.5's ThreadRng is cryptographically secure
let mut rng = rand::thread_rng();
(0..NONCE_LENGTH)
.map(|_| {
let mut v = rng.gen_range(0x21u8..0x7e);
if v == 0x2c {
v = 0x7e
}
v as char
})
.collect()
}

impl ScramSha256 {
/// Constructs a new instance which will use the provided password for authentication.
pub fn new(password: &[u8], channel_binding: ChannelBinding) -> ScramSha256 {
// rand 0.5's ThreadRng is cryptographically secure
let mut rng = rand::thread_rng();
let nonce = (0..NONCE_LENGTH)
.map(|_| {
let mut v = rng.gen_range(0x21u8..0x7e);
if v == 0x2c {
v = 0x7e
}
v as char
})
.collect::<String>();
let password = Credentials::Password(normalize(password));
ScramSha256::new_inner(password, channel_binding, nonce())
}

ScramSha256::new_inner(password, channel_binding, nonce)
/// Constructs a new instance which will use the provided key pair for authentication.
pub fn new_with_keys(keys: ScramKeys<32>, channel_binding: ChannelBinding) -> ScramSha256 {
let password = Credentials::Keys(keys.into());
ScramSha256::new_inner(password, channel_binding, nonce())
}

fn new_inner(password: &[u8], channel_binding: ChannelBinding, nonce: String) -> ScramSha256 {
fn new_inner(
password: Credentials<32>,
channel_binding: ChannelBinding,
nonce: String,
) -> ScramSha256 {
ScramSha256 {
message: format!("{}n=,r={}", channel_binding.gs2_header(), nonce),
state: State::Update {
nonce,
password: normalize(password),
password,
channel_binding,
},
}
Expand Down Expand Up @@ -192,20 +223,32 @@ impl ScramSha256 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid nonce"));
}

let salt = match STANDARD.decode(parsed.salt) {
Ok(salt) => salt,
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, e)),
};
let (client_key, server_key) = match password {
Credentials::Password(password) => {
let salt = match base64::decode(parsed.salt) {
Ok(salt) => salt,
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, e)),
};

let salted_password = hi(&password, &salt, parsed.iteration_count);
let salted_password = hi(&password, &salt, parsed.iteration_count);

let mut hmac = Hmac::<Sha256>::new_from_slice(&salted_password)
.expect("HMAC is able to accept all key sizes");
hmac.update(b"Client Key");
let client_key = hmac.finalize().into_bytes();
let make_key = |name| {
let mut hmac = Hmac::<Sha256>::new_from_slice(&salted_password)
.expect("HMAC is able to accept all key sizes");
hmac.update(name);

let mut key = [0u8; 32];
key.copy_from_slice(hmac.finalize().into_bytes().as_slice());
key
};

(make_key(b"Client Key"), make_key(b"Server Key"))
}
Credentials::Keys(keys) => (keys.client_key, keys.server_key),
};

let mut hash = Sha256::default();
hash.update(client_key.as_slice());
hash.update(client_key);
let stored_key = hash.finalize_fixed();

let mut cbind_input = vec![];
Expand Down Expand Up @@ -236,7 +279,7 @@ impl ScramSha256 {
.unwrap();

self.state = State::Finish {
salted_password,
server_key,
auth_message,
};
Ok(())
Expand All @@ -247,11 +290,11 @@ impl ScramSha256 {
/// This should be called when the backend sends an `AuthenticationSASLFinal` message.
/// Authentication has only succeeded if this method returns `Ok(())`.
pub fn finish(&mut self, message: &[u8]) -> io::Result<()> {
let (salted_password, auth_message) = match mem::replace(&mut self.state, State::Done) {
let (server_key, auth_message) = match mem::replace(&mut self.state, State::Done) {
State::Finish {
salted_password,
server_key,
auth_message,
} => (salted_password, auth_message),
} => (server_key, auth_message),
_ => return Err(io::Error::new(io::ErrorKind::Other, "invalid SCRAM state")),
};

Expand All @@ -275,11 +318,6 @@ impl ScramSha256 {
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, e)),
};

let mut hmac = Hmac::<Sha256>::new_from_slice(&salted_password)
.expect("HMAC is able to accept all key sizes");
hmac.update(b"Server Key");
let server_key = hmac.finalize().into_bytes();

let mut hmac = Hmac::<Sha256>::new_from_slice(&server_key)
.expect("HMAC is able to accept all key sizes");
hmac.update(auth_message.as_bytes());
Expand Down Expand Up @@ -466,7 +504,7 @@ mod test {
let server_final = "v=U+ppxD5XUKtradnv8e2MkeupiA8FU87Sg8CXzXHDAzw=";

let mut scram = ScramSha256::new_inner(
password.as_bytes(),
Credentials::Password(normalize(password.as_bytes())),
ChannelBinding::unsupported(),
nonce.to_string(),
);
Expand Down
7 changes: 7 additions & 0 deletions postgres-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@

use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use lazy_static::lazy_static;
use std::io;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

pub mod authentication;
pub mod escape;
Expand All @@ -27,6 +29,11 @@ pub type Oid = u32;
/// A Postgres Log Sequence Number (LSN).
pub type Lsn = u64;

lazy_static! {
/// Postgres epoch is 2000-01-01T00:00:00Z
pub static ref PG_EPOCH: SystemTime = UNIX_EPOCH + Duration::from_secs(946_684_800);
}

/// An enum indicating if a value is `NULL` or not.
pub enum IsNull {
/// The value is `NULL`.
Expand Down
Loading