Skip to content
Open
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
18 changes: 18 additions & 0 deletions examples/official-site/content/functions/basic_auth_password.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
icon: key
since: 0.7.2
category: identity-and-security
summary: Read the password sent with HTTP Basic authentication.
return_type: TEXT
---

Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request.
If the header is absent, SQLPage sends an HTTP Basic challenge. Browsers normally respond by prompting for credentials.

### Example

```sql
SELECT 'authentication' AS component,
(SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash,
sqlpage.basic_auth_password() AS password;
```
18 changes: 18 additions & 0 deletions examples/official-site/content/functions/basic_auth_username.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
icon: user
since: 0.7.2
category: identity-and-security
summary: Read the username sent with HTTP Basic authentication.
return_type: TEXT
---

Returns the username from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request.
If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials.

### Example

```sql
SELECT 'authentication' AS component,
(SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash,
sqlpage.basic_auth_password() AS password;
```
31 changes: 31 additions & 0 deletions examples/official-site/content/functions/hash_password.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
icon: spy
since: 0.7.2
category: identity-and-security
summary: Hash a password with Argon2id for storage.
parameters:
- name: password
type: TEXT
required: true
description: The password to hash.
---

Hashes a password with the Argon2id variant and outputs it in the [PHC string format](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md), ready to store in your users table.

Every call generates a brand new cryptographic salt so that two people choosing the same password still end up with different hashes, which defeats rainbow-table attacks and lets you safely reveal only the hash.

Use this function only when creating or resetting a password (for example while inserting a brand new user): it writes the stored value. Later, at login time, the [authentication component](documentation.sql?component=authentication#component) reads the stored hash, hashes the visitor's password with the embedded salt and parameters, and grants access only if they match.

### Example

```sql
SELECT 'form' AS component;
SELECT 'username' AS name;
SELECT 'password' AS name, 'password' AS type;

INSERT INTO users (name, password_hash) VALUES (:username, sqlpage.hash_password(:password));
```

### Try online

You can try the password hashing function [on this page](/examples/hash_password.sql).
111 changes: 111 additions & 0 deletions examples/official-site/content/functions/hmac.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
---
icon: shield-lock
since: 0.38.0
category: identity-and-security
summary: Sign data with a shared secret using HMAC.
parameters:
- name: data
type: TEXT
required: true
description: The input data to compute the HMAC for. Can be any text string. Cannot be NULL.
- name: key
type: TEXT
required: true
description: The secret key used to compute the HMAC. Should be kept confidential. Cannot be NULL.
- name: algorithm
type: TEXT
description: 'The hash algorithm and output format. Optional, defaults to `sha256` (hex output). Supported
values: `sha256`, `sha256-base64`, `sha512`, `sha512-base64`. Defaults to `sha256`.'
---

Creates a unique "signature" for some data using a secret key.
This signature proves that the data hasn't been tampered with and comes from someone who knows the secret.

## HMAC use cases

[**HMAC**](https://en.wikipedia.org/wiki/HMAC) (Hash-based Message Authentication Code) is commonly used to:
- **Verify webhooks**: Use HMAC to ensure only a given external service can call a given endpoint in your application.
The service signs their request with a secret key, and you verify the signature before processing the data they sent you.
Used for instance by [Stripe](https://docs.stripe.com/webhooks?verify=verify-manually), and [Shopify](https://shopify.dev/docs/apps/build/webhooks/subscribe/https#step-2-validate-the-origin-of-your-webhook-to-ensure-its-coming-from-shopify).
- **Secure API requests**: Prove that an API request comes from an authorized source
- **Generate secure tokens**: Create temporary access codes for downloads or password resets
- **Protect data**: Ensure data hasn't been modified during transmission

## Signing data

The `sqlpage.hmac` function takes three inputs:
1. **Your data** - The text you want to sign (like a message or request body)
2. **Your secret key** - A password only you know (keep this safe!)
3. **Algorithm** (optional) - The hash algorithm and output format:
- `sha256` (default) - SHA-256 with hexadecimal output
- `sha256-base64` - SHA-256 with base64 output
- `sha512` - SHA-512 with hexadecimal output
- `sha512-base64` - SHA-512 with base64 output

It returns a signature string. If someone changes even one letter in your data, the signature will be completely different.

### Example: Verify a Webhooks signature

When Shopify sends you a webhook (like when someone places an order), it includes a signature. Here's how to verify it's really from Shopify.
This supposes you store the secret key in an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) named `WEBHOOK_SECRET`.

```sql
SET body = sqlpage.request_body();
SET secret = sqlpage.environment_variable('WEBHOOK_SECRET');
SET expected_signature = sqlpage.hmac($body, $secret, 'sha256');
SET actual_signature = sqlpage.header('X-Webhook-Signature');

-- redirect to an error page and stop execution if the signature does not match
SELECT
'redirect' as component,
'/error.sql?err=bad_webhook_signature' as link
WHERE $actual_signature != $expected_signature OR $actual_signature IS NULL;

-- If we reach here, the signature is valid - process the order
INSERT INTO orders (order_data) VALUES ($body);

SELECT 'json' as component, 'jsonlines' as type;
SELECT 'success' as status;
```

### Example: Time-limited links

You can create links that will be valid only for a limited time by including a signature in them.
Let's say we have a `download.sql` page we want to link to,
but we don't want it to be accessible to anyone who can find the link.
Sign `file_id|expires_at` with a secret. Accept only if not expired and the signature matches.

#### Generate a signed link

```sql
SET expires_at = datetime('now', '+1 hour');
SET token = sqlpage.hmac(
$file_id || '|' || $expires_at,
sqlpage.environment_variable('DOWNLOAD_SECRET'),
'sha256'
);
SELECT '/download.sql?file_id=' || $file_id || '&expires_at=' || $expires_at || '&token=' || $token AS link;
```

#### Verify the signed link

```sql
SET expected = sqlpage.hmac(
$file_id || '|' || $expires_at,
sqlpage.environment_variable('DOWNLOAD_SECRET'),
'sha256'
);
SELECT 'redirect' AS component, '/error.sql?err=expired' AS link
WHERE $expected != $token OR $token IS NULL OR $expires_at < datetime('now');

-- serve the file
```

### Important Security Notes

- **Keep your secret key safe**: If your secret leaks, anyone can forge signatures and access protected pages
- **The signature is case-sensitive**: Even a single wrong letter means the signature won't match
- **NULL handling**: Always use `IS DISTINCT FROM`, not `=` to check for hmac matches.
- `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature` will not redirect if `$signature` is NULL (the signature is absent).
- `SELECT 'redirect' as component WHERE sqlpage.hmac(...) IS DISTINCT FROM $signature` checks for both NULL and non-NULL values (but is not available in all SQL dialects).
- `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature OR $signature IS NULL` is the most portable solution.
100 changes: 100 additions & 0 deletions examples/official-site/content/functions/oidc_logout_url.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
---
icon: logout
since: 0.41.0
category: identity-and-security
summary: Build a sign-out URL for an OpenID Connect session.
parameters:
- name: redirect_uri
type: TEXT
description: The relative URL path where the user should be redirected after logout. Must start with `/`.
Defaults to `/` if not provided.
---

The `sqlpage.oidc_logout_url` function generates a secure logout URL for users authenticated via [OIDC Single Sign-On](/sso).

When a user visits this URL, SQLPage will:
1. Remove the authentication cookie
2. Redirect the user to the OIDC provider's logout endpoint (if available)
3. Finally redirect back to the specified `redirect_uri`

## Security Features

This function provides protection against **Cross-Site Request Forgery (CSRF)** attacks:
- The generated URL contains a cryptographically signed token
- The token includes a timestamp and expires after 10 minutes
- The token is signed using your OIDC client secret
- Only relative URLs (starting with `/`) are allowed as redirect targets

This means that malicious websites cannot trick your users into logging out by simply including an image or link to your logout URL.

## Add a logout button

```sql
select 'button' as component;
select
'Logout' as title,
sqlpage.oidc_logout_url('/') as link,
'logout' as icon,
'red' as outline;
```

This creates a logout button that, when clicked:
1. Logs the user out of your SQLPage application
2. Logs the user out of the OIDC provider (if the provider supports [RP-Initiated Logout](https://openid.net/specs/openid-connect-rpinitiated-1_0.html))
3. Redirects the user back to your homepage (`/`)

## Examples

### Logout Button in Navigation

```sql
select 'shell' as component,
'My App' as title,
json_array(
json_object(
'title', 'Logout',
'link', sqlpage.oidc_logout_url('/'),
'icon', 'logout'
)
) as menu_item;
```

### Logout with Return to Current Page

```sql
select 'button' as component;
select
'Sign Out' as title,
sqlpage.oidc_logout_url(sqlpage.path()) as link;
```

### Conditional Logout Link

```sql
select 'button' as component
where sqlpage.user_info('sub') is not null;
select
'Logout ' || sqlpage.user_info('name') as title,
sqlpage.oidc_logout_url('/') as link
where sqlpage.user_info('sub') is not null;
```

## Requirements

- OIDC must be [configured](/sso) in your `sqlpage.json`
- If OIDC is not configured, this function returns NULL
- The `redirect_uri` must be a relative path starting with `/`

## Provider Support

The logout behavior depends on your OIDC provider:

| Provider | Full Logout Support |
|----------|-------------------|
| Keycloak | ✅ Yes |
| Auth0 | ✅ Yes |
| Google | ❌ No (local logout only) |
| Azure AD | ✅ Yes |
| Okta | ✅ Yes |

When the provider doesn't support RP-Initiated Logout, SQLPage will still remove the local authentication cookie and redirect to your specified URI.
28 changes: 28 additions & 0 deletions examples/official-site/content/functions/random_string.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
icon: arrows-shuffle
since: 0.7.2
category: identity-and-security
summary: Generate a cryptographically secure random string.
parameters:
- name: length
type: INTEGER
required: true
description: The length of the string to generate.
---

Returns a cryptographically secure random string of the given length.

When used as a standalone selected column in a query that returns several rows, `random_string` runs once per returned row.
Use `SET token = sqlpage.random_string(32)` first if you want one token reused later in the page.

### Example

Generate a random string of 32 characters and use it as a session ID stored in a cookie:

```sql
INSERT INTO login_session (session_token, username) VALUES (sqlpage.random_string(32), :username)
RETURNING
'cookie' AS component,
'session_id' AS name,
session_token AS value;
```
Loading
Loading